Skip to content

fix(orchestration): stop retiring a Run on any write to it between pages - #43885

Merged
brennanb2025 merged 11 commits into
mainfrom
brennanb2025/run-retirement-mid-yield-guards
Nov 18, 2026
Merged

brennanb2025 merged 11 commits into
mainfrom
brennanb2025/run-retirement-mid-yield-guards

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Orca's background cleanup deletes finished orchestration Runs a day after their last activity, one small page at a time. Between pages, a few things could slip through: a Task result corrected in place, an agent starting to wait on the Run's mailbox, or a Delivery acknowledged. The next page then went on deleting the Run's records anyway, including the corrected result. Now any write to the Run, or a reader starting to wait on its mail, stops the cleanup before the next page, and the Run is kept.

What Changed

  • Any write to a Run stops its retirement. While one Run is being retired, connection-local triggers on every table the retirement deletes or reads mark the Run as written. That includes inserts, in-place updates such as a completed -> completed Task result correction or a Delivery acknowledgment, and deletes. Each page, and the final Run-row delete, stops if the Run was written since the previous page. Rows are keyed to the Run or to one of its Dispatches or legacy principals; those keys are snapshotted when the watch starts, so they still match after their parent rows are deleted. The triggers are connection-local: nothing persists in the file, so older builds are unaffected,, they roll back with their write, and a WHEN gate skips their body unless a retirement is running. They see every write because the runtime is the database's only writer connection.
  • This replaces the per-page touch mark. The mark only saw a newer runs.updated_at, newer rows or reopened work, and re-read several aggregates on every page.
  • A reader that starts waiting mid-retirement stops it. Each page, and the final Run-row delete, checks the few mailboxes a reader is blocked on (for example a pane-less orca orchestration check --peek --wait). One counts when it is among the Run's parties, or is the Run's own or one of its Dispatches' mailbox.
  • Final check uses a Set. The last party comparison was Array.includes per party inside the write transaction. It is now a Set lookup.
  • Clean stop. When maintenance stops mid-Run it closes the retirement steps, so the watch never stays armed.
  • RuntimeMessageWaiters.has() replaces two copies of the same waiter check.

Boundary

Pages committed before a write are not restored. A write stops the next page, not earlier ones. That is the same paging trade-off #43550 made to keep main-thread pauses short. Restoring them would need staged, reversible deletes.

Deferred

  • A structured send reserved for a message retirement already deleted, through a direct session or worker mailbox, can leave one stale structured_mail_sends row. No data is lost: the message is already gone. Making reservations require their message changes the store's behavior for other callers, so it is left for a follow-up (tracked in STA-16052).
  • A waiter on a free-form handle that equals one of the Run's internal principal: keys would keep the Run while it waits. It can only keep a Run longer, never delete one wrongly (tracked in STA-16053).

Why

Tracked in STA-15856 (a corrected Task result deleted with the Task), STA-15855 (a pane-less mailbox reader not stopping the page deletes) and STA-15748 (quadratic party matching in the final check). The Delivery-acknowledgment, relay-item and remote-question cases came up in review and are in the same class.

Verification

  • Tests: settled-run-retention.test.ts adds two scenarios. In one, a Task result is corrected between pages, and the Run keeps its Task, the corrected result, its Dispatch and its mail. In the other, a reader starts waiting on the Run mailbox between pages, and the Run keeps its mail. With the source reverted to main, both fail and the other 12 pass.
  • Checks: pnpm check:changed passes on the exact head 477e8d3 (25 checks, run on Linux).
  • Final party check (STA-15748): timed on Linux with the current retirement, Set vs main's includes. The final step takes 1.0–2.2 ms with either at 1,003, 5,003 and 20,003 parties. Since fix(orchestration): retire settled Runs a page at a time so the main thread never stalls #43550's paging, the Run's child rows are already gone by the final check, so it compares only the few parties the Run row still names. The quadratic case no longer happens on main; the Set just keeps it O(n).
  • Perf: A/B of the retention pass, main vs this head. On a quiet machine the head matches main: 1 one-second window over 100 ms each, worst pause 229–279 ms, the same CPU and writes, and the same idle CPU, heap, writes and wakeups. A real 1,842-worktree profile shows the same work. Tables are in the PR comments.

