From ec92f44dbe34e00e0b57aa5eacc7b78fbfbe9ee4 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger Date: Tue, 4 Aug 2026 16:38:37 -0500 Subject: [PATCH 1/4] Make National playback motion-first Owner retest showed the playing path still failed after PR #20: a camera change paused the loop for a full 20-frame viewport re-preparation, a second pan surfaced RadarSourceSupersededError as the could-not-change-scans notice, the play session held the exclusive resident-only reservation so backfill and polling starved forever, and home-view playback pruned the complete-domain refined presentation. Motion now starts immediately at the always-resident factor-4 commons and is never stopped by sharpness or a camera change. Quality preparation runs beside the loop as prefetch-only residency work: the relaxed commitPrefetchedStaging guard admits the selected observation while its common level is active, prefetch commits wait for paint quiescence, and the prepared factor upgrades the quality lock between frames with a normal receipt. A camera change drops the lock to the camera-independent commons and re-prepares in the background; supersession is filtered from every playback error surface; playback holds no reservation so backfill and strictly-newer polling continue during motion; below the sharp threshold preparation touches no residency, so the refined presentation survives home-view playback. Contract, README, current-state, and findings documents record the motion-first owner decision dated 2026-08-04. Backfill download pipelining stays deferred: the Rust history store holds a single staged frame slot. Co-Authored-By: Claude Fable 5 --- docs/11_ENGINEERING_CONTRACT.md | 2 +- docs/20_ALPHA_CURRENT_STATE.md | 4 +- .../29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md | 11 ++ docs/README.md | 2 +- src/App.tsx | 68 ++++--- src/national-radar/NationalGridLayer.ts | 30 ++- ...ationalHistoryWorkingSetController.test.ts | 5 + .../NationalHistoryWorkingSetController.ts | 11 +- .../NationalPlaybackQuality.test.ts | 47 ++--- src/national-radar/NationalPlaybackQuality.ts | 30 +-- .../NationalPlaybackController.test.ts | 88 +++++---- src/playback/NationalPlaybackController.ts | 177 ++++++++---------- 12 files changed, 268 insertions(+), 207 deletions(-) diff --git a/docs/11_ENGINEERING_CONTRACT.md b/docs/11_ENGINEERING_CONTRACT.md index d1f1e65..fe0e3b0 100644 --- a/docs/11_ENGINEERING_CONTRACT.md +++ b/docs/11_ENGINEERING_CONTRACT.md @@ -73,7 +73,7 @@ Mistr's normal UI follows `PRODUCT.md` and `DESIGN.md`; diagnostics remain hidde Merged Phase 3 owns the explicit `National`/`Site` source panel because it delivers the complete National session, numeric renderer, exact interrogation, and paint-truth path. Selecting Site reveals the existing searchable station list; supporting/accessibility copy identifies National as CONUS. Keyboard, focus-return, compact-layout, painted-truth, and one-panel behavior remain mandatory. -Merged Phase 4 exposes up to 20 exact National timeline observations. It enables playback only after two complete common-level observations are resident, uses direct scrubbing without separate previous/next controls, and names partial backfill truthfully. Regional play may perform one bounded all-frame factor-1/factor-2 preparation before motion begins; once locked, active play/scrub performs no acquisition, grid decode, bulk IPC, or upload work. Hidden `window.__MISTR_NATIONAL_PHASE2__`, `window.__MISTR_NATIONAL_PHASE3__`, and `window.__MISTR_NATIONAL_PHASE4__` evidence APIs do not become normal controls. +Merged Phase 4 exposes up to 20 exact National timeline observations. It enables playback only after two complete common-level observations are resident, uses direct scrubbing without separate previous/next controls, and names partial backfill truthfully. Playback is motion-first (owner decision, 2026-08-04): motion begins immediately at the always-resident complete common level and is never held or stopped for sharpness or a camera change. A bounded all-frame factor-1/factor-2 preparation runs beside the loop as prefetch-only residency work, upgrades the quality lock between frames when complete, and is superseded silently by a newer camera. Frame selection itself remains resident-only: no acquisition, grid decode, bulk IPC, or upload ever gates a frame advance. Backfill and strictly-newer polling continue during playback; each history commit briefly pauses and resumes the loop through the existing replacement contract, and sharp preparation defers until retained history settles. Hidden `window.__MISTR_NATIONAL_PHASE2__`, `window.__MISTR_NATIONAL_PHASE3__`, and `window.__MISTR_NATIONAL_PHASE4__` evidence APIs do not become normal controls. Required surfaces: diff --git a/docs/20_ALPHA_CURRENT_STATE.md b/docs/20_ALPHA_CURRENT_STATE.md index 2a2359d..e8c0ecb 100644 --- a/docs/20_ALPHA_CURRENT_STATE.md +++ b/docs/20_ALPHA_CURRENT_STATE.md @@ -242,7 +242,9 @@ Release readiness also corrects a demonstrated installer defect: prior bundles d ## National performance remediation (2026-08-04) -Owner-reported National symptoms — slow startup, full restaging on every pan/zoom, and repeated pixelate/sharpen cycles — were diagnosed in [National radar performance findings](29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md) and remediated on `claude/national-performance-fixes`: the selected observation now refines to a camera-independent complete-domain factor-1 presentation at any zoom, history commits preserve that detail instead of resetting to the overview, and GPU uploads share a measured 4 ms frame budget instead of one fixed 32-row band per vsync. Playback's viewport-bounded sharp preparation and its zoom-6 gate are unchanged by memory necessity. Packaged before/after startup and pan/zoom evidence remains to be captured on the validation machine. +Owner-reported National symptoms — slow startup, full restaging on every pan/zoom, and repeated pixelate/sharpen cycles — were diagnosed in [National radar performance findings](29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md) and remediated on `claude/national-performance-fixes` (merged, PR #20): the selected observation now refines to a camera-independent complete-domain factor-1 presentation at any zoom, history commits preserve that detail instead of resetting to the overview, and GPU uploads share a measured 4 ms frame budget instead of one fixed 32-row band per vsync. + +The owner's packaged retest showed the playing path still failed: camera changes stopped the loop for a full viewport re-preparation, supersession surfaced as a `could not change scans` notice, playback starved backfill, and home-view playback deleted the refined presentation. Round 2 (findings §0.1, `claude/national-playback-continuity`) makes playback motion-first as an owner decision dated 2026-08-04: motion starts immediately on the resident commons and never stops for sharpness or a camera change, quality preparation is prefetch-only beside the loop, supersession never reaches the operator, and backfill/polling continue during playback. Packaged before/after evidence remains to be captured on the validation machine. ## Pull-request checkpoint diff --git a/docs/29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md b/docs/29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md index 3d9be1c..07c15a2 100644 --- a/docs/29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md +++ b/docs/29_NATIONAL_RADAR_PERFORMANCE_FINDINGS.md @@ -15,6 +15,17 @@ Memory contract after F1: 20 factor-4 commons (61.3 MiB) + selected whole-domain factor-1 detail (46.7 MiB) + one staged replacement (46.7 MiB) ≈ **154.7 MiB** peak, inside the 200 MiB target; the 256 MiB hard-ceiling checks are unchanged and still enforced at commit time. +## 0.1 Round 2 — owner retest findings and remediation (2026-08-04) + +The owner retested the packaged build after PR #20 merged: pan/zoom **while playing** still froze the loop, a `Mistr could not change scans` notice appeared on roughly half of pans, playback blocked backfill from ever finishing, and blur-then-sharpen persisted around playback sessions. Round 1 fixed only the paused path. Verified round-2 root causes, remediated on `claude/national-playback-continuity`: + +1. **Playback stopped for every camera change and for quality preparation.** `notifyCameraChanged` paused the loop, re-prepared all 20 viewport-detail frames, and only then restarted; `play()` was also gated behind that preparation. Remediation: **motion-first playback** — motion starts immediately at the always-resident factor-4 commons, sharp preparation runs beside the loop as prefetch-only residency work (`prefetchDetail` for every frame, including the selected one, which the relaxed `commitPrefetchedStaging` guard now permits while the common level is active), and the quality lock upgrades between frames with a normal paint receipt. A camera change drops the lock to the commons — whole-domain, therefore camera-independent — without stopping motion, and re-prepares in the background. +2. **Supersession surfaced as a user-facing error.** A second pan during an in-flight preparation raised `RadarSourceSupersededError`, which the `moveend`/play/scrub handlers rendered as the playback-area notice. Remediation: supersession is normal control flow and is now filtered everywhere before `setPlaybackError`; the camera notification path no longer produces awaited rejections at all. +3. **Playback starved acquisition.** The play session held the exclusive resident-only reservation for its entire duration while `runNationalAcquisition` spun on it, so backfill and strictly-newer polling made no progress while playing. Remediation: motion is resident-only by construction and holds no reservation; backfill and polling continue during playback, with each commit briefly pausing/resuming the loop through the existing replacement contract. Sharp preparation defers until retained history settles (`pendingBackfillCount` = 0) and the post-commit resume re-runs it. +4. **Home-view playback deleted the complete-domain detail.** The below-threshold branch of quality preparation reset to the overview and pruned all detail, forcing a ~1 s re-refinement blur after every home-view play. Remediation: below the sharp threshold, preparation touches no residency at all. + +Deferred with reason: pipelining backfill downloads against GPU commits requires a staged-frame queue in Rust (`national_history.rs` holds a single `staged` slot); backfill remains serial per frame. The engineering-contract playback sentence was updated for the motion-first model as an owner decision dated 2026-08-04. + ## 1. Reported symptoms 1. **Initial National load takes far too long** before the timeline feels usable. diff --git a/docs/README.md b/docs/README.md index 3c8996a..154681b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,7 +18,7 @@ The merged National path is: fixed NOAA MRMS host -> strict chronological history -> exact u16/value-aware levels -> PackedGrid v1 -> shared two-credit IPC -> all-frame common GPU residency -> quality-locked playback/scrub -> coverage-aware GPU receipt ``` -It paints the newest observation first, backfills up to 19 strictly older observations, then polls for strictly newer inventory. Every retained frame keeps a complete factor-4 GPU presentation, and the selected observation refines to a complete-domain factor-1 presentation that is camera-independent: pan and zoom never restage, refetch, or degrade the paused view at any zoom, and history commits preserve the selected frame's detail. Regional playback prepares factor-1 coverage for all frames, or factor 2 when needed to remain under the 200 MiB target, before zero-I/O motion begins. GPU uploads share a measured 4 ms per-frame budget rather than one fixed row band per vsync. +It paints the newest observation first, backfills up to 19 strictly older observations, then polls for strictly newer inventory — including while playback runs. Every retained frame keeps a complete factor-4 GPU presentation, and the selected observation refines to a complete-domain factor-1 presentation that is camera-independent: pan and zoom never restage, refetch, or degrade the paused view at any zoom, and history commits preserve the selected frame's detail. Playback is motion-first: the loop starts immediately on the resident commons and is never stopped by a camera change or by sharpness — regional factor-1/factor-2 preparation runs beside it as prefetch-only work and upgrades the quality lock between frames. GPU uploads share a measured 4 ms per-frame budget rather than one fixed row band per vsync. ## Alpha direction diff --git a/src/App.tsx b/src/App.tsx index 64db550..75089b4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -108,6 +108,7 @@ import { } from "./national-radar/NationalGridLayer"; import { NationalHistoryWorkingSetController, + isNationalWorkingSetBusy, observationId as nationalObservationId, type NationalHistoryWorkingSetResult, } from "./national-radar/NationalHistoryWorkingSetController"; @@ -1679,6 +1680,10 @@ export function App() { ) { throw new Error("National playback detail cannot prepare before paint is complete"); } + // Sharp preparation waits for the retained history to settle; motion + // runs at the complete common level while backfill continues, and the + // resume after the final backfill commit re-runs this preparation. + if ((latestNationalHistory?.pendingBackfillCount ?? 0) > 0) return 4; const cameraKey = nationalCameraKey(instance); const alreadyComplete = activeLayer.finestCompletePlaybackFactor(); if ( @@ -1692,7 +1697,6 @@ export function App() { if ( !isCurrent() || cancelled - || nationalResidentOnlyReservations < 1 || transferGeneration !== expectedGeneration || nationalCameraKey(instance) !== cameraKey || painted?.source.kind !== "national" @@ -1703,23 +1707,44 @@ export function App() { ); } }; - const result = await prepareNationalPlaybackQuality({ - zoom: instance.getZoom(), - observations, - selectedObservationId, - bounds, - workingSet: activeWorkingSet, - layer: activeLayer, - ownershipCheck, - }); - if (result.factor === 1 || result.factor === 2) { - nationalPlaybackDetailCameraKey = cameraKey; - nationalPlaybackDetailFactor = result.factor; - } else { - nationalPlaybackDetailCameraKey = null; - nationalPlaybackDetailFactor = null; + // Motion may still be painting the selected observation's previous + // detail right after a camera change; prefetching that observation is + // only additive once the common level is the active presentation. + const commonActiveDeadline = Date.now() + 5_000; + while (activeLayer.getSnapshot().presentationFactor !== 4) { + ownershipCheck(); + if (Date.now() > commonActiveDeadline) return 4; + await waitMilliseconds(50); + } + const maximumBusyAttempts = 3; + for (let attempt = 1; ; attempt += 1) { + ownershipCheck(); + await activeWorkingSet.waitForIdle(); + ownershipCheck(); + try { + const result = await prepareNationalPlaybackQuality({ + zoom: instance.getZoom(), + observations, + selectedObservationId, + bounds, + workingSet: activeWorkingSet, + layer: activeLayer, + ownershipCheck, + }); + if (result.factor === 1 || result.factor === 2) { + nationalPlaybackDetailCameraKey = cameraKey; + nationalPlaybackDetailFactor = result.factor; + } else { + nationalPlaybackDetailCameraKey = null; + nationalPlaybackDetailFactor = null; + } + return result.factor; + } catch (error) { + if (attempt >= maximumBusyAttempts || !isNationalWorkingSetBusy(error)) { + throw error; + } + } } - return result.factor; }; nationalMoveHandler = () => { if (radarSessionCoordinatorRef.current!.snapshot().painted?.source.kind !== "national") return; @@ -1734,9 +1759,7 @@ export function App() { if (!playbackEngaged) return; nationalPlaybackDetailCameraKey = null; nationalPlaybackDetailFactor = null; - void nationalPlaybackController?.notifyCameraChanged(true).catch((error) => { - setPlaybackError(error instanceof Error ? error.message : String(error)); - }); + nationalPlaybackController?.notifyCameraChanged(); }; instance.on("moveend", nationalMoveHandler); @@ -2970,6 +2993,7 @@ export function App() { if (snapshot.playing || snapshot.preparingQuality) controller.pause(); else { void controller.play().catch((error) => { + if (isRadarSourceSuperseded(error)) return; setPlaybackError(error instanceof Error ? error.message : String(error)); }); } @@ -2997,7 +3021,9 @@ export function App() { } } } catch (error) { - setPlaybackError(error instanceof Error ? error.message : String(error)); + if (!isRadarSourceSuperseded(error)) { + setPlaybackError(error instanceof Error ? error.message : String(error)); + } } finally { scrubRunningRef.current = false; if (queuedScrubRef.current !== null) queueScrub(queuedScrubRef.current); diff --git a/src/national-radar/NationalGridLayer.ts b/src/national-radar/NationalGridLayer.ts index e91a75e..04cf9aa 100644 --- a/src/national-radar/NationalGridLayer.ts +++ b/src/national-radar/NationalGridLayer.ts @@ -566,7 +566,16 @@ export class NationalGridLayer implements CustomLayerInterface { commitPrefetchedStaging(timelineObservationIds: readonly string[]): void { const staging = this.requireCompleteStaging(); const identity = nationalObservationIdentity(staging.manifest); - if (identity.observationId === this.getSnapshot().selectedObservationId) { + // Prefetch is additive residency: it must never retire the presentation + // that is currently painting. The selected observation may prefetch new + // detail while its complete common level is active (motion-first playback + // paints the upgrade later, with a receipt, through frame selection), but + // replacing an active detail presentation without a paint is forbidden. + if ( + identity.observationId === this.getSnapshot().selectedObservationId + && this.active + && this.active.manifest.presentationFactor !== 4 + ) { throw new Error("selected National detail requires an authoritative paint receipt"); } const previous = this.captureResidencyState(); @@ -677,6 +686,25 @@ export class NationalGridLayer implements CustomLayerInterface { + sharedBytes; } + /** + * Wait until no frame paint or paint waiter is in flight. Residency + * mutations that bypass the paint path (prefetch commits) call this so a + * concurrent motion paint's captured rollback state can never be made + * stale by a mid-fence residency change. + */ + async waitForPaintQuiescence(timeoutMs = 10_000): Promise { + if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 120_000) { + throw new RangeError("National paint quiescence wait must be between 100 and 120000 ms"); + } + const started = performance.now(); + while (this.pendingPaint || this.paintWaiter) { + if (performance.now() - started > timeoutMs) { + throw new Error("National paint quiescence wait timed out"); + } + await nextAnimationFrame(); + } + } + async waitForCommonResidency(timeoutMs = 60_000): Promise { if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 120_000) { throw new RangeError("National residency wait must be between 100 and 120000 ms"); diff --git a/src/national-radar/NationalHistoryWorkingSetController.test.ts b/src/national-radar/NationalHistoryWorkingSetController.test.ts index 466376a..c61d130 100644 --- a/src/national-radar/NationalHistoryWorkingSetController.test.ts +++ b/src/national-radar/NationalHistoryWorkingSetController.test.ts @@ -12,6 +12,7 @@ describe("NationalHistoryWorkingSetController", () => { const fixture = historyFixture(); const events: string[] = []; const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() {}, beginStaging() { events.push("begin"); }, async uploadStagedChunk() { events.push("upload"); }, async commitInitialHistoryStaging() { @@ -41,6 +42,7 @@ describe("NationalHistoryWorkingSetController", () => { const fixture = historyFixture(); const events: string[] = []; const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() {}, beginStaging() { events.push("begin"); }, async uploadStagedChunk() { events.push("upload"); }, async commitInitialHistoryStaging() { throw new Error("not used"); }, @@ -76,6 +78,7 @@ describe("NationalHistoryWorkingSetController", () => { const fixture = historyFixture(); const events: string[] = []; const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() {}, beginStaging() { events.push("begin"); }, async uploadStagedChunk() { events.push("upload"); }, async commitInitialHistoryStaging() { throw new Error("not used"); }, @@ -112,6 +115,7 @@ describe("NationalHistoryWorkingSetController", () => { const events: string[] = []; const committedFactors: number[] = []; const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() {}, beginStaging() {}, async uploadStagedChunk() {}, async commitInitialHistoryStaging() { throw new Error("not used"); }, @@ -142,6 +146,7 @@ describe("NationalHistoryWorkingSetController", () => { const events: string[] = []; let checks = 0; const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() {}, beginStaging() {}, async uploadStagedChunk() {}, async commitInitialHistoryStaging() { return fixture.receipt; }, diff --git a/src/national-radar/NationalHistoryWorkingSetController.ts b/src/national-radar/NationalHistoryWorkingSetController.ts index 7e223f8..3adc3a3 100644 --- a/src/national-radar/NationalHistoryWorkingSetController.ts +++ b/src/national-radar/NationalHistoryWorkingSetController.ts @@ -44,6 +44,7 @@ type HistoryGridLayer = Pick< | "rollbackHistoryMutation" | "rollbackStaging" | "uploadStagedChunk" + | "waitForPaintQuiescence" >; export class NationalHistoryWorkingSetController { @@ -148,6 +149,7 @@ export class NationalHistoryWorkingSetController { (manifest, version) => viewportCoverage(manifest, bounds, version), ownershipCheck, async () => { + await this.layer.waitForPaintQuiescence(); this.layer.commitPrefetchedStaging(timelineObservationIds); return undefined; }, @@ -180,7 +182,7 @@ export class NationalHistoryWorkingSetController { deferExternalCommit = false, ): Promise { if (this.operation) { - return Promise.reject(new Error("a National history working-set mutation is already active")); + return Promise.reject(new Error(WORKING_SET_BUSY_MESSAGE)); } const operation = this.stage( observation, @@ -299,6 +301,13 @@ export function observationId(observation: NationalHistoryObservation): string { return `${observation.observationTimeUnixMs}:${observation.contentSha256}`; } +const WORKING_SET_BUSY_MESSAGE = "a National history working-set mutation is already active"; + +/** True when a mutation was rejected only because another one was in flight. */ +export function isNationalWorkingSetBusy(error: unknown): boolean { + return error instanceof Error && error.message === WORKING_SET_BUSY_MESSAGE; +} + function assertManifestIdentity( manifest: PackedGridManifest, observation: NationalHistoryObservation, diff --git a/src/national-radar/NationalPlaybackQuality.test.ts b/src/national-radar/NationalPlaybackQuality.test.ts index 5844753..4177397 100644 --- a/src/national-radar/NationalPlaybackQuality.test.ts +++ b/src/national-radar/NationalPlaybackQuality.test.ts @@ -7,7 +7,7 @@ import { import { observationId } from "./NationalHistoryWorkingSetController"; describe("National playback quality preparation", () => { - it("returns to the complete overview and releases old regional detail", async () => { + it("leaves existing residency untouched below the sharp threshold", async () => { const fixture = qualityFixture(); const result = await prepareNationalPlaybackQuality({ ...fixture.options, @@ -15,10 +15,12 @@ describe("National playback quality preparation", () => { }); expect(result).toEqual({ factor: 4, projectedGpuBytes: 0, detailedObservationCount: 0 }); - expect(fixture.events).toEqual(["select:3:4", "prune:"]); + // No selection, no staging, no pruning: a complete-domain refined + // presentation survives a home-view playback session intact. + expect(fixture.events).toEqual([]); }); - it("prepares exact viewport detail for every retained observation before playback", async () => { + it("prefetches exact viewport detail for every retained observation without painting", async () => { const fixture = qualityFixture({ 1: 120_000_000 }); const result = await prepareNationalPlaybackQuality({ ...fixture.options, @@ -31,7 +33,7 @@ describe("National playback quality preparation", () => { detailedObservationCount: 3, }); expect(fixture.events).toEqual([ - "stage:3:1", + "prefetch:3:1", "prune:3", "prefetch:1:1", "prefetch:2:1", @@ -48,18 +50,17 @@ describe("National playback quality preparation", () => { expect(result.factor).toBe(2); expect(result.projectedGpuBytes).toBe(130_000_000); expect(fixture.events).toEqual([ - "stage:3:1", + "prefetch:3:1", "prune:3", - "select:3:4", "prune:", - "stage:3:2", + "prefetch:3:2", "prune:3", "prefetch:1:2", "prefetch:2:2", ]); }); - it("restores the complete overview when no fine all-frame level fits", async () => { + it("returns the common factor without selecting when no fine all-frame level fits", async () => { const fixture = qualityFixture({ 1: 230_000_000, 2: 210_000_000 }); const result = await prepareNationalPlaybackQuality({ ...fixture.options, @@ -67,7 +68,8 @@ describe("National playback quality preparation", () => { }); expect(result.factor).toBe(4); - expect(fixture.events.slice(-2)).toEqual(["select:3:4", "prune:"]); + expect(fixture.events.at(-1)).toBe("prune:"); + expect(fixture.events.some((event) => event.startsWith("select"))).toBe(false); }); it("cleans partial detail when ownership is superseded", async () => { @@ -83,7 +85,7 @@ describe("National playback quality preparation", () => { }, })).rejects.toThrow("superseded"); - expect(fixture.events.slice(-2)).toEqual(["select:3:4", "prune:"]); + expect(fixture.events.at(-1)).toBe("prune:"); }); it("requests exact then half-resolution detail only above the regional threshold", () => { @@ -107,19 +109,6 @@ function qualityFixture(projected: Partial> = {}) { bounds: { west: -102, south: 35, east: -94, north: 42 }, ownershipCheck() {}, workingSet: { - async stageSelectedDetail( - observation: NationalHistoryObservation, - _bounds: unknown, - _timeline: readonly string[], - _ownership: () => void, - _beforeCommit: undefined, - factor: 1 | 2 = 1, - ) { - preparedFactor = factor; - detailed = 1; - events.push(`stage:${observationId(observation).split(":")[0]}:${factor}`); - return {} as never; - }, async prefetchDetail( observation: NationalHistoryObservation, _bounds: unknown, @@ -127,7 +116,12 @@ function qualityFixture(projected: Partial> = {}) { _ownership: () => void, factor: 1 | 2 = 1, ) { - detailed += 1; + if (observationId(observation) === selectedObservationId) { + preparedFactor = factor; + detailed = 1; + } else { + detailed += 1; + } events.push(`prefetch:${observationId(observation).split(":")[0]}:${factor}`); return {} as never; }, @@ -146,11 +140,6 @@ function qualityFixture(projected: Partial> = {}) { } events.push(`prune:${ids.map((id) => id.split(":")[0]).join(",")}`); }, - async selectResidentAndWait(id: string, factor: number) { - preparedFactor = factor as 1 | 2 | 4; - events.push(`select:${id.split(":")[0]}:${factor}`); - return {} as never; - }, }, }, }; diff --git a/src/national-radar/NationalPlaybackQuality.ts b/src/national-radar/NationalPlaybackQuality.ts index b807815..caa13c6 100644 --- a/src/national-radar/NationalPlaybackQuality.ts +++ b/src/national-radar/NationalPlaybackQuality.ts @@ -15,7 +15,7 @@ export const NATIONAL_SHARP_PLAYBACK_MIN_ZOOM = 6; type PlaybackQualityWorkingSet = Pick< NationalHistoryWorkingSetController, - "stageSelectedDetail" | "prefetchDetail" + "prefetchDetail" >; type PlaybackQualityLayer = Pick< @@ -23,7 +23,6 @@ type PlaybackQualityLayer = Pick< | "finestCompletePlaybackFactor" | "projectedUniformDetailGpuBytes" | "pruneDetailResidency" - | "selectResidentAndWait" >; export interface NationalPlaybackQualityPreparationOptions { @@ -50,6 +49,16 @@ export function nationalPlaybackDetailCandidates( return zoom >= NATIONAL_SHARP_PLAYBACK_MIN_ZOOM ? [1, 2] : []; } +/** + * Prepare sharp playback detail beside a running loop. Every staging is a + * prefetch: nothing here selects, paints, or otherwise changes the visible + * observation — the caller applies the returned factor through the playback + * quality lock, and the next frame selection paints it with a receipt. + * + * Below the sharp-zoom threshold no detail is staged and existing residency + * is left untouched, so a complete-domain refined presentation survives a + * home-view playback session intact. + */ export async function prepareNationalPlaybackQuality( options: NationalPlaybackQualityPreparationOptions, ): Promise { @@ -72,14 +81,8 @@ export async function prepareNationalPlaybackQuality( if (!selected || timelineIds.length < 1) { throw new Error("National playback quality requires the selected retained observation"); } - const resetToCommon = async () => { - await layer.selectResidentAndWait(selectedObservationId, 4); - layer.pruneDetailResidency([]); - }; const candidates = nationalPlaybackDetailCandidates(options.zoom); if (candidates.length < 1) { - ownershipCheck(); - await resetToCommon(); ownershipCheck(); return { factor: 4, projectedGpuBytes: 0, detailedObservationCount: 0 }; } @@ -87,12 +90,11 @@ export async function prepareNationalPlaybackQuality( try { for (const factor of candidates) { ownershipCheck(); - await workingSet.stageSelectedDetail( + await workingSet.prefetchDetail( selected, bounds, timelineIds, ownershipCheck, - undefined, factor, ); ownershipCheck(); @@ -102,7 +104,7 @@ export async function prepareNationalPlaybackQuality( factor, ); if (projectedGpuBytes > gpuTargetBytes) { - await resetToCommon(); + layer.pruneDetailResidency([]); continue; } for (const observation of observations) { @@ -130,7 +132,11 @@ export async function prepareNationalPlaybackQuality( } return { factor: 4, projectedGpuBytes: 0, detailedObservationCount: 0 }; } catch (error) { - await resetToCommon().catch(() => {}); + try { + layer.pruneDetailResidency([]); + } catch { + // Preserve the preparation error; residency pruning is best-effort here. + } throw error; } } diff --git a/src/playback/NationalPlaybackController.test.ts b/src/playback/NationalPlaybackController.test.ts index 2a92ac5..0f43c9a 100644 --- a/src/playback/NationalPlaybackController.test.ts +++ b/src/playback/NationalPlaybackController.test.ts @@ -118,7 +118,7 @@ describe("NationalPlaybackController", () => { expect(controller.snapshot().selectedObservationId).toBe(observationId(observations[0])); }); - it("prepares and locks playback to complete exact viewport detail", async () => { + it("starts motion immediately and upgrades quality in the background", async () => { vi.useFakeTimers(); const observations = frames(3); const layer = new FakeNationalLayer(observations); @@ -136,28 +136,28 @@ describe("NationalPlaybackController", () => { }); controller.establishInitialPaint(layer.receipt()); - const play = controller.play(); - await vi.waitFor(() => { - expect(controller.snapshot()).toMatchObject({ - playing: false, - preparingQuality: true, - holdReason: "PREPARING_PLAYBACK_QUALITY", - }); + await controller.play(); + // Motion is running at the complete common level while sharp detail + // prepares; the loop is never held. + expect(controller.snapshot()).toMatchObject({ + playing: true, + preparingQuality: true, }); - finishPreparation(); - await play; + expect(controller.snapshot().holdReason).toBeUndefined(); + expect(layer.qualityLock).toBe(4); + await vi.advanceTimersByTimeAsync(100); + expect(layer.selectFactors.every((factor) => factor === 4)).toBe(true); + finishPreparation(); + await vi.advanceTimersByTimeAsync(0); expect(layer.qualityLock).toBe(1); - expect(layer.getSnapshot().presentationFactor).toBe(1); + expect(controller.snapshot()).toMatchObject({ playing: true, preparingQuality: false }); await vi.advanceTimersByTimeAsync(100); - expect(layer.selectFactors.every((factor) => factor === 1)).toBe(true); - controller.pause(); - - await controller.scrub(0); expect(layer.selectFactors.at(-1)).toBe(1); + controller.pause(); }); - it("treats user cancellation during quality preparation as a clean pause", async () => { + it("treats a pause during quality preparation as a clean stop at the common level", async () => { vi.useFakeTimers(); const observations = frames(3); const layer = new FakeNationalLayer(observations); @@ -165,13 +165,9 @@ describe("NationalPlaybackController", () => { const preparation = new Promise((resolve) => { finishPreparation = resolve; }); - let releases = 0; const refined: string[] = []; const controller = new NationalPlaybackController(layer, observations, { refinementSettleMs: 50, - async acquireResidentOnlyActivity() { - return () => { releases += 1; }; - }, async preparePlaybackQuality(isCurrent) { await preparation; if (!isCurrent()) throw new Error("superseded preparation"); @@ -184,19 +180,17 @@ describe("NationalPlaybackController", () => { controller.establishInitialPaint(layer.receipt()); const play = controller.play(); - await vi.waitFor(() => expect(controller.snapshot().preparingQuality).toBe(true)); + expect(controller.snapshot().preparingQuality).toBe(true); + await play; controller.pause(); - await vi.advanceTimersByTimeAsync(100); - expect(refined).toEqual([]); finishPreparation(); + await vi.advanceTimersByTimeAsync(0); - await expect(play).resolves.toBeUndefined(); expect(controller.snapshot()).toMatchObject({ playing: false, preparingQuality: false, }); expect(layer.qualityLock).toBeUndefined(); - expect(releases).toBe(1); await vi.advanceTimersByTimeAsync(49); expect(refined).toEqual([]); await vi.advanceTimersByTimeAsync(1); @@ -297,7 +291,7 @@ describe("NationalPlaybackController", () => { }); }); - it("returns an overview camera to common residency without scheduling fine detail", async () => { + it("treats a paused camera change as a no-op for the camera-independent presentation", async () => { vi.useFakeTimers(); const observations = frames(2); const layer = new FakeNationalLayer(observations); @@ -307,21 +301,25 @@ describe("NationalPlaybackController", () => { onRefinementRequested: (observation) => refined.push(observationId(observation)), }); - await controller.notifyCameraChanged(false); + controller.notifyCameraChanged(); await vi.advanceTimersByTimeAsync(500); - expect(layer.selectFactors).toEqual([4]); + // No forced common selection, no refinement scheduling: the paused + // presentation needs nothing from the camera. + expect(layer.selectFactors).toEqual([]); expect(refined).toEqual([]); }); - it("re-prepares the moved viewport before resuming active playback", async () => { + it("keeps motion running through a camera change and re-prepares in the background", async () => { vi.useFakeTimers(); const observations = frames(3); const layer = new FakeNationalLayer(observations); let preparations = 0; + const playingSeen: boolean[] = []; const controller = new NationalPlaybackController(layer, observations, { dwellMs: 100, latestDwellMs: 100, + onState: (snapshot) => playingSeen.push(snapshot.playing), async preparePlaybackQuality(isCurrent) { expect(isCurrent()).toBe(true); preparations += 1; @@ -332,17 +330,23 @@ describe("NationalPlaybackController", () => { controller.establishInitialPaint(layer.receipt()); await controller.play(); + await vi.advanceTimersByTimeAsync(0); expect(controller.snapshot()).toMatchObject({ playing: true, qualityLockFactor: 1 }); + const statesBeforeCamera = playingSeen.length; - await controller.notifyCameraChanged(true); - + controller.notifyCameraChanged(); + // The sharp lock drops to the complete common level without stopping motion. + expect(controller.snapshot().playing).toBe(true); + await vi.advanceTimersByTimeAsync(0); expect(preparations).toBe(2); expect(controller.snapshot()).toMatchObject({ playing: true, qualityLockFactor: 2 }); + expect(playingSeen.slice(statesBeforeCamera).every((playing) => playing)).toBe(true); + await vi.advanceTimersByTimeAsync(100); expect(layer.selectFactors.at(-1)).toBe(2); controller.pause(); }); - it("cancels superseded quality preparation and restarts only for the newest camera", async () => { + it("supersedes stale quality preparation so only the newest camera locks", async () => { const observations = frames(3); const layer = new FakeNationalLayer(observations); let finishFirstPreparation!: () => void; @@ -353,24 +357,26 @@ describe("NationalPlaybackController", () => { const controller = new NationalPlaybackController(layer, observations, { async preparePlaybackQuality(isCurrent) { preparations += 1; - if (preparations === 1) await firstPreparation; - if (!isCurrent()) return 4; + if (preparations === 1) { + await firstPreparation; + expect(isCurrent()).toBe(false); + throw new Error("superseded preparation"); + } layer.completeFactor = 1; return 1; }, }); controller.establishInitialPaint(layer.receipt()); - const initialPlay = controller.play(); - await vi.waitFor(() => expect(controller.snapshot().preparingQuality).toBe(true)); - const firstCamera = controller.notifyCameraChanged(true); - const newestCamera = controller.notifyCameraChanged(true); + await controller.play(); + expect(controller.snapshot().preparingQuality).toBe(true); + controller.notifyCameraChanged(); finishFirstPreparation(); - await initialPlay; - await Promise.all([firstCamera, newestCamera]); + await vi.waitFor(() => { + expect(controller.snapshot()).toMatchObject({ playing: true, qualityLockFactor: 1 }); + }); expect(preparations).toBe(2); - expect(controller.snapshot()).toMatchObject({ playing: true, qualityLockFactor: 1 }); controller.pause(); }); }); diff --git a/src/playback/NationalPlaybackController.ts b/src/playback/NationalPlaybackController.ts index 8137743..6f9b075 100644 --- a/src/playback/NationalPlaybackController.ts +++ b/src/playback/NationalPlaybackController.ts @@ -57,12 +57,9 @@ export class NationalPlaybackController { private transitionCount = 0; private completedCycles = 0; private playRequest = 0; - private cameraChangeRequest = 0; - private cameraPlaybackRestartPending = false; + private qualityRequest = 0; private preparingQuality = false; private refinementAfterQualityPreparation = false; - private playbackStartOperation: Promise | null = null; - private playbackActivityRelease: (() => void) | null = null; private readonly dwellMs: number; private readonly latestDwellMs: number; private readonly refinementSettleMs: number; @@ -125,84 +122,81 @@ export class NationalPlaybackController { this.emit(); } + /** + * Motion-first playback: motion begins immediately at the always-resident + * complete common level, and sharp quality upgrades in the background. The + * loop is never held for preparation, and a camera change never stops it. + */ play(): Promise { this.assertActive(); - if (this.playing || this.preparingQuality || this.observations.length < 2) { + if (this.playing || this.observations.length < 2) { return Promise.resolve(); } - const operation = this.startPlayback(); - this.playbackStartOperation = operation; - void operation.then( + const request = this.playRequest + 1; + this.playRequest = request; + this.clearRefinementTimer(); + this.playing = true; + this.layer.setPlaybackQualityLock(4); + this.emit(); + this.beginQualityUpgrade(); + return this.ensureCommonSelection(4).then( () => { - if (this.playbackStartOperation === operation) this.playbackStartOperation = null; + if (this.playing && this.playRequest === request && !this.operation) { + this.scheduleNext(this.dwellForCurrent()); + } }, - () => { - if (this.playbackStartOperation === operation) this.playbackStartOperation = null; + (error) => { + if (this.playRequest === request) this.stopPlayback(); + throw error; }, ); - return operation; } - private async startPlayback(): Promise { - const request = this.playRequest + 1; - this.playRequest = request; - this.clearRefinementTimer(); + /** + * Prepare sharp playback beside the running loop. The prepared factor is + * applied through the quality lock and takes effect on the next frame + * selection; failure or supersession leaves motion at the common level. + */ + private beginQualityUpgrade(): void { + const prepare = this.options.preparePlaybackQuality; + if (!prepare) return; + const request = this.qualityRequest + 1; + this.qualityRequest = request; + const isCurrent = () => !this.disposed + && this.playing + && this.qualityRequest === request; this.preparingQuality = true; this.emit(); - let release: (() => void) | null = null; - try { - release = await this.acquireResidentOnlyActivity(); - const isCurrent = () => !this.disposed && this.playRequest === request; - if (!isCurrent()) { - release(); - return; - } - let qualityFactor: NationalPlaybackQualityFactor; + void (async () => { try { - qualityFactor = await this.options.preparePlaybackQuality?.(isCurrent) - ?? this.layer.finestCompletePlaybackFactor(); - } catch (error) { - if (!isCurrent()) return; - throw error; - } - if (!isCurrent()) { - release(); - return; + const factor = await prepare(isCurrent); + if (isCurrent() && (factor === 1 || factor === 2)) { + this.layer.setPlaybackQualityLock(factor); + } + } catch { + // Superseded, busy, or unavailable sharp detail: motion continues at + // the complete common level rather than pausing or surfacing an error. + } finally { + if (this.qualityRequest === request) { + this.preparingQuality = false; + this.emit(); + const deferred = this.refinementAfterQualityPreparation; + this.refinementAfterQualityPreparation = false; + if (deferred && !this.playing) this.scheduleRefinement(); + } } - this.layer.setPlaybackQualityLock(qualityFactor); - this.playbackActivityRelease = release; - release = null; - this.playing = true; - this.emit(); - void this.ensureCommonSelection().then( - () => { - if (this.playing && !this.operation) this.scheduleNext(this.dwellForCurrent()); - }, - () => { - this.stopPlayback(); - }, - ); - } finally { - release?.(); - const scheduleDeferredRefinement = this.refinementAfterQualityPreparation; - this.refinementAfterQualityPreparation = false; - this.preparingQuality = false; - this.emit(); - if (scheduleDeferredRefinement) this.scheduleRefinement(); - } + })(); } pause(): void { if (this.disposed) return; - this.cameraChangeRequest += 1; - this.cameraPlaybackRestartPending = false; this.playRequest += 1; + this.qualityRequest += 1; + this.preparingQuality = false; this.playing = false; if (this.timer !== null) globalThis.clearTimeout(this.timer); this.timer = null; this.layer.setPlaybackQualityLock(undefined); - this.playbackActivityRelease?.(); - this.playbackActivityRelease = null; this.emit(); if (!this.operation) this.scheduleRefinement(); } @@ -258,46 +252,27 @@ export class NationalPlaybackController { } } - async notifyCameraChanged(requestRefinementAfterSettle = true): Promise { - const shouldResumePlayback = this.playing - || this.preparingQuality - || this.cameraPlaybackRestartPending; - const pendingStart = this.playbackStartOperation; - const pendingPaint = this.operation; - if (shouldResumePlayback) { - this.pause(); - this.clearRefinementTimer(); - this.cameraPlaybackRestartPending = true; - const request = this.cameraChangeRequest + 1; - this.cameraChangeRequest = request; - try { - await pendingStart; - await pendingPaint; - } catch { - // A superseded preparation or paint cannot change the new camera request. + /** + * A settled camera never stops motion. The paused presentation is + * complete-domain and camera-independent, so a paused camera change is a + * no-op. While playing, the sharp lock was prepared for the previous + * viewport: motion drops to the always-complete common level between + * frames and a fresh background preparation upgrades it again. + */ + notifyCameraChanged(): void { + if (this.disposed) return; + if (!this.playing) { + if (this.preparingQuality) { + this.qualityRequest += 1; + this.preparingQuality = false; + this.emit(); } - if ( - this.disposed - || this.cameraChangeRequest !== request - || !this.cameraPlaybackRestartPending - ) return; - this.cameraPlaybackRestartPending = false; - await this.play(); return; } - const request = this.cameraChangeRequest + 1; - this.cameraChangeRequest = request; - this.clearRefinementTimer(); - try { - await this.ensureCommonSelection(requestRefinementAfterSettle ? undefined : 4); - if ( - requestRefinementAfterSettle - && !this.disposed - && this.cameraChangeRequest === request - ) this.scheduleRefinement(); - } catch { - // A newer camera, source, or renderer request owns presentation truth. - } + this.qualityRequest += 1; + this.layer.setPlaybackQualityLock(4); + this.emit(); + this.beginQualityUpgrade(); } snapshot(): NationalPlaybackSnapshot { @@ -319,7 +294,6 @@ export class NationalPlaybackController { qualityLockFactor: renderer.playbackQualityFactor, refining: this.refinementTimer !== null, preparingQuality: this.preparingQuality, - ...(this.preparingQuality ? { holdReason: "PREPARING_PLAYBACK_QUALITY" } : {}), ...(this.operation ? { holdReason: "AWAITING_GPU_PAINT" } : {}), ...(renderer.status === "recovering" || !commonResidencyComplete ? { holdReason: "GPU_RECOVERY_REHYDRATING" } @@ -393,6 +367,11 @@ export class NationalPlaybackController { } finally { this.operation = null; this.emit(); + // A pause that landed while this selection was awaiting its paint could + // not schedule refinement; the settled selection schedules it now. + if (!this.playing && !this.disposed && this.refinementTimer === null) { + this.scheduleRefinement(); + } } } @@ -430,12 +409,12 @@ export class NationalPlaybackController { private stopPlayback() { this.playRequest += 1; + this.qualityRequest += 1; + this.preparingQuality = false; this.playing = false; if (this.timer !== null) globalThis.clearTimeout(this.timer); this.timer = null; this.layer.setPlaybackQualityLock(undefined); - this.playbackActivityRelease?.(); - this.playbackActivityRelease = null; this.emit(); } From 16f20fa25a8ff37c4942930c217907a4664a93c4 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger Date: Tue, 4 Aug 2026 18:40:19 -0500 Subject: [PATCH 2/4] Honor suppressed refinement across pending paints pauseAndWait(false) callers - source transitions and history replacement - settle resident paint precisely so no detail work races them. The settled-selection refinement hook ignored that suppression and armed the timer once the pending paint completed. A suppression flag now spans the awaited operation, and both the suppressed and the plain-pause paths are covered by tests. Co-Authored-By: Claude Fable 5 --- .../NationalPlaybackController.test.ts | 68 +++++++++++++++++++ src/playback/NationalPlaybackController.ts | 25 +++++-- 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/src/playback/NationalPlaybackController.test.ts b/src/playback/NationalPlaybackController.test.ts index 0f43c9a..0670177 100644 --- a/src/playback/NationalPlaybackController.test.ts +++ b/src/playback/NationalPlaybackController.test.ts @@ -280,6 +280,74 @@ describe("NationalPlaybackController", () => { expect(refined).toEqual([layer.selected]); }); + it("honors suppressed refinement across a selection that settles after the pause", async () => { + vi.useFakeTimers(); + const observations = frames(3); + const layer = new FakeNationalLayer(observations); + let finishPaint!: (receipt: NationalPaintReceipt) => void; + const pendingPaint = new Promise((resolve) => { + finishPaint = resolve; + }); + vi.spyOn(layer, "selectResidentAndWait").mockImplementation(async (id, factor) => { + layer.selected = id; + layer.presentationFactor = factor; + layer.selectFactors.push(factor); + return pendingPaint; + }); + const refined: string[] = []; + const controller = new NationalPlaybackController(layer, observations, { + dwellMs: 100, + latestDwellMs: 100, + refinementSettleMs: 50, + onRefinementRequested: (observation) => refined.push(observationId(observation)), + }); + controller.establishInitialPaint(layer.receipt()); + + const play = controller.play(); + await vi.waitFor(() => expect(layer.selectFactors.length).toBeGreaterThan(0)); + // A transition-style pause suppresses refinement while the paint settles: + // the history/source mutation that asked for it owns the working set next. + const settled = controller.pauseAndWait(false); + finishPaint(layer.receipt()); + await play.catch(() => {}); + await settled; + await vi.advanceTimersByTimeAsync(500); + expect(refined).toEqual([]); + }); + + it("schedules refinement when a plain pause lands during a pending paint", async () => { + vi.useFakeTimers(); + const observations = frames(3); + const layer = new FakeNationalLayer(observations); + let finishPaint!: (receipt: NationalPaintReceipt) => void; + const pendingPaint = new Promise((resolve) => { + finishPaint = resolve; + }); + vi.spyOn(layer, "selectResidentAndWait").mockImplementation(async (id, factor) => { + layer.selected = id; + layer.presentationFactor = factor; + layer.selectFactors.push(factor); + return pendingPaint; + }); + const refined: string[] = []; + const controller = new NationalPlaybackController(layer, observations, { + dwellMs: 100, + latestDwellMs: 100, + refinementSettleMs: 50, + onRefinementRequested: (observation) => refined.push(observationId(observation)), + }); + controller.establishInitialPaint(layer.receipt()); + + const play = controller.play(); + await vi.waitFor(() => expect(layer.selectFactors.length).toBeGreaterThan(0)); + controller.pause(); + expect(refined).toEqual([]); + finishPaint(layer.receipt()); + await play.catch(() => {}); + await vi.advanceTimersByTimeAsync(50); + expect(refined).toEqual([observationId(observations.at(-1)!)]); + }); + it("uses the same timeline model for a non-shipping 30-frame diagnostic", () => { const observations = frames(30); const layer = new FakeNationalLayer(observations); diff --git a/src/playback/NationalPlaybackController.ts b/src/playback/NationalPlaybackController.ts index 6f9b075..aca396a 100644 --- a/src/playback/NationalPlaybackController.ts +++ b/src/playback/NationalPlaybackController.ts @@ -60,6 +60,7 @@ export class NationalPlaybackController { private qualityRequest = 0; private preparingQuality = false; private refinementAfterQualityPreparation = false; + private suppressSettledRefinement = false; private readonly dwellMs: number; private readonly latestDwellMs: number; private readonly refinementSettleMs: number; @@ -204,8 +205,18 @@ export class NationalPlaybackController { async pauseAndWait(scheduleRefinement = true): Promise { const wasPlaying = this.playing; this.pause(); - if (!scheduleRefinement) this.clearRefinementTimer(); - if (this.operation) await this.operation; + if (!scheduleRefinement) { + // Callers settling resident paint for a transition or history mutation + // must not have refinement armed behind their back when the pending + // selection completes. The settled-selection hook below honors this. + this.clearRefinementTimer(); + this.suppressSettledRefinement = true; + } + try { + if (this.operation) await this.operation; + } finally { + if (!scheduleRefinement) this.suppressSettledRefinement = false; + } return wasPlaying; } @@ -368,8 +379,14 @@ export class NationalPlaybackController { this.operation = null; this.emit(); // A pause that landed while this selection was awaiting its paint could - // not schedule refinement; the settled selection schedules it now. - if (!this.playing && !this.disposed && this.refinementTimer === null) { + // not schedule refinement; the settled selection schedules it now unless + // the pausing caller explicitly suppressed refinement for a transition. + if ( + !this.playing + && !this.disposed + && this.refinementTimer === null + && !this.suppressSettledRefinement + ) { this.scheduleRefinement(); } } From 7cde86ca22980045c8ef70b8075559dddc7140b3 Mon Sep 17 00:00:00 2001 From: Travis Curtsinger Date: Tue, 4 Aug 2026 18:50:19 -0500 Subject: [PATCH 3/4] Join a settling paint when play restarts after a mid-paint pause A pause that lands while a selection awaits its paint receipt leaves that operation in flight with the play control re-enabled; a second click then rejected with 'a National frame selection is already awaiting paint' and surfaced as a playback error. play() now awaits the settling selection as part of its own start before issuing the common selection, and the rapid pause/play cycle is covered by a test. Co-Authored-By: Claude Fable 5 --- .../NationalPlaybackController.test.ts | 39 +++++++++++++++++++ src/playback/NationalPlaybackController.ts | 25 +++++++----- 2 files changed, 55 insertions(+), 9 deletions(-) diff --git a/src/playback/NationalPlaybackController.test.ts b/src/playback/NationalPlaybackController.test.ts index 0670177..d5eae0c 100644 --- a/src/playback/NationalPlaybackController.test.ts +++ b/src/playback/NationalPlaybackController.test.ts @@ -348,6 +348,45 @@ describe("NationalPlaybackController", () => { expect(refined).toEqual([observationId(observations.at(-1)!)]); }); + it("restarts cleanly when play is clicked while a paused selection still awaits paint", async () => { + vi.useFakeTimers(); + const observations = frames(3); + const layer = new FakeNationalLayer(observations); + let finishPaint!: (receipt: NationalPaintReceipt) => void; + let pendingPaint = new Promise((resolve) => { + finishPaint = resolve; + }); + let holdNextPaint = true; + vi.spyOn(layer, "selectResidentAndWait").mockImplementation(async (id, factor) => { + layer.selected = id; + layer.presentationFactor = factor; + layer.selectFactors.push(factor); + if (holdNextPaint) { + holdNextPaint = false; + return pendingPaint; + } + return layer.receipt(); + }); + const controller = new NationalPlaybackController(layer, observations, { + dwellMs: 100, + latestDwellMs: 100, + }); + controller.establishInitialPaint(layer.receipt()); + + const firstPlay = controller.play(); + await vi.waitFor(() => expect(layer.selectFactors.length).toBe(1)); + controller.pause(); + // The pause left the first selection awaiting its paint; a second click + // must join that settling paint rather than reject against it. + const secondPlay = controller.play(); + finishPaint(layer.receipt()); + await firstPlay.catch(() => {}); + await expect(secondPlay).resolves.toBeUndefined(); + expect(controller.snapshot().playing).toBe(true); + expect(layer.selectFactors.length).toBeGreaterThan(1); + controller.pause(); + }); + it("uses the same timeline model for a non-shipping 30-frame diagnostic", () => { const observations = frames(30); const layer = new FakeNationalLayer(observations); diff --git a/src/playback/NationalPlaybackController.ts b/src/playback/NationalPlaybackController.ts index aca396a..99d5fe6 100644 --- a/src/playback/NationalPlaybackController.ts +++ b/src/playback/NationalPlaybackController.ts @@ -140,17 +140,24 @@ export class NationalPlaybackController { this.layer.setPlaybackQualityLock(4); this.emit(); this.beginQualityUpgrade(); - return this.ensureCommonSelection(4).then( - () => { - if (this.playing && this.playRequest === request && !this.operation) { - this.scheduleNext(this.dwellForCurrent()); - } - }, - (error) => { + return (async () => { + // A pause can land while a selection is still awaiting its paint + // receipt, leaving that operation in flight with the play control + // already re-enabled. That settling selection is part of this start: + // await it instead of rejecting the user's click against it. + const pending = this.operation; + if (pending) await pending.catch(() => {}); + if (this.disposed || !this.playing || this.playRequest !== request) return; + try { + await this.ensureCommonSelection(4); + } catch (error) { if (this.playRequest === request) this.stopPlayback(); throw error; - }, - ); + } + if (this.playing && this.playRequest === request && !this.operation) { + this.scheduleNext(this.dwellForCurrent()); + } + })(); } /** From 86a9e4d8932224771b4630fd5d9862f1cd29134a Mon Sep 17 00:00:00 2001 From: Travis Curtsinger Date: Tue, 4 Aug 2026 19:01:40 -0500 Subject: [PATCH 4/4] Gate staging on paint quiescence, not the active factor The sharp-preparation gate read the active presentation factor, which flips to the commons before the paint receipt lands, so preparation could reach beginStaging during an unfinished paint; the rejection was swallowed by the background upgrade and sharp playback silently stayed at factor 4. The App gate now requires the authoritative painted factor-4 receipt, and the working set waits out any pending paint immediately before beginStaging - the begin call runs synchronously in that continuation, which no timer-driven selection can interleave with, closing the same window for history commits staged beside motion. Co-Authored-By: Claude Fable 5 --- src/App.tsx | 13 +++++++++-- ...ationalHistoryWorkingSetController.test.ts | 22 ++++++++++++++++++- .../NationalHistoryWorkingSetController.ts | 6 +++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 75089b4..a7b9d98 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1709,10 +1709,19 @@ export function App() { }; // Motion may still be painting the selected observation's previous // detail right after a camera change; prefetching that observation is - // only additive once the common level is the active presentation. + // only additive once the common level has actually painted. The active + // presentation factor alone flips before the receipt lands, so gate on + // the authoritative painted receipt. const commonActiveDeadline = Date.now() + 5_000; - while (activeLayer.getSnapshot().presentationFactor !== 4) { + while (true) { ownershipCheck(); + const snapshot = activeLayer.getSnapshot(); + if ( + snapshot.status === "painted" + && snapshot.presentationFactor === 4 + && snapshot.paintReceipt?.presentationFactor === 4 + && !snapshot.mutationAwaitingCommit + ) break; if (Date.now() > commonActiveDeadline) return 4; await waitMilliseconds(50); } diff --git a/src/national-radar/NationalHistoryWorkingSetController.test.ts b/src/national-radar/NationalHistoryWorkingSetController.test.ts index c61d130..39001fc 100644 --- a/src/national-radar/NationalHistoryWorkingSetController.test.ts +++ b/src/national-radar/NationalHistoryWorkingSetController.test.ts @@ -141,6 +141,26 @@ describe("NationalHistoryWorkingSetController", () => { expect(committedFactors).toEqual([1]); }); + it("waits for paint quiescence before beginning any staging", async () => { + const fixture = historyFixture(); + const events: string[] = []; + const controller = new NationalHistoryWorkingSetController(fixture.client(events), { + async waitForPaintQuiescence() { events.push("quiesce"); }, + beginStaging() { events.push("begin"); }, + async uploadStagedChunk() { events.push("upload"); }, + async commitInitialHistoryStaging() { return fixture.receipt; }, + async commitHistoryStaging() { throw new Error("not used"); }, + commitPrefetchedStaging() { throw new Error("not used"); }, + async rollbackHistoryMutation() { throw new Error("not used"); }, + rollbackStaging() {}, + }); + + await controller.stageInitialOverview(fixture.observation, () => {}); + + expect(events.indexOf("quiesce")).toBeGreaterThanOrEqual(0); + expect(events.indexOf("quiesce")).toBeLessThan(events.indexOf("begin")); + }); + it("rolls a provisional GPU paint back when ownership is superseded after the fence", async () => { const fixture = historyFixture(); const events: string[] = []; @@ -161,7 +181,7 @@ describe("NationalHistoryWorkingSetController", () => { await expect(controller.stageInitialOverview(fixture.observation, () => { checks += 1; - if (checks >= 8) throw new Error("superseded"); + if (checks >= 9) throw new Error("superseded"); })).rejects.toThrow("superseded"); expect(events).toContain("rollback-provisional"); diff --git a/src/national-radar/NationalHistoryWorkingSetController.ts b/src/national-radar/NationalHistoryWorkingSetController.ts index 3adc3a3..2842880 100644 --- a/src/national-radar/NationalHistoryWorkingSetController.ts +++ b/src/national-radar/NationalHistoryWorkingSetController.ts @@ -241,6 +241,12 @@ export class NationalHistoryWorkingSetController { if (projectedGpuBytes > 256 * 1024 * 1024) { throw new Error("National presentation exceeds the 256 MiB hard ceiling"); } + // Motion-first playback keeps painting while mutations stage. beginStaging + // rejects during an unfinished paint, so wait the current paint out; the + // begin call runs synchronously in this continuation, which no timer-driven + // selection can interleave with. + await this.layer.waitForPaintQuiescence(); + ownershipCheck(); this.layer.beginStaging(manifest, coverage); let chunkWireBytes = 0; let receipt: NationalPaintReceipt | undefined;