Skip to content

Make worker completion and cleanup authoritative - #13927

Merged
Jinwoo-H merged 7 commits into
mainfrom
worker_done-with-mismatched-sender-identity-retu
Aug 12, 2026
Merged

Jinwoo-H merged 7 commits into
mainfrom
worker_done-with-mismatched-sender-identity-retu

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

ELI5

Orca previously trusted two "probably done" signals. A worker could send worker_done with the wrong identity and the CLI could print ok:true even though the task was still running. Separately, a worker terminal that had already disappeared could remain permanently marked "retained." This PR makes both decisions use authoritative state: only the Task/Dispatch owner can confirm completion, and only the owning terminal provider can prove an exact process incarnation is gone before cleanup releases it.

What Changed

  • Require an explicit lifecycle verdict for current worker_done calls.
  • For legacy responses that lack a verdict, accept success only when bounded authoritative Task, Dispatch, and durable report-receipt reads all agree.
  • Make federated completion wait for the Run-home verdict, capability-negotiate protocol v3, replay lost acknowledgements, and atomically settle the exact remote attachment.
  • Reconcile retained external/user-owned/transferred workers to released only when the authoritative local/WSL or exact SSH provider positively excludes their immutable process incarnation. Unknown inventory remains retained, and this path never closes a process.
  • Add one combined Electron E2E that launches real freshly compiled out/cli/index.js processes for wrong-identity completion, valid completion, and dead-worker release.

Why

Fixes #13858

Fixes #13860

The invariant is: a CLI may report completion only after the authoritative Task/Dispatch owner proves the exact report settled, and cleanup may release retained ownership only after the authoritative terminal provider proves the exact immutable process incarnation is absent.

The structural ownership fix is the best long-term implementation. A CLI-only patch cannot prove Run-home settlement, and treating a missing process listing as death could close or release remote work incorrectly. The chosen design fails closed across version skew and unknown provider state while keeping normal current-version calls constant-time.

Downsides and risks:

  • Federation peers below protocol v3 now reject before mutation instead of returning an optimistic success.
  • The legacy no-verdict fallback performs two concurrent bounded reads.
  • Retained-worker release performs one bounded provider inventory call (3-second existing timeout); unavailable or malformed inventory intentionally leaves the resource retained.
  • Live physical Windows/WSL, SSH reconnect, and paired-runtime journeys were not run locally. Provider contracts cover those routing semantics, and this diff does not change ConPTY, window lifecycle, filesystem, updater, or Git behavior.

Linked Issue

Fixes #13858

Fixes #13860

Supersedes #13920.

Visual Proof

N/A — this changes CLI/runtime orchestration state and has no renderer or UI diff.

Testing

Deterministic byte-identical oracle:

pnpm run build:cli
SKIP_BUILD=1 pnpm exec playwright test \
  tests/e2e/orchestration-worker-settlement-release-cli.spec.ts \
  --config tests/playwright.config.ts \
  --project electron-headless \
  --workers=1
  • Latest main 5ea7df1a5b: red. A real compiled CLI process using the wrong worker identity exited 0 with ok:true while the Dispatch stayed dispatched; the valid caller received no explicit lifecycle verdict; worker-release left SQLite at external/retained.
  • Combined candidate: green. Wrong identity exits nonzero with JSON ok:false / dispatch_capability_invalid; Task and Dispatch remain dispatched; the exact worker receives {action:"completed"}; an independent RPC read observes completed; compiled worker-release returns released with processAction:"none"; an independent SQLite read observes released/released; the coordinator terminal remains live.
  • Candidate with the claimed production files restored to merge-base 64aec94cb2: red with the same false-success and retained-state failures.
  • Final rebased head 1416f0f126 on latest origin/main 4b9fb46646: green in 19.3 seconds.

