Skip to content

fix(orchestration): reland process-incarnation reap for stale worker terminal handles - #23583

Merged
brennanb2025 merged 2 commits into
mainfrom
brennan/sta-8493-stale-remote-server-worker-terminal-handles-unreaped-after
Sep 28, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennan/sta-8493-stale-remote-server-worker-terminal-handles-unreaped-after

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1180 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1180
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​164 $\color{#cf222e}{\Huge{\mathbf{−}}}$​60 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​104

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-read reported the terminal missing, and worker-stop and worker-release refused to close it. The agent process kept running on the host.

After: when the saved handle resolves nowhere, inspectWorkerTerminal looks 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, never exited. 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 awaits readStructuredWorkerOutput; that is kept, and the live handle is added before it. In worker-observation.ts, main added the structured-worker addressable field; it is kept alongside the new terminalHandle: null. The test files match #18790 except for one change: they now use typed vi.spyOn on the public runtime methods instead of as unknown as casts. Current oxfmt moved #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

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Run on macOS:

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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

  • Remote/SSH: this is the Remote Server leak fix. An SSH worker with no liveness verdict stays unverifiable, and only a positive exited from the host can settle a missing terminal.
  • Cross-platform: the match is exact string equality on ${ptyId}:${incarnationId}, so Windows drive-letter PTY ids and relay ids containing colons work. The tests cover both.
  • Compatibility: no persisted schema, RPC frame, or mobile contract changes. The live handle is internal and is not published.
  • Performance: the fallback is a linear scan of tracked PTYs, and only runs when the saved handle no longer resolves. It adds no polling or subprocesses.
  • Known gap, not addressed here and also present in fix(orchestration): reap leaked worker terminals via process-incarnation fallback — stops an unbounded PTY/process leak on Remote Server (OOM / cgroup PID exhaustion) #18790: on the execution host, the federated attachment inspector (federation-attachment-observation.ts) still uses only the saved handle.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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, pnpm test, and pnpm build pass (or CI will cover; local preferred)

…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
@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The 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 be642

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 Review

Security architecture risk: 🟡 Moderate · up to be642

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly reachable actions are observation, output reading, stopping, and release of a recorded worker whose saved handle is stale. The inspected resolver does not support selecting an arbitrary PTY on another host.

Trust Boundaries and Controls

  • observed — A reminted handle is checked against the dispatch's current pane and process incarnation. Release additionally requires the worker's durable handle to match its resource and checks host authority and resource identity conflicts before proceeding.
  • observed — The reviewed worker-show, worker-read, worker-stop, and worker-release handlers address a caller-supplied dispatch ID. The examined RPC dispatch path does not itself establish a caller-to-dispatch authorization check for those methods; their effective caller boundary remains unverified.

Resilience and Maintainability Implications

  • observed — Contact loss or incomplete inventory is not treated as proof of process exit. Dead-process settlement requires a matching incarnation and transactional release preconditions, including archive preservation.

Hardening Proposals

  • proposed — Verify the caller-to-dispatch authorization boundary for each worker RPC, including callers selecting a dispatch whose saved terminal handle has become stale. This is a proof gap, not an established bypass.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 91.30% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 13 files.
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 and concisely describes the primary change: restoring process-incarnation-based cleanup for stale worker terminal handles.
Description check ✅ Passed The description follows the required template and explains the user impact, implementation, rationale, linked issue, testing, compatibility considerations, and scope. It also documents that there are …
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR

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.

🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts (1)

19-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse createOrchestrationWorkerReleaseHarness and remove the stacked lint directives.

setup, findMethod, call, startWorker, settle, and startSettledWorker copy createOrchestrationWorkerReleaseHarness in worker-release.test-support.ts line for line. That harness already maps term_reminted in its pane-key, incarnation, and authority spies, and it exposes inspectProcessLiveness. worker-release-runtime-incarnation.test.ts already 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-assertions comments 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 the as unknown as line.
  • 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

📥 Commits

Reviewing files that changed from the base of the PR and between a174a08 and be6422d.

📒 Files selected for processing (13)
  • src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts
  • src/main/runtime/orca-runtime-terminal-handle-incarnation.test.ts
  • src/main/runtime/orchestration/worker-terminal-process-liveness.test.ts
  • src/main/runtime/orchestration/worker-terminal-process-liveness.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-incarnation-fallback.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-reap-fixed.func.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/structured-worker-release-stop.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-release-runtime-incarnation.test.ts
  • src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts
  • src/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.

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

ℹ️ 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 — inspectWorkerTerminal surfaces terminalHandle (durable or re-minted), and worker-control/worker-stop/worker-release-completion/worker-terminal-release-lease now 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 settleDeadWorkerTerminalRelease block moved out of the mode === 'recovery' gate so a provably-exited missing worker settles released in interactive mode too, now with processAction: '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-assertions comments 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-line as never/as unknown assertion 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

✅ 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 resolveTerminalHandleByProcessIncarnation and inspectTerminalProcessIncarnationLiveness through vi.spyOn on the public OrcaRuntimeService methods, dropping the runtime as unknown as { … } fixtures and the stacked oxlint-disable-next-line typescript/consistent-type-assertions directives 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 the MockInstance<OrcaRuntimeService['inspectTerminalProcessIncarnationLiveness']> typing and the vi.spyOn interception hold. Spies are restored via the existing afterEach(() => vi.restoreAllMocks()), and the resolveByIncarnation assertions still prove the re-mint is what production calls.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant