Skip to content

fix(terminal): sweep leftover processes when a PTY exits on its own - #22348

Open
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/pty-exit-descendant-sweep
Open

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/pty-exit-descendant-sweep

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1047 $\color{#cf222e}{\Huge{\mathbf{−}}}$​47 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1000
Prod 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​988 $\color{#cf222e}{\Huge{\mathbf{−}}}$​83 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​905

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:

  • The root's pid and start time.
  • Its controlling terminal.
  • Every process group the session has been seen to own.

Kill, shutdown and natural exit now share one sweep built on that record.

Mechanism:

  • Identity (pty-session-identity.ts)

    • Recorded at spawn: the root pid and the terminal name.
    • About 750ms after spawn, Orca reads the session's own terminal. This picks up the root's start time and group, plus the group of any child that already moved itself into a new session.
    • Every process-table read Orca already takes feeds a small observer (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:

    • A group is recorded only on evidence of ownership: a descendant of the live root, or a process the sweep already verified. It is never recorded from a bare group id seen on some other row.
    • Every whole-host capture drops the groups it shows with no member, because an empty group's id is free for reuse.
    • For the root's own group, ownership extends to the root's exit, since the root held that id as its pid until then.
  • Targets (pty-session-sweep-targets.ts, a pure function). The target set is the union, taken to a fixpoint, of:

    • The ppid tree, while the root is still alive and its start time matches.
    • Members of a recorded group, but only once the group proves it was never reissued. If the group's leader is in the table, it must have been born before the group was last owned; a later-born leader means a stranger took the id, and the whole group is refused. Without a leader, each member must itself have been born before that moment.
    • Processes still on the session's terminal, but only while the root is alive in the same capture. After a natural exit, a process counts only if its start time is clearly before the recorded exit. A kill records no exit time, so once the root is gone the terminal claim is not used at all. That way a recycled terminal's new owner is never claimed.

    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)

    • Every round reads a fresh table and sends SIGTERM to each verified target, one pid at a time. No signal is ever sent to a whole group: a group signal reaches whoever holds the id when it is delivered, which no table can vouch for. A process forked between rounds is found by the next round, 150ms later.
    • After a grace period, a target gets SIGKILL, but only if it:
      • already received SIGTERM with the same start time and group, and
      • still passes the existing hasUnambiguousStartIdentity check, so a recycled pid is never force-killed.
    • The sweep runs within a fixed verification window.
  • Cost:

    • Kill with nothing left behind (the common case): the pre-kill walk found no descendants, and a 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.
    • Natural exit: first, one kill(-pgid, 0) per recorded group (a syscall each, no fork). If every group is empty, one ps -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.
    • The terminal is read only on the first round; later rounds reach terminal-born work through its descent or group.
  • Natural exit (terminal-host.ts, terminal-session-teardown.ts)

    • When a session exits, the root is marked as exited and the sweep runs, unless a kill is already sweeping that session.
    • Daemon disposal waits for any in-flight exit sweeps.
  • Behaviour change: a job started with nohup cmd & or disown, 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:

  • Each group stores when it was last seen owned, not its leader's start time. The captures that teach groups come from a shared process-table tier that has no start-time column. Also, a leader's start time only covers groups whose leader is still alive. "Born before the group was last owned" answers the same question, "could this process be the stranger that took a freed id?", and it also covers leaderless groups.
  • No group-wide signal after verification. Verifying a group and then signalling the group id still leaves a gap in which the id could change hands. Signalling only verified pids, with a fresh table each round, has no such gap.
  • The terminal claim is only useful before exit on macOS. Closing the pty master revokes the terminal, so survivors show no terminal afterwards (verified with a probe). Process groups are therefore the durable claim, and the terminal is a best-effort extra.
  • Groups are learned from process-table reads Orca already takes, not a dedicated periodic re-read. A group created and abandoned between two reads is only caught through the terminal or the post-spawn read.
  • The post-spawn read happens at about 750ms and reads only the session's terminal. Adding a terminal column to the whole-host table cost 12.9s against 0.16s without it, so terminal lookups always use ps -t <tty>.
  • Escalation is bounded by a fixed verification window rather than repeating until everything is gone. Anything still alive at the deadline is reported live, and an unreadable table is reported unverifiable, 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

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

New tests:

  • pty-session-sweep-targets.test.ts: the pure targeting function. Covers:

    • the ppid tree and the terminal match;
    • a verified recorded group;
    • a reused group id that is refused (a leader born after the group was last owned, plus that leader's children in another group);
    • a leaderless member born too late;
    • the root's own group before and after exit;
    • protection of the daemon and its ancestors;
    • a root that is absent, a recycled pid, and duplicate rows.
  • pty-session-descendant-sweep.test.ts:

    • escalation timing;
    • SIGKILL only after a same-identity SIGTERM;
    • only pids are signalled, never a group;
    • the Windows no-op;
    • the natural-exit probe (no whole-host read when every recorded group is empty);
    • the terminal read happens once.

    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:

    • the post-spawn terminal read records the root plus groups traceable to it, not unrelated processes that share the terminal;
    • groups are pruned when a capture shows them empty;
    • a capture tier without a group column prunes nothing;
    • the last-owned time moves forward.
  • 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:

    • the shell exits naturally;
    • the session is killed.

    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:

    • 20 concurrent sweeps share process-table reads (2 reads, not 40);
    • a kill that left nothing behind reads no table at all;
    • a kill whose earlier job group is still populated does sweep.

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.

Removed Fails
Group verification entirely, so any recorded group id is claimed (the previous behavior) 5 tests, including refuses a recorded group whose id a stranger took… and leaves alone a stranger that took the group id… (via the live observer)
Leader birth check only refuses a recorded group whose id a stranger took…, leaves alone a stranger that took the group id…
Leaderless member birth check only without a leader, claims only members born while the group was still owned, leaves alone a later member of a leaderless group…
"Group-only matches never teach groups" without a leader, claims only members born while the group was still owned
Pruning empty groups forgets a group once a whole-host capture shows it empty…, forgets a group the live captures saw empty…
Natural-exit probe (reverted to "skip only when no group is recorded") settles a natural exit whose only group is the root's, now empty, with one terminal read
Kill fast path settles 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.
Terminal claim limited to a live root or a recorded exit time (run against the previous commit's rule) trusts no terminal row once the root is gone without a recorded exit time
Live observer recording groups both real-PTY integration tests (the escaped job survives), reaps the job the live tree was seen to own

From 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.ts alone, 4 runs: 4/4 pass.

Not tested on Linux or Windows locally. Linux uses the same code path with pts/N terminal names. Windows returns before any sweep.

AI Disclosure

Written with Claude Code (Claude Opus).

Review

Author: @BrennanKB5

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

Remaining gaps and adjacent issues (not fixed here):

  • Flaky native test: src/main/daemon/pty-subprocess-io-failure-native.test.ts also fails intermittently on main under 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 on main. After this change the test passed 4/4 alone and passed in the full directory run.
  • Short-lived groups: a session that exits before any process-table read has observed it relies only on the post-spawn terminal read and the terminal itself. A group created and abandoned between reads can still escape.
  • Detached daemons: a daemon a session launched with its own new session and no terminal is outside every claim. That is deliberate, since Orca has no evidence it owns it.

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)

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

coderabbitai Bot commented Sep 22, 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 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 22937

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.74% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 38 functions across 22 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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, … Add the required issue reference under Linked Issue, such as Fixes #22348`` if applicable. Confirm the required validation commands pass, or explicitly state that CI will cover them, and update the related checklist items.
✅ Passed checks (3 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 and concisely describes the main change: cleaning up leftover processes when a PTY exits naturally.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d4ed4c1b-2873-4fbb-bd8f-9fa8a87b4511

📥 Commits

Reviewing files that changed from the base of the PR and between 7cb4380 and 229374e.

📒 Files selected for processing (23)
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-descendant-shutdown.test.ts
  • src/main/daemon/terminal-host-disposal.ts
  • src/main/daemon/terminal-host-natural-exit-sweep.test.ts
  • src/main/daemon/terminal-host-retired-incarnations.ts
  • src/main/daemon/terminal-host-session-identity-observation.ts
  • src/main/daemon/terminal-host-session-shutdown.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/terminal-session-descendant-sweep.test.ts
  • src/main/daemon/terminal-session-descendant-sweep.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/pty-session-descendant-sweep.integration.test.ts
  • src/main/pty-session-descendant-sweep.test.ts
  • src/main/pty-session-descendant-sweep.ts
  • src/main/pty-session-identity.test.ts
  • src/main/pty-session-identity.ts
  • src/main/pty-session-sweep-targets.test.ts
  • src/main/pty-session-sweep-targets.ts
  • src/main/pty-session-tty-process-table.ts
  • src/main/pty/posix-pty-foreground-group.ts
  • src/shared/cheap-process-table-snapshot-reader.ts
  • src/shared/process-table-capture-observers.ts
  • src/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.

Comment thread src/main/pty-session-identity.ts Resolved
Comment on lines +189 to +200
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)

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.

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

Comment thread src/main/pty-session-sweep-targets.ts Resolved

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

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 — Session now carries a PtySessionProcessIdentity (root pid, tty, root lstart, knownPgids, rootExitedAtMs), populated at spawn, from a 750ms ps -t read of the session's own terminal, and from every shared process-table capture via a new observer registry.
  • Target set — collectSessionSweepTargets unions the ppid walk (only while the root is present and its lstart matches), known-group membership, and tty membership (post-exit gated on a start time before rootExitedAtMs), with Orca's pid/ancestors/groups protected and the tty claim dropped when Orca shares the terminal.
  • Sweep — sweepSessionDescendants re-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; dispose awaits in-flight exit sweeps; the retired-incarnation map was extracted into TerminalHostRetiredIncarnations.
  • Support — readTtyProcessTable (ps -t), the normalizeTty → normalizePtyTtyName export, 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).

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

Comment thread src/main/pty-session-identity.ts Resolved
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.

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

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: Set became ownedGroups: Map<pgid, {lastOwnedAtMs}>; recordPtySessionGroups advances the last-owned time with Math.max, and a new prunePtySessionGroups drops any group a whole-host capture shows empty so a freed id cannot be claimed later.
  • Group verification — collectSessionSweepTargets now verdicts every recorded group as leader-verified / leaderless / reused and 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 extend learnedGroups.
  • Signalling — dropped wholesale group signals; sweepSessionDescendants SIGTERMs 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 -t read.
  • Wiring — the shutdown module was renamed to terminal-session-descendant-sweep.ts carrying both sweepTerminalSessionDescendants and sweepSessionFromSnapshot; shared process-table captures now carry capturedAtMs; terminal-host-session-shutdown.ts and the teardown paths route through the shared snapshot entry.

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

Comment on lines +105 to +107
const leader = byPid.get(pgid)
if (!leader || leader.pgid !== pgid) {
return 'leaderless'

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.

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]`.

Comment on lines +72 to +80
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')

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.

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?

@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 in this delta.

Reviewed changes

  • Terminal-claim boundary — claimsTty now trusts a tty row only while the root is alive in the same capture, or when a recorded rootExitedAtMs bounds 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.

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

This branch has not been deployed

No deployments
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