Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): prune events the projections already cover #29806

Mergedjuliusmarmingemerged 5 commits intomain fromrefs/pull/29806/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Problem

The event log grows without bound. On cups statev2.sqlite is 12.4 GB, and orchestration_events takes up 6.25 GB of table plus 1.28 GB of indexes, for 1.475M events. The largest event types are turn-item.updated (2.5 GB), node.updated (0.59 GB), subagent.updated (0.56 GB) and provider-turn.updated (0.27 GB). The 6-hour background compaction deletes only superseded events, so the history projections could be rebuilt from could stay. Since the maintainer decision below, that guarantee is gone: once a projection has applied an event, nothing needs that event again.

Step 0: who reads old events

ReaderOldest event it needsAfter pruning
Thread resume subscribeOrchestrationV2Thread({afterSequence}) (ws.ts, client-runtime threads)events after the client cursorgap = wrong state (partial replay). Added: a cursor below the pruned-through sequence loads a snapshot
Shell resume subscribeOrchestrationV2Shell → canReplayPersistedRange / readApplicationEventsevents after the cursorsame gap; same snapshot fallback added
Snapshot sequences: getThreadSnapshot, history pages, shell MAX(sequence), ThreadFind.readRevision, latestAgentSequence(threadId)newest event of each streamthe stream head is never pruned
latestAgentSequence() / latestApplicationSequence / EventSink.latestSequenceglobal maxthe newest event is a stream head, so it is kept
Stream stream_version (MAX(stream_version)+1 on append, unique index)newest event per streamthe stream head is kept
EventSink.stream({afterSequence}) users: Orchestrator run.updated watcher, streamDomainEvents, CommandOutputHub, MCP task wait, ThreadManagement, GuestSharecursor taken from the current head or snapshotonly recent events; fine
readByCommandId (replayed dispatch: ThreadLaunch, delegate_task, RemoteDelegation, metadata MCP)that command's events, for as long as the command can be retriedtail. Retries come within the retained day. A retry older than that finds its events gone (the same thing already happens for superseded types, and callers like ThreadMetadataMcp fall back to projections)
Subagent prompt dedupe (promptSequence → anchor row, restored on every read)anchors referenced by retained rowsanchors referenced by retained rows are kept, including rows appended mid-pass (checked in the delete transaction)
CodexUsageHistory (first running run.updated per attempt → model selection/speed tier)arbitrarily oldkept: run.updated rows with status running are never pruned (8,166 rows, ~12 MB on cups)
Legacy V1 importer (orchestration_events_v2_created_threads_idx: a thread with no v2 thread.created counts as not imported)thread.created foreverkept (3,389 rows, 6 MB)
Legacy V1 events / receiptsnone once the transcript is importedexisting rule kept (imported threads only)
Command receiptsdedupe on command idkept; receipts provide idempotency
verify / rebuild / t3 doctorthe whole logremoved from production (see below)
Peer / relay / linked environmentsuse the same thread and shell subscriptionscovered by the snapshot fallback

Every gap either resyncs from a snapshot or falls inside the retained tail. No reader needs arbitrarily old events beyond the rows that are always kept.

Change

  • ProjectionMaintenance.pruneEventStore replaces compactEventStore. Each 6 h pass records the log head as a mark in orchestration_v2_projection_metadata. Once that mark is a day old, the next pass first publishes event-log-pruned-through and then deletes every event at or below min(mark, projection last_sequence), except:

    • each stream's newest event
    • thread.created
    • run.updated rows with status running
    • referenced prompt anchors
    • v1 rows, which follow the old imported-legacy rule

    At least a day of history always remains (between 24 and ~30 h). Pacing is unchanged: 50-row pages run on the reader worker, deletes run on the writer, and there is a rest at 10 % duty after every page, including between loops. No transaction or reader lock is held across a yield; the only transaction wraps a reference read plus a delete. Scan bounds are fixed when the pass starts.

  • OrchestrationEventStore.prunedThroughSequence: thread and shell resumes from an older cursor take the existing snapshot path.

  • verify/rebuild move to testkit/ProjectionReplay.ts, a test-only oracle that checks a projection equals a replay of an unpruned test log. Production can no longer run a destructive rebuild against a pruned log. t3 doctor compaction no longer verifies or refuses (DatabaseProjectionsInvalidError is removed).

  • Docs: docs/internals/overview.md no longer calls the event log the source of truth, and the user storage note says history older than a day is removed.

Tests

  • ProjectionMaintenance.test.ts (rewritten from TurnItemCompaction.test.ts):
    • Nothing is pruned before the mark is a day old.
    • After that day, events at or below the mark are gone; thread.created, the running run update, referenced anchors, and the tail are kept.
    • High water and per-thread head are unchanged, prunedThroughSequence equals the mark, the projection is unchanged, and borrowed prompts still resolve.
    • An anchor that a row appended during the pass borrows from is kept. This fails with the in-transaction reference read disabled.
  • ws.test.ts: thread and shell resumes from a cursor below the boundary load a snapshot. Both fail without the ws.ts change.
  • FoundationPersistence.test.ts: discovery stays on the reader worker, pacing is 270 ms after every page, fixed scan bounds hold, and imported v1 events and legacy receipts still go.
  • vp run check:changed is green. runtimeLayer plus the LegacyV1Cutover and ProviderSwitch integration suites pass (155 tests).

Measurements (cups, read-only)

With the boundary about 30 h before the head (seq 2,323,418 of 2,425,586), the first pass deletes 1,361,455 of 1,475,233 events (92 %), ~4.67 GB of row data plus about 1.1 GB of their index entries. About 100k events (~204 MB) remain in the tail. Those pages go on the freelist; existing databases have auto_vacuum = NONE, so the file only shrinks after t3 doctor or the next PR in this stack.

Scope and approval

Maintainer-approved (Julius): projections are the source of truth once applied.

Independent review fixes (0955847)

  • Idle threads no longer resend their body on resume. A thread untouched since before the pruned boundary resumes at its own high-water, so it missed nothing; the snapshot fallback now needs the cursor to be below both the thread's newest event and the boundary. New ws test fails on the previous condition.
  • Retained stream heads keep their prompt anchor. A stream's newest row is kept even below the boundary; when it borrows its prompt (promptSequence), its anchor was deleted and the row became undecodable. Each pass now also collects references from below-boundary stream heads (index-only scan, 0.4 s warm / 11.6 s cold on the full 1.45M-event cups log, read-only reader). New ProjectionMaintenance test fails without it.

