perf(renderer): assemble streamed final batches from their fragments
What
A cold streamed load drew every flat mesh twice: once as a throwaway streaming fragment, then again when finalizeStreaming rebuilt each streamed bucket from its meshes. The rebuild re-did merge, lattice-collapse check (#9068), quantize, the f32 topology check and the vertex upload, then LOD1. Those meshes had already gone through all of that as fragments of the same bucket, in the same order and the same frame.
The baseline report (stage0, main@004934fa88) names geometry finalization on the main thread as the bound on browser-cold and first-reopen for every fixture except FZK. scene.finalize takes 0.4–1.6 s wall, stream.queueDrain 0.3–2.3 s.
This PR builds each streamed bucket's final batch from those fragments:
- GPU assembly (
scene-stream-assembly.ts). A streamed bucket qualifies when its meshes are exactly the concatenation of live fragments: whole meshes, same order, the frame the rebuild would pick, one encoding. Its vertex buffer is then acopyBufferToBufferof the fragments' buffers. Only the indices are rebased on the CPU. LOD1 is built from a positions-and-entity gather, which usesmergeGeometry's arithmetic and is the only part of the record LOD reads. - One lattice origin per streamed bucket (
LatticeFrameinquantize.ts). Fragments quantize against a shared, lattice-aligned origin, centred in the u16 range on the first fragment.quantMin + q·stepis exact on the 2^-10 lattice (main.wgsl.ts:146), so decoded positions are unchanged. - Fragments draw in the model's shared frame once it exists. That is the frame the finalize rebuild uses; before this, first-append buckets drew in their own first mesh's centre and were re-merged in the shared frame anyway.
- Stream-lifetime topology memo. Each streamed mesh was scanned four times per load: append validation plus routing (#8241), the fragment's upload, the finalize regroup and the final batch. It is now scanned about once per (mesh, frame), with a memo that no longer allocates string keys. The memo is dropped at the swap, by in-place position edits, and on clear.
- Regroup keeps intact buckets. A streamed bucket that re-routing would rebuild exactly as it stands is kept, re-inserted at the map position re-routing would give it, so the draw order is unchanged. "Exactly as it stands" means unsplit, every mesh still keyed to it, no moved mesh joins it, and the same fresh frame.
- Fallback. Any bucket that cannot be proven identical takes today's full rebuild: f32 fragments, a lattice origin that didn't fit, a mesh re-keyed while streaming, split pieces, the fragment budget, or a fragment drawn before a scene-snapshot capture was armed. Load-trace counters
render.finalize.assembled.*,render.finalize.rebuilt.{uncovered,f32,lattice,frame,capture}andgpu.assembleCopy.*report which path each bucket took.
Scope of the identity claim. Meshes handed to the scene are owned by it. In-place geometry edits go through Scene's own APIs: the model translation and the rotation paths (scene.ts) call streamWork.invalidate(), so no fragment's bytes are reused after them. A caller writing raw values into a registered mesh's positions/normals arrays between upload and finalize is outside that contract; no production caller does so (the only in-place writes, in the roof and stair/railing ghosts, fill fresh meshes before they reach the scene). On main such a write was not honoured either: the fragment drawn while streaming kept the uploaded values.
Progressive display is unchanged: every fragment still uploads and draws while streaming. The #5555 dead end (skipping later fragment uploads) is not repeated. The renderer-only change does not touch #9628's streaming/shard code.
scene.ts ends below its allowlisted budget (4104 → 4065). The pure same-colour piece merge moved verbatim to scene-mesh-pieces.ts.
Scoreboard (deterministic, in CI)
scene-finalize-work.test.ts streams a multi-cell, multi-colour, georeferenced scene through the real Scene, with a recording GPU stub, then runs the time-sliced finalize.
| finalize work | main | this PR |
|---|---|---|
| vertex bytes written to the GPU by finalize | 1,036,800 | 0 (all GPU copies) |
mergeGeometry vertices in finalize | all | 0 |
f32 topology scans, whole load (Math.fround calls) | 4,352,832 | 1,432,512 |
Of its 6 tests, 4 fail on main and all 6 pass with this PR. The two that pass on main are identity checks, and they must pass there:
- One compares every decoded final batch against the full rebuild, forced through a snapshot capture: key, ids, models, frame, bounds, indices, LOD1, and exact decoded positions, normals and lanes.
- The other covers positions edited in place mid-stream.
Two tests cover stale fragments: a same-key recolour that changes the entity-lane salt, and an in-place translate. Each failed against this PR's first head, which assembled from the stale bytes; the fix is commit 1b02d369d1.
Real fixtures: deterministic replay
The real meshes of each fixture were dumped from a cold load of the real viewer. They were replayed through the real Scene with the viewer's settings (32 m chunks, LOD on, quantized, residency budgets), streamed in arrivals of 250 meshes, then finalizeStreamingAsync. The GPU was stubbed, so these numbers are pure main-thread CPU.
| fixture | finalize vertex re-upload, main → PR | finalize topology scans | final batches identical (decoded hash) |
|---|---|---|---|
| FZK | 1.18 → 0.86 MB | 0.6 M → 0 | ✅ 5d7ceeacef95f26f |
| advanced_model | 19.1 → 11.5 MB | 11.3 M → 0 | ✅ 696c6d3fda6393d7 |
| skolebygg | 21.5 → 3.7 MB | 16.3 M → 0 | ✅ e1dab1b14eeb0ab7 |
| Holter | 18.8 → 0.6 MB | 13.6 M → 0 | ✅ 3a7541beab6d60c2 |
| BWK | 29.3 → 7.7 MB | 26.4 M → 0 | ✅ 5e1bf6a7654272e3 |
Assembled batches: Holter 273 of 290, advanced_model 105 of 113, FZK 25 of 27. The rest are f32 or lattice fallbacks.
Finalize CPU in the replay, median of 3–5 interleaved runs on a loaded host (untimed diagnostic, not benchmark evidence): Holter 624 → 325 ms, BWK 917 → 518, skolebygg 717 → 361, advanced_model 294 → 219. The streaming phase is unchanged within noise.
Browser evidence
All runs below are untimed. Builds were made on Pop: main@5790205e37 against 7d19184ff8, which is main + this PR (1b02d369d1) + #9685. #9685, a typed LOD cell table, was later withdrawn: isolated LOD1 runs on the same fixtures showed no change, so everything measured here belongs to this PR. The WASM (7bc42a9b…) and perf_probe are byte-identical on both sides.
Per-element output identity. The scoreboard harness from #9607 (e81af4d905) ran with kind compare, fingerprinting flat and instanced geometry. All 21 of 21 base/branch cells are identical: 7 fixtures (FZK, ISSUE_129, advanced_model, schependomlaan, Holter, skolebygg, BWK) × cold, first reopen and snapshot reopen.
- Every cached reopen hit the IndexedDB cache.
- Every snapshot reopen adopted the scene snapshot. FZK is uncached by policy.
- 0 page errors; GPU health clean.
Real-Chrome work counters, one cold load per build:
| Holter main → PR | BWK main → PR | skolebygg main → PR | |
|---|---|---|---|
render.mergeGeometry.vertices | 3.07 M → 1.58 M | 3.06 M → 1.73 M | 3.36 M → 2.68 M |
gpu.staticUpload.bytes | 62.4 → 44.5 MB | 65.9 → 50.0 MB | 70.6 → 60.8 MB |
| buckets assembled / rebuilt | 260 / 17 | 221 / 7 | 308 / 118 |
scene.finalize wall (single run, not a timing claim) | 767 → 374 ms | 2,143 → 1,798 | 757 → 654 |
skolebygg's rebuilt buckets are mostly f32 (105). Their fragments failed the #9068 lattice-collapse check (thin members), so those buckets take the old path unchanged.
Pixels. Each fixture loaded cold in main, then the PR, then main again; the colour frame was captured 6 s after interactive.
| fixture | main vs main (px) | main #1 vs PR (px) | main #2 vs PR (px) |
|---|---|---|---|
| FZK | 0 | 0 | 0 |
| ISSUE_129 | 0 | 0 | 0 |
| advanced_model | 2,402 | 2,348 | 66 |
| schependomlaan | 8,306 | 10,446 | 7,436 |
| Holter | 5,908 | 5,903 | 12 |
| skolebygg | 51 | 6 | 49 |
| BWK | 11,850 | 14,286 | 8,595 |
The settled frame is not deterministic even within main. The PR's frame always falls inside main's own run-to-run spread, and on Holter and advanced_model it is closer to one main run than the two main runs are to each other.
GPU e2e (Pop NVIDIA, viewer-e2e project). These 17 specs ran: rte-gpu-witness, federation-control-triplet, visibility-chips, visibility-empty-result, visibility-scenarios, section-extra-planes, section-measure-lasting-5893, selection-mask-depth, selective-clipping, edge-line-continuity, ortho-depth-nudge, projection-depth, perspective-distance-depth, model-reposition, viewer-smoke, hierarchy-row-selection, entity-context-menu.
- Main: 41 passed, 1 skipped, 1 failed. PR: the same 41 / 1 / 1.
- The failure is identical on both:
ortho-depth-nudge#6729, "row Infinity, predicted 113.2". It is a local-environment failure that main shares.
Firefox (Playwright Firefox, WebGPU on): FZK and advanced_model load to complete on both builds, with the same mesh counts (317 and 6,323) and no page errors.
Timed verdict (exclusive A/B)
Benchmark job 1968786f on Pop: exclusive admission, Balanced profile at 5.3 GHz, NVIDIA adapter, harness #9607.
- Base:
main@5790205e37. Branch: main + this PR (1b02d369d1) + #9685. #9685 measured no LOD change in isolation (Holter 86 vs 81 ms, BWK 172 vs 176) and was closed, so the gains below are this PR's. - 7 fixtures × 4 lanes × 5 interleaved rounds, plus a memory pass.
- Verdict rule: gain ≥ 2× the noise floor, where the floor is the larger of the stage-0 A/A floor and this run's own.
| fixture | lane | main | this | gain | 2× floor | verdict |
|---|---|---|---|---|---|---|
| Holter | browser-cold interactive | 6,029 ms | 5,622 ms | +6.8% | 6.3% | PASS gain |
| BWK | browser-cold interactive | 4,565 ms | 4,172 ms | +8.6% | 7.9% | PASS gain |
| skolebygg | browser-cold interactive | 3,812 | 3,632 | +4.7% | 8.1% | no significant difference |
| advanced_model | browser-cold interactive | 2,109 | 2,147 | −1.8% | 9.5% | no significant difference |
| every other fixture × lane × metric | no significant difference |
- No regression in any lane or metric: interactive, first geometry, UI quiet, peak memory. skolebygg's first-reopen peak memory is also lower: −6.8%, PASS.
- Output identical in every sample (element hashes, flat + instanced).
scene.finalizemedian, browser-cold, main → this: Holter 651 → 433 ms, BWK 1,584 → 1,239, skolebygg 625 → 444, advanced_model 468 → 397.- First reopen (warm1) does not move, as expected. A cache hit caps fragments at first paint, so its buckets have little to assemble from. That lane's lever is W2: capture the snapshot at the end of the cold load.
- UI quiet stays bound by the post-stream drain. That is fragment building for the backlog, which this PR does not remove.
Report: ~/.t3/scratch/2026-11-10-ifc-load-hillclimb/cold-finalize/runs/ab-timed/report.md. Log: cold-finalize-LOG.md.
Re-confirmation on current main (with #9728's cold capture armed)
Benchmark job 63c161c9 on Pop (exclusive admission, Balanced, 2026-11-12 04:14–04:21 UTC). Base main@12fd328582 (#9728, #9628, #9629), branch main + this PR (3fb357d873); Holter + BWK, browser-cold + first reopen, 5 interleaved rounds; same verdict rule.
| fixture | lane | main | this | gain | 2× floor | verdict |
|---|---|---|---|---|---|---|
| BWK | browser-cold interactive | 3,861 ms | 3,678 ms | +4.7% | 3.6% | PASS gain |
| Holter | browser-cold interactive | 4,554 ms | 4,314 ms | +5.3% | 6.3% | no significant difference |
| Holter | first reopen interactive | 1,804 | 1,797 | +0.4% | 5.6% | no significant difference |
| BWK | first reopen interactive | 1,558 | 1,549 | +0.6% | 4.9% | no significant difference |
- On current main the cold gain is significant on BWK and not significant on Holter (+5.3% against a 6.3% bar); the earlier PASS on Holter was on
main@5790205e37, before #9628/#9629 removed other main-thread work from the same window. - No regression in any cell (interactive, first geometry, UI quiet). Cold output identical in all 10 samples per fixture. First-reopen samples carry no element hashes in this harness (unverifiable there, as on main).
- Report:
~/.t3/scratch/2026-11-10-ifc-load-hillclimb/cold-finalize/l1/runs/s4-9684/report.md.
Review fixes after the A/B (92f37d04ed)
- Ephemeral (huge-file) streams no longer keep the stream-long topology memo, which held every mesh's arrays until the stream ended (CodeRabbit). A new test fails against the previous head and passes now.
- The scoreboard test's failure paths are bounded.
- The memo check asserts a boolean. A failing
assert.equal(memo, null)makes Node render the whole memo, every mesh array included: ~2 GiB in 2 s under a cgroup cap. - Identity compares one batch at a time with a short message.
- Flush loops fail after 64 flushes without progress.
- Against the old code the test now fails in 3.5 s at 240 MB.
- The memo check asserts a boolean. A failing
- Changeset bumped to
minor. The publicquantizeInterleavedandsimplifyIndicesByClusteringgain optional parameters. - These touch only the ephemeral path and tests. The A/B build (
1b02d369d1) differs from this head only in them, plus the test-stub fixc63d6149dc.
Adversarial review fixes (bcd51948b9)
- Device recovery left fragment records holding released CPU geometry (FZK: 38 records, 1.79 MB after
releaseGeometryData).discardGpuResourcesForRecoveryandreleaseGeometryDatanow clear the stream assembly: records, lattice pins and topology memo. Every path that drops CPU geometry also drops the records: finalize swap, rollback, ephemeral finish, release, recovery, andclear/clearFlatGeometry/clearFlatGeometryForRebuild, which covers model removal. - After a device loss, final batches, assembled or not, are ordinary bucket batches. Recovery destroys them and rebuilds them from the buckets' CPU meshes. Assembly declines outside a finalize. A finalize that follows a loss mid-stream has no live old-device fragments, so it rebuilds those buckets from CPU and assembles only from fragments drawn since.
- New tests cover records and retained bytes being 0 in four situations: after recovery; after the finalize that follows two losses mid-stream; after release; after a reset. The recovered scene's batches equal the full rebuild's. Both tests failed on the previous head (
20 records, 944,640 bytes) and pass now. - The reviewer's NVIDIA readback compared assembled and rebuilt GPU buffers byte for byte: 1,086 final batches over Holter, BWK, skolebygg and a georeferenced FZK, with LOD1 included, plus a 70,002-vertex batch. 0 mismatches.
Re-check on the final head. The replay of the real mesh streams through bcd51948b9 gives the same decoded-batch identity hashes as main on FZK, advanced_model, skolebygg, Holter and BWK. The work counts are unchanged from the A/B head: Holter assembles 273 of 290 buckets with 0.6 MB vertex rewrite against 18.8 MB, and 0 topology scans in finalize.
These fixes are off the hot path: a recovery-time clear, plus an ephemeral-only condition. So the timed A/B stands.
Folded in from #9759 (a13f096046, e5dc367866, b8e9b68ccd)
A scene-snapshot capture keeps the assembly. createBatchedMesh used to skip the assembly whenever a capture was armed, because only the CPU rebuild produced the bytes the capture stores. #9728 arms that capture on every primary cold load, so main + #9684 + #9728 would have rebuilt every cold bucket and lost this PR's gain.
- Now, while a capture is armed, each fragment keeps the vertex bytes it uploaded.
assemble()hands the capture those bytes, concatenated in copy order, plus the rebased indices and LOD1 indices, under the same batch id it publishes.- A fragment drawn before the capture was armed rebuilds its bucket, counted as
render.finalize.rebuilt.capture. - Test: with a capture armed, every bucket is assembled (0 finalize vertex writes), and the snapshot's vertex, index and LOD1 bytes equal the GPU buffers. It fails on
e8a832fcd8. - This also applies on main without #9728: the first reopen of a cached model arms a capture too. That path draws fragments only up to its first-paint budget, so only buckets covered by those fragments assemble; the rest rebuild exactly as on main.
Review fixes in #9684's own code (CodeRabbit on #9759):
- Each finalize now retires its own fragment set. Before, a synchronous finalize run during a pending async one replaced the pending set, and its records stayed alive. Test: 89 records / 1,416,960 bytes retained before the fix.
- A failed async finalize now keeps the bytes of a mesh that joined a kept bucket meanwhile. Test: 84 bytes counted for 168 held before the fix.
The lifecycle test stub now tracks buffer contents through GPU copies.
Renderer suite on b8e9b68ccd (same code as the final head, which only merges the changesets): Node 22.23.2 and 24.22.0, 2,723 pass, 0 fail.
Tests on the final head (49f1e37595, main 52c82a099d merged)
Per SLOT-RULES, no local four-shard viewer suite while fleet capacity is short; the merge queue runs the full viewer, Node and Rust suites. Run here instead:
- Viewer, 59 files (fleet job
56ff9fba, PC, source commit49f1e37595): 367 tests, 354 pass, 0 fail, 13 skipped. The selection is every file that drives the renderer Scene's stream/finalize/capture path (useGeometryStreaming*,sceneSnapshot*/scene-snapshot*,coldCapture,appearance-instance*,useIfcLoader*,useIfcCache*,*finalize*), plus the four viewer tests whose fake GPU devices stream into a real Scene without the copy encoder this PR's assembly now uses (measurePointMode,usePlacementMutationDrain,usePlacementCoordinateInfo,model-placement/bounds-revision.count-uploads). That second group is the same class of failure #9747's full suite found. Skipped is not passed: the 13 are conditional skips, either thereal-ifccases gated on the C20 fixture (the PC fleet checkout has no fetched fixtures) or harness-gated cases. The fleet script keeps no per-test log. The full suite on3fb357d873ran with fixtures on Pop (below), and the merge queue covers them on this head. - Renderer: sources byte-identical to
3fb357d873and8a414d2967(no renderer/geometry/load-trace change from main since). Full renderer suite on this head (fleet jobe049dbd0, PC, clean checkout of49f1e37595): 2,731 tests, 2,729 pass, 0 fail, 2 skipped (also 2,729/0 on Node 22.23.2 and 24.22.0 at3fb357d873). sceneSnapshotLoad.coldCapture.test.ts10/10 and renderer tsc on this head.
Earlier full viewer suites
| head | result |
|---|---|
2986b7397d | 9 test-stub failures, fixed in c63d6149dc |
3fb357d873 | shards 0/2/3 green; shard 1: 7 failures, all in #9728's sceneSnapshotLoad.coldCapture.test.ts (stub device without createCommandEncoder/queue.submit), fixed in c5fdb382d0 |
8a414d2967 | PC job db374804: shard 0/4 green (5,825 tests, 0 fail), then the job died in the 11:17 PC restart (no outcome for shards 1–3) |
Landing: CI green on 49f1e37595 (and on 8a414d2967 with the eager-JS ratchet passing: 17,539,748 B against 17,761,137, after #9772 and #9742).
The perf ledger entry goes to #9673, not this PR.
🤖 Generated with Claude Code
Summary by CodeRabbit
- Performance
- Scene finalization can reuse compatible streamed geometry, reducing repeated processing while preserving the existing rebuild path when data cannot be safely reused.
- Color changes retain unaffected geometry where possible; changed or moved geometry is refreshed.
- Mesh simplification and position quantization support configurable alignment options, while existing defaults remain unchanged.
- Snapshot capture continues to reflect the assembled geometry, including data copied during finalization.