Notes

  • Reviewed in six passes by independent reviewers, with a design council on how to detect in-place writes. The options were per-page stamps, indexed stamps, persistent triggers that touch the Run, connection-local triggers, and a fence that makes writers refuse a retiring Run. Connection-local triggers won: they are O(1) per page, persist nothing, and change no writer's behavior.

… connection-local write watch

Replaces the per-page touch mark and stamp checks: every page and the Run row now stop if anything wrote to the Run since the last page, including writes in place.
…ed trigger targets; key orphan-prone children by principal and mailbox
@brennanb2025
brennanb2025 marked this pull request as draft November 18, 2026 03:44
@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Settled-run retirement now checks for database writes and live mailbox readers during page processing and before deleting a Run. The change adds connection-local mutation tracking, exposes mailbox-waiter handle checks, and adds tests for a reader appearing or a task result changing between pages. Maintenance also attempts to close retirement steps when stopped.

Merge Risk: Low · up to 8b2da

Retirement now keeps a Run whose Run or Dispatch mailbox has a waiting reader, and it stops when watched rows are written between pages. One narrow issue remains. While a Run is being retired, replacing a terminal archive for one of its Dispatches can fail with a unique-constraint error. It is limited to that window and the earlier archive row is kept. Fix it before merge or accept it explicitly.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the repository template and explains the change, its risks, and a deferred stale-row case. It lacks several required items: a linked issue, a Visual Proof statement, a Risk sec… Add or fix these items: (1) Add a real issue reference in the Linked Issue section using “Fixes #”. The tracker IDs in Why are not sufficient. (2) Write “N/A” in Visual Proof and give a short reason, because the change has no UI eff…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names the main change: a Run is no longer retired when any write to it happens between pages. The changeset adds write-watch triggers, a live-reader check, and the page-stop logic that match…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: a Run is no longer retired when any write to it happens between pages. The changeset adds write-watch triggers, a live-reader check, and the page-stop logic that match this. The title follows the conventional commit format and is specific. It does not cover the secondary changes (Set lookup, RuntimeMessageWaiters.has(), clean stop), which is expected.

Full details: Description check

Explanation

The description follows the repository template and explains the change, its risks, and a deferred stale-row case. It lacks several required items: a linked issue, a Visual Proof statement, a Risk section and back-out plan, an AI Disclosure answer, an Agent skill upstream boundary checkbox, and completed Testing checklist items. It does not state whether macOS, Windows, or SSH were tested. It also contains the typo “unaffected,,”.

Resolution

Add or fix these items: (1) Add a real issue reference in the Linked Issue section using “Fixes #<number>”. The tracker IDs in Why are not sufficient. (2) Write “N/A” in Visual Proof and give a short reason, because the change has no UI effect. (3) Add a Risk section. State the Level as Low, Medium, or High. Describe the riskiest part, the user-visible failure impact, and the back-out method. State that a plain revert does not undo any specified effects. (4) Complete the AI Disclosure section, or leave it blank if the author is a StablyAI team member. (5) Complete the Agent skill upstream boundary checkbox. (6) Tick the applicable Testing checklist items and state which platforms were tested, including whether testing was limited to Linux. (7) Replace “unaffected,,” with “unaffected,”.

  • 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

Recent 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: 97e8ae8f-5d78-4ece-8b75-0032183464f5
Commits

Reviewing files that changed from the base of the PR and between 5cf633c and 8b2dac1.

Files selected for processing: 3

  • src/main/runtime/orchestration/db/maintenance/run-retirement-write-watch.ts
  • src/main/runtime/orchestration/db/maintenance/settled-run-retention.test.ts
  • src/main/runtime/orchestration/db/maintenance/settled-run-retirement.ts

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

@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: 1b21d427-d5b0-41e7-a739-43eeb382f1ce
Commits

Reviewing files that changed from the base of the PR and between 80c7d95 and 477e8d3.

