Skip to content

fix(orchestration): preserve mailbox delivery identity - #13717

Merged
Jinwoo-H merged 18 commits into
mainfrom
orchestration-mailbox-delivery
Aug 15, 2026
Merged

Jinwoo-H merged 18 commits into
mainfrom
orchestration-mailbox-delivery

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #14522
Linear: https://linear.app/stably/issue/STA-4325/orchestration-queue-re-delivers-the-same-already-processed-message

  • give every coordinator message one durable authoritative mailbox before its insert commits
  • preserve historical coordinator handles so old and mixed-version runtimes cannot orphan direct mail during rebind
  • keep one fixed Delivery ID and fixed message batch until explicit acknowledgment
  • reconcile detached Run and Dispatch mail in bounded, indexed pages without duplicate notifications
  • suppress federation duplicate wakes after a replayed row is already read
  • tolerate healthy SSH pointer backpressure for the full 60-second bounded settlement window

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 check looked 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:

inserted to historical/current coordinator handle
  -> SQLite trigger canonicalizes to run:<id> atomically
  -> unread/read=0
  -> optional pointer staging sets delivered_at only
  -> check creates or replays one outstanding Delivery
  -> explicit ack marks exactly that Delivery's message IDs read=1

Delivery:

none
  -> outstanding(id, fixed message_ids, consumer_generation)
  -> replay same id until ack
  -> acknowledged on explicit matching ack
  -> fenced if Run consumer_generation changes

Federation duplicate:

remote relay item
  -> imported once by stable message identity
  -> ACK may be lost
  -> replay returns the same local row
  -> if row is already read, duplicate import does not notify or wake
  -> next fresh sequence imports and wakes normally

delivered_at records 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:

  • idle notification inspected terminal-direct rows
  • a bound check consumed run:<id>
  • direct rows stayed unread but were invisible under that Run authority
  • ordinary checks correctly replayed one fixed Delivery until explicit ack, which masked newer hidden receipts

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: 76a2d672d27e04e5b1db2f52df3b303468bdf006be7cfd003bf443618a856c35

Target Result Evidence
reported v1.4.180 0b62333cf179 0/5 two announced vs one retrievable; restart hid direct mail; 125 old-handle rows stayed direct; commit-without-notify stayed orphaned; CLI returned one of two
latest main 9bb8836bb6 0/5 identical failures
candidate 816c014004 5/5 counts, stable message IDs, one Delivery ID, filters, ack, restart, backlog, and CLI/SQLite all aligned
candidate production changes reverted to 9bb8836bb6 0/5 identical failures returned

The oracle uses only disposable temporary profiles and SQLite databases. It never reads or acknowledges a real orchestration mailbox.

Federation and mixed-version evidence

  • focused dropped-ACK, reconnect/restart, and protocol v1/v2 lifecycle set: 52/52
  • broader federation and cross-version set: 77/77
  • real OrchestrationDb rows prove a lost ACK reimports the same stable row, an already-read duplicate does not wake, and the next fresh sequence still wakes
  • v27 -> v28 migration and v28 DB writes by an old runtime preserve A -> B -> C coordinator history
  • no wire compatibility change; old and new clients can update independently

Live 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

  • final STA-4325 identity oracle: 5/5
  • registered mailbox/reliability command: 245/245
  • broad runtime/RPC command: 1,293 passed, 1 skipped
  • focused federation command: 52/52
  • broader federation/cross-version set: 77/77
  • typecheck and CLI build: passed
  • oxlint, formatting, native and type-aware code-quality audits: passed
  • reliability manifest, max-lines ratchet, and git diff --check: passed
  • independent DB/concurrency review: clean
  • independent federation/mixed-version review: clean
  • independent adversarial/performance review: clean
  • CodeRabbit findings addressed; fresh DB/concurrency, federation, and performance re-reviews: clean

