Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): bound getThreadProjection history with explicit paging #11514

Closedsaphid(GitHub profile, opens in a new tab)wants to merge 250+ commits intot3code/codex-turn-mapping fromrefs/pull/11514/headopened View on GitHub

Summary

orchestration.getThreadProjection materialized an entire long-lived thread — every turn item, payload, and checkpoint — into one response. Simply capping the reply is not acceptable: a response silently cut to N rows leaves clients with no path to older history. This PR bounds snapshot rows, encoded bytes, and decode work while keeping the complete raw history in storage and adding cursor-based paging to reach it, with an explicit opt-in so legacy clients are never silently truncated.

Behavior

  • getThreadProjection stays opt-in: only requests with acceptBoundedSnapshot: true receive the bounded recent-turn window plus paging metadata (snapshotSequence, historyCursor, hasMoreHistory, latestLocalTurnOrdinal, payloadBudgetExceeded). Pre-PR clients never send the flag and keep the full projection — complete history and out-of-window checkpoint rewind included.
  • Bounded reads bound work inside the query: bounded_json write-time previews (migration 054 backfills them) mean oversized raw payloads never cross SQLite→JS; the window enforces row and byte budgets, keeps the newest rows, drops a partial oldest turn at its exact (ordinal, turn_item_id) boundary, and shares the budget across fork ancestry. Rows bigger than any budget stay reachable through at-least-one-row semantics.
  • Older history pages through orchestration.getThreadHistoryPage (WS) or the existing HTTP history endpoint with the same opaque cursor. Cursor v2 anchors on (thread digest, ordinal, item digest) — fixed size regardless of id length and stable across driver id mangling; v1 cursors still decode. A deleted or superseded anchor returns typed invalid_history_cursor; the client reseeds progressive history from a fresh bounded snapshot (guarded by applyLock and the snapshot sequence so it cannot clobber in-flight socket events), and a structured not-found marks the thread deleted.
  • orchestration.getThreadCheckpointContext returns whole-history checkpoint metadata (run/scope/checkpoint ids, ordinals, status, refs — no payloads) so bounded clients resolve rewind ordinals without the full projection. The threadCheckpointContext capability advertises it; revertThreadCheckpoint prefers it and falls back to an unbounded projection read on older servers. stopThreadSession also reads the unbounded projection so ready provider sessions outside the retained cohort are still detached.
  • Migration 055 adds item_id_digest (+ index) so v2 anchor resolution is an indexed lookup, not a per-page payload decode of every equal-ordinal sibling.
  • Both new RPCs require the existing orchestration.read scope.

Limitations

  • Interactive arrays (approval_request.options, todo_list.steps, user_input_request.questions/options) preserve all members in previews — dropping them would silently change what the user is asked — so a preview can exceed the per-row byte cap; emitted items are still billed at their true size, so window budgets hold.
  • Bounded snapshots retain only the timeline cohort's dependent collections; live control state outside the cohort is reachable via getThreadCheckpointContext or an unbounded read, not via visibleTurnItems.
  • Memory reduction is established by row/byte-budget tests, not a measured heap-profile run.

Test plan

  • 183 focused tests green on the head: ProjectionStore.test.ts, threadHistoryPaging.test.ts, ws.test.ts, commands.test.ts, threads-sync.test.ts, 054/055 migration tests — huge histories, oversized single rows, pagination to the true beginning (v1+v2 cursors, equal-ordinal siblings, lone-surrogate ids, fork markers), reconnect/reseed, legacy decode, and authorization.
  • Regressions mutation-verified (wrapper-vs-item billing, ordinal-only alignment, exempt-all collision groups all detected).
  • Per-package typecheck clean; fmt clean.

Supersedes the approach explored in #10512 — credited for the earlier proposal.


