Repository navigation
fix(orchestration): reland process-incarnation reap for stale worker terminal handles - #23583
Conversation
…terminal handles Relands the orchestration part of #18790, which #22601 reverted in full because that squash commit also bundled an unannounced agent. Only the worker terminal-reap fix returns; no agent catalog changes. When a worker's saved terminal handle stops resolving while its process is still running, worker-show/read, worker-stop and worker-release now re-mint a live handle from the recorded process incarnation (exact pty id + incarnation id, same host scope) and act on it, instead of reporting the terminal missing and leaving the process running on the host. Fixes STA-8493
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 📝 WalkthroughWalkthroughThe runtime can resolve a terminal handle by exact process incarnation and serialized host scope. Worker observation returns the effective handle, which read, stop, and release paths use when available. Release also checks process liveness before settling missing-terminal cases. Tests cover matching, reminting, release outcomes, and protection against closing a PTY with a replacement incarnation. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to This change lets worker read, stop, and release reach a still-running process after its saved terminal handle goes stale, with safeguards against closing a replacement process. No functional problems were found. The remaining feedback concerns test cleanup only. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to Recovering a stale worker handle can prevent abandoned processes, but it also changes which terminal can be read or stopped and when a release is considered complete. The identity and ownership checks are substantial; caller authorization and some downstream receipt behavior remain unverified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 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.
🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts (1)
19-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
createOrchestrationWorkerReleaseHarnessand remove the stacked lint directives.
setup,findMethod,call,startWorker,settle, andstartSettledWorkercopycreateOrchestrationWorkerReleaseHarnessinworker-release.test-support.tsline for line. That harness already mapsterm_remintedin its pane-key, incarnation, and authority spies, and it exposesinspectProcessLiveness.worker-release-runtime-incarnation.test.tsalready uses it. If the two copies drift, the release fixtures will disagree without warning.The file also has many repeated
oxlint-disable-next-line typescript/consistent-type-assertionscomments that suppress nothing:
- Lines 26-29 and 199-203 stack up to six copies before a single
(. The disable applies to the(line, not to theas unknown asline.- Lines 161-162, 380, 492-493, 535, 537, and 584 sit before code that has no type assertion.
These comments hide where real suppressions are needed.
♻️ Sketch
-describe('orchestration worker release incarnation fallback', () => { - let db: OrchestrationDb - ... - function setup(): void { ... } +describe('orchestration worker release incarnation fallback', () => { + const h = createOrchestrationWorkerReleaseHarness() + afterEach(() => h.cleanup()) + /** Replace the runtime resolver with a stub for one scenario. */ + function stubResolver(value: string | null) { + const fn = vi.fn().mockReturnValue(value) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test stubs a runtime method. + ;(h.runtime as unknown as { resolveTerminalHandleByProcessIncarnation: typeof fn }) + .resolveTerminalHandleByProcessIncarnation = fn + return fn + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 8c423e9d-be07-4811-8d9f-a86ec1d19cb0
📒 Files selected for processing (13)
src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.tssrc/main/runtime/orca-runtime-terminal-handle-incarnation.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.test.tssrc/main/runtime/orchestration/worker-terminal-process-liveness.tssrc/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.tssrc/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.tssrc/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-control.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-observation.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-release-runtime-incarnation.test.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-stop.tssrc/main/runtime/rpc/methods/orchestration/worker/worker-terminal-release-lease.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — one cleanup nit in the relaunched test files.
Reviewed changes
resolveTerminalHandleByProcessIncarnation— new runtime method that re-mints a live handle from the recorded${ptyId}:${incarnationId}plus host scope when the durable handle is stale; exact-incarnation, same-scope, fail-closed, and continues past ambiguous scope mismatches.- Effective-handle plumbing —
inspectWorkerTerminalsurfacesterminalHandle(durable or re-minted), andworker-control/worker-stop/worker-release-completion/worker-terminal-release-leasenow probe pane, incarnation, authority, and close through it while ownership still compares the durable handle to the resource. - Released-on-positive-exit ordering — the exited-incarnation
settleDeadWorkerTerminalReleaseblock moved out of themode === 'recovery'gate so a provably-exited missing worker settlesreleasedin interactive mode too, now withprocessAction: 'none'. releaseUnknownRecovery— recovery guidance centralized and reworded to require a fresh request id.- Tests — new direct resolver tests, unit release/stop/read tests, a two-plane functional leak reproduction, and a real-runtime integration test.
The merge resolutions against current main check out: worker-control keeps the awaited readStructuredWorkerOutput with the live handle added before it, and the structured branch of worker-observation keeps addressable beside terminalHandle: null. I traced the remint through the real runtime — after a graph reload clears handles/handleByPtyIncarnation, the synthetic pty: handle still resolves the PTY record's own paneKey/incarnationId, so isDispatchProcessCurrent passes and the close actually lands. Moving the settle block is exact-incarnation CAS fenced, never closes, and matches the pre-existing worker-release.ts retained branch; no consumer branches on the old 'closed_exited_terminal' value on this path.
ℹ️ Nitpicks
- Stacked/duplicated
// oxlint-disable-next-line typescript/consistent-type-assertionscomments in the three relaunched test files — roughly 80 extra lines (e.g.src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts:26-29,:53-55,:60-62,:67-69). Each multi-lineas never/as unknownassertion carries two or three adjacent disables where one suffices. It reads like a reland artifact; dropping the redundant copies would cut a lot of noise. Not CI-blocking — the changed-code gate explicitly exempts casting-directive unused warnings.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
… casting the runtime
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This run reviewed the delta since the prior pullfrog review (be6422d3dc → ac2809c920): a test-only commit touching three relaunched test files.
- Typed spies replace boundary casts — the relaunched tests now stub
resolveTerminalHandleByProcessIncarnationandinspectTerminalProcessIncarnationLivenessthroughvi.spyOnon the publicOrcaRuntimeServicemethods, dropping theruntime as unknown as { … }fixtures and the stackedoxlint-disable-next-line typescript/consistent-type-assertionsdirectives around them. Both methods are public, so the casts were never required. - No production or behavior change — all three changed files are tests; the production hunks are untouched since the previous review. I ran the three changed test files (31/31 pass) and
pnpm run typecheck:node(pass), confirming theMockInstance<OrcaRuntimeService['inspectTerminalProcessIncarnationLiveness']>typing and thevi.spyOninterception hold. Spies are restored via the existingafterEach(() => vi.restoreAllMocks()), and theresolveByIncarnationassertions still prove the re-mint is what production calls.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
When Orca runs an orchestration worker, it saves the address of that worker's terminal. That address can stop working while the worker's program is still running. Orca would then say the terminal was gone and never shut the program down, so on a Remote Server those programs piled up until the machine ran out of memory or process slots. This brings back the fix that finds the same terminal again from the worker's saved process identity, so stopping and releasing the worker actually ends it.
What Changed
This is the orchestration half of #18790, and nothing else. #22601 reverted all of #18790 because its squash commit also added an unannounced third-party agent. This PR restores only the worker terminal cleanup. It makes no agent catalog, icon, locale, README, docs, mobile or telemetry changes.
Before: a worker's saved terminal handle can stop resolving while its process lives, because handles are tied to one runtime session and one renderer terminal list. When that happened,
worker-show/worker-readreported the terminalmissing, andworker-stopandworker-releaserefused to close it. The agent process kept running on the host.After: when the saved handle resolves nowhere,
inspectWorkerTerminallooks up the worker's recorded process identity (exact PTY id plus incarnation id, on the same recorded host scope) and issues a fresh live handle for that PTY. Read, stop, release, archive capture, and the release ownership checks use that live handle. The saved handle still decides ownership, so a reused PTY id belonging to another process is never matched. If the host scope is unknown, the lookup finds nothing and changes nothing.If no live terminal carries the worker's incarnation and the host positively reports that process as exited, release settles it as released. A release in recovery mode no longer waits for another pass to do this. Loss of contact still reports
unverifiable, neverexited. A structured-worker release failure now tells the caller to retry with a fresh request id, since replaying the old id only returns the same receipt.Main has changed since the revert, and two merges needed hand resolution. In
worker-control.ts, main now awaitsreadStructuredWorkerOutput; that is kept, and the live handle is added before it. Inworker-observation.ts, main added the structured-workeraddressablefield; it is kept alongside the newterminalHandle: null. The test files match #18790 except for one change: they now use typedvi.spyOnon the public runtime methods instead ofas unknown ascasts. Currentoxfmtmoved #18790's stacked lint-suppression comments off the cast lines, which failed the changed-code casting gate. The test logic is unchanged.Why
The saved handle only ever lasts one runtime session. The recorded process incarnation and host scope are the identity that outlives it, and they already fence the release. Deriving the live handle from that identity each time, without persisting a second copy, means no new stored state can go stale or disagree. The lookup fails closed: it needs an exact incarnation match on the same host scope, and the result still has to pass the existing process-current and lease checks before anything is closed.
This relands the change that was already reviewed in #18790, adapted to current main, instead of redesigning it. The ticket asks for exactly that, and the leak has been live on Remote Server since the revert. A broader follow-up would have every path that acts on a dispatch's terminal, including mail delivery and the federated attachment inspector, resolve through one shared "live handle for this dispatch" resolver. This PR does not do that.
Linked Issue
Fixes STA-8493. Relands the orchestration part of #18790 (reverted by #22601).
Visual Proof
N/A: no UI changes. This only changes how the background worker cleanup finds its terminal. The runtime tests below cover the behavior.
Testing
Run on macOS:
pnpm tc:node: pass.src/main/runtime/rpc/methods/orchestration,src/main/runtime/rpc/methods/orchestration-worker*andsrc/main/runtime/orchestration: 219 files, 1,817 tests pass (10 skipped).resolveTerminalHandleByProcessIncarnationforced to return null, 8 tests fail. These are the 4 direct runtime lookup tests plus the release, stop, read and disconnected runtime-composition tests. Restoring it makes all 45 pass again.oxlintandoxfmt --checkon the changed files, andcheck:code-quality:changed: pass.git grep -i freebufffinds nothing this PR adds.inspectWorkerTerminalmakes 5 of the spy-based tests fail again.AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
unverifiable, and only a positiveexitedfrom the host can settle a missing terminal.${ptyId}:${incarnationId}, so Windows drive-letter PTY ids and relay ids containing colons work. The tests cover both.federation-attachment-observation.ts) still uses only the saved handle.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)