Performance and tradeoffs

  • bulk rebind/startup routing is O(affected backlog) in one indexed update
  • detached routing improved from 96/429/1,908 ms at 5k/10k/20k rows to 40/77/187 ms; 100k drained in 1.04 s across 2,000 cooperative pages
  • filtered Run peek over 100k rows measured 0.08-0.13 ms using typed partial indexes
  • trigger overhead measured about 0.6-1.0 microseconds per inserted message
  • SSH pointer settlement keeps one cleared, unrefed timer per write and moves the deadline from 5 to 60 seconds, beyond the 20-second mux health window; the tradeoff is a longer bounded wait before declaring a truly wedged write failed
  • no polling, provider fanout, subprocess, renderer work, or persistent listener was added

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.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: preserving orchestration mailbox delivery identity.
Description check ✅ Passed The description provides a detailed explanation of the problem, solution, linked issue, validation, performance, and remaining gaps.
Linked Issues check ✅ Passed The changes address issue #14522 by stabilizing delivery identity, preventing duplicate replay, supporting acknowledgment, and aligning mailbox counts.
Out of Scope Changes check ✅ Passed The schema, federation, routing, SSH settlement, and test changes support the stated mailbox delivery reliability objectives.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@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: 3

🧹 Nitpick comments (4)
src/main/runtime/orchestration-mailbox-notification-consistency.test.ts (1)

263-270: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verify this checks the production revalidation path, not a synthetic query.

This block builds its own SQL with an INDEXED BY idx_messages_id hint and runs EXPLAIN QUERY PLAN against it. INDEXED BY forces 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 BY hint so the query plan reflects the planner's natural choice.

src/main/runtime/orca-runtime.test.ts (1)

18689-18689: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Weak delivered_at assertions recur across orca-runtime.test.ts and terminal-send-stale-leaf-liveness.test.ts. Both files add new assertions on delivered_at using .not.toBeNull() or !== null, which pass for undefined as well as a genuinely set value. orchestration-mailbox-notification-consistency.test.ts in this same PR already uses the stronger expect.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 with expect(...).toEqual(expect.any(String)).
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts#L506-L589: replace the !== null checks 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 win

Strengthen the delivered_at assertions.

These assertions use !== null or .not.toBeNull(). Both pass for undefined as well as a genuinely set value. If delivered_at is 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 win

Add 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, and rpc/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 only orchestration-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

📥 Commits

Reviewing files that changed from the base of the PR and between 550eabe and 74568a9.

📒 Files selected for processing (6)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-mailbox-notification-consistency.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts

Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/orchestration/db.ts Resolved
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

CodeRabbit follow-up is in 03f5543. In addition to the three resolved threads, this strengthens every new delivered_at assertion to require a timestamp string, verifies and EXPLAINs the exact production submit-time SQL using idx_messages_id, and records evidence for both reliability-gate commands. Validation: 42/42 focused lifecycle/DB tests; 31/31 registered gate tests; 1,250 passed and 1 skipped across the wider runtime/RPC set; typecheck, oxlint, formatting, reliability-gate validation, and max-lines ratchet pass. Fresh adversarial correctness and performance reviews are clean.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 21627da4-24d0-4e78-90ba-36a69bb48223

📥 Commits

Reviewing files that changed from the base of the PR and between 74568a9 and 03f5543.

📒 Files selected for processing (7)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-mailbox-notification-consistency.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
  • src/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

Comment thread config/reliability-gates.jsonc Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
@Jinwoo-H
Jinwoo-H force-pushed the orchestration-mailbox-delivery branch from 03f5543 to 6aa9190 Compare August 11, 2026 04:38
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

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.

@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: 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 win

Guard idx_messages_undelivered_direct_run on delivery_contract.

A pre-v19 database can contain delivered_at without delivery_contract. Since createTables() calls this method before migrateLegacyContractStorage(), SQLite raises no such column: delivery_contract, and the OrchestrationDb constructor fails. Check both columns before creating the partial index; migrate() retries after adding delivery_contract.

src/main/ipc/pty.ts (1)

5334-5340: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Propagate provider.write failures through the renderer write helpers.

writePtyProviderInputWithinLimit and writePtyProviderInputChunks discard provider.write results. A false result therefore makes pty:writeAccepted return true and suppresses pty:writeUnavailable. Match the !== false handling at line 5336.

🧹 Nitpick comments (1)
src/main/runtime/orchestration/formatter.test.ts (1)

189-190: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for a non-run: mailbox handle.

The new conditional in formatMessagePointer has three branches: run: prefix, other prefix, and no handle. Line 189 covers the run: branch and line 195 covers the no-handle branch. A dispatch: handle must produce no --run flag, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 680a9d9 and 6aa9190.

