Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): projection maintenance finally has an entrypoint #15759

ClosedAdamulek123(GitHub profile, opens in a new tab)wants to merge 6 commits intomain fromrefs/pull/15759/headopened View on GitHub

Problem

ProjectionMaintenance had no production caller in the base code. Projection verification and event compaction were therefore unreachable from the running server, and there was no supported offline verify/rebuild command.

Change

  • Register the existing maintenance service with the shared Scheduler, after server activation.
  • Verify projections daily and compact events hourly. A due verification that returns invalid skips that sweep; the next hourly sweep compacts without re-verifying, even if drift persists. No successful verification result is cached. Exceptions also consume the applicable interval before the scheduler logs the failure.
  • Add t3 projections verify|rebuild, refusing to run when persisted runtime state identifies a live server for that data directory.
  • Skip threads with unfinished runs, outbox effects, or runtime requests. Re-evaluate eligibility in DELETE ... RETURNING, and allow only explicitly listed terminal statuses so unknown statuses block deletion.
  • Keep V2 command receipts, messages, turn items, and soft-deleted history. This does not establish a general retention policy or shrink the SQLite file with VACUUM.

Scope and approval

The maintenance module had a startup caller in #4971. Commit 792d2ffa4b8730ca46c76dbef09bf96405b356bf in #2829 removed that caller. This PR restores a production entrypoint through the Scheduler and adds an offline verify/rebuild CLI.

The hourly destructive compaction cadence and the new CLI require review as policy and interface choices. The previous caller compacted once after startup; this PR adds recurring deletion.

Retention is only partly addressed. #5550 asked for bounded activity history, event compaction, protection of unresolved work, a thread lifecycle policy, safe checkpoint/VACUUM, a diagnostics/settings view, configurable thresholds, and a dry-run estimate. This PR provides event compaction and an offline projection verifier/rebuilder, with unfinished-work guards. It does not deliver the rest of that request or establish that #4971 fully satisfied #5550.

Verification

  • From apps/server: vp test run on ProjectionMaintenance.test.ts, runtimeLayer.test.ts, FoundationPersistence.test.ts, Scheduler.test.ts, and Scheduler.integration.test.ts: 130/130 passed.
  • New real-Scheduler/TestClock coverage corrupts a SQLite projection, observes two daily invalid verifications, and confirms compaction within one hour after each failure while verification still reports invalid. This test passes against the original production behavior; the reported permanent compaction stall is not present at a9fe2cc5ef.
  • The unknown-status negative control failed as intended with a temporary known-active-status predicate: one event was deleted where zero was expected. The terminal-status allowlist was restored before the passing suite run.
  • Server vp run typecheck: exit 0, 178 advisory diagnostics, zero TypeScript errors, zero diagnostics in changed files. Repository-root vp run typecheck failed during task planning because the marketing package's astro executable is missing; a repository-wide diagnostic total was not obtained.
  • Targeted vp lint --report-unused-disable-directives: exit 0. git diff --check: clean.

Measurement gap

No synthetic sweep benchmark was run, and no real installation database was used. Verification and compaction timings as row counts grow, SQLite blocking time, and impact on a running server remain unmeasured. No developer live userdata was accessed. Paging and yielding do not quantify that cost or substitute for a benchmark. The hourly destructive sweep still needs maintainer evaluation of those gaps.

No browser/client pass was run. The CLI is covered in-process through the registered command and its layer composition; it was not run as a standalone process against a real installation.

Initial implementation used gpt-6.1-sol through Codex; earlier audit fixes used opencode/space-bunny-free through OpenCode. This follow-up used gpt-6.1-sol through Codex.

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

    2. Data point from a real install, in case it helps prioritize this.

      Setup: macOS 27.0 on an M1 Pro, T3 Code Nightly 0.0.46-nightly.20261005.2702. In daily use since March 2026, migrated to V2 on Oct 3, 2,295 threads.

      ~/.t3/userdata/statev2.sqlite is 13.7 GB. Largest tables (dbstat):

      TableSizeRowsLast write
      orchestration_events6.23 GB1,187,811today
      projection_thread_activities4.92 GB649,7202026-10-02 23:53 (V2 migration)
      orchestration_v2_projection_turn_items0.40 GBtoday
      orchestration_command_receipts0.20 GB1,052,342today

      Payload by event type in orchestration_events:

      Event typeEventsPayloadWritten since the migration
      thread.activity-appended824,1804.96 GB0
      turn-item.updated60,1880.42 GB25,161
      thread.message-sent121,4980.06 GB0

      So about 10 GB of the 13.7 GB is V1 activity history stored twice: once as thread.activity-appended events and once in projection_thread_activities. Neither has been written since the migration, and projection_thread_messages / projection_turns stopped at the same timestamp. orchestration_v2_legacy_imports covers all 2,177 V1 threads with no last_error.

      Two things that matter for this install beyond restoring the caller:

      1. Compaction alone won't shrink the file. This database has auto_vacuum = 0 and freelist_count = 0. Whatever compaction deletes goes to the freelist, which stops growth but keeps the 13.7 GB on disk until something runs VACUUM (or converts to auto_vacuum = INCREMENTAL, which itself needs one VACUUM). A one-off VACUUM gated on a large freelist, run while the server has no other connections, would return the space.
      2. The frozen V1 activity data is the bulk of the size. Once every thread has a successful legacy import, the V1 activity events and V1 projections look like the natural first retention horizon, perhaps after the stable-rollback window. That's the maintainer decision the description calls out; these numbers show how much it is worth here.

      Related: #14701 (thread list reads block on large databases), #12758, #16647.

    3. Thanks for wiring this up. Here are numbers from a large real install, for the measurement gap the description calls out, plus the risks I see in the diff. Nothing below comes from running this branch. The numbers are read-only measurements of the database or estimates from them, and the cost points come from reading the code.

      Code checked at PR head 18b2dd58983d115cf47b6708ca2ce0b67d6b1ed4; file:line refs below are at that head (ProjectionMaintenance.ts, ProjectionStore.ts).

      Install: Linux, nightly 0.0.46-nightly.20261007.2787, one long-lived server driving agent swarms. statev2.sqlite is 21.5 GB with auto_vacuum = 0. orchestration_events holds 3.19M rows (1.47M v1, 1.72M v2) and takes 14.3 GB with its indexes. On swarm days it grows 0.34-0.40 GB/h.

      Estimated candidates before unfinished-work guards (superseded share = events minus distinct entities; superseded bytes use per-type average sizes):

      rulecandidate eventsestimated payload
      v1 events of imported threads (all 177 imported)~1.47M1.86 GB
      older node.updated per entity~347k~0.68 GB
      older thread-state events per thread~16k~40 MB
      older message.updated per entity~3.5k~6 MB
      total~1.84M (~58% of rows)~2.6 GB (~28% of event payload)

      Actual deletions depend on eligibility: canCompactThread (ProjectionMaintenance.ts:239-254) skips threads with open runs, outbox effects or runtime requests, and I did not apply those guards.

      With auto_vacuum off, compaction does not shrink the file. Reusable space and the reduction in future growth have not been measured. As a rough physical-space estimate, the candidates occupy about 3 GB of pages. The kept types are the bulk: older snapshots of turn-item.updated (~2.2 GB), subagent.updated (~0.47 GB) and provider-turn.updated (~0.45 GB) make up an estimated 43% of historical v2 event payload. That is fine for this PR's scope; the details are on #6897.

      Risks I see in the diff

      1. The daily verify blocks every other DB statement for its whole run. verify runs inside sql.withTransaction (ProjectionMaintenance.ts:122). In nodeSqliteClient.ts:262-285 the transaction takes the client's only semaphore permit for its whole scope, with BEGIN IMMEDIATE. Inside it, getUnreadableThreadIds (ProjectionStore.ts:3589) pages through 16 projection tables and schema-decodes every payload_json. Here that is about 4 GB of row data (turn items 3.10 GB, nodes 0.62 GB). The yieldNows let other fibers run, but their queries wait on the permit, so event appends, shell snapshots and thread lists all stall until verify commits. I have not timed it. For scale, a plain read-only page walk of orchestration_v2_projection_turn_items alone (dbstat, idle I/O priority) took 23 s on this machine. Could the scheduled path run the decode scan outside the transaction, paged like compaction, and keep only the cheap checks (thread set, metadata, latest sequence) in a short transaction? The offline CLI can keep the current shape.
      2. "Daily" verify is attempted on every server start. register runs the source once at activation (Scheduler.ts:53). nextVerifyAt and nextCompactionAt start at 0 and live in memory (ProjectionMaintenance.ts:418-419). Each activation attempts verification and, if it succeeds and returns valid, starts compaction (:430-435), right when clients reconnect and load snapshots. This install's update loop restarts the server about every four hours for nightly updates. Persisted deadlines could preserve the cadence across restarts; an initial delay could reduce overlap with reconnects.
      3. Every hourly sweep scans all remaining events. The code comment says this "never gets cheaper" (ProjectionMaintenance.ts:437). The first pass over this measured backlog needs about 6,400 event-discovery queries of at most 500 rows; before compaction the table measured 12.1 GB (7.7 GB without overflow pages). Later passes still scan all remaining events; their size after compaction is unmeasured. One option is to store the high-water sequence of the last full pass. Later sweeps then read only newer events and delete older rows for the keys they find, using the existing (stream_id, sequence) index. That would also have to revisit candidates skipped by the unfinished-work guards, even when those keys produce no newer compactable events.
      4. Possible cache cost, unmeasured. A full scan could evict useful SQLite pages and reduce the benefit of a larger cache such as #17844 (mine). I have not measured eviction or the effect on shell reads.
      5. Minor, unmeasured: the discovery query reads a column stored after the payload. application_event_version was added by ALTER TABLE, so it is the last column, after payload_json and metadata_json. I suspect large v2 rows make SQLite follow overflow pages to reach it, but have not measured that. If it shows up, reading the version from idx_orchestration_events_application_sequence, with v1 and v2 handled in separate passes, might avoid those reads.

      The guards in canCompactThread, the status allowlist and the live-server check in the CLI look right to me. On the 10-07 build I found no live reader of v1 thread events other than the MAX(stream_version) lookup on append. v1 project events stay, because the project stream ignores the version.

      Not covered by this PR, so maybe worth one line in the description: the v1 projection_thread_activities table (0.86 GB here; 4.92 GB on the install in the comment above), rows of deleted threads (#17845), and getting the space back (VACUUM).

      On #6897 I offered a synthetic pacing benchmark. If it helps here, I can run this branch against a synthetic DB shaped like this one (3.2M events, same type mix) and report per-page stall times, the verify hold time and the first-run duration from the server's own event-loop stall trace. Just say if you'd want that.

      Drafted with Claude Opus 5.5 in Claude Code (T3 Code harness); install numbers measured read-only, code read at the PR head named above.

      🤖 Generated with Claude Code

    4. Note

      This comment is posted by Julius' dot

      Hourly event deletion and a new offline verify/rebuild command go beyond restoring the old startup caller. The PR identifies these as new policy and interface choices, but no maintainer approval is linked or present in the discussion. These behavior changes need prior approval, so I'm closing this for now. Please agree on the cadence and CLI scope with a maintainer before resubmitting.

    5. juliusmarminge closed this

Sign in to join this conversation.