Repository navigation
fix(orchestration): preserve mailbox delivery identity - #13717
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis change adds run- and dispatch-scoped mailbox routing with coordinator-handle history, indexed queries, paginated reconciliation, ownership fencing, waiter filtering, and delivery-state tracking. PTY providers now return synchronous write status and support asynchronous settlement. Runtime mailbox delivery delegates to dedicated ownership, notification, pointer-delivery, and pointer-state components. RPC, federation, migration, integration, E2E, and reliability-gate tests cover routing, rebinding, restart recovery, acknowledgments, cancellation, transport failure, and bounded delivery. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
src/main/runtime/orchestration-mailbox-notification-consistency.test.ts (1)
263-270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winVerify this checks the production revalidation path, not a synthetic query.
This block builds its own SQL with an
INDEXED BY idx_messages_idhint and runsEXPLAIN QUERY PLANagainst it.INDEXED BYforces SQLite to use the named index. The assertion at line 270 only proves the index exists in the schema. It does not prove that the actual submit-time revalidation code in the application uses this index.Replace this with a check on the real revalidation code path, for example by spying on the database method that Orca calls during submit-time revalidation. Alternatively, remove the
INDEXED BYhint so the query plan reflects the planner's natural choice.src/main/runtime/orca-runtime.test.ts (1)
18689-18689: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winWeak delivered_at assertions recur across
orca-runtime.test.tsandterminal-send-stale-leaf-liveness.test.ts. Both files add new assertions ondelivered_atusing.not.toBeNull()or!== null, which pass forundefinedas well as a genuinely set value.orchestration-mailbox-notification-consistency.test.tsin this same PR already uses the strongerexpect.any(String)pattern for the identical check.
src/main/runtime/orca-runtime.test.ts#L18689-L18689: replace this and the other 12.not.toBeNull()occurrences at lines 18735, 18776, 33640, 33691, 33817, 33864, 33970, 34152, 34206, 34255, 34386, and 34397 withexpect(...).toEqual(expect.any(String)).src/main/runtime/terminal-send-stale-leaf-liveness.test.ts#L506-L589: replace the!== nullchecks at lines 506 and 543, and the.not.toBeNull()check at line 589, with the same stronger form.src/main/runtime/terminal-send-stale-leaf-liveness.test.ts (1)
506-506: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winStrengthen the delivered_at assertions.
These assertions use
!== nullor.not.toBeNull(). Both pass forundefinedas well as a genuinely set value. Ifdelivered_atis ever omitted from the row instead of set, these checks still pass.Use
expect(...).toEqual(expect.any(String))for a precise check that the field holds a real timestamp string.Also applies to: 543-543, 589-589
config/reliability-gates.jsonc (1)
7497-7535: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd evidence for the second registered command.
This gate lists two "commands" entries. The second command runs
orca-runtime.test.ts,terminal-send-stale-leaf-leaf-liveness.test.ts, andrpc/methods/orchestration.test.ts, and these three files also appear in "testFiles". However, "evidenceRuns" contains only one recorded run, matching the first command, and "assertionRefs" cites onlyorchestration-mailbox-notification-consistency.test.ts.Add an evidenceRun entry for the second command, or add assertionRefs justifying why those three files belong to this gate. Without this, the gate's evidence trail does not show that the second command was actually executed for this gate.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 2d7123f9-7b29-4ba1-adc9-c655c55aa26b
📒 Files selected for processing (6)
config/reliability-gates.jsoncsrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-mailbox-notification-consistency.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/terminal-send-stale-leaf-liveness.test.ts
|
CodeRabbit follow-up is in 03f5543. In addition to the three resolved threads, this strengthens every new |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 21627da4-24d0-4e78-90ba-36a69bb48223
📒 Files selected for processing (7)
config/reliability-gates.jsoncsrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-mailbox-notification-consistency.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/orchestration-worker-dispatch-db.test.tssrc/main/runtime/terminal-send-stale-leaf-liveness.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
- src/main/runtime/orca-runtime.test.ts
- src/main/runtime/orchestration/db.ts
03f5543 to
6aa9190
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/runtime/orchestration/db.ts (1)
1407-1418: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winGuard
idx_messages_undelivered_direct_runondelivery_contract.A pre-v19 database can contain
delivered_atwithoutdelivery_contract. SincecreateTables()calls this method beforemigrateLegacyContractStorage(), SQLite raisesno such column: delivery_contract, and theOrchestrationDbconstructor fails. Check both columns before creating the partial index;migrate()retries after addingdelivery_contract.src/main/ipc/pty.ts (1)
5334-5340: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winPropagate
provider.writefailures through the renderer write helpers.
writePtyProviderInputWithinLimitandwritePtyProviderInputChunksdiscardprovider.writeresults. Afalseresult therefore makespty:writeAcceptedreturntrueand suppressespty:writeUnavailable. Match the!== falsehandling at line 5336.
🧹 Nitpick comments (1)
src/main/runtime/orchestration/formatter.test.ts (1)
189-190: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for a non-
run:mailbox handle.The new conditional in
formatMessagePointerhas three branches:run:prefix, other prefix, and no handle. Line 189 covers therun:branch and line 195 covers the no-handle branch. Adispatch:handle must produce no--runflag, and that branch is not asserted.💚 Proposed additional assertion
expect(formatMessagePointer(1, 'run:run_1')).toBe( '\nYou have 1 orchestration message. Run `orca orchestration check --run run_1`.\n' + ) + expect(formatMessagePointer(1, 'dispatch:dispatch_1')).toBe( + '\nYou have 1 orchestration message. Run `orca orchestration check`.\n' )
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 821cc901-474a-4670-a83c-dd310d191179
📒 Files selected for processing (21)
config/reliability-gates.jsoncsrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/ipc/pty.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/pty-provider-contract.tssrc/main/providers/ssh-pty-provider.test.tssrc/main/providers/ssh-pty-provider.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-mailbox-notification-consistency.test.tssrc/main/runtime/orchestration-mailbox-notification-test-harness.tssrc/main/runtime/orchestration-mailbox-routing-races.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/formatter.test.tssrc/main/runtime/orchestration/formatter.tssrc/main/runtime/orchestration/orchestration-worker-dispatch-db.test.tssrc/main/runtime/rpc/methods/orchestration.tssrc/main/runtime/terminal-send-stale-leaf-liveness.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
5064ae4 to
8e40a38
Compare
8e40a38 to
481d8bb
Compare
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)
3960-3977: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winGuard
scheduleRestoredMessageRepointsagainst a throwing database read.
getOrchestrationDbandsetOrchestrationDbcallscheduleRestoredMessageRepointssynchronously. That method callsgetUndeliveredUnreadMailboxHandlesandrouteDetachedDirectMessages, which read the database. If either throws, the exception escapesgetOrchestrationDb, and every unrelated caller that only wants the database handle fails.
repointPendingMessagesForHandleat Line 32427 already wraps its delivery call for this reason. Apply the same isolation here.🛡️ Proposed fix
private scheduleRestoredMessageRepoints(): void { - const handles = this._orchestrationDb?.getUndeliveredUnreadMailboxHandles?.() ?? [] + let handles: string[] = [] + try { + handles = this._orchestrationDb?.getUndeliveredUnreadMailboxHandles?.() ?? [] + } catch { + // A failed restore scan must not break database attach. + return + } for (const handle of handles) { if (handle.startsWith('dispatch:')) { continue } if (handle.startsWith('run:')) { this.mailPointerRepointScheduler.schedule(handle) continue } - const routed = this.orchestrationMailboxOwner.routeDetachedDirectMessages(handle) + let routed: ReturnType< + OrchestrationMailboxOwner['routeDetachedDirectMessages'] + > + try { + routed = this.orchestrationMailboxOwner.routeDetachedDirectMessages(handle) + } catch { + this.mailPointerRepointScheduler.schedule(handle) + continue + }
🧹 Nitpick comments (7)
src/main/runtime/orchestration-mailbox-detached-routing.test.ts (1)
174-204: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace the manual microtask loop with
vi.waitFor.Lines 185-190 poll
messageWaitersByHandlewith a fixed count ofawait Promise.resolve(). The same file already usesvi.waitForat Line 214 for the identical condition. Usevi.waitForhere to keep one waiting idiom and to avoid a flake if waiter installation needs more microtask turns.src/main/runtime/orchestration-mailbox-notification-consistency.test.ts (1)
40-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winClose the SQLite handle in
afterEachacross the new mailbox test files. Every test callsdb.close()as its last statement, so the handle leaks whenever an earlier assertion fails.rmSyncthen fails on Windows because the SQLite file is still locked, and that secondary failure hides the original assertion error.
src/main/runtime/orchestration-mailbox-notification-consistency.test.ts#L40-L45: track the openOrchestrationDbin a describe-scoped variable and close it in the hook beforermSync.src/main/runtime/orchestration-mailbox-detached-routing.test.ts#L28-L33: apply the same hook change and drop the per-testdb.close()calls.src/main/runtime/orchestration-mailbox-routing-races.test.ts#L31-L35: apply the same hook change, and addvi.useRealTimers()andvi.restoreAllMocks()to match the sibling files.src/main/runtime/orchestration-message-delivery-identity.test.ts#L168-L173: close the databases created bycreateDatabasein the hook; the CLI test already usestry/finallyand needs no change.src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts (1)
12-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
tempDiris not cleared after removal.The hook removes
tempDirbut leaves the variable set. If a later test throws before Line 20 assigns a new value, the hook removes the same path again.rmSyncwithforce: truetolerates the missing path, so behavior is safe today. Clear the variable to keep the hook state accurate.♻️ Proposed cleanup
afterEach(() => { db?.close() + db = undefined if (tempDir) { rmSync(tempDir, { recursive: true, force: true }) + tempDir = undefined } })src/main/runtime/rpc/methods/orchestration.test.ts (1)
1307-1316: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe
waitForMessagemock ignores the arguments the handler passes.The mock always inserts a
worker_donemessage and returns'notified'. It does not readtypeFilter,exclusive, ortimeoutMs. The test therefore proves the peek re-read path, but not that the handler forwards the filter. Assert on the received options to cover the contract.♻️ Suggested assertion
- vi.spyOn(runtime, 'waitForMessage').mockImplementation(async () => { + const waitSpy = vi.spyOn(runtime, 'waitForMessage').mockImplementation(async () => { arrivedId = db.insertMessage({expect(peeked).toMatchObject({ count: 1, messages: [{ id: arrivedId }] }) + expect(waitSpy).toHaveBeenCalledWith( + `run:${activeRunId}`, + expect.objectContaining({ typeFilter: ['worker_done'] }) + )src/main/runtime/orchestration/db.ts (1)
2616-2639: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueWrap the trigger swap in one transaction.
createCoordinatorMailRoutingTriggerrunsDROP TRIGGERandCREATE TRIGGERas two statements in autocommit mode. A second process that inserts a message during the gap skips canonicalization. Detached-mail reconciliation recovers those rows later, so the impact is bounded, but the gap is avoidable.♻️ Proposed change to make the swap atomic
private createCoordinatorMailRoutingTrigger(): void { this.db.exec(` + BEGIN IMMEDIATE; DROP TRIGGER IF EXISTS trg_messages_route_coordinator_mail; CREATE TRIGGER trg_messages_route_coordinator_mail AFTER INSERT ON messagesBEGIN UPDATE messages SET to_handle = 'run:' || NEW.run_id WHERE sequence = NEW.sequence; END; + COMMIT; `) }src/main/providers/ssh-pty-write.test.ts (1)
41-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRestore real timers in an
afterEachhook.Both tests call
vi.useRealTimers()as the last statement. If an assertion fails before that line, fake timers stay installed and leak into the following tests in this worker. AnafterEachhook restores them on every exit path.♻️ Proposed refactor
-import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { SshPtyProvider } from './ssh-pty-provider' import { SSH_PTY_WRITE_SETTLEMENT_TIMEOUT_MS } from './ssh-pty-write' describe('SSH PTY writes', () => { + afterEach(() => { + vi.useRealTimers() + })Then remove the trailing
vi.useRealTimers()from Line 59 and Line 84.src/main/runtime/orchestration/mailbox-owner.ts (1)
132-201: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared mailbox-resolution body.
resolveRunMailboxandresolveDispatchMailboxdiffer only in the mailbox prefix and the routing call. The requested-mailbox guard, thehasDirectMailcomputation, therequireRequestedMailgate, and the routed-types/hasMoreblock are identical. Divergence between the two gates would be easy to introduce and hard to notice. Extract one private method that takes the resolved mailbox handle and a routing callback.♻️ Sketch of the extraction
+ private resolveRoutedMailbox( + db: OrchestrationDb, + leaf: OrchestrationMailboxLeaf, + terminalHandle: string, + mailbox: string, + runId: string, + requestedMailbox: string | undefined, + options: { requireRequestedMail?: boolean; routeDirectMail?: boolean }, + route: () => { types?: string[]; hasMore?: boolean } | undefined + ): string | null { + if (requestedMailbox && requestedMailbox !== terminalHandle && requestedMailbox !== mailbox) { + return null + } + const hasDirectMail = + options.routeDirectMail === false + ? false + : (db.hasUndeliveredDirectMessageForRun?.(runId, terminalHandle) ?? false) + if (options.requireRequestedMail && requestedMailbox === terminalHandle && !hasDirectMail) { + return null + } + if (hasDirectMail) { + const routed = route() + this.deps.onRoutedMessageTypes(mailbox, routed?.types ?? []) + if (routed?.hasMore) { + this.scheduleDirectReconciliation(leaf) + } + } + return mailbox + }
🔇 Additional comments (71)
src/main/runtime/orchestration-message-delivery-identity.test.ts (3)
1-1: 📐 Maintainability & Code QualityNote on the static analysis hint for
node:child_process.The hint flags the
spawnimport as a command-execution surface. The call at Line 145 usesspawnwithprocess.execPathand an argument array, and every argument is a literal or an identifier produced by the local test database. No shell is used. No change is required.Source: Linters/SAST tools
29-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
⚠️ Unverified finding
Sandbox verification was unavailable.The test fails when the CLI bundle is absent.
CLI_PATHpoints atout/cli/index.js, and Line 432 asserts the file exists. A contributor who runs the unit suite without a prior build gets a failure that does not describe the missing build step. Either skip the test when the bundle is absent, or state the required build command in the assertion message.♻️ Suggested guard
- it('keeps the built CLI count and Delivery output aligned with isolated SQLite state', async () => { - expect(existsSync(CLI_PATH)).toBe(true) + it.skipIf(!existsSync(CLI_PATH))( + 'keeps the built CLI count and Delivery output aligned with isolated SQLite state', + async () => {If the reliability gate requires this test to always run, keep the assertion and add the build command to the message instead. Confirm which behavior the gate expects.
Also applies to: 431-432
175-261: LGTM!Also applies to: 263-334, 336-384, 386-429, 431-508
src/main/runtime/rpc/methods/orchestration.ts (6)
48-66: LGTM!Also applies to: 749-758, 775-798
1048-1061: 🩺 Stability & Availability
⚠️ Unverified finding
Sandbox verification was unavailable.Confirm the detached continuation cannot outlive the database handle.
After an abort, the code schedules
routeAllMailboxPages(routePage)onsetImmediatewith no signal. That continuation callsdb.routeUnreadDispatchMailboxToRunMailboxafter the request has already failed. If the orchestration database is closed or replaced during shutdown or a runtime restart, the continuation runs against a stale handle, and the rejection is swallowed by.catch(() => undefined).Also confirm the swallowed error is acceptable for observability. A failed background migration currently leaves no log entry.
1193-1201: 🎯 Functional Correctness
⚠️ Unverified finding
Sandbox verification was unavailable.Verify that every
cancelledresult on a direct mailbox means Run ownership.The handler maps any
cancelledwait result toconsumer_fencedwith the message "This direct mailbox became owned by a Run while the check was waiting." The abort case is already handled at Line 1193. Confirm thatcancelMessageWaitersis only invoked for the direct handle when a Run claims the mailbox. If shutdown, PTY exit, or handle retirement also cancels these waiters, the caller receives a misleading error code.
830-850: 🗄️ Data Integrity & Integration
⚠️ Unverified finding
Sandbox verification was unavailable.Peek results omit
deliveryIdandreplayedwhile non-peek results include them.
peekResultreturnsrunId,messages,count, andacknowledged. The non-peek branches also returndeliveryId,replayed,timedOut,cancelled, andconnectionLost. A CLI or client that readsresult.deliveryIdon a peek response now readsundefinedinstead ofnull. Confirm that the CLI and typed clients treat the missing keys as absent rather than as a shape error.Also applies to: 868-870, 917-919, 932-939, 952-960
659-659: LGTM!Also applies to: 679-687, 1290-1290
1001-1090: LGTM!Also applies to: 1114-1114
src/main/runtime/orchestration-mailbox-detached-routing.test.ts (1)
35-69: LGTM!Also applies to: 110-153, 232-252, 254-298, 300-347, 349-380, 382-423
src/main/runtime/orchestration-mailbox-notification-consistency.test.ts (2)
184-233: 📐 Maintainability & Code Quality
⚠️ Unverified finding
Sandbox verification was unavailable.Query-plan and SQL-text assertions are strict; confirm they are intentional guards.
Lines 200, 211, 220, and 231 assert that specific index names appear in
EXPLAIN QUERY PLANoutput. Lines 276-277 assert on raw SQL text of a prepared statement. These assertions break when SQLite chooses a different plan after a version bump or when the production SQL is reworded, even if behavior stays correct. If the intent is a performance regression gate, the assertions are appropriate. Confirm the reliability gate documents them so a future SQLite upgrade has a clear failure explanation.Also applies to: 235-281
47-71: LGTM!Also applies to: 73-100, 102-144, 146-182, 283-314, 316-341, 343-387, 389-428, 430-471, 473-491, 493-511, 513-571, 573-603, 605-631, 633-663, 665-699, 701-741, 743-774
src/main/runtime/orchestration-mailbox-routing-races.test.ts (1)
37-60: LGTM!Also applies to: 62-143, 145-192, 194-259, 261-287, 289-318, 320-347, 349-377, 379-386, 388-424
src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts (1)
19-64: LGTM!Also applies to: 66-109, 111-137
src/main/runtime/rpc/methods/orchestration.test.ts (1)
298-315: LGTM!Also applies to: 336-361, 1274-1302
src/main/runtime/rpc/orchestration-legacy-mail.ts (1)
165-165: LGTM!src/main/runtime/rpc/methods/orchestration-runs.ts (1)
62-65: LGTM!Also applies to: 108-112
tests/e2e/helpers/orchestration-mail-store.ts (1)
6-16: LGTM!Also applies to: 38-54, 57-70
tests/e2e/orchestration-idle-mail-delivery.spec.ts (1)
4-6: LGTM!Also applies to: 30-30, 40-43, 69-77, 188-198, 257-270, 282-296, 309-396, 407-429, 484-488, 516-588, 605-608
tests/e2e/orchestration-idle-mail-restore.spec.ts (1)
118-121: LGTM!Also applies to: 153-153, 180-180
src/main/runtime/orchestration-mailbox-transport-settlement.test.ts (1)
1-66: LGTM!config/reliability-gates.jsonc (3)
886-886: LGTM!Also applies to: 3281-3281
8788-8951: LGTM!Also applies to: 9006-9017
8952-9004: 🎯 Functional Correctness | ⚡ Quick winFix the runtimeBudget: recorded evidence exceeds the declared p95 bound.
runtimeBudget.p95Secondsis 15 for this gate (line 8991). One of the four recordedevidenceRuns(src/main/runtime/orca-runtime.test.ts src/main/runtime/terminal-send-stale-leaf-liveness.test.ts src/main/runtime/rpc/methods/orchestration.test.ts, dated 2026-08-14) reportsdurationSeconds: 17.4(line 8986), which is above the stated 15-second p95 budget.Every other gate in this file sets
p95Secondscomfortably above its own reported evidence-run durations. This gate's declared budget contradicts its own evidence, which undermines the purpose of the reliability-gate manifest as an accurate promotion record.Update
p95Secondsto a value that covers the 17.4-second observed run (with margin), or explain the discrepancy if 15 seconds bounds something other than the individual evidence-run duration.🛠️ Proposed fix
"runtimeBudget": { - "p95Seconds": 15, + "p95Seconds": 20, "scope": "deterministic runtime, SQLite, and RPC contract tests" },src/main/runtime/orchestration/db.ts (11)
90-108: LGTM!
313-314: LGTM!Also applies to: 346-347
394-425: LGTM!
560-565: LGTM!Also applies to: 680-680
1068-1089: LGTM!
1472-1501: LGTM!
2062-2065: LGTM!Also applies to: 2346-2346, 2838-2841, 7665-7665
2463-2470: 🗄️ Data Integrity & Integration
⚠️ Unverified finding
Sandbox verification was unavailable.Verify that a bound coordinator handle cannot also be an active Dispatch assignee in the same Run.
routeAllUnreadDirectMessagesToRunMailboxmoves every unread current-delivery row addressed to the handle intorun:${runId}. It does not apply the active-dispatch exclusion thattrg_messages_route_coordinator_mailapplies at Line 2630. If one terminal is both the Run coordinator and an active Dispatch assignee in that Run, its worker-directed mail moves into the Run mailbox at rebind time.Confirm that an upstream check rejects this overlap, or add the same
NOT EXISTS (... dispatch_contexts ... status IN ('pending','dispatched'))predicate to the routing UPDATE.
2986-3010: LGTM!Also applies to: 3673-3706
3756-3805: LGTM!Also applies to: 3839-3888, 3927-4057, 4059-4103
4130-4149: LGTM!Also applies to: 5568-5585, 7267-7288
src/main/runtime/orchestration/federation-acknowledgment-migration.test.ts (1)
30-30: LGTM!Also applies to: 44-44
src/main/runtime/orchestration/mutation-receipt-capacity.test.ts (1)
106-106: LGTM!src/main/runtime/orchestration/orchestration-db-retention-pagination.test.ts (1)
243-243: LGTM!Also applies to: 280-280, 312-312, 331-331
src/main/runtime/orchestration/orchestration-reset-db.test.ts (1)
60-62: LGTM!src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts (1)
166-189: LGTM!src/main/runtime/orchestration/federation-sync.test.ts (1)
3-3: LGTM!Also applies to: 122-197, 203-210
src/main/daemon/client.test.ts (2)
667-684: 🩺 Stability & Availability | ⚡ Quick win
⚠️ Unverified finding
Sandbox verification was unavailable.Restore real timers after this test.
Line 673 enables fake timers and the test never calls
vi.useRealTimers(). This suite starts a real mock daemon over a socket, so any later test that runs under leaked fake timers can hang on connect or handshake timeouts.Confirm that an existing
afterEachrestores timers. If it does not, restore them in this test.💚 Proposed fix if no suite-level restore exists
await expect(pending).resolves.toBe(false) expect(client.isConnected()).toBe(false) + vi.useRealTimers() })
647-665: LGTM!src/main/runtime/orchestration/federation-sync.ts (1)
132-134: LGTM!src/main/runtime/orchestration/mailbox-pointer-eligibility.ts (1)
5-49: LGTM!src/main/runtime/orchestration/mailbox-pointer-submit.ts (1)
25-91: LGTM!src/main/runtime/orchestration/mailbox-notification-coordinator.ts (2)
42-69: LGTM!
126-137: 🩺 Stability & AvailabilityEnsure residual detached direct-mail pages trigger another reconciliation pass.
When a bounded routing page reports
hasMore, the continuation schedules only the mailboxes routed in that page and can skip the original detached handle. Confirm that another pass re-enters routing for that handle; otherwise rows beyond the first page can remain unpointed until a newer message arrives.src/main/runtime/orchestration/mailbox-pointer-delivery.ts (1)
58-136: LGTM!src/main/daemon/client.ts (1)
26-26: LGTM!src/main/daemon/daemon-pty-adapter.ts (1)
1067-1107: LGTM!src/main/providers/ssh-pty-write.test.ts (1)
6-39: LGTM!src/main/providers/ssh-pty-write.ts (1)
7-17: LGTM!src/main/runtime/orchestration/mailbox-delivery-target.ts (2)
29-34: 🗄️ Data Integrity & Integration
⚠️ Unverified finding
Sandbox verification was unavailable.Verify the run branch resolves rebound coordinator handles.
For a
run:mailbox, the resolution depends only ongetRun(runId)?.coordinator_handle. If the coordinator terminal was rebound and therunsrow still holds a historical handle,hasTerminalHandlefails and the method returnsnull. Delivery then stops with no pane-key fallback, unlike the dispatch branch. The PR adds coordinator-handle history in schema v28, so confirm thatgetRunreturns the canonical current handle, or resolve through the history table here.
52-65: 🩺 Stability & Availability | ⚡ Quick win
⚠️ Unverified finding
Sandbox verification was unavailable.Guard against a probe promise that never settles.
probeDeferredPtyIdsis cleared only in thethenandcatchhandlers. IfisLeafPtyProvenAbsent(ptyId)never settles, the entry stays in the set. Every later call for that PTY then returnstrueat Line 53 and no redelivery is ever scheduled, so mail for that PTY stalls until the PTY is replaced. Confirm that the probe always settles. If it can hang, bound it and clear the set entry on expiry.src/main/runtime/orchestration/mailbox-owner.ts (4)
41-89: LGTM!
122-130: LGTM!
203-222: LGTM!
111-119: 🩺 Stability & Availability
⚠️ Unverified finding
Sandbox verification was unavailable.Both reconciliation drains depend on an unverified pagination contract. Each drain re-arms itself while the routing query reports
hasMore, and each guard entry is cleared before the next pass runs. Termination requires that every page routes at least one row. IfrouteForeignDirectMessagesToOwnedMailboxescan reporthasMore: truewith no routed rows, both paths become self-perpetuatingsetImmediateloops that starve the event loop.
src/main/runtime/orchestration/mailbox-owner.ts#L111-L119: confirm the leaf-scoped drain advances a cursor across pages, or bound the number of consecutive rescheduled passes.src/main/runtime/orchestration/mailbox-owner.ts#L229-L243: apply the same confirmation or bound to the detached-handle drain.src/main/runtime/orchestration/mailbox-pointer-state.ts (3)
26-51: LGTM!
67-117: LGTM!
140-164: LGTM!src/main/runtime/orca-runtime.ts (5)
170-176: LGTM!Also applies to: 2099-2104
1757-1757: LGTM!
2924-2975: LGTM!
32381-32390: LGTM!
13953-13953: LGTM!Also applies to: 32392-32404
src/main/daemon/daemon-pty-router.test.ts (1)
79-79: LGTM!Also applies to: 458-468
src/main/daemon/degraded-daemon-pty-provider.test.ts (1)
40-40: LGTM!Also applies to: 376-388
src/main/ipc/pty.ts (1)
5433-5443: LGTM!src/main/providers/ssh-pty-provider.ts (1)
26-26: LGTM!Also applies to: 208-213
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 145e1777-373a-4cab-b076-c0992c1ddfe5
📒 Files selected for processing (51)
config/reliability-gates.jsoncsrc/main/daemon/client.test.tssrc/main/daemon/client.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-router.test.tssrc/main/daemon/daemon-pty-router.tssrc/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/ipc/pty.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/pty-provider-contract.tssrc/main/providers/ssh-pty-provider.tssrc/main/providers/ssh-pty-write.test.tssrc/main/providers/ssh-pty-write.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-mailbox-detached-routing.test.tssrc/main/runtime/orchestration-mailbox-notification-consistency.test.tssrc/main/runtime/orchestration-mailbox-notification-test-harness.tssrc/main/runtime/orchestration-mailbox-routing-races.test.tssrc/main/runtime/orchestration-mailbox-transport-settlement.test.tssrc/main/runtime/orchestration-message-delivery-identity.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/federation-acknowledgment-migration.test.tssrc/main/runtime/orchestration/federation-sync.test.tssrc/main/runtime/orchestration/federation-sync.tssrc/main/runtime/orchestration/formatter.test.tssrc/main/runtime/orchestration/formatter.tssrc/main/runtime/orchestration/mailbox-delivery-target.tssrc/main/runtime/orchestration/mailbox-notification-coordinator.tssrc/main/runtime/orchestration/mailbox-owner.tssrc/main/runtime/orchestration/mailbox-pointer-delivery.tssrc/main/runtime/orchestration/mailbox-pointer-eligibility.tssrc/main/runtime/orchestration/mailbox-pointer-state.tssrc/main/runtime/orchestration/mailbox-pointer-submit.tssrc/main/runtime/orchestration/mutation-receipt-capacity.test.tssrc/main/runtime/orchestration/orchestration-creator-authority-performance.test.tssrc/main/runtime/orchestration/orchestration-db-retention-pagination.test.tssrc/main/runtime/orchestration/orchestration-reset-db.test.tssrc/main/runtime/orchestration/orchestration-run-delivery-db.test.tssrc/main/runtime/orchestration/orchestration-worker-dispatch-db.test.tssrc/main/runtime/orchestration/run-coordinator-handle-migration.test.tssrc/main/runtime/rpc/methods/orchestration-runs.tssrc/main/runtime/rpc/methods/orchestration.test.tssrc/main/runtime/rpc/methods/orchestration.tssrc/main/runtime/rpc/orchestration-legacy-mail.tssrc/main/runtime/terminal-send-stale-leaf-liveness.test.tstests/e2e/helpers/orchestration-mail-store.tstests/e2e/orchestration-idle-mail-delivery.spec.tstests/e2e/orchestration-idle-mail-restore.spec.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- src/main/runtime/orchestration/formatter.test.ts
- src/main/providers/local-pty-provider.test.ts
- src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
- src/main/runtime/orchestration/formatter.ts
- src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts
- src/main/daemon/degraded-daemon-pty-provider.ts
- src/main/providers/pty-provider-contract.ts
- src/main/providers/local-pty-provider.ts
- src/main/daemon/daemon-pty-router.ts
- src/main/runtime/orchestration-mailbox-notification-test-harness.ts
- src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
- src/main/runtime/orca-runtime.test.ts
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/main/runtime/orca-runtime.ts (2)
2924-2975: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winFix
getPaneKeyForHandlefor PTY-only handles.Use
getPaneKeyForTerminalHandle(handle)so detached routing receives the PTY's recorded pane key, or no key when unavailable, instead ofpty:<id>:pty:<id>.
3971-3977: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winInvalidate pending pointer deliveries before replacing the orchestration database.
OrchestrationMailboxPointerStateretains delayed flights, timers, parked deliveries, and watermarks without tracking database identity.setOrchestrationDbcan therefore run an old callback against the new database. Add a generation guard that cancels timers and retires the exact pending reservations before the swap. The notification coordinator is stateless and needs no separate reset.src/main/runtime/orchestration/mailbox-pointer-delivery.ts (1)
125-130: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winCarry
reservedTypesthrough the absence-probe retry.At Lines 90-105,
reservedTypesexcludes message types fromunread. The callback at Lines 125-130 passes only the leaf, PTY ID, and mailbox handle.redeliverAfterProbethen callsdeliverwithoutreservedTypes.The retry can therefore select a message type reserved by another delivery path.
Proposed fix
- (probedLeaf, ptyId, probedMailbox) => - this.redeliverAfterProbe(probedLeaf, ptyId, probedMailbox) + (probedLeaf, ptyId, probedMailbox) => + this.redeliverAfterProbe(probedLeaf, ptyId, probedMailbox, options.reservedTypes) ... private redeliverAfterProbe( leaf: OrchestrationMailboxLeaf, ptyId: string, - mailboxHandle: string + mailboxHandle: string, + reservedTypes?: ReadonlySet<string> ): void { ... - this.deliver(currentLeaf, { mailboxHandle, skipAbsenceProbe: true }) + this.deliver(currentLeaf, { mailboxHandle, reservedTypes, skipAbsenceProbe: true })Also applies to: 155-167
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 94c138da-2c0d-4a90-9703-ae31ccb8c35c
📒 Files selected for processing (15)
config/reliability-gates.jsoncsrc/main/daemon/client.test.tssrc/main/daemon/client.tssrc/main/providers/ssh-pty-write.test.tssrc/main/providers/ssh-pty-write.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/orchestration-mailbox-detached-routing.test.tssrc/main/runtime/orchestration-mailbox-routing-races.test.tssrc/main/runtime/orchestration-message-delivery-identity.test.tssrc/main/runtime/orchestration/db.tssrc/main/runtime/orchestration/federation-sync.test.tssrc/main/runtime/orchestration/mailbox-pointer-delivery.tssrc/main/runtime/orchestration/mailbox-pointer-state.tssrc/main/runtime/orchestration/run-coordinator-handle-migration.test.tssrc/main/runtime/rpc/methods/orchestration.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- src/main/runtime/orchestration/federation-sync.test.ts
- src/main/daemon/client.ts
- src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts
- src/main/runtime/orchestration/mailbox-pointer-state.ts
- src/main/providers/ssh-pty-write.ts
- src/main/runtime/rpc/methods/orchestration.test.ts
- config/reliability-gates.jsonc
- src/main/daemon/client.test.ts
- src/main/runtime/orchestration/db.ts
- src/main/runtime/orchestration-mailbox-detached-routing.test.ts
|
Follow-up
Fresh local evidence:
GitHub CI is rerunning on the new head; do not merge until it is clean. |
|
External review follow-up at 57152c2: Four independent reviewers completed: Claude Fable 5 architecture, OpenCode DB/concurrency, OpenCode federation/wire compatibility, and OpenCode adversarial/performance. Validated and fixed:
Rejected after validation:
Validation:
No merge performed. |
|
Base-update/schema collision resolution: main introduced schema v28 ( |
* test(orchestration): reproduce mailbox pointer mismatch * fix(orchestration): align pointers with actionable mailboxes * fix(orchestration): harden pointer reservation lifecycle * fix(orchestration): bound mailbox reconciliation * fix(orchestration): make pointer staging restart-safe * test(orchestration): expect scoped dispatch index * fix(orchestration): guard skewed inbox indexes * refactor(orchestration): extract mailbox notification lifecycle * fix(orchestration): settle mailbox pointer writes * fix(orchestration): bound mailbox recovery work * fix(orchestration): fence inactive mailbox snapshots * test(orchestration): cover mailbox notification boundary * test(orchestration): pin STA-4325 delivery identity * fix(orchestration): preserve mailbox delivery identity * fix(orchestration): harden mailbox settlement * test(orchestration): make mailbox gates self-contained * fix(orchestration): preserve paged mailbox ownership --------- Co-authored-by: Jinwoo-H <[email protected]>
Summary
Fixes #14522
Linear: https://linear.app/stably/issue/STA-4325/orchestration-queue-re-delivers-the-same-already-processed-message
ELI5
The notification bell and the inbox were looking at two different mailboxes. The bell could see mail addressed to an old terminal name, while
orchestration checklooked at the Run mailbox. That made real unread mail look missing and made the same visible status seem to return forever.This change labels coordinator mail with the Run mailbox inside the same SQLite insert that creates it. Checks then replay one receipt until the coordinator explicitly acknowledges it. A restart or lost federation acknowledgment can retry safely, but it cannot invent a new message or wake again for an already-read duplicate.
Exact state machines
Message:
Delivery:
Federation duplicate:
delivered_atrecords successful pointer staging/submission only. It does not mark a message read and does not replace explicit Delivery acknowledgment.Root cause and authoritative fix
The reported symptom was hidden mail, not proven deletion:
run:<id>Schema v28 adds durable
run_coordinator_handles. SQLite triggers record Run insert/rebind history, including A -> B -> C writes by an older v27 runtime, clear history with Run deletion, and canonicalize coordinator-addressed current-delivery messages in the insertion transaction. Startup backfills current handles and recreates the message trigger after old table-rebuild migrations.Rebind moves the complete indexed old/current backlog in one transaction. Detached routing uses duplicate-free coordinator, exact-Dispatch, and pane-Dispatch ownership branches, each capped at 51 rows before the final merge; one transaction routes at most 50 and yields before continuing. Run/Dispatch selection and update predicates remain aligned under
BEGIN IMMEDIATE.No RPC parameter, stream opcode, or published payload changed.
Byte-identical red/green matrix
Oracle SHA-256:
76a2d672d27e04e5b1db2f52df3b303468bdf006be7cfd003bf443618a856c350b62333cf1799bb8836bb6816c0140049bb8836bb6The oracle uses only disposable temporary profiles and SQLite databases. It never reads or acknowledges a real orchestration mailbox.
Federation and mixed-version evidence
OrchestrationDbrows prove a lost ACK reimports the same stable row, an already-read duplicate does not wake, and the next fresh sequence still wakesLive headed/headless two-runtime acceptance remains uncollected because the required Electron validation skill is unavailable in this environment. The causal DB/runtime/federation path is covered deterministically; no computer-use substitute was used.
Validation
git diff --check: passedPerformance and tradeoffs
Remaining gaps
Headed Electron restart, physical SSH, paired hosted runtimes, WSL, and native Linux/Windows acceptance remain promotion evidence gaps. Direct and Dispatch mail remains durable and explicitly checkable; passive renderer unread UI and any new coordinator wake policy remain separate product work.
Do not merge until current CI and review automation are clean.