Files selected for processing: 8

  • src/main/runtime/construction/runtime-service-state.ts
  • src/main/runtime/orchestration/db/maintenance/orchestration-db-maintenance.ts
  • src/main/runtime/orchestration/db/maintenance/run-retirement-write-watch.ts
  • src/main/runtime/orchestration/db/maintenance/settled-run-retention.test.ts
  • src/main/runtime/orchestration/db/maintenance/settled-run-retirement.ts
  • src/main/runtime/orchestration/db/projection-mutation-triggers.ts
  • src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts
  • src/main/runtime/orchestration/mailbox/runtime-message-waiters.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh reviewer, full perf-scan on the PR diff at 6379c1e; builds on an earlier full scan of 69127af that also passed).

PERF-SCAN: PASS. Reviewed all eight changed files, building on the earlier scan after confirming the repair changes only the snapshot predicate. Six-question dispositions: admission is gated before trigger bodies; ownership is once per connection; synchronous SQLite uses indexed probes; pages advance and snapshot work matches required output; no new host-dependent work exists; finally/stop/close release watch state. Touched regression classes—synchronous SQLite, hot-path rescans, and entity lifetime—show no introduced amplification. Cadence is unchanged. For 1,200 Runs, the repaired principal branch performs 2,400 seeks plus matching-row visits; at 10×, 24,000 seeks, replacing repeated global scans. Pre-existing principal cleanup scans remain at settled-run-retirement.ts:14,32–34: each scan can visit all L principals per invocation, including receipt pages; unchanged by this span. Evidence is source inspection and isolated EXPLAIN, without builds, tests, app execution, or timing claims.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Benchmark: head=477e8d32c4173fdf4a10853ee9af954b3afef65e gate=PASS listeners=none (main-process maintenance only; no publication or subscription changed)

Retention pass A/B, main (d01558a) vs this head. Each arm ran the app for 900 s against a 1.7 GB orchestration.db with 1,226 settled, aged Runs (132,663 messages, 15,322 Dispatches). Every arm deleted 1,225 of them. Event-loop delay was measured in 1 s windows on the main process; idle is 419–899 s.

Quiet machine (M4Air, load 3–9), synthetic database with the real shape

arm load (pass) pass: 1 s windows > 100 ms > 50 ms worst pause pass main CPU-s pass disk writes idle main CPU idle heap (median) idle disk writes idle wakeups/s idle windows > 100 ms
main #1 5.1 1 3 267 ms 13.0 6.8 GB 0.65% 70 MB 13.6 kB/s 188 1
head 4.1 1 2 279 ms 14.2 6.9 GB 0.56% 69 MB 13.5 kB/s 207 0
main #2 9.0 1 9 229 ms 18.2 7.0 GB 0.72% 70 MB 13.6 kB/s 210 0

Real 1,842-worktree profile (this Mac, load 11–41)

arm load (pass) pass: windows > 100 ms worst pause pass main CPU-s pass disk writes
main #1 27 6 3,910 ms 31.0 7.1 GB
head 41 7 227 ms 31.1 7.2 GB
main #2 11 0 28 ms 15.0 6.7 GB
  • Same stall profile as main. On the quiet machine, the head's pass matches both main arms: one window over 100 ms each, worst pause 229–279 ms. fix(orchestration): retire settled Runs a page at a time so the main thread never stalls #43550's stall win holds.
  • The write watch costs nothing measurable. Pass CPU and writes match main on both machines. Idle CPU, heap, writes and wakeups match on the quiet machine.
  • Caveat on the real-profile run: the machine's load swung from 11 to 41 between arms, so those stall numbers can't be compared with each other. The head arm's idle window there was lost: its app was stopped by a signal 7 minutes in, after the pass had finished. The quiet-machine run covers idle.
  • Final party check (STA-15748), timed on Linux: 1.0–2.2 ms for the final step, with the Set or with main's includes, at 1,003 / 5,003 / 20,003 parties.

@brennanb2025

brennanb2025 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status