🤖 Generated with Claude Code

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

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

      Approvability

      Verdict: Needs Human Approval

      Macroscope's review found this PR requires human approval — Automatic maintenance now prunes projection-covered events older than roughly one day, making projections authoritative and eliminating full log-based rebuilds. The changed default retention policy and irreversible loss of recovery history require human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. github-actions[bot](GitHub profile, opens in a new tab)commented

      Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      CodexLive turn WebSocket decoded21.6 KiB21.6 KiB0 B (0.0%)24.4 KiB✅
      CodexLive turn messages220 (0.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.9 KiB21.9 KiB0 B (0.0%)24.4 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: f6503f0 · PR result: e2ecefd · Source CI: success

      Scenario 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.

    4. @coderabbitai review

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review.

      Walkthrough

      Projection maintenance replaces event-store compaction with age-based pruning bounded by projection progress. The event store records a pruning boundary, and WebSocket resumes use snapshots when replay is unavailable. Projection verification and rebuilding move to a testkit service.

      Changes: Event Retention and Replay

      Layer / File(s)Summary
      Pruning algorithm and retention tests
      apps/server/src/orchestration-v2/ProjectionMaintenance.ts, apps/server/src/persistence/OrchestrationEventStore.ts, apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts, apps/server/src/orchestration-v2/FoundationPersistence.test.ts, apps/server/src/orchestration-v2/TurnItemCompaction.test.ts
      pruneEventStore replaces event-store compaction. It prunes eligible events and imported legacy history in bounded pages, subject to projection, retention, and reference rules. Tests cover retention timing, prompt references, and concurrent appends.
      WebSocket replay fallback
      apps/server/src/ws.ts, apps/server/src/ws.test.ts
      Thread and shell resumption load snapshots when the pruning boundary makes replay unavailable, including when pruning advances during a replay read.
      Test-only projection replay
      apps/server/src/orchestration-v2/testkit/ProjectionReplay.ts, apps/server/src/orchestration-v2/{FoundationPersistence,legacy/*,runtimeLayer,testkit/ProviderSwitch.integration}.test.ts, apps/server/src/persistence/Migrations/*.test.ts, apps/server/src/project/ProjectService.deletion.test.ts
      ProjectionReplay verifies projected thread IDs and sequence metadata against the event log. It rebuilds projections by replaying events in pages. Existing tests use this service for verification and rebuild operations.
      Database maintenance and retention documentation
      apps/server/src/persistence/{DatabaseMaintenance,DatabaseStorage}.ts, apps/server/src/persistence/{DatabaseMaintenance,DatabaseStorage}.test.ts, apps/server/src/server.ts, docs/internals/overview.md, docs/user/background-service.md
      Database maintenance calls pruneEventStore without projection verification. The documentation describes the retention period, preserved event types, and resume behavior.

      Estimated code review effort: 4 (Complex) | ~60 minutes

      Change: Other

      Sequence Diagram(s)

      sequenceDiagram
        participant DatabaseStorage
        participant ProjectionMaintenanceV2
        participant OrchestrationEventStore
        participant WebSocketResume
        participant SnapshotLoader
        DatabaseStorage->>ProjectionMaintenanceV2: call pruneEventStore
        ProjectionMaintenanceV2->>OrchestrationEventStore: record pruning boundary and delete eligible rows
        WebSocketResume->>OrchestrationEventStore: read boundary and persisted events
        OrchestrationEventStore-->>WebSocketResume: return boundary and replay rows
        WebSocketResume->>SnapshotLoader: load snapshot when pruning invalidates replay

      Possibly related issues

      • pingdotgg/t3code#24003 — Pruning deletes eligible old events, but does not change thread.visited payload size or transaction frequency.
      • pingdotgg/t3code#28903 — This change adds age-based pruning bounded by projection progress, but does not cap turn-item or activity history.
      • pingdotgg/t3code#29434 — This change adds retention for eligible orchestration events, but not VACUUM, per-thread archives, or a manual prune command.
      • pingdotgg/t3code#26224 — This change replaces the compaction path with bounded, paged pruning.
      • pingdotgg/t3code#27598 — Eligible superseded events can be pruned, but payload size per update remains unchanged.

      Possibly related PRs

      • pingdotgg/t3code#22630 — Both PRs implement one-day retention and snapshot fallback; this PR replaces the earlier per-thread model with a global prune boundary.
      • pingdotgg/t3code#28144 — This PR is a predecessor for event retention and cursor fallback, which this change replaces with a global pruning boundary.
      • pingdotgg/t3code#20877 — Both changes address event-maintenance bounds and paged work; this PR changes the maintenance operation to pruneEventStore.

      Suggested reviewers: macroscopeapp

      Merge Risk: Minimal · up to e2ece

      The retention documentation now distinguishes V2 receipts from imported legacy receipts. No actionable merge-blocking risk is established.

      Pre-merge checks: Passed 4
      Check nameStatusExplanation
      Title checkPassedThe title "perf(server): prune events the projections already cover" matches the main change: ProjectionMaintenance now exposes pruneEventStore in place of compactEventStore, deleting events that proj…
      Description checkPassedThe description follows the repository template. It has Problem, Change, Scope and approval, and Verification sections, and each contains specific content. The Problem section gives measured data and …
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Full details: Title check

      Explanation

      The title "perf(server): prune events the projections already cover" matches the main change: ProjectionMaintenance now exposes pruneEventStore in place of compactEventStore, deleting events that projections have already applied. It is a conventional commit title in plain language, and the scope (server) matches the changed files. The title does not mention the snapshot fallback for resumes or the removal of verify/rebuild from production, but it does not need to cover every detail.

      Full details: Description check

      Explanation

      The description follows the repository template. It has Problem, Change, Scope and approval, and Verification sections, and each contains specific content. The Problem section gives measured data and a reader-by-reader analysis. The Change section lists the pruning rules, the snapshot fallback, the move of verify/rebuild to a test-only oracle, and the doc updates. Scope cites maintainer approval from Julius. Verification lists the focused tests, the check:changed result, and the measurements. Two template items are weak: the Scope section gives no link to the triaged issue or the approval comment itself, and the template's agent-model footer is absent, though the description does say it was generated with Claude Code. These gaps are minor and do not outweigh the rest of the description.

      Finishing Touches
      Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      CodeRabbit Verify

      • Run CodeRabbit Verify to test the changes in this pull request.
      Recent review info
      Run configuration
      Commits

      Reviewing files that changed from the base of the PR and between 0b5b885ba2e339edee97b92a538b2013dbd5fea8 and e2ecefda3a9416614fe3203d13d7d114e03961af.

      Files selected for processing: 1
      • docs/internals/overview.md
      Files skipped from review as they are similar to previous changes: 1
      • docs/internals/overview.md

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

      • Fix comments: Fix CodeRabbit comments on this PR
    6. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Action not completed

      Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

      Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

      • Fix comments: Fix CodeRabbit comments on this PR
      • Fix comments: Fix CodeRabbit comments on this PR
    7. juliusmarminge merged this550c5fa

    8. juliusmarminge closed this

Sign in to join this conversation.