perf(viewer): store the cold load's finished scene so the first reopen adopts it (W2)

Merged
LO
20d ago
+1342-88

W2 of the load-time hillclimb (reopen lane): the first reopen of a cached model adopts the stored scene instead of streaming the cache hit.

Timed verdict (exclusive scoreboard A/B, Pop) — measured on 151dfdacd2; confirmation A/B on the review-fix head pending

Job aa4adfdb, 2026-11-11 12:04–12:45 UTC, Balanced 5.3 GHz, NVIDIA adapter. main@5187254915 vs this head (151dfdacd2). 7 fixtures × 4 lanes × 5 interleaved rounds, plus a memory pass. 280 samples, 0 failed. The wasm differs only by the embedded checkout path (byte-identical once normalised). Per-element output is IDENTICAL on all 21 browser cells.

browser-warm1 (first reopen), interactive ms, median, base → branch:

fixturebasebranchgain2× noise floorverdict
ISSUE_1291,069832+22.1%10.1%PASS
advanced_model1,7391,143+34.3%5.6%PASS
schependomlaan1,202985+18.0%9.0%PASS
Holter3,6692,435+33.6%5.6%PASS
skolebygg (holdout)2,2261,361+38.9%9.0%PASS
BWK (holdout)2,9271,940+33.7%5.9%PASS
FZK (uncached, <10 MB)601639——no significant difference (expected)
  • First reopen ≈ snapshot reopen. Branch first reopen vs branch second reopen: Holter 2,435 vs 2,397; BWK 1,940 vs 1,947; skolebygg 1,361 vs 1,308.
  • UI quiet on the first reopen: PASS on all 6 cached fixtures (Holter 4,038 → 2,916).
  • Peak memory on the first reopen: PASS on Holter −28%, skolebygg −26%, BWK −22% (no finalize rebuild); the rest are within noise.
  • Controls: browser-cold interactive, UI quiet, peak memory and first geometry show no significant difference on all 7 fixtures. Native-cold and browser-warm (the snapshot reopen) show no significant difference on all 7.
  • Every branch first reopen adopted the snapshot (30/30 cached samples). No capture, store or hydration-refusal messages in any console log.
  • Capture cost at the finalize swap: scene.finalize.capture is at most about 9 ms (Holter: 0.16% of cold interactive).
  • Eager JS: +3,533 B raw (17,745,781 → 17,749,314, measured with measure-bundle.mjs on the A/B builds). About 13.6 KB of headroom remains under the ceiling plus tolerance.

Review fixes (reviews 5859228882 and 5860266137)

  • The capture can never fail the finalize. A throw drops it with reason failed. The cache-hit capture on main shared this exposure and is fixed by the same change.
  • Edit between the swap and the store. The entry is serialized from live meshes after the swap. The renderer hands over a check at the swap: no dirty bucket, and every captured bucket still drawing the batch it was captured from. That check and the level-offset check run right before the store. On failure the outcome is scene-changed.
  • A finalize completes only the capture armed before it started. A retry's or a second file's capture survives an older finalize that is still running.
  • Arming happens at the viewport's first streaming sync of the load, before any piece is queued, instead of racing a renderer poll. A non-streaming first sync (renderer started after the stream ended, #7032) records not-armed:not-streamed. A load that fails before or after its geometry arrives releases the capture (load-failed).
  • Reason codes. Every eligible cold load ends with exactly one cache.writeSceneSnapshot span. It is either the write with its outcome, or not-armed / not-captured with a reason.
  • The writer is loaded lazily, by dynamic import after the load is interactive.

Deliberate behaviour change on main's existing reopen snapshot

SNAPSHOT_CAPTURE_MAX_BYTES (64 MiB of merged flat geometry) applies to both captures: the cold one and the existing cache-hit one. Above it no snapshot is kept (not-captured:over-cap), and reopens stream the hit as before. No corpus model is affected: the largest capture measured is BWK at 31.8 MB, from a 327 MB file.

Cost before interactive (timed A/B aa4adfdb, cold, n=5 per side)

  • scene.finalize.capture at the swap: Holter 8.9 ms [8.5–9.1], BWK 7.0 ms [6.7–7.6].
  • Per-piece recording while streaming (stream.queue, where notePiece runs), main → branch: Holter 5.1 → 7.8 ms, BWK 2.3 → 5.3 ms.
  • About 10–12 ms in total, roughly 0.2% of cold interactive.
  • Cold peak memory, memory pass, median [range] MiB:
    • Holter: 3,748 [3,739–3,870] → 3,958 [3,745–4,029]. That is +210 MiB at the median, flagged not significant against the 8.1% floor, with overlapping ranges, but larger than the 29 MB capture, so the confirmation A/B re-measures it.
    • BWK: 5,093 → 5,077.
    • First-reopen peaks fall: Holter −28%, BWK −22%.