📒 Files selected for processing (21)
  • config/reliability-gates.jsonc
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/ipc/pty.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/ssh-pty-provider.test.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-mailbox-notification-consistency.test.ts
  • src/main/runtime/orchestration-mailbox-notification-test-harness.ts
  • src/main/runtime/orchestration-mailbox-routing-races.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/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

Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/orchestration/db.ts Resolved
Comment thread src/main/runtime/orchestration/db.ts Resolved
@Jinwoo-H
Jinwoo-H force-pushed the orchestration-mailbox-delivery branch 4 times, most recently from 5064ae4 to 8e40a38 Compare August 14, 2026 04:04
@Jinwoo-H
Jinwoo-H force-pushed the orchestration-mailbox-delivery branch from 8e40a38 to 481d8bb Compare August 14, 2026 21:59
@Jinwoo-H Jinwoo-H changed the title fix(orchestration): align mailbox pointers with checks fix(orchestration): preserve mailbox delivery identity Aug 14, 2026
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

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.

@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: 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 win

Guard scheduleRestoredMessageRepoints against a throwing database read.

getOrchestrationDb and setOrchestrationDb call scheduleRestoredMessageRepoints synchronously. That method calls getUndeliveredUnreadMailboxHandles and routeDetachedDirectMessages, which read the database. If either throws, the exception escapes getOrchestrationDb, and every unrelated caller that only wants the database handle fails.

repointPendingMessagesForHandle at 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 value

Replace the manual microtask loop with vi.waitFor.

Lines 185-190 poll messageWaitersByHandle with a fixed count of await Promise.resolve(). The same file already uses vi.waitFor at Line 214 for the identical condition. Use vi.waitFor here 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 win

Close the SQLite handle in afterEach across the new mailbox test files. Every test calls db.close() as its last statement, so the handle leaks whenever an earlier assertion fails. rmSync then 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 open OrchestrationDb in a describe-scoped variable and close it in the hook before rmSync.
  • src/main/runtime/orchestration-mailbox-detached-routing.test.ts#L28-L33: apply the same hook change and drop the per-test db.close() calls.
  • src/main/runtime/orchestration-mailbox-routing-races.test.ts#L31-L35: apply the same hook change, and add vi.useRealTimers() and vi.restoreAllMocks() to match the sibling files.
  • src/main/runtime/orchestration-message-delivery-identity.test.ts#L168-L173: close the databases created by createDatabase in the hook; the CLI test already uses try/finally and needs no change.
src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts (1)

12-17: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

tempDir is not cleared after removal.

The hook removes tempDir but leaves the variable set. If a later test throws before Line 20 assigns a new value, the hook removes the same path again. rmSync with force: true tolerates 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 value

The waitForMessage mock ignores the arguments the handler passes.

The mock always inserts a worker_done message and returns 'notified'. It does not read typeFilter, exclusive, or timeoutMs. 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 value

Wrap the trigger swap in one transaction.

createCoordinatorMailRoutingTrigger runs DROP TRIGGER and CREATE TRIGGER as 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 messages
       BEGIN
         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 win

Restore real timers in an afterEach hook.

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. An afterEach hook 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 win

Extract the shared mailbox-resolution body.

resolveRunMailbox and resolveDispatchMailbox differ only in the mailbox prefix and the routing call. The requested-mailbox guard, the hasDirectMail computation, the requireRequestedMail gate, and the routed-types/hasMore block 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 Quality

Note on the static analysis hint for node:child_process.

The hint flags the spawn import as a command-execution surface. The call at Line 145 uses spawn with process.execPath and 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_PATH points at out/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) on setImmediate with no signal. That continuation calls db.routeUnreadDispatchMailboxToRunMailbox after 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 cancelled result on a direct mailbox means Run ownership.

The handler maps any cancelled wait result to consumer_fenced with 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 that cancelMessageWaiters is 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 deliveryId and replayed while non-peek results include them.

peekResult returns runId, messages, count, and acknowledged. The non-peek branches also return deliveryId, replayed, timedOut, cancelled, and connectionLost. A CLI or client that reads result.deliveryId on a peek response now reads undefined instead of null. 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 PLAN output. 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 win