Problem: Orca's hourly cleanup deletes a settled orchestration Run a page at a time, yielding between pages. A write made in place during a yield was invisible to the per-page check: for example a completed -> completed Task result correction, or a Delivery acknowledged in place. So was a reader that started waiting on the Run's mailbox without a pane. The next pages kept deleting, and the corrected result went with its Task.

Change for users: a Run that anything writes to, or that a reader starts waiting on, while it is being cleaned up is kept. Its corrected results and its mail survive, and the next hourly pass picks it up once it is quiet again.

Fixed: STA-15856 (in-place Task correction), STA-15855 (pane-less mailbox reader) and STA-15748 (the final party check is now a Set lookup). The benchmark shows that on main that check is already linear, because #43550's paging deletes the child rows first. Review also found the same gap for a Delivery acknowledgment, a new relay item and a remote question; all are covered by the same mechanism. A reader waiting on one of the Run's Dispatch mailboxes now counts too (8b2dac1, found in review; the test covers both mailbox kinds and fails without the fix).

Design: a council of three fresh agents (Claude + 2x Codex) chose connection-local write detection (TEMP triggers, gated, keyed to the retiring Run and its Dispatches and legacy principals) over per-page stamps, indexed stamps, persistent triggers that touch the Run, and a writer fence. It is O(1) per page, persists nothing in the file, and changes no writer's behavior.

Deferred:

  • Pages committed before a write are not restored: the write stops the next page. This is the paging trade-off fix(orchestration): retire settled Runs a page at a time so the main thread never stalls #43550 made.
  • A send reserved for a message that retirement has already deleted, through a direct session or worker mailbox, can leave one stale structured_mail_sends row. No data is lost; this is a follow-up (tracked in STA-16052).
  • A waiter on a free-form handle that equals one of the Run's internal principal: keys would keep the Run while it waits. Nothing creates such a handle, and this can only keep a Run longer, never delete one wrongly (tracked in STA-16053).

Verified:

  • Two new tests fail with the source reverted to main (other 12 pass).
  • pnpm check:changed: 25/25 on 477e8d3. I didn't run it on the final merge with main (bc4e872) because the remote check machine was down. That merge resolved one comment-only conflict, and PR CI is the gate for it. A static-analysis ratchet from main (blocking helpers per file) then needed one helper generator folded back into retireSettledRun (5cf633c, behavior-preserving, reviewed clean).
  • Review passes through 8b2dac1. Claude Opus was clean. Codex gpt-6.1-sol was clean except the deferred principal-key note above. Both perf-scans passed.
  • perf-scan PASS (posted above).
  • A/B of the retention pass, posted above: three quiet-machine runs, two of them at the final head, plus the real 1,842-worktree profile. Work and idle cost match main. The worst pause stays within main's range. Each head arm had one window over 100 ms (132–279 ms), at the moment the pass starts; main arms had 0–1.

@brennanb2025
brennanb2025 marked this pull request as ready for review November 18, 2026 13:49
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan of 5cf633c (fresh reviewer): this commit keeps the write watch inside retireSettledRun so the main-blocking-helper ratchet counts one function, as before. The change is behavior-preserving.

  • All return values and yield positions are preserved: sender-page yields, child-delete yields, and the final deletion yield remain in the same order.
  • In settled-run-retirement.ts:219–220, finally unwatches on normal completion, either in-body return false, transaction rejection, or a thrown error. Maintenance’s steps.return(false) (orchestration-db-maintenance.ts:130) runs that cleanup at every suspension point, just as delegated-generator closure did previously.
  • The initial non-retired return (settled-run-retirement.ts:137–140) still occurs before watching. Closing an unstarted generator creates no watch. Errors during watch setup remain outside try, unchanged.
  • Performance screen: admission gates, hourly cadence, synchronous SQLite operations, page bounds/progress, cache invalidation, and watcher lifetime are unchanged. No new host-specific work or ownership multiplication. The refactor removes one helper-generator allocation per eligible run and its delegation overhead; database work counts remain identical at N and 10N.
  • Static review only; no builds or tests run.

PERF-SCAN: PASS

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Remove the duplicate dirty-key insert from the write watch. · run-retirement-write-watch.ts:6-7