Output identity of the reopen lanes

The scoreboard marks cached reopens UNVERIFIABLE for instanced output (#9740), so identity comes from a direct real-GPU check:

  • Draws and GPU bytes: on ISSUE_129, advanced_model, Holter and BWK, every cold, first-reopen and second-reopen open has the same instanced draws, instanced GPU bytes, draw calls and batches drawn. On the branch the reopen's flat GPU batch bytes equal the cold load's exactly.
  • Pixels: the reopen equals the cold frame with 0 differing pixels on ISSUE_129, advanced_model and BWK. Holter reaches 0 once the asynchronous IfcGrid overlay has settled; that overlay lands after "interactive" on every load kind, cold included, and on main too.
  • e2e spec: compares per-element mesh bytes and instanced output on two cached fixtures.

Separate pre-existing findings (not changed here)

  • The cache entry is serialized from the live meshes after finalizeModel (main useIfcLoader.ts:1936, then writeCache(allMeshes) at :1953). placeMesh shares positions (model-translation.ts:122), and translateFlatMeshesForEntity edits them in place (scene.ts:1574). So a move, edit card or exploded display before serialization is written into the entry.
  • A recolour while pieces are still queued misses them. The store's updateMeshColors replaces recoloured meshes with new objects (dataSlice.ts:298). The scene's updateMeshColors only walks pieces already in meshDataMap (scene.ts:2370–2374). A piece still in the stream queue (queueMeshes, scene.ts:1859–1862) therefore keeps the old colour without dirtying anything; a snapshot would preserve that. It never fired on the seven fixtures (30/30 cached first reopens adopted, no not-exact skip); the worker pool emits no colour updates during streaming.

Why

Only a streamed cache hit captured the scene snapshot. The first reopen after a cold load therefore always streamed the hit, rebuilt every batch in finalize and then wrote the snapshot; only the second reopen drew from it.

What changes

  • The cold path arms the same finalize capture (armColdSceneCapture) for a primary load whose cache plan writes an entry. Nothing on the load's path awaits it. If no renderer exists yet, it arms when one appears, but only on an empty scene.

  • The capture is frozen at the swap. It holds the merged arrays finalize uploaded, which no batch keeps (batches keep only GPU buffers). Later edits, recolours, section planes or federated adds cannot change the stored bytes, and nothing is cloned. A scene changed before the swap is refused by the capture's existing checks: pristine scene, batch id and piece count, level offsets, and the type-visibility key read at the swap.

  • Ordering. Hydration matches pieces by ordinal. A cold load queues meshes in arrival order, but the cache writer stores them in spatial chunks, and a reopen decodes them in that order. Without remapping, every cold-written snapshot was refused on reopen and then cleared; the untimed GPU check caught this.

    • captureNextFinalize now also reports the mesh each piece was queued from.
    • CacheWriteOptions.onGeometryOrder reports the stored mesh order.
    • reorderSnapshotPieces moves the ordinals to that order at write time.
    • If a queued mesh is missing from the entry, the write is skipped (order-mismatch).
  • The snapshot attaches to exactly one write. setCached resolves the identity of the write it committed ({ createdAt, fullSourceHash }, or null when skipped). The snapshot is compare-and-set onto that write through the existing putSceneSnapshot, which also guards quota headroom.

  • Deferred, sliced, cancellable write (sceneSnapshotWrite.ts):

    • It starts only after the store reports the load interactive (not loading, not streaming), followed by an idle period.
    • It copies the bytes in 4 MiB Blob slices with an idle gap between them. encodeSceneSnapshotInSlices produces the same bytes as encodeSceneSnapshot.
    • It is dropped when another file opens.
    • A hidden tab does not wait for idle.
    • It skips a capture whose batch policy the scene has since left (policy-changed, e.g. quantization enabled late).
    • The hit path uses the same writer instead of encoding inside the settle window.
  • Tracing: every eligible cold load (and every snapshot-less hit) ends with exactly one cache.writeSceneSnapshot span, whose outcome attribute (and, where shown, reason) is one of:

    • the deferred write: written, refused (entry replaced or purged, or quota short), abandoned (reason superseded, load-failed or entry-timeout), no-entry, policy-changed, order-mismatch, scene-changed (reason scene-changed or level-offsets), failed (encode or store threw; reason writer-load if the lazy writer chunk failed to load);
    • a zero-length record when no write starts: not-armed (reason snapshots-off, level-offsets, superseded, no-geometry, not-streamed, load-failed) or not-captured (reason cleared, ephemeral, replaced, not-exact, failed, superseded, load-failed, over-cap, no-scene-bounds, no-fit-bounds, level-offsets).

    The scoreboard already waits for open cache.write* spans before a reopen. scene.finalize.capture times the capture's work at the swap (attrs captured, outcome).

This avoids what sank #9622: there is no timer standing in for readiness, no unchunked encode, no deep clone, and the write is cancelled when a new file opens.

Correctness evidence

  • Untimed real-GPU check (Pop, ifc-gpu-check; ISSUE_129, advanced_model, Holter, BWK; main vs branch):
    • The cold load writes the snapshot.
    • The first reopen adopts it with no scene.finalize.
    • The snapshot's SHA-256 is unchanged after the first and second reopens, so hydration accepted it rather than clearing it.
    • The second reopen adopts it again.
    • Flat output (mesh count, triangles, signature) is identical to the cold load on every open, on both sides.
    • A cold-written snapshot is not byte-identical to one written by a first reopen on main, because the merge order differs. Equivalence is shown by per-element output identity (scoreboard) and by accepted hydration.
  • Unit tests:
    • cache geometry-chunks.test.ts: the reported order equals the decode order and differs from the input.
    • renderer scene-snapshot-lifecycle.test.ts: refused without the remap, hydrated with it.
    • renderer scene-snapshot.test.ts: the sliced encode gives identical bytes.
    • viewer sceneSnapshotWrite.test.ts (9): waits for interactive; abandoned on supersession; no entry; hidden tab; policy changed; order remap and mismatch; the cold arm writes onto its own entry; a late renderer with queued pieces is not armed.
    • viewer ifc-cache.test.ts: the identity of the committed write.
  • e2e: cold-load-scene-snapshot.e2e.spec.ts (viewer-e2e and viewer-e2e-ci). A cold load of C20-Institute (10.3 MiB, cached tier) ends with cache.writeSceneSnapshot = written and a snapshot on the entry. The first reopen has scene.snapshotAdopted, no scene.finalize, and the same mesh count. Every value read back is a count or a name.

Still running (head 89611a3c45)

  • Full four-shard viewer suite plus the renderer and cache suites, by fleet receipt.
  • Real-GPU e2e set and identity check on this head.
  • Exclusive confirmation A/B (Holter, BWK, ISSUE_129, FZK; cold and first reopen; 5 rounds plus memory) with the #9740 harness from main.
  • Entry/eager bundle re-measure against the merge base.

No perf-sensitive Rust path is touched.

Merge-queue failure (run 43080434246) — cause and fix (3c545ce91c, test only)

The e2e spec failed on C20 under CI's SwiftShader GPU (instanced.drawn 0 vs 22, same GPU bytes). I reproduced it on the queue's own tree and build (CI's viewer-dist, 4-core quota, viewer-e2e-ci flags) and traced it per frame in 172 instrumented runs. The viewer's output was complete in every run. The test read it at the wrong moment, for two reasons:

  • Stale frame stats: frame stats describe the last rendered frame. Adoption uploads every batch and template at once. On a software GPU the frame pacer (#5865) then holds the next frame while three submitted frames are still owed, and Chrome stops issuing frames while the GPU process is busy. In 34 of 63 adopted reopens, the frame on record at "interactive" was the one rendered before adoption. The render request stays pending and is drawn without input as soon as the queue drains (0.05–2.5 s). Renderer and scene identity, and batch and template counts, were checked per frame.
  • Cold capture refused: quantized-batch admission starts with the viewport, i.e. with the first file. On SwiftShader it finished after the cold load's finalize in 109 of 172 runs, so the writer correctly refused the capture (policy-changed).

The spec now:

  • reads output from a frame rendered after the load ended;
  • opens the uncached FZK fixture on the cold page first and waits for the viewer's [Viewport] quantized vertices line.

Result: 40/40 (C20 and ISSUE_129, 20 each) on the same build and configuration. Unfixed, C20 passed about 1 run in 6 there.

This is not caused by W2: the adoption path is the same one main's second reopen already uses. W2 makes the first reopen take it. On a software GPU, a snapshot reopen keeps showing the previous frame until the GPU queue drains, then draws the model without user input.

🤖 Generated with Claude Code