diff --git a/desktop/src/__tests__/hologram-display-correction.test.ts b/desktop/src/__tests__/hologram-display-correction.test.ts index 85e35fc1..b348d01e 100644 --- a/desktop/src/__tests__/hologram-display-correction.test.ts +++ b/desktop/src/__tests__/hologram-display-correction.test.ts @@ -61,6 +61,20 @@ function fixture(reducedMotion: boolean) { } describe('display collision correction in the production frame',()=>{ + it('keeps the accepted correction camera fixed after a subthreshold camera settle',()=>{ + const f=fixture(false),{h,camera}=f; + try { + h.desiredCamera.z+=.0005;h.desiredLookAt.x+=.0003; + const prepare=h.prepareDisplayCorrection.bind(h);let accepted:number[]|null=null; + h.prepareDisplayCorrection=()=>{accepted=camera.matrixWorld.toArray();prepare();}; + h.displayRelaxationPending=true;h.render(1/60); + expect(accepted).not.toBeNull(); + for(let i=0;i<180;i++){h.render(1/60);if(!h.displayTransition.moving)break;} + expect(h.displayTransition.moving).toBe(false); + expect(camera.matrixWorld.toArray()).toEqual(accepted); + }finally{f.dispose();} + }); + it('keeps emergency state latched and returns to idle after a visible redraw',()=>{ const f=fixture(false),{h}=f; const callbacks=new Map();let serial=0,now=0; diff --git a/desktop/src/__tests__/projected-relaxation.test.ts b/desktop/src/__tests__/projected-relaxation.test.ts index 96b905da..53a23fd6 100644 --- a/desktop/src/__tests__/projected-relaxation.test.ts +++ b/desktop/src/__tests__/projected-relaxation.test.ts @@ -83,3 +83,37 @@ describe('dense viewports keep core separation ahead of optional whitespace',()= expect(diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests); }); }); + +describe('candidate admission and fixed geometry work',()=>{ + const points=()=>Array.from({length:2048},()=>({x:320,y:240,radius:1.6})); + class CountedPins extends Set{ + calls=0; + override has(value:number){this.calls++;return super.has(value);} + } + it('retains all fixed offsets without quadratically querying fixed memberships',()=>{ + const input=points(),fixed=new CountedPins(input.map((_,i)=>i)),prior=new Float64Array(input.length*2); + prior[14]=4;prior[15]=-2; + const r=relaxProjectedCircles(input,viewport,fixed,prior); + expect([...r.offsets]).toEqual([...prior]); + expect(fixed.calls).toBeLessThanOrEqual(input.length); + expect(r.diagnostics.pairTests).toBe(0); + expect(r.diagnostics.candidateVisits).toBe(0); + }); + it('bounds traversal with only two movable points and preserves immutable pins',()=>{ + const input=points(),fixed=new CountedPins(Array.from({length:2046},(_,i)=>i)); + const r=relaxProjectedCircles(input,viewport,fixed); + expect(fixed.calls).toBeLessThanOrEqual(input.length); + expect([...r.offsets.slice(0,4092)].every(value=>value===0)).toBe(true); + expect([...r.offsets].every(Number.isFinite)).toBe(true); + expect(r.diagnostics.candidateVisits).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.candidateVisits); + expect(r.diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests); + }); + it('reports bounded partial work instead of treating skipped traversal as free',()=>{ + const r=relaxProjectedCircles(points(),viewport); + expect(r.diagnostics.candidateVisits).toBeGreaterThan(0); + expect(r.diagnostics.candidateVisits).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.candidateVisits); + expect(r.diagnostics.pairTests).toBeLessThanOrEqual(PROJECTED_RELAXATION_LIMITS.pairTests); + expect(r.diagnostics.budgetExhausted).toBe(true); + expect([...r.offsets].every(Number.isFinite)).toBe(true); + }); +}); diff --git a/desktop/src/knowledge/hologram.ts b/desktop/src/knowledge/hologram.ts index f8dd2489..452a54b3 100644 --- a/desktop/src/knowledge/hologram.ts +++ b/desktop/src/knowledge/hologram.ts @@ -1142,6 +1142,14 @@ export class KnowledgeHologram { ||this.lookAt.distanceToSquared(this.desiredLookAt)>0||this.orbitActive; const alpha=this.reducedMotionEnabled||this.paused?1:1-Math.exp(-12*elapsed); this.camera.position.lerp(this.desiredCamera,alpha);this.lookAt.lerp(this.desiredLookAt,alpha); + const cameraRestDistanceSquared=0.000001; + // A correction accepted as stationary must keep the same camera while its + // offsets animate. Otherwise subthreshold interpolation moves the cores + // away from the screen-space constraints that were just solved. + if(!this.orbitActive){ + if(this.camera.position.distanceToSquared(this.desiredCamera)<=cameraRestDistanceSquared)this.camera.position.copy(this.desiredCamera); + if(this.lookAt.distanceToSquared(this.desiredLookAt)<=cameraRestDistanceSquared)this.lookAt.copy(this.desiredLookAt); + } this.camera.lookAt(this.lookAt);this.orbit.target.copy(this.lookAt);this.orbit.update(); this.camera.updateMatrixWorld(true); @@ -1154,7 +1162,7 @@ export class KnowledgeHologram { // Include perspective motion from depth changes at the viewport corners. const perspectiveBound = Math.hypot(1, halfFovTangent * Math.hypot(1, this.camera.aspect)); const denseOverview=this.view.hops===0&&this.view.nodes.length>120; - const cameraMoving=this.camera.position.distanceToSquared(this.desiredCamera)>0.000001||this.lookAt.distanceToSquared(this.desiredLookAt)>0.000001; + const cameraMoving=this.camera.position.distanceToSquared(this.desiredCamera)>cameraRestDistanceSquared||this.lookAt.distanceToSquared(this.desiredLookAt)>cameraRestDistanceSquared; this.plasticity.setDisplayScale(2 * nearestDepth * halfFovTangent / (Math.max(1, this.viewport.height) * perspectiveBound * (denseOverview?OVERVIEW_DISPLAY_GAIN:1))); const pointsMoving = this.plasticity.moving || this.positionTransition.moving; diff --git a/desktop/src/knowledge/projected-relaxation.ts b/desktop/src/knowledge/projected-relaxation.ts index 05a97106..be285f37 100644 --- a/desktop/src/knowledge/projected-relaxation.ts +++ b/desktop/src/knowledge/projected-relaxation.ts @@ -1,9 +1,9 @@ import type { ProjectedCircle, ProjectionViewport } from './projected-layout-metrics'; -export const PROJECTED_RELAXATION_LIMITS = Object.freeze({ nodes: 2048, passes: 16, pairTests: 131072, shiftCssPx: 10, gapCssPx: 4.5 }); +export const PROJECTED_RELAXATION_LIMITS = Object.freeze({ nodes: 2048, passes: 32, gapPasses: 8, pairTests: 131072, candidateVisits: 524288, shiftCssPx: 10, gapCssPx: 4.5 }); export interface RelaxationResult { offsets: Float64Array; - diagnostics: { nodes: number; passes: number; effectiveGapCssPx:number; pairTests: number; corePairTests:number; gapPairTests:number; coreContacts:number; moved: number; maxShift: number; budgetExhausted: boolean; inputTruncated: boolean }; + diagnostics: { nodes: number; passes: number; effectiveGapCssPx:number; candidateVisits:number; candidateBudgetExhausted:boolean; pairTests: number; corePairTests:number; gapPairTests:number; coreContacts:number; moved: number; maxShift: number; budgetExhausted: boolean; inputTruncated: boolean }; } /** Bounded display-only offsets. No identities, edges, source coordinates or @@ -12,25 +12,27 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor pinned: ReadonlySet = new Set(), initialOffsets?: Float64Array): RelaxationResult { const limits = PROJECTED_RELAXATION_LIMITS, count = Math.min(input.length, limits.nodes); const offsets = new Float64Array(count * 2), x = new Float64Array(count), y = new Float64Array(count); - const active = new Uint8Array(count), dx = new Float64Array(count), dy = new Float64Array(count); - const diagnostics = { nodes: count, passes: 0, effectiveGapCssPx:0, pairTests: 0, corePairTests:0, gapPairTests:0, coreContacts:0, moved: 0, maxShift: 0, + const active = new Uint8Array(count), fixed = new Uint8Array(count), dx = new Float64Array(count), dy = new Float64Array(count); + const diagnostics = { nodes: count, passes: 0, effectiveGapCssPx:0, candidateVisits:0, candidateBudgetExhausted:false, pairTests: 0, corePairTests:0, gapPairTests:0, coreContacts:0, moved: 0, maxShift: 0, budgetExhausted: false, inputTruncated: input.length > count }; const { left, top, width, height } = viewport; if (![left,top,width,height].every(Number.isFinite) || width <= 0 || height <= 0) return { offsets, diagnostics }; - let maxRadius = 0, retainedCorrection = false; + let maxRadius = 0, movableCount = 0, retainedCorrection = false; for (let i = 0; i < count; i++) { const p = input[i]; x[i] = p.x; y[i] = p.y; if (![p.x,p.y,p.radius].every(Number.isFinite) || p.radius <= 0 || p.inClipVolume === false || p.x < left || p.x > left + width || p.y < top || p.y > top + height || p.radius * 2 > width || p.radius * 2 > height) continue; - active[i] = 1; maxRadius = Math.max(maxRadius, p.radius); + active[i] = 1; fixed[i] = Number(pinned.has(i)); + if (!fixed[i]) movableCount++; + maxRadius = Math.max(maxRadius, p.radius); if (initialOffsets?.length === count * 2) { const ox = initialOffsets[i*2], oy = initialOffsets[i*2+1], size = Math.hypot(ox,oy); if (Number.isFinite(size)) { if (size > 0) retainedCorrection = true; const gain = size > limits.shiftCssPx ? limits.shiftCssPx / size : 1; - x[i] = pinned.has(i) ? p.x + ox * gain : Math.max(left + p.radius,Math.min(left + width - p.radius,p.x + ox * gain)); - y[i] = pinned.has(i) ? p.y + oy * gain : Math.max(top + p.radius,Math.min(top + height - p.radius,p.y + oy * gain)); + x[i] = fixed[i] ? p.x + ox * gain : Math.max(left + p.radius,Math.min(left + width - p.radius,p.x + ox * gain)); + y[i] = fixed[i] ? p.y + oy * gain : Math.max(top + p.radius,Math.min(top + height - p.radius,p.y + oy * gain)); } } } @@ -39,10 +41,12 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor // source/semantic distance or a guarantee that every packing is feasible. const gap = Math.min(limits.gapCssPx,Math.sqrt(width*height/Math.max(1,visibleCount))*.1); diagnostics.effectiveGapCssPx = gap; - for (let pass = 0; pass < limits.passes; pass++) { + for (let pass = 0; movableCount > 0 && pass < limits.passes; pass++) { + if (diagnostics.pairTests >= limits.pairTests || diagnostics.candidateVisits >= limits.candidateVisits) break; dx.fill(0); dy.fill(0); const budget = Math.floor((limits.pairTests - diagnostics.pairTests) / (limits.passes - pass)); - let tested = 0, contacts = 0, coreContacts = 0; + const visitBudget = Math.floor((limits.candidateVisits - diagnostics.candidateVisits) / (limits.passes - pass)); + let tested = 0, visited = 0, contacts = 0, coreContacts = 0, passCutoff = false; const accumulate = (gap:number, core:boolean) => { const cellSize = Math.max(1, maxRadius * 2 + gap); const columns = Math.ceil(width / cellSize) + 3; @@ -54,12 +58,23 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor } outer: for (let slot = 0; slot < count; slot++) { const a = (slot + pass * 257) % count; - if (!active[a]) continue; + // A fixed point never needs its own query. Its contacts are visited by + // movable neighbors, including neighbors with a larger original index. + if (!active[a] || fixed[a]) continue; const cx = Math.floor((x[a] - left) / cellSize), cy = Math.floor((y[a] - top) / cellSize); - for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++) - for (const b of grid.get(gy * columns + gx) ?? []) { - if (b <= a || pinned.has(a) && pinned.has(b)) continue; - if (tested >= budget) { diagnostics.budgetExhausted = true; break outer; } + for (let gx = cx - 1; gx <= cx + 1; gx++) for (let gy = cy - 1; gy <= cy + 1; gy++) { + const cell = grid.get(gy * columns + gx); + if (!cell) continue; + for (let k = 0; k < cell.length; k++) { + // Admit a cell entry before reading it, including duplicate/self + // entries that will not cause a distance calculation. + if (visited >= visitBudget) { + diagnostics.budgetExhausted = diagnostics.candidateBudgetExhausted = passCutoff = true; + break outer; + } + const b = cell[k]; visited++; diagnostics.candidateVisits++; + if (b === a || b < a && !fixed[b]) continue; + if (tested >= budget) { diagnostics.budgetExhausted = passCutoff = true; break outer; } tested++; diagnostics.pairTests++; if(core)diagnostics.corePairTests++;else diagnostics.gapPairTests++; let vx = x[a] - x[b], vy = y[a] - y[b], distance = Math.hypot(vx, vy); @@ -68,14 +83,16 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor if (distance >= (core ? radii : separation)) continue; contacts++;if(core){coreContacts++;diagnostics.coreContacts++;} if (distance < 1e-9) { - const angle = ((Math.imul(a + 1, 2654435761) ^ Math.imul(b + 1, 1597334677)) >>> 0) / 4294967296 * Math.PI * 2; - vx = Math.cos(angle); vy = Math.sin(angle); distance = 1; + const first=Math.min(a,b),second=Math.max(a,b),sign=a>> 0) / 4294967296 * Math.PI * 2; + vx = Math.cos(angle)*sign; vy = Math.sin(angle)*sign; } else { vx /= distance; vy /= distance; } const amount = Math.max(.1, separation - Math.hypot(x[a]-x[b],y[a]-y[b])) * .55; - const share = pinned.has(a) || pinned.has(b) ? 1 : .5; - if (!pinned.has(a)) { dx[a] += vx * amount * share; dy[a] += vy * amount * share; } - if (!pinned.has(b)) { dx[b] -= vx * amount * share; dy[b] -= vy * amount * share; } + const share = fixed[b] ? 1 : .5; + dx[a] += vx * amount * share; dy[a] += vy * amount * share; + if (!fixed[b]) { dx[b] -= vx * amount * share; dy[b] -= vy * amount * share; } } + } } }; // Spend each pass on actual overlapping cores before optional whitespace. @@ -83,10 +100,15 @@ export function relaxProjectedCircles(input: readonly ProjectedCircle[], viewpor // A retained correction is already a settled display choice. Reprojection // repairs new core contacts without repeatedly spending optional whitespace. // Extra convergence rounds are for cores only, not repeated whitespace. - if (!retainedCorrection && !coreContacts && tested < budget && pass < Math.floor(limits.passes/2)) accumulate(gap,false); + if (!retainedCorrection && !passCutoff && !coreContacts && tested < budget && pass < limits.gapPasses) accumulate(gap,false); diagnostics.passes++; - if (!contacts) break; - for (let i = 0; i < count; i++) if (active[i] && !pinned.has(i)) { + if (!contacts) { + // An exhausted prefix is not evidence that the unvisited suffix is free + // of contacts. Use the next bounded, rotated round when capacity remains. + if (passCutoff) continue; + break; + } + for (let i = 0; i < count; i++) if (active[i] && !fixed[i]) { const step = Math.hypot(dx[i],dy[i]), gain = step > 2 ? 2 / step : 1; let ox = x[i] + dx[i] * gain - input[i].x, oy = y[i] + dy[i] * gain - input[i].y; const total = Math.hypot(ox,oy); diff --git a/docs/evaluation/projection-budget-20261025.md b/docs/evaluation/projection-budget-20261025.md new file mode 100644 index 00000000..0f911251 --- /dev/null +++ b/docs/evaluation/projection-budget-20261025.md @@ -0,0 +1,91 @@ +# Projected work admission and state transitions + +Baseline9a723050532432f57e9afdf0f24a80f96427b1b3 had an arithmetic pair cap but +no candidate-entry cap. A source-bound observer with exactly equal output offsets +measured8,388,608 entries with2048 fixed points and29,347,842 with2046 fixed points +and2 movable points. The latter performed only22,508 distance tests. These are +synthetic helper states; the installed overview normally has at most one focus pin. + +Pin membership is now snapshotted once per active point. Only movable points query +neighbor cells; free/fixed pairs are still processed regardless of index, while +fixed/fixed pairs require no query. The coincident-pair seed uses ordered indices +and an antisymmetric sign so reversing the free/fixed query retains its direction. +A cell entry is admitted *before it is read*, including self/reversed entries. +Candidate524288 and arithmetic131072 ceilings are independent.32 core rounds may +use remaining capacity, with optional whitespace restricted to the first8 rounds. +The node2048 and display-shift10px ceilings remain unchanged. No saved coordinate, +relation, semantic force, title, identity, index, embedding or model changes. + +```mermaid +stateDiagram-v2 + [*] --> Validate + Validate --> RetainFixed: no movable points + Validate --> BuildGrid: movable points and capacity + BuildGrid --> AdmitEntry + AdmitEntry --> Partial: local visit or pair quota + AdmitEntry --> Skip: self or reverse free pair + Skip --> AdmitEntry + AdmitEntry --> Compare: admitted unordered movable contact + Compare --> AdmitEntry + Compare --> Clamp: round ends with contacts + Clamp --> BuildGrid: rounds and global capacity remain + Partial --> BuildGrid: next rotated bounded round + Partial --> Done: global capacity or rounds exhausted + AdmitEntry --> Done: full round has no contacts + RetainFixed --> Done + Done --> [*] +``` + +The diagram describes control states, not a model-checked GUI proof. An exhausted +prefix with no contacts is not evidence about an unvisited suffix; it must not be +used as convergence. A private constant64 witness catches the previous break: +correct code visits64 entries and moves the coincident pair; the break mutant +stops at2 entries without moving. Disabling the visit guard produces66 and is +rejected. The default524288 guard mutant reached473689 on the selected dense +workload and was **not** rejected; that result is retained, not counted as full +mutation coverage. An observer after the admission guard exactly matches the +counter and leaves output offsets unchanged on all three selected pin regimes. + +Resource argument: letN≤2048, P≤32, G≤8, V≤524288 and T≤131072. Counters start at0. +Every admitted increment follows a remaining-capacity check, and local quotas are +at most the remaining global capacity. Induction over admitted entries/pairs +therefore preservesV/T ceilings. At mostP+G grids are built, at most9(P+G)N neighbor +lookups and(P+G)N grid-insertion lookups occur (10(P+G)N Map reads +in total), and the active/fixed/update arrays requireO(N) memory. Candidate +loop work is bounded byV rather than an uncounted quadratic suffix. This counts +operations and does not establish worst-case JS Map latency, allocation/GC time, +OS scheduling, primary UI latency, GPU/FPS or battery. Spatial pruning alone is +not a universal linear-time theorem for arbitrary graph sizes or caller policies. + +Offset projection still enforces norm≤10px on finite admitted inputs; valid fixed +prior offsets remain fixed under the existing cap. No theorem says every dense +packing can separate. For2048 equal radius1.6 circles with coincident original +centers and center displacement≤10, disjoint cores would require +`2048*(1.6²) ≤ (10+1.6)²`. The left side5242.88 exceeds134.56. This necessary area +condition alone proves zero overlap impossible for that fixture; it does not +prove sufficiency for any other packing or semantic/entity correctness. + +The three new regressions fail on the baseline. Full frontend1155 checks in103 +files and TypeScript check pass. CPU comparisons use ordinary Set,3 warmups and21 +alternating measured rounds. Synthetic all-fixed p50 31.038→0.120ms; two-movable +145.157→0.938ms. A free coincident stress case5.285→5.912ms and core overlap261392→ +261679 are retained. Saved already-corrected native points used as fresh inputs +show7.494→4.001ms(default) and5.729→4.454ms(compact). These are separate solver-only +cohorts, not a production raw-input or universal speedup claim. Existing native +core residuals5 have penetration0.0005–0.153px; they are not removed by tolerance. +New canonical native/install results live under the task's projection-budget- +20261025 evidence, rather than being inferred from these CPU tests. + +Current-source external Pro/Gemini/reverse verification remainsNOT_RUN under the +preserved upload rejection. Original tabs/jobs, exact requested model constraints, +shared SDK/runtime pins, production queues and normal release/notary holds remain. + +A first native candidate reduced compact5→1 (default0), with25 rounds and no +quota exhaustion. Its remaining penetration was0.00236px; the initial correction +input was not recorded, so that snapshot alone did not establish a cause. A +separate actual-frame regression reproduced a stationary-camera contract defect: +correction was accepted at z8.0000906 while later interpolation moved it toward +z8.0005000. The renderer now snaps position/look-at using the same rest criterion +before accepting correction, outside active orbit input. The accepted-camera +matrix remains exact through offset animation; no overlap oracle/tolerance is +relaxed. The first native candidate remains preserved and was not installed.