src/main/runtime/orchestration/db/maintenance/run-retirement-write-watch.ts:6-7
Minor · Data Integrity & Integration · Quick win

Remove the duplicate dirty-key insert from the write watch.

While a Run is retiring, replacing the archive of a watched Dispatch fails. The update trigger runs two INSERT OR IGNORE statements for the same dispatch:<id> key. The upsert in storeWorkerTerminalArchive overrides the trigger's OR IGNORE, so the second insert raises UNIQUE constraint failed: run_retirement_dirty.key. The archive keeps its previous row. The error reaches the stop and release callers.

In watched, guard each dirty-table insert with NOT EXISTS (SELECT 1 FROM run_retirement_dirty WHERE key = <key>). Use a plain INSERT with that guard. OR IGNORE does not prevent the error.

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: 4a2c4d09-2fcf-493d-9887-f78a1c34b942
Commits

Reviewing files that changed from the base of the PR and between bc4e872 and 5cf633c.

Files selected for processing: 1

  • src/main/runtime/orchestration/db/maintenance/settled-run-retirement.ts

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

@brennanb2025

brennanb2025 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Perf scan of 8b2dac1 (fresh reviewer). It covers 5cf633c and 8b2dac1 and builds on the full scans of 69127af and 6379c1e above, which cover every file in the diff. Surfaces from perf-surface-detect: hot-path.

Perf. Each page looks up each waited mailbox once, by primary key, in a small TEMP table (one row for the Run plus one per Dispatch). Few waiters exist at a time, and the statement is served from the SyncDatabase.statementCache (sync-database.ts:98). The number of pages per Run is bounded by rows/128. This doesn't grow with the fleet, nothing repeats on its own, nothing new runs on idle, and the main-thread cost per step is fixed and in the microseconds. No regression class from the scan list applies.

PERF-SCAN: PASS

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Benchmark: head=8b2dac1a834af471601cc6222e1f463e9ae70800 gate=PASS listeners=none (main-process maintenance only; no publication or subscription changed)

Retention pass A/B at the current head, main (d01558a) vs 8b2dac1, run twice on a quiet machine (M4Air, load 3–7). Same setup as the earlier comment: a 1.7 GB synthetic database with the real shape, 900 s per arm. Every arm deleted 1,225 of 1,226 Runs.

run arm load (pass) pass: 1 s windows > 100 ms > 50 ms worst pause pass main CPU-s pass disk writes idle main CPU idle heap idle writes idle windows > 100 ms
2 main 2.9 0 4 96 ms 18.6 6.9 GB 0.53% 70 MB 13.5 kB/s 0
2 head 2.6 1 2 132 ms 17.9 7.0 GB 0.97% 73 MB 13.5 kB/s 0
2 main 3.0 0 1 63 ms 17.7 6.9 GB 1.02% 71 MB 13.6 kB/s 0
3 main 5.4 0 2 62 ms 12.0 6.7 GB 0.64% 71 MB 12.1 kB/s 0
3 head 7.2 1 8 159 ms 16.1 7.0 GB 0.93% 72 MB 13.4 kB/s 0
3 main 6.4 1 5 119 ms 14.2 6.8 GB 1.01% 69 MB 13.6 kB/s 0
  • Work and idle cost match main: CPU, writes, heap and wakeups are within the spread of the main arms.
  • Windows over 100 ms: across the three quiet runs (this one, and 477e8d3 in the earlier comment), each head arm had exactly one window over 100 ms. The main arms had 0 or 1. Each of the head's slow windows is the window when the first maintenance pass starts (about 60 s after launch); a main arm also has one there (119 ms).
  • Not the triggers: timed in a test, installing the write-watch triggers on first use takes 3–4 ms, and later watches take under 0.1 ms.
  • Worst pause (132–279 ms across head runs) stays within main's range (62–267 ms), and the delete span is the same, so fix(orchestration): retire settled Runs a page at a time so the main thread never stalls #43550's stall win holds.

@brennanb2025
brennanb2025 merged commit edac85a into main Nov 18, 2026
46 checks passed
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.

1 participant