Additional validation:

  • 242/242 combined focused CLI/runtime/DB/federation/release tests.

  • 4/4 combined Electron cases: compiled CLI, legacy/current restart recovery, and worker visibility.

  • Fresh combined reviews: architecture/adversarial 89 tests; performance/resource 149 tests; platform/security/compatibility 520 tests; all clean.

  • pnpm typecheck

  • pnpm lint (only existing WorktreeJumpPalette.tsx hook warnings)

  • reliability manifest, max-lines ratchet, changed-code quality, localization checks, and git diff --check

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implemented and reviewed with Codex agent assistance under maintainer supervision.

Review

Fresh adversarial architecture/readiness, performance/resource, and security/platform/wire-compatibility reviews found no actionable issues. Optional wire fields are capability-negotiated; missing or malformed identities remain unknown; no new polling, retries, unbounded collections, subprocess fanout, or process-close path was added. SSH uses the exact target inventory, while local/WSL use the provider's combined inventory and match only exact immutable PTY incarnation.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, and proportional focused/E2E builds and tests pass; full CI is required before merge

Author

  • X / Twitter: N/A

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bd471d18-f4c3-48ac-81cf-1cf4d026aa2f

📥 Commits

Reviewing files that changed from the base of the PR and between d4cf101 and 1416f0f.

📒 Files selected for processing (2)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.ts

📝 Walkthrough

Walkthrough

Added federated lifecycle settlement support with protocol version 3 and capability negotiation. Remote worker results now wait for Run-home confirmation. Federation synchronization exchanges settlement records and replays unacknowledged relays. CLI handling validates legacy worker reports and throws structured rejection errors. Worker release now checks exact process-incarnation liveness and reconciles dead resources without closing processes. Tests and reliability-gate metadata cover settlement, replay, rejection, migration, JSON output, release, and compiled-CLI behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the PR's main changes: authoritative worker completion and cleanup decisions.
Description check ✅ Passed The description covers all required sections, linked issues, testing, visual proof, risks, review considerations, and checklist items.
✨ 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.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Review rate limited.

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.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Review rate limited.

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.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 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.

Actionable comments posted: 6

🧹 Nitpick comments (7)
src/cli/handlers/orchestration.ts (1)

605-607: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

This rejection branch is unreachable.

Line 594 throws RuntimeClientError for any result whose lifecycle.action is rejected, including the relay shape. printResult therefore never runs with a rejected relay lifecycle, so this branch is dead code.

Remove it, or restrict the throw at line 594 to the non-relay shapes if the relay case is meant to print instead of fail.

src/main/runtime/rpc/methods/orchestration-federation-relay.ts (2)

89-98: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider logging settlements dropped above the acknowledged watermark.

The filter discards any settlement whose sequence exceeds throughSequence without a response signal. The sending peer receives acknowledgedThrough only, so it cannot tell that its settlement was ignored. The Run-home waiter then blocks until the 30-second timeout in src/main/runtime/rpc/methods/orchestration.ts and returns operation_unknown. A debug log at the drop point would make that path diagnosable.

The publish-after-acknowledge ordering is correct. The durable acknowledgement commits before waiters are released.


22-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive FederatedLifecycleSettlement from the shared schema.

The inline schema duplicates FederatedLifecycleSettlement. Export the schema from src/main/runtime/orchestration/federation-lifecycle-settlement.ts, infer the type from it, and remove the cast at Line 95. This keeps the wire contract and TypeScript type aligned.

Zod 4 supports multi-value discriminators, so z.enum(['completed', 'failed']) is valid here.

src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts (1)

23-49: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assert that the handler rejected before you format the error.

If ORCHESTRATION_HANDLERS['orchestration send'] resolves instead of rejecting, rejection stays undefined. reportCliError then prints a runtime_error envelope and the test fails on the code mismatch. The failure message points at the envelope contents rather than at the missing rejection, which makes the regression harder to diagnose.

An explicit guard names the real cause.

♻️ Proposed refactor
   } catch (error) {
     rejection = error
   }
 
+  expect(rejection).toBeDefined()
   reportCliError(rejection, true, { commandPath: ['orchestration', 'send'] })

The fixture is otherwise correct. The rejected lifecycle carries no relay key and no authority, so the verdict short-circuits the compatibility reads and the single call mock is sufficient.

