perf(viewer): deliver instanced shards outside the store while streaming
What
While geometry streams, each batch's GPU-instancing (IFNS) shards went through the viewer store. The loader appended them to pendingInstancedShards, the Viewport's drain effect uploaded them, then cleared the field. That was two store writes per batch. Each write ran the whole subscriber fan-out and re-rendered the Viewport, which selected the field.
Raw store log from a Holter (177 MB) cold load, before this change: 462 store updates, 264 of them this hop (132 appends + 132 clears, about 3.5 ms apart). An untimed attribution of the same load put the fan-out at ~560 ms and Viewport re-renders at ~530 ms of main thread. In that load the workers are done by ~2.5 s, and the main thread is the critical path.
Design
store/instancedShardQueue.tsis a module queue outside React. Its producers are the streaming loader (primary, per batch), the federated finalize (once the id offset is known, #1912), the cache hit and the snapshot fallback.components/viewer/useInstancedShardDrain.tsis the renderer's single consumer. It subscribes to the queue and drains in a task of its own, scheduled on the first enqueue since the last drain. By then React has committed any store write from the same task, so a federated model'smodelIdToIndex/modelIdToOffsetentries are present, exactly as when the drain was an effect. Shards enqueued before the renderer exists, or while the device is lost, stay queued until init or agpuRecoveryEpochbump.- Shards belong to the model that produced them (review A1).
removeModelwithdraws that model's queued shards, andclearAllModels/resetViewerStatewithdraw all of them.- A shard whose owner is missing from the drain's maps waits only while the store still lists that model. Otherwise it is dropped and counted (
viewer.instancedShardsDropped.ownerless), and never uploaded under model 0. - Every producer passes the queue generation it captured when its load began. A full discard bumps the generation, so a superseded load's late shards are refused on arrival (
…superseded) and cannot sit in the queue holding their buffers.
- The drain is exception-safe: the consumer settles each shard as
uploaded,droppedorwaiting. On a throw, unsettled shards go back to the front in order, and nothing is uploaded twice. Retries back off at most 3 times. - e2e observation point: the queue is not store state, so it publishes
subscribeInstancedShardsasglobalThis.__ifc_lite_instanced_shards__, as the store publishes itself. Theenqueuedevent carries the shards it added.retained-viewer.e2e.spec.tsuses it. - Placement indexing (
lib/model-placement/spatial-index.ts) read the store field for readiness and invalidation. It now asks the queue (hasPendingInstancedShards) and hears enqueue/drain events throughuseModelPlacementSync. - Federated loads published
setProgressper batch. They now publish at the flat-render throttle's cadence, as primary loads already did. - Unchanged: decode, federation re-homing, level lift, per-shard failure containment, the retained instance-only camera fit.
The hasInstancedShards registry readers (assistant clash availability, empty-result notice, RTC rebase) are still correct. Every enqueue site is followed by a store write: completion and setLoading for streaming, setIfcDataStore for a cache hit. A snapshot's shards are registered at adoption.
Evidence
Timed verdict (exclusive Pop slot, job 9b5655a2): base main@d45ace6b65 vs main + this PR + #9629 (feb241bc59), the pair as one arm. 7 fixtures × 4 lanes × 5 rounds plus a memory pass, harness main f991ffc52a. A gain must exceed 2× the A/A noise floor.
| Holter lane | interactive, base → pair | 2× floor | verdict |
|---|---|---|---|
| cold | 5,527 → 4,745 ms (+14.1%) | 6.6% | gain |
| first reopen | 3,631 → 3,352 ms (+7.7%) | 4.9% | gain |
| snapshot reopen | 2,405 → 2,159 ms (+10.2%) | 6.6% | gain |
- advanced_model first reopen: +5.2% (floor 4.0%), a gain.
- FZK is not significant on any lane.
- No regression on any fixture or lane, and native-cold, the control, shows no difference.
- Cold output: per-element identical on all 7 fixtures.
Untimed diagnostics:
- Reopen output identity (older harness that hashes reopens): identical, base vs pair, on Holter, advanced_model and BWK.
- Real-GPU reopen check (base vs pair, Holter / advanced_model / BWK, with and without the scene snapshot):
instancedDrawnon every reopen equals cold on both sides: 742 / 160 / 1,243.- Flat identity holds everywhere, and reopen-vs-cold pixel deltas equal base's.
- The frame is captured after the drain settles, with no input.
- Memory attribution (Holter, n=3): snapshot-reopen peak base 2,106 → this PR 2,075 MiB. This PR adds no memory.
- Store traffic:
useIfcLoader.streamingStoreTraffic.test.tsxstreams 48 batches through the real loader into the Viewport's wiring. main: 109 store notifications and 99 renders, so the test fails. This PR: 7 and 5, with all 48 shards uploaded once, in order.
Hidden tab. The drain is a setTimeout(0) task. Chrome aligns a hidden page's timers to 1 s wake-ups. Its intensive 1-minute throttling needs a timer chain nested 5 deep, and the drain's chain is at most 4 (one timer plus three retries), started from worker-message tasks.
- Worst case: the upload lands about 1 s after the last enqueue, and the frame is drawn when the tab becomes visible, as before.
useInstancedShardDrain.lifecycle.test.tsxthrottles timers to 1 s. Nothing drains early, readiness reports the shards pending, and one wake-up uploads every shard once, in order, under its own model.
Real-GPU reopen after #9728 (main d0be5a6e95 vs main + #9628 + #9629, Holter and BWK, untimed). The cold load writes the scene snapshot, and both reopens adopt it with no re-finalize, on both sides.
- Holter: instanced draws 742 and instanced GPU bytes 8,100,540 on cold, first reopen and second reopen, on both sides. Reopen-vs-cold pixel difference is 21.40% on both sides, so the gap is the same on main; the reopen frame differs from the cold one there too.
- BWK: instanced draws 1,243 and 5,403,304 instanced GPU bytes on every load; reopen-vs-cold pixel difference is 0% on both sides.
- Flat per-element identity holds everywhere, including cold main vs pair.
- Main vs pair, the frames differ in 2.6% (Holter) and 4.6% (BWK) of pixels. That is sub-visual, with draw counts unchanged, and the pre-#9728 run showed the same 4.3%. On BWK the pair also uses 647 KB (2.1%) less batch buffer, consistent with batches grouped differently by flush timing rather than different content.
Untypechecked consumers. I grepped for pendingInstancedShards / appendInstancedShards / clearInstancedShards in:
- all 82 e2e specs,
tests/(542 files),scripts/includingperfandperf-ratchet(1,017),examples/(161) anddocs/(196); .github, the other apps and packages, and*.md/*.mjs/*.js.
The only reader was retained-viewer.e2e.spec.ts, now ported. The other hits are CHANGELOG history and geometry.worker.ts's own unrelated private field.
Size (pair, production build vs current main): fits. The CI perf ratchet measures each PR merged with main:
- this PR on main a166ae0372 (after #9728): entry 2,170,941 B, eager 17,758,355 B;
- #9629 on main edb8173bdf: entry 2,170,423 B, eager 17,752,774 B.
- With the other PR's measured delta added (#9628 +900 B entry, +1,780 B eager; #9629 +541 B, +719 B), the pair is about 2,171.5 KB entry against an allowance of 2,184,108 B (about 12.6 KB spare) and about 17,759.1 KB eager against 17,762,882 B (about 3.8 KB spare).
- It no longer waits for #9742.
Tests
- New tests:
store/instancedShardQueue.test.ts: exception safety, generation, and the e2e tap.useInstancedShardDrain.lifecycle.test.tsx: removal, clear, survivor, lagging maps, ownerless drop, superseded refusal, throw after upload, hidden tab.useIfcLoader.supersededShards.test.tsx.useIfcCache.staleness.test.tsx: a full clear during a live cache hit.LocationMap.deferred.test.tsx.
- Ported: every test that drove shards through the old store field, and the five
retained-viewere2e tests.ci:native-adapteris set soviewer-retainedruns. - After #9728 landed, this PR conflicted on one import line in
sceneSnapshotLoad.ts; I merged main (abd5fb5ae5) and kept both imports. #9728 adds no instanced-shard producer. Rerun on the merge: viewertscclean; the shard tests plus #9728's snapshot and cache tests, 28 files, 185/185; renderer snapshot tests 20/20; cache 248/248. - Locally: viewer
tscpasses after merging main edb8173bdf, the shard/streaming/placement set is 124/124, and the module-size, test-glob, i18n, entry-guard and changeset guards pass. - Full 4-shard viewer suite on this head: green on abd5fb5ae5 (Pop, Chrome toolchain): 4/4 shards, 22,874 tests, 0 failed. CI is green, and
viewer-retained(geometry-platformnative-adapter) passes 25 tests, including all five ported ones; its 2 skips are inretained-setting.e2e.spec.ts, which this PR does not touch.
Self-driven work from a load-time hillclimb (lever NEW-1), so no issue.
🤖 Generated with Claude Code
Summary by CodeRabbit
- Improvements
- Instanced geometry shards are now processed through a dedicated queue, helping prevent duplicate uploads and discard outdated data when models are replaced or removed.
- Shards remain queued when the graphics device is unavailable and can be processed after recovery.
- Tests
- Expanded coverage for shard delivery, recovery, model cleanup, and streaming behavior.