You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(orchestration): delete settled Runs and expired rows from the orchestration database on a timer - #41757
Orca never threw away finished orchestration work, so its orchestration database kept growing until someone reset it. Now Orca deletes a finished Run's records a day after the Run was last touched, on its own, while it runs.
What Changed
Run retention. An hourly sweep, plus one a minute after the database opens, deletes every Run whose work all settled and that nothing touched for orchestrationRunRetentionHours (default 24; 0 turns retention off). Each Run goes in its own BEGIN IMMEDIATE transaction, and the sweep yields to the event loop between Runs. A Run is kept while it has any of these:
a Task that is pending, ready, dispatched or blocked; a Dispatch that is pending or dispatched
a worker or remote attachment in a live state; a worker terminal Orca still owns and has not released, or one handed to another Dispatch
a pending question, decision gate or remote question; an unacked relay item; an armed home auto-release
any coordinator the Run ever bound that is still live. That covers every handle in run_coordinator_handles, the current coordinator_handle and coordinator session, and every pane the Run's coordinators worked from (the Run's coordinator pane, Dispatch creator panes, Task creator panes, and the panes coordinator mail was sent from). A pane counts as live while a process holds it, even before its re-minted terminal has a handle, so a long-lived external coordinator such as a drive that reuses a Run id for its next worker-start keeps every Run it bound for as long as its terminal is open
unread current_delivery mail whose reader is still reachable: an open terminal, a waiter, or a structured session whose custody is not elsewhere
any row in the window: Run, Task, Dispatch, worker, message, question, gate or delivery
legacy, remote-homed, peer, adopted, or remote-owned (remote_run_links, remote_placements, remote_dispatches, remote_owned_questions) Runs are never retired
Delete order. Dispatch-keyed rows go first (archives, relay items and sequences, remote questions and attachments, attempt facts, federated dispatches, worker terminals, workers), then Run-keyed rows, then the Run. The removed-work capture records each deletion under its Run, and trg_runs_forget_removed_work drops those records with the Run. A record the sweep leaves without an existing Run is deleted in the same transaction.
Expired rows go in batches of 256 per table per transaction. Relay items acked before the window are deleted, except the newest row of each (dispatch_id, direction) stream, because legacy enqueue numbers from MAX(sequence); peer-run and peer-mail conversations are left alone. Worker rows, worker terminal archives and worker terminals whose Dispatch is gone are deleted, and so are removed-work records whose Run is gone.
Mutation receipts. Completed receipts now expire after 24 hours instead of 30 days, through the existing ensureMutationReceiptCapacity delete, so the ledger triggers stay in step.
Receipt compaction. Each sweep also compacts orchestration.check and orchestration.reply receipts completed more than 15 minutes ago (MUTATION_RECEIPT_FULL_REPLAY_MINUTES), 256 rows per transaction, paged by rowid. Each embedded message keeps only its id and the fields its stored row does not repeat, such as a report follow_up, and a reply's question.answer_body goes when it equals the reply body. A --retry-request replay after that rebuilds each message from the messages table, and orchestration.requestShow shows the rebuilt receipt. A message whose stored body differs from the receipt, or that is not stored here (peer-mail and remote-home replies), keeps its full receipt; every other method keeps its full receipt too. If a message is deleted before a late replay, the replay fails with operation_unknown instead of returning a result without it. On a copy of a live database holding 4 hours of receipts, compaction took 897 check receipts from 4,688,604 to about 298,521 bytes and 887 reply receipts from 1,655,931 to about 449,279 bytes, so 6.3 MB became 0.75 MB. 51 check messages whose stored body differed stayed full.
Every cutoff compares julianday() on both sides, because these tables mix datetime('now') and ISO timestamps. The receipt-expiry delete moved from a text comparison to julianday(updated_at), served by a new expression index idx_mutation_receipts_completed_age.
Two more indexes, question_threads(run_id) and worker_terminal_resources(origin_dispatch_id), keep candidate selection off full scans. All three are created on open with the other CREATE INDEX IF NOT EXISTS statements.
Under a long-running coordinator that opens one Run per job (about 350 Runs a day), orchestration.db grew about 7.5 MB an hour and reached 242 MB in a day. At 88 MB, orca terminal list took 12 s. By table at 88 MB: tasks 35 MB, messages 18 MB, federation_relay_items 9 MB with 2,452 rows of which all but 12 were acked, question_threads 8 MB, worker_terminal_resources 3 MB, and mutation_receipts 2.7 MB with 988 completed. The only way to shrink it was orca orchestration reset, which drops every Run, live ones included.
There is no VACUUM on this path: freed pages are reused by later writes, and auto_vacuum is off on these databases, so incremental_vacuum would do nothing.
A Run whose work Orca sees as settled can still be in use: an external coordinator keeps a job's Run id after the worker finishes, reuses it for the next worker-start --run <id>, and reads dispatch_not_found from worker-show as a dead lane. Deleting settled Runs that such a coordinator still referenced ended 72 live lanes on one machine. So retention never deletes a Run while any coordinator it bound is live, and the Dispatches of a kept Run stay with it. I did not add an explicit pin (a run-create --retain flag or a retain_until column): the coordinator binding already marks every Run such a coordinator uses, and a pin adds CLI, RPC and schema surface that no caller sets yet. A coordinator that runs outside any Orca terminal or session has no binding to protect its Runs; if that case matters, a pin can follow.
orca orchestration run-list was also reported at 20.2 s on a 61.5 MB database at load 61, while orca terminal list took 0.28 s. Its query, SELECT * FROM runs ORDER BY created_at DESC, id DESC LIMIT ?, scans 387 rows and sorts them in a temporary B-tree. On a 72 MB copy that took 12 ms cold and under 1 ms warm, and neither the handler nor the CLI does a per-row lookup. Five back-to-back runs of the command against the live runtime took 0.20 to 0.40 s at load 17, and one orca terminal list in the same minute took 7.2 s. The 20 s was the runtime's main thread being busy rather than this query, so this PR leaves run-list as it is. What it does address is the size of the tables that other synchronous reads on that thread scan.
N/A: no UI change. The effect is a smaller database and faster orchestration reads.
Testing
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Every added test fails without this change and avoids the test anti-patterns
orchestration-retention.test.ts deletes a settled Run with all its rows and no removed-work records left, next to a live Run that stays. It also checks that a Run stays while any coordinator it bound is live, whether by handle, by run: mailbox or by pane. Other cases keep a Run while a live reader has unread mail in it, while it was touched inside the window, and while its worker terminal belongs to a live Run. The last two cases delete acked relay items except the newest of a stream, and orphaned worker rows with no records left behind.
I ran the same selection and delete SQL with sqlite3 against a copy of a real 64 MB database, with a one-hour window. It retired 124 of 359 Runs at 10 to 40 ms per transaction, and the expired-row passes deleted 1,292 relay items at 5 to 17 ms each. Afterwards integrity_check and foreign_key_check came back clean and the receipt ledger still matched its table. I did not run the vitest suite locally; CI covers it.
Risk
Level: Medium
The riskiest part is deleting a Run that is still in use. Every liveness check runs again inside the delete transaction, and recipient liveness is checked before the lock, with mail that arrives in between keeping the Run. A wrong verdict shows up as a Run missing from orca orchestration run-show a day after its last activity. Receipts now replay for 24 hours instead of 30 days, so a --retry-request older than that runs again instead of replaying. A revert stops retention; Runs it already deleted stay deleted.
AI Disclosure
Written with Claude Code (Claude Opus 5.5); the delete logic had one finder pass from OpenAI Codex (gpt-6.1-sol), whose findings are addressed in this diff. A second pass over the coordinator-binding rule and the julianday comparisons found two ways a live coordinator could look absent (a historical handle re-minted in the same pane, and a connected pane whose terminal has no handle yet), both fixed by checking panes directly.
Review
Cross-platform: SQLite and timers only; no paths or processes.
SSH/remote: remote-homed, peer and remote-owned Runs are excluded; relay streams keep their newest row so cursors and enqueue sequences continue.
Agents and integrations: none.
Performance: candidate selection over 359 Runs took 17 to 28 ms; each delete transaction holds the write lock for one Run.
UI quality: no UI. The setting has no Settings control yet.
Security: none.
Agent skill upstream boundary
Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
This PR is small and focused
I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
I stated the risk: what could break, for whom, and how to back it out
Before/after screenshots or videos attached for UI changes, or N/A with reason
Self-reviewed for correctness, security, and performance
Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)
The change adds configurable retention for settled orchestration runs, with a 24-hour default and a value of zero to keep records. Database operations select and delete eligible runs and expired orchestration rows, with checks for live parties and related records. A runtime scheduler runs cleanup periodically. Completed mutation receipts are compacted and now have a 24-hour age limit. The change also adds database indexes and retention tests.
Severity of issue fixed: High
Merge Risk: Low · up to 5018e
Mergeable with bounded follow-up: disabling Run retention leaves expired rows accumulating, and retries of compacted replies can return changed delivery timestamps. Preserve cleanup independently of Run retention and retain recorded delivery timestamps.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: a timer that deletes settled Runs and expired rows from the orchestration database. It follows the conventional-commit style. The title is a single sentence and does n…
Description check
The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #41756), Visual Proof (N/A with reason), Testing, Risk (Level: Medium with rollback notes), AI…
Linked Issues check
Test.
Out of Scope Changes check
Test.
Full details: Title check
Explanation
The title names the main change: a timer that deletes settled Runs and expired rows from the orchestration database. It follows the conventional-commit style. The title is a single sentence and does not list files. It omits the receipt compaction and the 24-hour receipt expiry, but those are secondary to the main change.
Full details: Description check
Explanation
The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #41756), Visual Proof (N/A with reason), Testing, Risk (Level: Medium with rollback notes), AI Disclosure, Review, Agent skill boundary, Notes, and Checklist. It is detailed and explains the mechanism, the alternatives considered, and the risks. Remaining gaps: the vitest suite was not run locally, the lint/typecheck/test/build checkbox is unchecked, and the 'Every added test fails without this change' claim is not verified.
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Functional Correctness · Quick win
Keep expired-row cleanup running when Run retention is 0.
When orchestrationRunRetentionHours is 0, the early return also skips deleteExpiredOrchestrationRows(). The setting documentation and the PR description limit 0 to Run retention. Acknowledged relay items and orphaned worker rows then receive no scheduled cleanup, and their growth continues.
Skip only the Run-deletion loop when the value is 0. Do not pass 0 to deleteExpiredOrchestrationRows(), because retentionAge(0) produces -0 hours. Run that cleanup with a separate nonzero window. The repository does not define that window, so choose its value explicitly.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Minor · Data Integrity & Integration · Quick win
Keep delivered_at in compacted receipt messages.
Compaction drops each embedded field that equals the stored row at compaction time. Expansion then takes that field from current storage. delivered_at can change after compaction. For example, a reply that is still unread after 15 minutes is compacted with delivered_at: null. A later delivery write can then set delivered_at. A retry of the same request ID inside the 24-hour window returns the new value, not the recorded null.
read is not part of this case. Receipt messages come from exposeMessage, which removes read before the response is recorded. The read condition in the earlier suggestion has no effect.
The loader in mutation-receipt-compaction.test.ts returns only id and body, so the test does not cover this path.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ELI5
Orca never threw away finished orchestration work, so its orchestration database kept growing until someone reset it. Now Orca deletes a finished Run's records a day after the Run was last touched, on its own, while it runs.
What Changed
orchestrationRunRetentionHours(default 24; 0 turns retention off). Each Run goes in its ownBEGIN IMMEDIATEtransaction, and the sweep yields to the event loop between Runs. A Run is kept while it has any of these:run_coordinator_handles, the currentcoordinator_handleand coordinator session, and every pane the Run's coordinators worked from (the Run's coordinator pane, Dispatch creator panes, Task creator panes, and the panes coordinator mail was sent from). A pane counts as live while a process holds it, even before its re-minted terminal has a handle, so a long-lived external coordinator such as a drive that reuses a Run id for its nextworker-startkeeps every Run it bound for as long as its terminal is opencurrent_deliverymail whose reader is still reachable: an open terminal, a waiter, or a structured session whose custody is notelsewhereremote_run_links,remote_placements,remote_dispatches,remote_owned_questions) Runs are never retiredtrg_runs_forget_removed_workdrops those records with the Run. A record the sweep leaves without an existing Run is deleted in the same transaction.(dispatch_id, direction)stream, because legacy enqueue numbers fromMAX(sequence); peer-run and peer-mail conversations are left alone. Worker rows, worker terminal archives and worker terminals whose Dispatch is gone are deleted, and so are removed-work records whose Run is gone.ensureMutationReceiptCapacitydelete, so the ledger triggers stay in step.orchestration.checkandorchestration.replyreceipts completed more than 15 minutes ago (MUTATION_RECEIPT_FULL_REPLAY_MINUTES), 256 rows per transaction, paged by rowid. Each embedded message keeps only its id and the fields its stored row does not repeat, such as a reportfollow_up, and a reply'squestion.answer_bodygoes when it equals the reply body. A--retry-requestreplay after that rebuilds each message from themessagestable, andorchestration.requestShowshows the rebuilt receipt. A message whose stored body differs from the receipt, or that is not stored here (peer-mail and remote-home replies), keeps its full receipt; every other method keeps its full receipt too. If a message is deleted before a late replay, the replay fails withoperation_unknowninstead of returning a result without it. On a copy of a live database holding 4 hours of receipts, compaction took 897 check receipts from 4,688,604 to about 298,521 bytes and 887 reply receipts from 1,655,931 to about 449,279 bytes, so 6.3 MB became 0.75 MB. 51 check messages whose stored body differed stayed full.julianday()on both sides, because these tables mixdatetime('now')and ISO timestamps. The receipt-expiry delete moved from a text comparison tojulianday(updated_at), served by a new expression indexidx_mutation_receipts_completed_age.question_threads(run_id)andworker_terminal_resources(origin_dispatch_id), keep candidate selection off full scans. All three are created on open with the otherCREATE INDEX IF NOT EXISTSstatements.OrchestrationMailboxDeliveryTargetgainsreachesOpenTerminal, sharing the owner lookupresolveTerminalalready did; pane liveness reuseshasLiveTerminalForPaneKey.Why
Under a long-running coordinator that opens one Run per job (about 350 Runs a day),
orchestration.dbgrew about 7.5 MB an hour and reached 242 MB in a day. At 88 MB,orca terminal listtook 12 s. By table at 88 MB:tasks35 MB,messages18 MB,federation_relay_items9 MB with 2,452 rows of which all but 12 were acked,question_threads8 MB,worker_terminal_resources3 MB, andmutation_receipts2.7 MB with 988 completed. The only way to shrink it wasorca orchestration reset, which drops every Run, live ones included.There is no
VACUUMon this path: freed pages are reused by later writes, andauto_vacuumis off on these databases, soincremental_vacuumwould do nothing.A Run whose work Orca sees as settled can still be in use: an external coordinator keeps a job's Run id after the worker finishes, reuses it for the next
worker-start --run <id>, and readsdispatch_not_foundfromworker-showas a dead lane. Deleting settled Runs that such a coordinator still referenced ended 72 live lanes on one machine. So retention never deletes a Run while any coordinator it bound is live, and the Dispatches of a kept Run stay with it. I did not add an explicit pin (arun-create --retainflag or aretain_untilcolumn): the coordinator binding already marks every Run such a coordinator uses, and a pin adds CLI, RPC and schema surface that no caller sets yet. A coordinator that runs outside any Orca terminal or session has no binding to protect its Runs; if that case matters, a pin can follow.orca orchestration run-listwas also reported at 20.2 s on a 61.5 MB database at load 61, whileorca terminal listtook 0.28 s. Its query,SELECT * FROM runs ORDER BY created_at DESC, id DESC LIMIT ?, scans 387 rows and sorts them in a temporary B-tree. On a 72 MB copy that took 12 ms cold and under 1 ms warm, and neither the handler nor the CLI does a per-row lookup. Five back-to-back runs of the command against the live runtime took 0.20 to 0.40 s at load 17, and oneorca terminal listin the same minute took 7.2 s. The 20 s was the runtime's main thread being busy rather than this query, so this PR leaves run-list as it is. What it does address is the size of the tables that other synchronous reads on that thread scan.Linked Issue
Fixes #41756
Visual Proof
N/A: no UI change. The effect is a smaller database and faster orchestration reads.
Testing
orchestration-retention.test.tsdeletes a settled Run with all its rows and no removed-work records left, next to a live Run that stays. It also checks that a Run stays while any coordinator it bound is live, whether by handle, byrun:mailbox or by pane. Other cases keep a Run while a live reader has unread mail in it, while it was touched inside the window, and while its worker terminal belongs to a live Run. The last two cases delete acked relay items except the newest of a stream, and orphaned worker rows with no records left behind.I ran the same selection and delete SQL with
sqlite3against a copy of a real 64 MB database, with a one-hour window. It retired 124 of 359 Runs at 10 to 40 ms per transaction, and the expired-row passes deleted 1,292 relay items at 5 to 17 ms each. Afterwardsintegrity_checkandforeign_key_checkcame back clean and the receipt ledger still matched its table. I did not run the vitest suite locally; CI covers it.Risk
Level: Medium
The riskiest part is deleting a Run that is still in use. Every liveness check runs again inside the delete transaction, and recipient liveness is checked before the lock, with mail that arrives in between keeping the Run. A wrong verdict shows up as a Run missing from
orca orchestration run-showa day after its last activity. Receipts now replay for 24 hours instead of 30 days, so a--retry-requestolder than that runs again instead of replaying. A revert stops retention; Runs it already deleted stay deleted.AI Disclosure
Written with Claude Code (Claude Opus 5.5); the delete logic had one finder pass from OpenAI Codex (gpt-6.1-sol), whose findings are addressed in this diff. A second pass over the coordinator-binding rule and the
juliandaycomparisons found two ways a live coordinator could look absent (a historical handle re-minted in the same pane, and a connected pane whose terminal has no handle yet), both fixed by checking panes directly.Review
Agent skill upstream boundary
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)