src/cli/handlers/orchestration-lifecycle-rejection.test.ts (2)

183-262: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider asserting the call count in the two acceptance tests.

expect(process.exitCode).not.toBe(1) passes for undefined, 0, and any value other than 1. The real signal in these tests is that the awaited handler did not reject. Neither test asserts that the two compatibility reads actually ran, so a regression that skips verification and accepts the report unconditionally would still pass.

The test on Line 105 already uses toHaveBeenCalledOnce() for the opposite case. The same style applies here.

♻️ Proposed refactor
-  expect(process.exitCode).not.toBe(1)
+  expect(callMock).toHaveBeenCalledTimes(3)
 })

Apply the same change to the retry test on Line 261.


13-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Drain callMock’s one-time queue in afterEach.

Add callMock.mockReset() after vi.clearAllMocks(). Do not replace vi.clearAllMocks(), because it also clears call history for printResult and other module mocks.

src/cli/handlers/orchestration-migration.test.ts (1)

15-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that settled results require only the send call.

Add expect(call).toHaveBeenCalledOnce() to ensure both settlement variants bypass compatibility reads.

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d49e322c-8578-473f-bf1b-5192961ea19c

📥 Commits

Reviewing files that changed from the base of the PR and between 64aec94 and d7b6089.

📒 Files selected for processing (18)
  • config/reliability-gates.jsonc
  • src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts
  • src/cli/handlers/orchestration-lifecycle-rejection.test.ts
  • src/cli/handlers/orchestration-migration.test.ts
  • src/cli/handlers/orchestration-worker-settlement.ts
  • src/cli/handlers/orchestration.test.ts
  • src/cli/handlers/orchestration.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/federation-lifecycle-settlement.ts
  • src/main/runtime/orchestration/federation-sync.ts
  • src/main/runtime/rpc/methods/orchestration-federated-worker-start.ts
  • src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation-relay.ts
  • src/main/runtime/rpc/methods/orchestration-federation-start-schema.ts
  • src/main/runtime/rpc/methods/orchestration-federation.test.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/main/runtime/rpc/methods/orchestration.ts
  • src/shared/protocol-version.ts

Comment thread config/reliability-gates.jsonc Resolved
Comment thread src/main/runtime/orchestration/db.ts Resolved

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

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

5359-5360: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add an intermediate-state assertion for worker_done settlement.

The production path omits settleRemoteOutcome and settles the attachment through the Run-home acknowledgment. Extend the existing lifecycle test to assert state: 'ready' before acknowledgment and the terminal state afterward.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a0bfef34-ac33-48dc-92cd-7af5deae8bba

📥 Commits

Reviewing files that changed from the base of the PR and between d7b6089 and fbdaebc.

📒 Files selected for processing (10)
  • config/reliability-gates.jsonc
  • src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts
  • src/cli/handlers/orchestration-lifecycle-rejection.test.ts
  • src/cli/handlers/orchestration-migration.test.ts
  • src/cli/handlers/orchestration-worker-settlement.ts
  • src/cli/handlers/orchestration.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/federation-lifecycle-settlement.ts
  • src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts
  • src/main/runtime/rpc/methods/orchestration-federation-relay.ts
💤 Files with no reviewable changes (1)
  • src/cli/handlers/orchestration.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/cli/handlers/orchestration-lifecycle-rejection.test.ts
  • src/cli/handlers/orchestration-worker-settlement.ts
  • config/reliability-gates.jsonc
  • src/main/runtime/orchestration/federation-lifecycle-settlement.ts
  • src/main/runtime/rpc/methods/orchestration-federation-relay.ts
  • src/cli/handlers/orchestration-migration.test.ts

