perf(server): window large thread snapshots #21475
main fromtakeover/terminal-preview-24/viewport-server·opened View on GitHubStack: #21475 (server/contracts) → #21476 (client hydration).
Large threads can still open with an entire tool-heavy turn, exceeding the initial transfer budget. This layer adds an optional viewport snapshot and paged history support; clients that do not opt in keep the existing response.
The snapshot retains up to 75 recent timeline rows and their initiating prompts, active/queued controls and pending requests. Historical checkpoint file lists load with their page, while summaries keep a count. History support is scoped to the requested thread, so inherited parent controls do not become child controls. SQL uses the existing indexes for prompt/control lookups.
Rebuilt from @maria-rcks’s #18220 against current main. This is the server/contracts layer of a two-layer replacement. The original rendering, sidebar, persistence, settings and native cleanup changes are omitted: current main already contains the relevant rendering/persistence work, and those concerns are outside this focused rebuild.
Verification: focused ProjectionStore, ThreadFind and threadHistoryPaging regressions fail before the implementation and pass afterward; server/contracts typecheck and scoped lint pass. Initial server suite: 66/69 → 69/69; review regressions: 91/94 → 94/94. The final integrated run passes all 374 tests in the ten changed test files. SQL/memory fixtures cover forks, queued prompts, notification runs, deferred checkpoint files and unchanged legacy responses.
Integrated Linux web proof with a disposable 5,002-row synthetic thread: the legacy compact response remains 3,694,234 bytes; the opted-in response is 58,369 bytes and 76 visible rows (75 plus its prompt), 98.42% fewer bytes. Earlier history restores all 4,927 omitted rows. These are response-size measurements, not paint or typing latency claims. Client proof and the interaction recording are in the upper layer.
Not verified here: Electron desktop, macOS, Windows, iOS or Android. No provider runtime behavior is changed. Native clients use the shared opt-in/cache contract, with native runtime validation still for a human.
Five independent whole-stack review rounds completed; both final reviewers found no confirmed code blockers. Earlier findings fixed fork control isolation, boundary prompts, indexed reads, paged recall and rewind. A suggested optimization to skip one batched metadata refresh per history page was left out because no regression was measured.
Prompt-budget regression: with a 20,000-byte policy, the initiating prompt and tail previously encoded to 33,799 bytes; the window now includes prompt costs and fits in 18,702 bytes. The existing test also recovers all 303 rows through cursors and preserves unavoidable oversized prompts with an explicit overflow flag. No test-count increase.
Checkpoint-budget regression: the final viewport now defers file lists for inactive runs removed by byte trimming, while preserving files for visible runs and active controls. The existing fixture falls from 1,092,600 to 898,006 bytes; 25/26 → 26/26 passing, with no test-count increase. Source projections and legacy file lists remain unchanged.
The current proof was rechecked against the final diff: the client patch is unchanged after the server fixes, and the measured synthetic thread has no checkpoint files affected by the final deferral change.
The byte policy remains a soft limit when mandatory control state or a single required row and its prompt are larger than the available budget. The overflow flag reports the final encoded payload. Human approval is still required for this feature; no merge is requested.
Implemented with Codex GPT-6.1-Sol; tests with GPT-6-Astra; independent reviews with Claude Opus 5.5 and GPT-6-Sol, through T3 Code.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge changed the title
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/threadHistoryPaging.ts line 596Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -504,3 +529,20 @@504529 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),505530 });506- const visibleTurnItems = renumberPositions(window.items);531+ const windowRunIds = new Set(window.items.map(({ item }) => item.runId));532+ const visibleItemIds = new Set(window.items.map((row) => row.sourceItemId));533+ const prompts = input.viewportWindow534+ ? controlProjection.visibleTurnItems.filter((row) => {535+ if (536+ row.item.runId == null ||537+ !windowRunIds.has(row.item.runId) ||538+ !(isThreadHistoryTurnStart(row.item) || row.item.type === "notification")539+ ) {540+ return false;541+ }542+ windowRunIds.delete(row.item.runId);543+ return !visibleItemIds.has(row.sourceItemId);544+ })545+ : [];546+ // The cursor stays at the row window so paging fills the gap below its prompt.547+ for (const prompt of prompts) visibleItemIds.add(prompt.sourceItemId);548+ const visibleTurnItems = renumberPositions(
🟡 Medium
orchestration-v2/threadHistoryPaging.ts:548Viewport snapshots can exceed
policy.maxEncodedBytesbecause prompts are appended afterselectRecentTimelineWindowenforces the row and byte limits, without charging their encoded size againstwindowBudget. With many runs whose prompts contain large attachments or text, this produces an oversized response;payloadBudgetExceededonly flags it and does not prevent it from being sent. Include prompt rows in the window’s budget before adding them tovisibleTurnItems.No longer relevant as of 2f304d711bee5391ef6390d7fe5aeee5840b621f
Fixed in ae55d13f70, now included in this PR’s current head. Initiating prompts are charged during window selection, deduplicated with visible rows and message records; active control messages are reserved up front. The existing 20,000-byte regression changes from 33,799 to 18,702 bytes and pages all 303 rows without repeated cursors. Mandatory single-row/prompt or control-state overflow remains explicit through the final payload flag.
The subsequent 2f304d711b also defers inactive checkpoint files removed by final byte trimming (1,092,600 → 898,006 bytes). All 374 focused tests pass; both fresh round-five whole-stack reviewers found no confirmed code blockers. Current-head CI and human approval are separate remaining gates.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — This PR introduces a substantial opt-in viewport and paged-history capability spanning server projection logic, SQL queries, WebSocket/HTTP transports, and shared contracts. Existing defaults remain compatible, but the new runtime path and deferred data-hydration behavior are broad enough to require human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire 5.0 KiB 5.0 KiB 0 B (0.0%) 6.8 KiB ✅ Codex Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Codex Live turn WebSocket wire 1.2 KiB 1.2 KiB 0 B (0.0%) 2.0 KiB ✅ Codex Live turn WebSocket decoded 20.9 KiB 20.9 KiB 0 B (0.0%) 29.3 KiB ✅ Codex Live turn messages 2 2 0 (0.0%) 8 ✅ Claude Total thread wire 5.0 KiB 5.0 KiB −7 B (−0.1%) 6.8 KiB ✅ Claude Thread snapshot wire 3.8 KiB 3.8 KiB 0 B (0.0%) 4.9 KiB ✅ Claude Live turn WebSocket wire 1.2 KiB 1.2 KiB −7 B (−0.6%) 2.0 KiB ✅ Claude Live turn WebSocket decoded 21.2 KiB 21.2 KiB 0 B (0.0%) 29.3 KiB ✅ Claude Live turn messages 2 2 0 (0.0%) 8 ✅ Baseline:
ab6be13· PR result:2f304d7· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 108.5 KiB
- Claude decoded thread snapshot: 108.8 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
-
⚙️ Run configuration
-
- Configuration used: Path: .coderabbit.config.ts
- Review profile: CHILL
- Plan: Team
- Run ID:
e0c375c3-3b20-4500-a852-f37698ba6655
📥 Commits
-
Reviewing files that changed from the base of the PR and between 50e81b87fa6e3757d3262e96d5d54f3da649d269 and 2f304d711bee5391ef6390d7fe5aeee5840b621f.
📒 Files selected for processing: 2
-
apps/server/src/orchestration-v2/threadHistoryPaging.test.tsapps/server/src/orchestration-v2/threadHistoryPaging.ts
Limit details: You’ve used all 10 included reviews currently available.
-
📝 Walkthrough
-
Thread snapshots can use viewport-window selection. This mode retains prompts and active items while deferring some historical checkpoint file details. History-page requests can optionally include related nodes, checkpoints, runs, and attempts.
Changes: Orchestration V2 thread history
Layer / File(s) Summary Snapshot and history request options
packages/contracts/src/environmentHttp.ts,packages/contracts/src/orchestrationV2.ts,apps/server/src/orchestration-v2/Orchestrator.ts,apps/server/src/orchestration-v2/ThreadManagementService.ts,apps/server/src/orchestration-v2/ThreadStream.ts,apps/server/src/orchestration-v2/http.ts,apps/server/src/ws.tsContracts and request handlers pass viewport-window and include-support options through snapshot and history processing. Viewport snapshot window selection
apps/server/src/orchestration-v2/ProjectionStore.ts,apps/server/src/orchestration-v2/ProjectionStore.test.tsSnapshot-window reads can retain prompts and active-control rows, omit the user-turn limit, and defer file lists for historical checkpoints. SQL and in-memory tests cover deferred details, runtime requests, and interleaved runs. Bounded viewport projection
apps/server/src/orchestration-v2/threadHistoryPaging.ts,apps/server/src/orchestration-v2/threadHistoryPaging.test.tsViewport mode adds run prompts and active items to the bounded projection while keeping the cursor based on the selected row window. Tests cover paging, byte limits, and checkpoint-file deferral. History-page support records
apps/server/src/orchestration-v2/ProjectionStore.ts,apps/server/src/orchestration-v2/ProjectionStore.test.ts,apps/server/src/orchestration-v2/ThreadFind.test.tsHistory pages can include support records related to items from the requested source thread. Tests cover deferred checkpoint details and fork-history support across SQL and memory stores. Priority: ➖ Normal
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Feature
Sequence Diagram(s)#
sequenceDiagram participant Client participant HistoryHTTP as threadHistoryPage participant ThreadManagementService participant Orchestrator participant ProjectionStore as ProjectionStoreV2 Client->>HistoryHTTP: Request history with includeSupport HistoryHTTP->>ThreadManagementService: Forward includeSupport ThreadManagementService->>Orchestrator: Request history page Orchestrator->>ProjectionStore: Read page and related support records ProjectionStore-->>Client: Return history page with supportSuggested reviewers:
maria-rcks
Merge Risk: ⚪ Minimal · up to
2f304-
The viewport snapshot change is mergeable after normal checks; no concrete issue requiring a fix was found.
Pre-merge checks:
4-
Check name Status Explanation Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Title check The title is concise, uses a conventional format, and clearly describes the main change: reducing large thread snapshot size through windowing. Description check The description covers the problem, implementation, scope, verification results, limitations, and test evidence. It does not include an explicit maintainer approval comment, but it explains the focuse… Full details: Description check
-
Explanation
The description covers the problem, implementation, scope, verification results, limitations, and test evidence. It does not include an explicit maintainer approval comment, but it explains the focused scope and states that human approval is still required; the description is otherwise substantially complete.
-
✨ Finishing Touches
-
📝 Generate docstrings
-
- Commit to this branch
- Create a new PR
🧪 Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
Thanks for the viewport work. #24589 (553203c57b) bounds long-turn snapshots, and #26240 adds bounded history paging. Please cut this down to the remaining checkpoint-file deferral and hydration work, with any necessary prompt-budget handling, rather than introducing a second viewport paging path.
Note
🤖 Claude Fable 5.2 responding on behalf of Theo
Closing:
mainnow does this another way. Thread snapshots are windowed (#24589, #33305, #34490) and history is paged (#26240, #24422). Out-of-window checkpoints are no longer sent, so there is nothing left to defer.Measured on current
mainwith real data: the six longest threads of one database open with 19 to 93 KB gzip (108 to 646 KB of JSON), against full snapshots of 3.3 to 7.7 MB.One part of this PR is not on
main: runs and checkpoints sent with history pages. It is not a perf gain, and its UI effect was not tested. The branches of this PR were not run for this comparison; it is from the diff.t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed