Repository navigation
fix(terminal): sweep leftover processes when a PTY exits on its own - #22348
brennanb2025 wants to merge 3 commits into
Conversation
A terminal session that ended by itself never had its descendants swept. The sweep ran only on an explicit kill or daemon shutdown, and it worked by walking the process table down from a live root — which a natural exit has already reaped. Anything that had reparented to pid 1, or that sat outside the terminal's foreground group where the kernel's hang-up never lands, survived its session indefinitely. Teardown now runs from an identity the session records while it is alive: its root pid and start time, its controlling terminal, and every process group it has been seen to own. Kill, shutdown and natural exit share that one sweep.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 📝 WalkthroughWalkthroughThe changes add PTY process identity capture and process-table observers. A shared descendant sweep selects and signals session processes using recorded identities, process groups, and terminal rows. Terminal teardown uses the sweep for killed and naturally exited sessions, and daemon disposal waits for in-flight exit sweeps. Retired session incarnation handling moves to a dedicated class. Unit and integration tests cover identity capture, target selection, signal escalation, and terminal lifecycle behavior. Priority: ➖ Normal Merge Risk: 🟠 High · up to Terminal cleanup can miss surviving jobs or stop unrelated processes. Resolve the identity and failed-read safeguards before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, platform impact, and checklist. However, it does not provide the required tracked issue link, and it does not confirm that lint, typecheck, test, and build pass or that CI will cover them.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: d4ed4c1b-2873-4fbb-bd8f-9fa8a87b4511
📒 Files selected for processing (23)
src/main/daemon/session.tssrc/main/daemon/terminal-descendant-shutdown.test.tssrc/main/daemon/terminal-host-disposal.tssrc/main/daemon/terminal-host-natural-exit-sweep.test.tssrc/main/daemon/terminal-host-retired-incarnations.tssrc/main/daemon/terminal-host-session-identity-observation.tssrc/main/daemon/terminal-host-session-shutdown.tssrc/main/daemon/terminal-host.tssrc/main/daemon/terminal-session-descendant-sweep.test.tssrc/main/daemon/terminal-session-descendant-sweep.tssrc/main/daemon/terminal-session-teardown.tssrc/main/pty-session-descendant-sweep.integration.test.tssrc/main/pty-session-descendant-sweep.test.tssrc/main/pty-session-descendant-sweep.tssrc/main/pty-session-identity.test.tssrc/main/pty-session-identity.tssrc/main/pty-session-sweep-targets.test.tssrc/main/pty-session-sweep-targets.tssrc/main/pty-session-tty-process-table.tssrc/main/pty/posix-pty-foreground-group.tssrc/shared/cheap-process-table-snapshot-reader.tssrc/shared/process-table-capture-observers.tssrc/shared/process-table-snapshot-reader.ts
💤 Files with no reviewable changes (1)
- src/main/daemon/terminal-descendant-shutdown.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.
| const timer = setTimeout(() => { | ||
| void readTtyTable(identity.ttyName ?? '').then( | ||
| (capture) => { | ||
| if (capture) { | ||
| observePtySessionTerminal(identity, capture.rows) | ||
| } | ||
| }, | ||
| () => { | ||
| // An unreadable terminal leaves the identity as spawn described it. | ||
| } | ||
| ) | ||
| }, deps.delayMs ?? POST_SPAWN_IDENTITY_CAPTURE_DELAY_MS) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Capture identity before a short-lived root can exit.
If a shell starts a detached, terminal-free job and exits within 750 ms, markPtySessionRootExited prevents this delayed capture from recording its group. The exit sweep then has neither a group nor a terminal row that identifies the surviving job. Start an identity capture promptly after spawn; retain the delayed capture to catch jobs that settle later.
There was a problem hiding this comment.
Important
The natural-exit sweep is well covered and the identity model reads consistently. Two things need a look before merge: a recycled root pid can seed the sweep's target set with a stranger's process group (the rest of the codebase guards exactly this), and the rename quietly breaks the daemon-shutdown oracle's --baseline mode.
Reviewed changes
- Session identity —
Sessionnow carries aPtySessionProcessIdentity(root pid, tty, rootlstart,knownPgids,rootExitedAtMs), populated at spawn, from a 750msps -tread of the session's own terminal, and from every shared process-table capture via a new observer registry. - Target set —
collectSessionSweepTargetsunions the ppid walk (only while the root is present and itslstartmatches), known-group membership, and tty membership (post-exit gated on a start time beforerootExitedAtMs), with Orca's pid/ancestors/groups protected and the tty claim dropped when Orca shares the terminal. - Sweep —
sweepSessionDescendantsre-derives targets each round, sends SIGTERM to each target and its group, and SIGKILLs only a pid that already took a same-identity SIGTERM, bounded by a verification window; Windows is a no-op. - Teardown wiring — kill, daemon shutdown, and a new natural-exit path (
handleSessionExit→sweepExitedSession, before the reap) all funnel through one sweep built on the identity;disposeawaits in-flight exit sweeps; the retired-incarnation map was extracted intoTerminalHostRetiredIncarnations. - Support —
readTtyProcessTable(ps -t), thenormalizeTty→normalizePtyTtyNameexport, and observer notification from both process-table readers.
I read the full diff, ran pnpm run typecheck:node (clean), the five new unit suites, terminal-session-teardown.test.ts, and the real-PTY integration suite (passes on Linux).
⚠️ The daemon-shutdown oracle's baseline mode no longer builds
run-daemon-shutdown-descendants-docker.mjs --baseline <ref> bundles the checked-out sources with the baseline versions of the files in its targets list substituted. The baseline terminal-session-teardown.ts and terminal-host-session-shutdown.ts still import { terminateShutdownDescendants } from './terminal-descendant-shutdown', and this PR deleted that module from the working tree, so esbuild cannot resolve it. Reproduced locally (ORCA_DOCKER=/bin/true node config/scripts/run-daemon-shutdown-descendants-docker.mjs --baseline HEAD^, EXIT 1): ERROR: Could not resolve "./terminal-descendant-shutdown" from both files. PR CI only runs the candidate bundle, so this will not fail the PR check, but it breaks the documented before/after command the tool exists for. The same rename also leaves the stale path in pr-code-change-scope.test.mjs (harmless — classification is src/-prefix based).
Technical details
# Oracle baseline cannot resolve the removed module
## Affected sites
- `config/scripts/run-daemon-shutdown-descendants-docker.mjs:23-29` — `targets` still names only the pre-rename production files.
- `config/scripts/run-daemon-shutdown-descendants-docker.mjs:58-73` — `baselinePlugin` only implements `onLoad`; it cannot resolve a path that no longer exists on disk.
- `config/scripts/pr-code-change-scope.test.mjs:225` — stale `terminal-descendant-shutdown.ts` entry.
## Required outcome
- `--baseline <ref>` bundles successfully again, with the baseline teardown/sweep sources replaced from `ref` and the candidate's new sweep modules used where the baseline did not have them.
- Changes to the new sweep files are attributed the same packaging scope the old file had.
## Suggested approach (optional)
- Add an `onResolve` to `baselinePlugin` that maps removed/renamed paths (`./terminal-descendant-shutdown`) to a virtual module holding the baseline content, or keep a deprecated re-export shim at the old path; and extend `targets` with the new `pty-session-*.ts` / `terminal-session-descendant-sweep.ts` files so a baseline build does not silently pick up candidate-only identity logic.
## Open questions for the human
- Is `--baseline` still expected to work (the README documents it), or has it been retired in favour of the candidate-only PR run?ℹ️ terminal-session-teardown.test.ts mocks the module this PR removed
The suite still does vi.mock('./terminal-descendant-shutdown', …) and drives its late-escalation test through terminateShutdownDescendantsMock, which now intercepts nothing. The test still passes, but finishDescendants() is inert and the case now blocks on the real sweep's 2.5s verification window instead of the injected promise — the first half of its assertions no longer prove anything. Pointing the mock at ./terminal-session-descendant-sweep restores the intended control.
Technical details
# Dead mock in terminal-session-teardown.test.ts
## Affected sites
- `src/main/daemon/terminal-session-teardown.test.ts:8-10` — `vi.mock('./terminal-descendant-shutdown')` targets a module that no longer exists.
- `src/main/daemon/terminal-session-teardown.test.ts:135` — `terminateShutdownDescendantsMock.mockReturnValueOnce(descendantVerification)` sets a promise production never reads.
- `src/main/daemon/terminal-session-teardown.test.ts:126-176` — the case named "waits for a late immediate escalation after graceful descendant verification settles".
## Required outcome
- The test gates escalation on an injected descendant-verification promise again, so `finishDescendants()` actually controls when the sweep settles.
## Suggested approach (optional)
- Mock `./terminal-session-descendant-sweep`'s `sweepTerminalSessionDescendants` in place of the removed module, and mock `../pty-session-identity` where needed (the real `rememberPtySessionPgids` currently runs against an unmocked `../pty-descendant-termination` whose `readProcessTable` is absent, so the sweep spins to its real deadline).DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
A group id is only the pid of the process that created it; once the group empties the kernel may give that id to an unrelated process. The sweep now records when each group was last seen owned, drops groups a capture shows empty, and claims a group member only when its leader (or, without one, the member itself) was born before that moment. Group-only matches never teach new groups, and only individually verified pids are signalled. A kill that left nothing behind and a natural exit whose owned groups are empty now settle from a signal-0 probe (plus one terminal read on natural exit) instead of reading the whole host table.
…or its exit time is known
There was a problem hiding this comment.
Important
Two soundness gaps in the new group-verification and fast-path logic: one can signal an unrelated process, the other lets a survivor escape the kill path. Both reproduced with probes.
Reviewed changes
- Group ownership model —
knownPgids: SetbecameownedGroups: Map<pgid, {lastOwnedAtMs}>;recordPtySessionGroupsadvances the last-owned time withMath.max, and a newprunePtySessionGroupsdrops any group a whole-host capture shows empty so a freed id cannot be claimed later. - Group verification —
collectSessionSweepTargetsnow verdicts every recorded group asleader-verified/leaderless/reusedand refuses group membership unless the leader (or the member itself, without a leader) was born before the group was last owned; group-only matches no longer extendlearnedGroups. - Signalling — dropped wholesale group signals;
sweepSessionDescendantsSIGTERMs only individually verified pids and SIGKILLs only a pid that already took a same-identity SIGTERM. - Fast paths — a kill whose pre-kill walk found nothing and whose non-root owned groups are all empty settles from a signal-0 probe with no table read; a natural exit whose owned groups are empty settles after one
ps -tread. - Wiring — the shutdown module was renamed to
terminal-session-descendant-sweep.tscarrying bothsweepTerminalSessionDescendantsandsweepSessionFromSnapshot; shared process-table captures now carrycapturedAtMs;terminal-host-session-shutdown.tsand the teardown paths route through the shared snapshot entry.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| const leader = byPid.get(pgid) | ||
| if (!leader || leader.pgid !== pgid) { | ||
| return 'leaderless' |
There was a problem hiding this comment.
verifyRecordedGroup reads the leader with byPid.get(pgid) without consulting the ambiguous set that indexRows already computes, even though rootRow and the accept loop both guard against duplicate pids. When a non-atomic capture holds the old leader row before a recycled stranger row for the same pid, the stale row proves leader-verified, and the stranger's children in that group are accepted and signalled. I reproduced it: collectSessionSweepTargets returned [8000] for a recycled group whose leader pid was duplicated.
Technical details
# Ambiguous leader row vouches for a recycled group id
## Affected sites
- `src/main/pty-session-sweep-targets.ts:105-107` — `byPid.get(pgid)` uses the first duplicate row; `ambiguous` is never consulted here.
- `src/main/pty-session-sweep-targets.ts:141` — `rootRow` is guarded by `ambiguous.has(identity.rootPid)`.
- `src/main/pty-session-sweep-targets.ts:200` — the accept loop skips `ambiguous.has(row.pid)`, but the leader has already vouched for the group at :174-175.
- `src/main/pty-session-sweep-targets.test.ts:185` — the duplicate-pid test duplicates a *member* pid, not the leader pid, so this is uncovered.
## Required outcome
- A recorded group may only be `leader-verified` when its leader row is unambiguous in this capture; an ambiguous leader must fall back to `leaderless` (each member proves its own birth time) or `reused`.
## Suggested approach (optional)
- Thread the `ambiguous` set into `verifyRecordedGroup` (or compute a guarded `byPid` once, as :141 does for the root) and return `leaderless` when `ambiguous.has(pgid)`.
## Evidence
- Probe: identity `rootPid=500`, `ownedGroups={777: {lastOwnedAtMs: 12:54:55}}`, exited; rows `[SELF_ROWS, {pid:777, pgid:777, startedAt:BEFORE}, {pid:777, pgid:777, startedAt:AFTER}, {pid:8000, ppid:777, pgid:777, startedAt:AFTER}]` → `targets.rows = [8000]`.| if ( | ||
| snapshot.descendants.length === 0 && | ||
| // The root's own group holds the root itself until the kill lands. | ||
| !hasLiveOwnedGroup(identity, { | ||
| exceptRootGroup: true, | ||
| ...(deps.probeGroup ? { probeGroup: deps.probeGroup } : {}) | ||
| }) | ||
| ) { | ||
| return Promise.resolve('exited') |
There was a problem hiding this comment.
The kill fast path skips the root's own group, so a descendant that reparented to pid 1 while staying in that group is unreachable by the pre-kill ppid walk and never probed — the sweep returns exited and the survivor lives on. I reproduced it: with the root group recorded and a reparented member 700 still in it, collectSessionSweepTargets returns 700, while sweepSessionFromSnapshot returns exited without signalling. This is a regression from 229374e, which always swept.
Technical details
# Kill fast path drops survivors that stayed in the root's group
## Affected sites
- `src/main/daemon/terminal-session-descendant-sweep.ts:72-80` — `snapshot.descendants.length === 0` plus `exceptRootGroup: true` returns `exited` with no read and no signal.
- `src/main/pty-session-descendant-sweep.ts:61-75` — `hasLiveOwnedGroup` skips `pgid === identity.rootPid`, which is exactly where a shell's non-job-control children live.
- `src/main/pty-session-sweep-targets.ts:109-110,169-175` — if the sweep ran, that survivor would be `leader-verified` for the root group and accepted.
## Required outcome
- A kill whose pre-kill walk found nothing must not settle while a recorded group that could still hold work is unverified. A member in the root's group is the motivating escapee of this PR; it should not be skipped by the optimization.
## Suggested approach (optional)
- The natural-exit path already pays one `ps -t <tty>` read (~30ms) before settling; a single terminal read before settling the kill fast path would see a reparented member still on the session's terminal. Alternatively, drop `exceptRootGroup` and accept that the root group can only be proven empty by a read, so the fast path applies only when no group is recorded.
## Open questions for the human
- Is "the root group holds only the root" an assumption you intend to rely on for non-interactive shells (`sh -c 'tool &'`), where children stay in the shell's group?There was a problem hiding this comment.
✅ No new issues found in this delta.
Reviewed changes
- Terminal-claim boundary —
claimsTtynow trusts a tty row only while the root is alive in the same capture, or when a recordedrootExitedAtMsbounds the row's start time. A kill records no exit time, so once the root is absent the terminal claim is dropped rather than accepting every row on a terminal that may have been reassigned to a new session. - Tests — two cases pin both directions: no terminal row is trusted after a kill reaped the root with no recorded exit time, and every terminal row is trusted while the root is alive in the capture.
The delta is a targeted tightening of the tty claim and reads consistently; the two soundness gaps from the previous review (ambiguous group leader at pty-session-sweep-targets.ts:105, and the kill fast path skipping the root's own group at daemon/terminal-session-descendant-sweep.ts:72-80) are unaffected by this commit and remain open as inline threads.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
When a terminal closes by itself (the shell exits, an agent finishes), Orca never cleaned up the programs that terminal had started in the background. Some of those programs keep running forever. One real case was a tool shell that sat at 85% CPU for a week after its agent session had ended. Orca now cleans up after a terminal however it ends, not only when you close it or quit the app.
What Changed
Before: Orca swept a session's leftover processes only on an explicit kill or on daemon shutdown. Even then it found them by walking down the process tree from the session's first process (the "root"). When a session exits on its own, the root has already been reaped. Its children have reparented to pid 1, and a shell's background jobs sit in their own process groups where the terminal's hang-up signal never reaches. So anything that ignored the hang-up survived indefinitely.
After: each session keeps a record of which processes it owns, so teardown still knows where to look after the root is gone:
Kill, shutdown and natural exit now share one sweep built on that record.
Mechanism:
Identity (
pty-session-identity.ts)process-table-capture-observers.ts). That lets live sessions learn their descendants' groups with no new polling.Group ownership (
pty-session-identity.ts). A group id is only the pid of the process that created it. Once every member exits, the kernel may give that id to an unrelated process's new group. So each recorded group carries the last time a capture showed the session owning it:Targets (
pty-session-sweep-targets.ts, a pure function). The target set is the union, taken to a fixpoint, of:A process claimed only through group membership never teaches the sweep another group. Only a process reached by descent or by the terminal extends what the session owns.
Protection: Orca's own pid, its ancestors, and their process groups are never targeted. If a protected process shares the terminal, the terminal claim is dropped entirely.
Escalation (
pty-session-descendant-sweep.ts)hasUnambiguousStartIdentitycheck, so a recycled pid is never force-killed.Cost:
kill(-pgid, 0)probe finds every recorded job group empty. It settles immediately with no process-table reads, as it did before this PR. The root's own group is skipped by this probe, because the root is still in it until the kill lands.kill(-pgid, 0)per recorded group (a syscall each, no fork). If every group is empty, oneps -t <tty>(about 30ms) is read. If nothing on the terminal predates the exit, the sweep ends there. The whole-host table is read only when a recorded group still has a member, or when the terminal still holds a process from before the exit.Natural exit (
terminal-host.ts,terminal-session-teardown.ts)Behaviour change: a job started with
nohup cmd &ordisown, followed by the shell exiting on its own, is now terminated. This matches what closing the terminal explicitly already does.Windows: unchanged. The per-PTY job object already owns the tree, and the sweep returns immediately on win32.
Why
The underlying bug was architectural. Cleanup was defined as "everything below the root", and that question has no answer once the root is gone. A second guard on the kill path would not have reached natural exits. Instead the session now carries the facts that still hold after exit (its groups, its terminal and its start time), and every teardown path uses them.
Deviations from a fuller design, each deliberate:
ps -t <tty>.live, and an unreadable table is reportedunverifiable, not assumed dead.SSH: the sweep runs inside the terminal daemon on the execution host, so remote sessions get it on their own host. Nothing new crosses the wire.
Linked Issue
No tracked issue; this was reported directly.
Visual Proof
N/A. This change only affects background process cleanup, with nothing on screen. Before/after evidence comes from the ablations below.
Testing
New tests:
pty-session-sweep-targets.test.ts: the pure targeting function. Covers:pty-session-descendant-sweep.test.ts:A second block learns groups through the production path, the live-session observer fed by
notifyProcessTableCapture, and then checks four cases. The job the live tree owned is reaped. A stranger leading a reused group id is left alone. A later member of a leaderless group is left alone. A group the live captures saw empty is forgotten.pty-session-identity.test.ts:pty-session-descendant-sweep.integration.test.ts(real PTY, skipped on Windows): the shell backgrounds a job into its own process group that ignores HUP/TERM/INT and loops. The job's group is learned from a real host capture through the live-session observer. Two variants:In both, the job is gone afterwards.
terminal-host-natural-exit-sweep.test.ts: a natural exit sweeps from the session's identity, skips when a kill is already sweeping, and dispose waits for the sweep.terminal-session-descendant-sweep.test.ts:Before/after evidence: each check below removes one part of the fix at the final commit, runs the tests, then restores the file from the commit. Each edit was asserted to match exactly once. Every one turns its test red, and every test passes with the fix in place.
refuses a recorded group whose id a stranger took…andleaves alone a stranger that took the group id…(via the live observer)refuses a recorded group whose id a stranger took…,leaves alone a stranger that took the group id…without a leader, claims only members born while the group was still owned,leaves alone a later member of a leaderless group…without a leader, claims only members born while the group was still ownedforgets a group once a whole-host capture shows it empty…,forgets a group the live captures saw empty…settles a natural exit whose only group is the root's, now empty, with one terminal readsettles a kill that left nothing behind without reading any table. The sibling test in that file also fails, because the aborted sweep leaks into it.trusts no terminal row once the root is gone without a recorded exit timereaps the job the live tree was seen to ownFrom the first commit of this PR, still holding: removing the natural-exit sweep call fails
sweeps from the exiting session identity, not from its reaped root pid.Commands run on macOS:
pnpm tc: pass.pnpm exec oxlint src/main src/shared: pass.pnpm run check:code-quality:changed: pass.env -u ORCA_STRUCTURED_SESSION pnpm test src/main/pty-session src/main/pty-descendant src/main/daemon src/shared: 982 files, 11052 passed, 141 skipped.pty-subprocess-io-failure-native.test.tsalone, 4 runs: 4/4 pass.Not tested on Linux or Windows locally. Linux uses the same code path with
pts/Nterminal names. Windows returns before any sweep.AI Disclosure
Written with Claude Code (Claude Opus).
Review
Author: @BrennanKB5
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
Remaining gaps and adjacent issues (not fixed here):
src/main/daemon/pty-subprocess-io-failure-native.test.tsalso fails intermittently onmainunder load. An earlier revision of this branch added a terminal read and a whole-host read to every kill, even one that left nothing behind. That cost is gone now: such a kill settles with no reads, as onmain. After this change the test passed 4/4 alone and passed in the full directory run.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)