Fix the runtimeBudget: recorded evidence exceeds the declared p95 bound.

runtimeBudget.p95Seconds is 15 for this gate (line 8991). One of the four recorded evidenceRuns (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) reports durationSeconds: 17.4 (line 8986), which is above the stated 15-second p95 budget.

Every other gate in this file sets p95Seconds comfortably 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 p95Seconds to 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.

routeAllUnreadDirectMessagesToRunMailbox moves every unread current-delivery row addressed to the handle into run:${runId}. It does not apply the active-dispatch exclusion that trg_messages_route_coordinator_mail applies 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 afterEach restores 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 & Availability

Ensure 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 on getRun(runId)?.coordinator_handle. If the coordinator terminal was rebound and the runs row still holds a historical handle, hasTerminalHandle fails and the method returns null. Delivery then stops with no pane-key fallback, unlike the dispatch branch. The PR adds coordinator-handle history in schema v28, so confirm that getRun returns 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.

probeDeferredPtyIds is cleared only in the then and catch handlers. If isLeafPtyProvenAbsent(ptyId) never settles, the entry stays in the set. Every later call for that PTY then returns true at 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. If routeForeignDirectMessagesToOwnedMailboxes can report hasMore: true with no routed rows, both paths become self-perpetuating setImmediate loops 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9bb8836 and 481d8bb.

📒 Files selected for processing (51)
  • config/reliability-gates.jsonc
  • src/main/daemon/client.test.ts
  • src/main/daemon/client.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts
  • src/main/daemon/degraded-daemon-pty-provider.test.ts
  • src/main/daemon/degraded-daemon-pty-provider.ts
  • src/main/ipc/pty.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/pty-provider-contract.ts
  • src/main/providers/ssh-pty-provider.ts
  • src/main/providers/ssh-pty-write.test.ts
  • src/main/providers/ssh-pty-write.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-mailbox-detached-routing.test.ts
  • src/main/runtime/orchestration-mailbox-notification-consistency.test.ts
  • src/main/runtime/orchestration-mailbox-notification-test-harness.ts
  • src/main/runtime/orchestration-mailbox-routing-races.test.ts
  • src/main/runtime/orchestration-mailbox-transport-settlement.test.ts
  • src/main/runtime/orchestration-message-delivery-identity.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/federation-acknowledgment-migration.test.ts
  • src/main/runtime/orchestration/federation-sync.test.ts
  • src/main/runtime/orchestration/federation-sync.ts
  • src/main/runtime/orchestration/formatter.test.ts
  • src/main/runtime/orchestration/formatter.ts
  • src/main/runtime/orchestration/mailbox-delivery-target.ts
  • src/main/runtime/orchestration/mailbox-notification-coordinator.ts
  • src/main/runtime/orchestration/mailbox-owner.ts
  • src/main/runtime/orchestration/mailbox-pointer-delivery.ts
  • src/main/runtime/orchestration/mailbox-pointer-eligibility.ts
  • src/main/runtime/orchestration/mailbox-pointer-state.ts
  • src/main/runtime/orchestration/mailbox-pointer-submit.ts
  • src/main/runtime/orchestration/mutation-receipt-capacity.test.ts
  • src/main/runtime/orchestration/orchestration-creator-authority-performance.test.ts
  • src/main/runtime/orchestration/orchestration-db-retention-pagination.test.ts
  • src/main/runtime/orchestration/orchestration-reset-db.test.ts
  • src/main/runtime/orchestration/orchestration-run-delivery-db.test.ts
  • src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts
  • src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts
  • src/main/runtime/rpc/methods/orchestration-runs.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/main/runtime/rpc/orchestration-legacy-mail.ts
  • src/main/runtime/terminal-send-stale-leaf-liveness.test.ts
  • tests/e2e/helpers/orchestration-mail-store.ts
  • tests/e2e/orchestration-idle-mail-delivery.spec.ts
  • tests/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

Comment thread src/main/daemon/client.ts Resolved
Comment thread src/main/providers/ssh-pty-write.ts Resolved
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

⚠️ Outside diff range comments (3)
src/main/runtime/orca-runtime.ts (2)

2924-2975: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix getPaneKeyForHandle for PTY-only handles.