Built with SWE-2 Max via Devin/T3 Code. Coordination: T3 thread c1c50bb3-6c48-44ec-a174-25715c55a302; campaign issue saphid/t3code-personal#298.

    1. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR substantially changes production history retrieval, persistence schemas, RPC contracts, authorization, and client defaults while introducing new paging and recovery capabilities. Its cross-cutting behavior and an unresolved high-severity missing-thread error-classification concern require human review.

      Not approved because:

      • Per-PR cost limit exceeded (workspace setting). Approvability relies on correctness review in order to determine eligibility
      Review your spending limits in [Billing settings](https://app.macroscope.com/pingdotgg/settings/billing), or comment `@macroscope-app review this PR` to bypass the limit and review now. You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/ProjectionStore.ts:4541

      getCheckpointContext fails every request because checkpoint_id is selected from orchestration_v2_projection_checkpoint_scopes, which has no such column. Remove this column from the scope query so existing threads return rewind metadata instead of a SQL read error.

      No longer relevant as of 619294f894e5dc367ac924cd7d3c687a2bcd4cae

    5. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    6. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Macroscope skipped reviewing this pull request. Per-PR cost limit exceeded (workspace setting).

      Reviews on this PR have cost $49.04 so far. This review would add an estimated $13.60, bringing the total to $62.63 — above your per-PR limit of $50.00.

      Tip

      To get this pull request reviewed, you can:

      1. Comment @macroscope-app on this PR to request a manual review (monthly spend limits still apply).
      2. Exclude large or generated files from review by adding a pattern to your .macroscope/ignore.md — note that creating this file replaces Macroscope's built-in default ignores rather than extending them.
      3. Raise your cost limit in your workspace billing settings.
      [Turn off this reminder going forward](https://app.macroscope.com/pingdotgg/settings#Personal)
    7. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    8. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    9. @@ -4865,0 +6408,21 @@
      6408+ ...snapshot.projection,
      6409+ thread,
      6410+ runs,
      6411+ attempts,
      6412+ nodes,
      6413+ subagents,
      6414+ providerSessions,
      6415+ providerThreads,
      6416+ providerTurns,
      6417+ runtimeRequests,
      6418+ messages,
      6419+ plans,
      6420+ checkpointScopes,
      6421+ checkpoints,
      6422+ contextHandoffs,
      6423+ contextTransfers,
      6424+ turnItems,
      6425+ visibleTurnItems: bounded,
      6426+ },
      6427+ };
      6428+ }).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/ProjectionStore.ts:6428

      Missing threads from getThreadSnapshot are reclassified as ProjectionStoreReadError, so callers and the HTTP isThreadNotFound mapper receive an internal read error instead of thread_not_found. Preserve ProjectionStoreThreadNotFoundError before wrapping other failures, matching the SQL implementation.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 6428:
      
      Missing threads from `getThreadSnapshot` are reclassified as `ProjectionStoreReadError`, so callers and the HTTP `isThreadNotFound` mapper receive an internal read error instead of `thread_not_found`. Preserve `ProjectionStoreThreadNotFoundError` before wrapping other failures, matching the SQL implementation.

      False positive — the mapError at :6428 is scoped inside the flatMap callback and wraps only the decode/bounding gen. service.getThreadSnapshot(threadId) is the pipe source: its ProjectionStoreThreadNotFoundError (from getThreadProjection at :5889) propagates past flatMap unwrapped, so callers see the bare error — error.cause._tag === "ProjectionStoreThreadNotFoundError" still matches isThreadNotFound → thread_not_found, identical to the SQL impl. Pinned by regression tests on both drivers in fc07d990b: "surfaces missing threads as not-found, not read errors" (SQL) and "memory snapshot windows surface missing threads as not-found, not read errors" (memory).

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    10. @@ -2777,3 +2869,5 @@
      27772869 {
      27782870 threadId: ThreadId,
      27792871 message: Schema.String,
      2872+ /** Optional failure category so clients can branch without parsing `message`. */
      2873+ reason: Schema.optionalKey(Schema.Literals(["invalid_history_cursor"])),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      reason is a single-value discriminator that callers use for control flow, duplicating the distinction already represented by an error type. Introduce a dedicated tagged RPC error for an invalid history cursor, include it in the RPC error union, and branch on its tag while preserving the current caller-visible message.

      This requires coordinated contract, server, and client changes, so no self-contained diff is appropriate.

      Posted via Macroscope — Effect Service Conventions

      Addressed in 1113521455: getThreadHistoryPage now carries a dedicated tagged error OrchestrationV2InvalidHistoryCursorError in its RPC error union (rpc.ts), raised at both cursor-invalid sites in ws.ts with the same caller-visible message ("Invalid thread history cursor."), and the single-value reason literal was removed from OrchestrationV2GetThreadProjectionError (the only producer). The HTTP surface keeps EnvironmentRequestInvalidError.reason — that union is multi-value and is what the client actually branches on.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    11. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    12. @@ -41,4 +40,4 @@
      4140 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
      4241 import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
      4342
      44-export class StorageCleanup extends Context.Service<
      43+class StorageCleanup extends Context.Service<
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This module still defines a Context.Service and owns its construction, but the change makes the tag private and removes its canonical layer, leaving application composition to call make and manually start the returned implementation. Keep the service boundary public and restore export const layer = Layer.effect(StorageCleanup, make) (and the Layer namespace import), then compose/start it through the service layer.

      This requires changes at the declaration, module tail, imports, and composition site, so no self-contained diff is appropriate.

      Posted via Macroscope — Effect Service Conventions
      saphid(GitHub profile, opens in a new tab)commented

      Addressed in the amended base-repair commit (1b657bbd2e): kept the service boundary public — the class tag and export const layer = Layer.effect(StorageCleanup, make) are restored, make is module-private, and server.ts now composes through the canonical pattern matching the adjacent PullRequestSyncReactor entry: Layer.effectDiscard(Effect.flatMap(StorageCleanup.StorageCleanup, s => s.start())).pipe(Layer.provideMerge(StorageCleanup.layer), Layer.provide(ProjectionStoreV2.layer)). Knip and server typecheck both clean locally.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    13. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions found 1 issue.

      • apps/server/src/storageCleanup.ts: the service tag was made private and its canonical layer removed, forcing manual construction at application composition.
      Posted via Macroscope — Effect Service Conventions
    14. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions: 1 issue found in apps/server/src/storageCleanup.ts. See the inline review comment for the required service boundary fix.

      Posted via Macroscope — Effect Service Conventions
    15. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions found a blocking convention violation in apps/server/src/storageCleanup.ts; the actionable details are attached inline to the changed service declaration.

      Posted via Macroscope — Effect Service Conventions
    16. Effect Service Conventions: 1 blocking issue found. The inline review identifies the required fix in apps/server/src/storageCleanup.ts.

      Posted via Macroscope — Effect Service Conventions
    17. @@ -116,4 +116,4 @@
      116116 );
      117117 }
      118118
      119-export const make = Effect.gen(function* () {
      119+const make = Effect.gen(function* () {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      The module owns this service's construction, so its canonical make should remain part of the public service boundary alongside StorageCleanup and layer. Export it rather than making construction accessible only indirectly through the layer.

      Suggested change
      119-const make = Effect.gen(function* () {
      119+export const make = Effect.gen(function* () {
      Posted via Macroscope — Effect Service Conventions

      Verified — re-exporting make regresses the repo's knip gate: with composition flowing through layer, make has no cross-module importer and knip flags it as an unused export (confirmed locally: Unused exports (1) make StorageCleanup). The public boundary consumers actually use is the tag + layer — matching how server.ts now composes it (same pattern as the adjacent PullRequestSyncReactor entry). Keeping make module-private is what keeps Check green; reverted the suggestion.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    18. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions found 1 issue.

      • apps/server/src/storageCleanup.ts: the service-owned make constructor was made private instead of remaining part of the canonical public service boundary.
      Posted via Macroscope — Effect Service Conventions
    19. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions: 1 blocking issue found. See the inline suggestion in apps/server/src/storageCleanup.ts.

      Posted via Macroscope — Effect Service Conventions
    20. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      The prior storageCleanup.ts service-boundary concern is partially addressed: the public service tag and canonical layer are restored. One remaining convention issue is that the module-owned make constructor is still private; the inline suggestion covers that final change.

      Posted via Macroscope — Effect Service Conventions
    21. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions found 1 blocking issue in apps/server/src/storageCleanup.ts: export the module-owned make constructor. The actionable fix is posted inline.

      Posted via Macroscope — Effect Service Conventions
    22. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions found 1 issue. See the inline suggestion in apps/server/src/storageCleanup.ts to export the canonical make constructor.

      Posted via Macroscope — Effect Service Conventions
    23. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Effect Service Conventions failed: apps/server/src/storageCleanup.ts keeps the canonical make constructor private. An inline suggestion provides the one-line fix.

      Posted via Macroscope — Effect Service Conventions
    24. Effect Service Conventions found 1 issue in apps/server/src/storageCleanup.ts. Export the canonical module-owned make; see the inline suggestion.

      Posted via Macroscope — Effect Service Conventions
    25. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    26. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    27. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    28. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    29. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    30. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    31. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    32. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    33. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    34. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    35. @juliusmarminge Please review and merge this OV2 fix when you are happy with it.

      Bound long-history reads with explicit paging; keep ordinary V2 histories usable.

      Checked 18 September at 10:58 UTC: current head 1efab13d28b78269cf8439cb527e8d25259c06fb is mergeable, all checks are green or intentionally skipped, and there is no new review feedback since the owner's completed scan. Current diff: +11,077/−610.

      The latest-head independent agent review is still pending capacity; no fresh clean review is claimed. This request is for this contribution PR. The two scheduling PRs (#11592/#11635) are being held for a separate integration finding.

    36. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    37. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      All clear

      Posted via Macroscope — Effect Service Conventions
    38. Closing as superseded. v2 landed its own bounded-projection model on Sep 11 (12fb985abc, e2c5227ad8, 60762405a0, c3e29202cc):

      • getThreadProjection is served from getThreadSnapshotWindow through buildBoundedThreadProjection and is bounded unconditionally, so stale clients cannot materialize a full transcript.
      • subscribeThread accepts acceptBoundedSnapshot and returns historyCursor / hasMoreHistory; older history pages through the HTTP endpoint in orchestration-v2/http.ts, and client-runtime already opts in.
      • Control-plane arrays (checkpoints, runs, provider sessions) stay whole; only messages / turnItems are windowed, which removes the need for a separate checkpoint-context RPC.

      That solves the unbounded read with a much smaller surface than this branch (three migrations, write-time previews, a new cursor format), so I don't want to carry both models. If there is a measured hot spot that the current paging does not cover, for example oversized single-row payloads, a small PR with the measurement attached would be welcome.

      Thanks for the effort on this.

    39. juliusmarminge closed this

Sign in to join this conversation.