fix(server): projection maintenance finally has an entrypoint #15759
main fromrefs/pull/15759/head·opened View on GitHubProblem#
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 runonProjectionMaintenance.test.ts,runtimeLayer.test.ts,FoundationPersistence.test.ts,Scheduler.test.ts, andScheduler.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-rootvp run typecheckfailed during task planning because the marketing package'sastroexecutable 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
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
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.sqliteis 21.5 GB withauto_vacuum = 0.orchestration_eventsholds 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):
rule candidate events estimated payload v1 events of imported threads (all 177 imported) ~1.47M 1.86 GB older node.updatedper entity~347k ~0.68 GB older thread-state events per thread ~16k ~40 MB older message.updatedper 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) andprovider-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
- The daily
verifyblocks every other DB statement for its whole run.verifyruns insidesql.withTransaction(ProjectionMaintenance.ts:122). InnodeSqliteClient.ts:262-285the transaction takes the client's only semaphore permit for its whole scope, withBEGIN IMMEDIATE. Inside it,getUnreadableThreadIds(ProjectionStore.ts:3589) pages through 16 projection tables and schema-decodes everypayload_json. Here that is about 4 GB of row data (turn items 3.10 GB, nodes 0.62 GB). TheyieldNows 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 oforchestration_v2_projection_turn_itemsalone (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. - "Daily" verify is attempted on every server start.
registerruns the source once at activation (Scheduler.ts:53).nextVerifyAtandnextCompactionAtstart 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. - 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. - 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.
- Minor, unmeasured: the discovery query reads a column stored after the payload.
application_event_versionwas added byALTER TABLE, so it is the last column, afterpayload_jsonandmetadata_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 fromidx_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 theMAX(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_activitiestable (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
- The daily
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.
juliusmarminge closed this
Sign in to join this conversation.
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.sqliteis 13.7 GB. Largest tables (dbstat):orchestration_eventsprojection_thread_activitiesorchestration_v2_projection_turn_itemsorchestration_command_receiptsPayload by event type in
orchestration_events:thread.activity-appendedturn-item.updatedthread.message-sentSo about 10 GB of the 13.7 GB is V1 activity history stored twice: once as
thread.activity-appendedevents and once inprojection_thread_activities. Neither has been written since the migration, andprojection_thread_messages/projection_turnsstopped at the same timestamp.orchestration_v2_legacy_importscovers all 2,177 V1 threads with nolast_error.Two things that matter for this install beyond restoring the caller:
auto_vacuum = 0andfreelist_count = 0. Whatever compaction deletes goes to the freelist, which stops growth but keeps the 13.7 GB on disk until something runsVACUUM(or converts toauto_vacuum = INCREMENTAL, which itself needs oneVACUUM). A one-offVACUUMgated on a large freelist, run while the server has no other connections, would return the space.Related: #14701 (thread list reads block on large databases), #12758, #16647.