Skip to content

perf(orchestration): delete settled Runs and expired rows from the orchestration database on a timer - #41757

Closed
yasyf wants to merge 1 commit into
stablyai:mainfrom
yasyf:orch-db-retention
Closed

yasyf wants to merge 1 commit into
stablyai:mainfrom
yasyf:orch-db-retention

Conversation

@yasyf

@yasyf yasyf commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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

  • 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.
  • OrchestrationMailboxDeliveryTarget gains reachesOpenTerminal, sharing the owner lookup resolveTerminal already did; pane liveness reuses hasLiveTerminalForPaneKey.

Why

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.

Linked Issue

Fixes #41756

Visual Proof

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)

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

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: Passed 4

Check name Status Explanation
Title check Passed 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 Passed 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 Passed Test.
Out of Scope Changes check Passed 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.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 39cfa121-c7af-44dc-9876-b43afb48a7cd
Commits

Reviewing files that changed from the base of the PR and between 309975d and 63f4549.

Files selected for processing: 12

  • src/main/runtime/construction/runtime-store-contract.ts
  • src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-capacity.ts
  • src/main/runtime/orchestration/db/orchestration-db-methods.ts
  • src/main/runtime/orchestration/db/orchestration-db.ts
  • src/main/runtime/orchestration/db/retention/orchestration-retention.test.ts
  • src/main/runtime/orchestration/db/retention/orchestration-retention.ts
  • src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts
  • src/main/runtime/orchestration/mailbox/routing/mailbox-delivery-target.ts
  • src/main/runtime/orchestration/retention/orchestration-retention-scheduler.ts
  • src/main/runtime/workspaces/persisted-surfaces/orchestration-database-binding.ts
  • src/shared/global-settings-types.ts

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

Comment on lines +53 to +54
if (retentionHours === 0) {
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

@yasyf
yasyf force-pushed the orch-db-retention branch from 63f4549 to 28cd4ec Compare November 13, 2026 02:57
@yasyf
yasyf force-pushed the orch-db-retention branch from 28cd4ec to 5018eb5 Compare November 13, 2026 10:50

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0992b056-729e-46a9-acd9-3f483c5e7f6d
Commits

Reviewing files that changed from the base of the PR and between 28cd4ec and 5018eb5.

Files selected for processing: 7

  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-compaction.test.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-compaction.ts
  • src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-store.ts
  • src/main/runtime/orchestration/retention/orchestration-retention-scheduler.ts
  • src/main/runtime/rpc/methods/orchestration/messaging/mailbox-message-receipt.ts
  • src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts
  • src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-executor.ts

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

Comment on lines +37 to +38
const kept = Object.entries(message).filter(
([key, value]) => key === 'id' || !(key in stored) || !sameValue(stored[key], value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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.

Suggested fix

--- "a/src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-compaction.ts"
+++ "b/src/main/runtime/orchestration/db/mutation-receipts/mutation-receipt-compaction.ts"
@@ -34,9 +34,13 @@
   if (!stored || !sameValue(stored.body, message.body)) {
     return undefined
   }
   const kept = Object.entries(message).filter(
-    ([key, value]) => key === 'id' || !(key in stored) || !sameValue(stored[key], value)
+    ([key, value]) =>
+      key === 'id' ||
+      key === 'delivered_at' ||
+      !(key in stored) ||
+      !sameValue(stored[key], value)
   )
   return { ...Object.fromEntries(kept), id: message.id }
 }
 
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
const kept = Object.entries(message).filter(
([key, value]) => key === 'id' || !(key in stored) || !sameValue(stored[key], value)
const kept = Object.entries(message).filter(
([key, value]) =>
key === 'id' ||
key === 'delivered_at' ||
!(key in stored) ||
!sameValue(stored[key], value)

@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks so much for this, @yasyf! This change landed in #43322, which carries your work forward with co-author credit. Closing this one in favor of it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] orchestration.db grows without bound: finished Runs, completed receipts and acked relay items are never deleted

2 participants