Use getPaneKeyForTerminalHandle(handle) so detached routing receives the PTY's recorded pane key, or no key when unavailable, instead of pty:<id>:pty:<id>.


3971-3977: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Invalidate pending pointer deliveries before replacing the orchestration database.

OrchestrationMailboxPointerState retains delayed flights, timers, parked deliveries, and watermarks without tracking database identity. setOrchestrationDb can 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 win

Carry reservedTypes through the absence-probe retry.

At Lines 90-105, reservedTypes excludes message types from unread. The callback at Lines 125-130 passes only the leaf, PTY ID, and mailbox handle. redeliverAfterProbe then calls deliver without reservedTypes.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 481d8bb and 816c014.

📒 Files selected for processing (15)
  • config/reliability-gates.jsonc
  • src/main/daemon/client.test.ts
  • src/main/daemon/client.ts
  • src/main/providers/ssh-pty-write.test.ts
  • src/main/providers/ssh-pty-write.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration-mailbox-detached-routing.test.ts
  • src/main/runtime/orchestration-mailbox-routing-races.test.ts
  • src/main/runtime/orchestration-message-delivery-identity.test.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/federation-sync.test.ts
  • src/main/runtime/orchestration/mailbox-pointer-delivery.ts
  • src/main/runtime/orchestration/mailbox-pointer-state.ts
  • src/main/runtime/orchestration/run-coordinator-handle-migration.test.ts
  • src/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

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Follow-up b002e00d4b fixes the two branch-owned CI contract gaps from the prior run without changing production behavior:

  • the built-CLI oracle now skips in ordinary fresh-checkout unit shards, while its registered reliability command builds the CLI first so the oracle cannot silently skip
  • the Electron Run A/Run B assertion now expects insertion-time canonicalization to run:<id>, matching the v28 DB invariant

Fresh local evidence:

  • exact STA-4325 CLI/SQLite oracle: 5/5
  • reliability manifest validation: 83/83 gates valid
  • complete changed Electron E2E set: 11/11
  • typecheck, focused oxlint/format, and git diff --check: passed

GitHub CI is rerunning on the new head; do not merge until it is clean.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

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:

  • Paged Run routing could steal direct mail owned by an active Dispatch when the Run coordinator and Dispatch shared a terminal handle. The paged Run path now applies the same active-Dispatch ownership guard as the trigger and bulk/rebind path.
  • Bounded reconciliation UPDATEs could make SQLite scan the remaining mailbox range once per 50-row page. All three page UPDATEs now force idx_messages_id point lookups. The same 100k detached backlog improved from 27.23 s reported before the patch to 2.19 s after the patch on this machine, with 2,000 pages and all 100,000 rows routed.
  • Removed the unused areUndeliveredUnreadMessages method identified by the architecture review.

Rejected after validation:

  • Outstanding Delivery replay ignoring --types is intentional: --types is a wake policy, while the one outstanding Delivery must retain stable identity and replay unchanged until explicit ack.
  • The claimed unbatched hot push path was stale; mailbox-owner already performs 50-row paging and schedules reconciliation.
  • SSH timeout teardown and staged-crash behavior are documented residual tradeoffs, not newly proven correctness defects.

Validation:

  • Focused post-fix suite: 217/217 passed across detached routing, notification consistency, routing races, delivery identity, Run delivery DB, and orchestration RPC.
  • Node typecheck, focused oxlint, oxfmt, max-lines ratchet, reliability-gate manifest, and git diff --check passed.
  • Added deterministic ownership and query-plan regressions; all three bounded UPDATE plans use idx_messages_id.

No merge performed.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Base-update/schema collision resolution: main introduced schema v28 (mutation_caller_identities) in 78d5920 after the latest published RC (v1.4.183-rc.0), and no stable/RC tag contains it. Kept user_version = 28; coordinator-handle history self-converges through idempotent table creation plus unconditional backfill, including a v28 DB from the other change. Post-merge validation: affected suite 23 files / 1,636 passed / 1 skipped; node typecheck, targeted lint, reliability gates, max-lines, and diff checks passed.

@Jinwoo-H
Jinwoo-H merged commit 1d8eaa8 into main Aug 15, 2026
48 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
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.

Orchestration queue re-delivers the same already-processed message indefinitely (count header inflated, new messages possibly masked)

1 participant