@Jinwoo-H
Jinwoo-H force-pushed the worker_done-with-mismatched-sender-identity-retu branch from fbdaebc to 6e4f891 Compare August 12, 2026 04:43
@Jinwoo-H Jinwoo-H changed the title Require authoritative worker_done settlement Make worker completion and cleanup authoritative Aug 12, 2026
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Addressed the remaining CodeRabbit test nit in d4cf101: the federation lifecycle oracle now asserts that the remote attachment is still ready after queueing and before Run-home acknowledgment, then asserts the terminal settled state afterward. The focused federation suite passed 9/9, typecheck passed, and the final compiled-CLI Electron oracle passed on this exact head. @coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

@Jinwoo-H The reported test-oracle update is clear. I will review the current PR changes.

⚠️ Action not completed

Already reviewed.

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.

🧹 Nitpick comments (2)
tests/e2e/orchestration-worker-settlement-release-cli.spec.ts (1)

243-253: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Set busy_timeout on the test SQLite handles.

The test opens orchestration.db while the Electron application holds the same file open. The application sets busy_timeout = 5000 (see src/main/runtime/orchestration/db.ts lines 325-327), but this handle does not. In WAL mode only one writer proceeds at a time, so a concurrent application write makes the UPDATE on line 250 fail immediately with SQLITE_BUSY instead of waiting.

The window is small because the worker already settled and its terminal is closed. Adding the pragma removes the residual flake risk on a reliability-gate spec.

Apply the same pragma to the verification handle opened on line 267.

♻️ Proposed change
   const db = new Database(path.join(userDataDir, 'orchestration.db'))
   try {
+    db.pragma('busy_timeout = 5000')
     db.prepare(
       `UPDATE worker_terminal_resources
        SET ownership_state = 'external', release_state = 'retained',
            retained_reason = 'external_terminal'
        WHERE owner_dispatch_id = ?`
     ).run(dispatch.result.dispatch!.id)
   } finally {
     db.close()
   }

Apply the same addition to the verification handle:

   const verified = new Database(path.join(userDataDir, 'orchestration.db'))
   try {
+    verified.pragma('busy_timeout = 5000')
     expect
       .soft(
src/main/runtime/rpc/methods/orchestration-worker-release.test.ts (1)

725-744: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert that transferred ownership remains unreleased. After the old dispatch release, assert that the second worker’s resource retains ownership_state: 'owned' and release_state: 'not_requested'.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1eba2d0e-afba-4dab-b2d0-a488ee40808c

📥 Commits

Reviewing files that changed from the base of the PR and between fbdaebc and d4cf101.

📒 Files selected for processing (9)
  • config/reliability-gates.jsonc
  • src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/worker-terminal-process-liveness.ts
  • src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.ts
  • tests/e2e/orchestration-worker-settlement-release-cli.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/rpc/methods/orchestration-federation-lifecycle-settlement.test.ts

@Jinwoo-H
Jinwoo-H force-pushed the worker_done-with-mismatched-sender-identity-retu branch from d4cf101 to 1416f0f Compare August 12, 2026 06:00
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Rebased onto current origin/main 4b9fb46. On exact head 1416f0f: pnpm run build:cli plus the real compiled-CLI Electron E2E passed; 89 focused completion, federation, and cleanup tests passed; typecheck, lint, reliability gates, and diff checks passed. @coderabbitai review the latest head.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

@Jinwoo-H I will review the latest head, including the rebase changes and the reported validation coverage.


🧠 Learnings used
Learnt from: CR
Repo: stablyai/orca PR: 0
File: tests/e2e/AGENTS.md:0-0
Timestamp: 2026-06-11T00:43:14.505Z
Learning: Build the app with `electron-vite build --mode e2e` before running E2E tests; the Zustand store is only exposed to `window.__store` when the preload bundle is built in `e2e` mode
⚠️ Action not completed

Already reviewed.

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.

@Jinwoo-H
Jinwoo-H merged commit 7319d59 into main Aug 12, 2026
53 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix: require authoritative worker completion verdicts

* Harden federated settlement replay

* fix(orchestration): reconcile dead retained workers

* docs: record SSH worker release coverage

* test(e2e): exercise worker settlement and release CLI

* docs: register combined orchestration CLI oracle

* test(orchestration): pin pre-ack attachment state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant