Skip to content

feat(daemon): reap PTY processes left behind when their owner is gone - #22343

Open
brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/daemon-orphan-reconciler
Open

brennanb2025 wants to merge 3 commits into
mainfrom
brennanb2025/daemon-orphan-reconciler

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​977 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​977
Prod 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1223 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1219

ELI5

Sometimes a terminal's programs keep running after Orca has stopped tracking them. This happens when the terminal daemon is killed by an update, crashes, or the machine sleeps through cleanup. One case we saw was a tool shell burning 85% CPU for seven days with no parent. Today nothing ever looks for these again. This PR makes the daemon write down exactly which processes it launched. Every few minutes it checks for anything launched by a daemon that has since died, and stops it. Processes a terminal leaves behind while its daemon keeps running, such as nohup server &, are not this PR's concern and are left alone.

What Changed

Before: descendant cleanup runs only when a terminal is torn down. If a teardown never happened, or a process escaped it, the process runs until reboot. After its parent dies it is reparented to pid 1, so no parent-walk can find it.

After: the daemon keeps a durable ownership record for every PTY it spawns, and runs a periodic reconciler against those records.

The record is daemon-v<N>.pty-owners.json, stored next to the daemon's pid file. It holds:

  • the root's pid and OS start time;
  • processes: the exact identities (pid + OS start time) the daemon owns;
  • process group ids, used only as a hint;
  • tty name, session id and incarnation id;
  • the owning daemon's pid and start time.

Writing it. A spawn only queues the root. About a second later, one ps -p pid1,pid2,… call (through runProcess, 15s deadline) fills in start times and groups for the whole batch, and one store write saves them. A root whose session is no longer live, or whose probed start time is later than the spawn, gets no start time. After that, every reconciler tick re-derives each live session's owned identities from the tree it can still walk from the root. The list is replaced wholesale, so dead processes and processes that deliberately detached drop out, and groups that no longer exist are pruned.

The reconciler runs 30s after start and then every 5 minutes, on an unref'd timer. POSIX only. Each tick reads one fresh process table and compares it with the records:

  • Record with a live session: left alone, and its identities are refreshed as above.
  • Record this daemon wrote, with no live session: dropped as session_ended, never reaped. The session ended under a daemon that ran its teardown, so an old snapshot of its tree is not kill authority for whatever outlived that teardown.
  • Record from a daemon that died, with no live session: the only candidates are recorded identities whose start time exactly matches the live row, plus their live descendants. They are reaped only on the second consecutive observation: SIGTERM, then an identity-checked SIGKILL after a grace. The reason is stranded_root or orphaned_descendant.
  • Nothing recorded is alive under its recorded identity: the record is dropped. It is settled if the pids are gone, or unprovable if a recorded pid is in use by something that cannot be proven ours. A root recorded without a start time never matches.

Safety rules:

  • A process group is never kill authority. Other processes in a recorded group are only counted, as unverifiedGroupMembers in the reap log.
  • Every live session's root, its descendants and their groups, plus the daemon's own ancestor chain and its groups, are excluded from every candidate set (protected_process).
  • Records owned by another daemon that is still alive are skipped, as are records younger than a 60s spawn grace.
  • A session that is live but reports no incarnation id protects every record for that session.

Retiring on session end. When a session is reaped under a running daemon, the recorder removes its record in its next batched write. A session id that has already respawned keeps its newer generation's record. The session_ended rule above re-derives the same outcome on the next tick, so a missed or failed removal cannot turn into a kill. "Written by this daemon" means same pid and a start time within 5s. A record from an earlier daemon that drew the same pid is still treated as a dead daemon's.

Records from another protocol version. The store file is named by protocol version, so an update that bumps the protocol would leave the previous daemon's file where no later daemon looks. Each tick lists the other daemon-v<N>.pty-owners.json files in the runtime dir. Once no daemon that wrote a file is still running, its rows are merged into the current store and the file is deleted:

  • a row whose key the current store already holds is not overwritten;
  • merged rows keep their original recordedAt, so the 24h expiry still applies;
  • the file is deleted only after the merge write lands;
  • a file whose writer is still alive is left to that writer;
  • an unreadable file is kept until its mtime is older than 24h, then deleted.

Every record has a way to die: it settles when its processes are gone, it is dropped as unprovable, or it expires after 24h. Identities are capped at 256 per record.

The pending-confirmation set is kept in memory only, so after a daemon restart every suspicion starts over at a first observation. The store caps at 512 rows. It validates each row separately, so one bad row does not hide the others. It never treats an unreadable file as empty, never rewrites an unreadable file, and writes through a temp file followed by a rename.

Log events go to the daemon's NDJSON log. Pid lists are capped at 16 entries, but the count field is always exact.

  • pty-orphan-reap: one event per reap, with sessionId, incarnationId, reason, pgids, pids, processCount and unverifiedGroupMembers.
  • pty-orphan-reconcile: a summary, written only on ticks where something happened.
  • Failure and refusal events: -failed, -records-unreadable, -process-table-empty.
  • pty-orphan-legacy-records-adopted / -expired: when another version's file is merged or removed.

Wiring: live sessions now report their root pid (only while alive) to the reconciler. TerminalHost gains an optional onPtySpawned hook, called right after the session is published. DaemonServer's existing onSessionReaped handler now also retires the session's record. DaemonServer builds the recorder and the reconciler through daemon-pty-ownership-lifecycle.ts, starts the reconciler with the server, and stops both on dispose. readFreshProcessTable is now exported from pty-descendant-termination.ts, so the reconciler takes its own capture instead of the shared, coalescing one that teardown uses.

Why

After a leftover's parent is gone, nothing in the process table links it back to Orca. The durable fact therefore has to be written while the link still exists, and kept somewhere that survives a daemon restart.

That fact is an identity, pid plus OS start time, not a location. Process groups are reissued once their leader exits, and on macOS every launchd app is parented by pid 1. So "is in a group we once used" or "looks orphaned" says nothing about whose process it is.

The reconciler answers only for daemons that died before tearing their sessions down. For such a record, it reaps processes whose exact identity was recorded at the session's last live observation and that are still running under that identity, plus their live descendants, and nothing else. That is not the same set teardown would have killed. Teardown signals the live tree at the moment it runs. This reaper can only act on what the last tick recorded, so it can miss processes born since then, and it may signal a recorded process that had detached on purpose before the daemon died. When a session ends under a daemon that is still running, whatever it leaves behind is the natural-exit sweep's concern (#22348), never this reaper's.

Alternatives considered, and deviations from the usual design for this job:

  • Polling instead of watching for owner death. A kernel-level exit watch per owner would catch death immediately. The daemon is Node, which has no such binding without a new native addon, so this PR polls. The cost is that leftovers live for up to about one interval plus the confirmation tick.
  • Identities recorded on live ticks, not continuously. A process born and orphaned between two live ticks (the first at 30s, then every 5 minutes) is never recorded, so it is not reaped. It only shows up as an unverified group member in the log. This PR accepts that gap in exchange for never signalling on a heuristic.
  • Group and tty are hints only. A whole-host ps that includes the tty column measured 19–28s on a 1,875-process Mac, against 0.12s without it, so tty is recorded but never scanned host-wide.
  • One kill per tick, no rescan until quiet. A reap is one SIGTERM, then an identity-checked SIGKILL. It does not keep rescanning until no new members appear. The record stays pending and the next tick re-derives and retries.
  • Escalation settings. The escalation uses its own process-table read with a 15s deadline. Teardown's default 1s deadline was measured to skip SIGKILL silently at load around 87, when ps took about 2s.

Linked Issue

No tracked issue: this came from a reported leak (a tool shell at 85% CPU for seven days with ppid 1).

Visual Proof

N/A: this is daemon-only background behaviour with no UI.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

Results:

  • pnpm test on the five new or changed daemon ownership test files: 5 files, 54 passed.
    • Plan unit tests:
      • a live tick records exact identities, skips start times inside the capture's own second, and prunes groups that no longer exist;
      • a missing root start time is only completed from the pid the host reports for that generation;
      • two-pass gating;
      • a stranded root, and an orphaned recorded descendant with its children;
      • a pgid reused by an unrelated process parented by init;
      • a pgid reused by a live session's root;
      • a recorded identity now inside a live session's tree;
      • a root pid reused when its start time was never captured;
      • root and descendant pids reused under a different start time;
      • unverified group members are counted but not signalled;
      • daemon-ancestry protection, another live daemon, spawn grace, settled, expiry, incarnation keying;
      • a record this daemon wrote whose session has ended, with a recorded survivor reparented to init, is dropped as session_ended and not reaped;
      • a record from an earlier daemon that held the same pid is still reaped;
      • the descendant walk stops on a cycle and gives no children to a pid the capture lists twice.
    • Recorder tests: spawns share one probe and one store write; the debounce timer flushes on its own; no start time is written for a dead or reused root; retire removes an ended session's record but keeps a live respawn under the same session id.
    • Other-version store tests: only other versions' files are listed; a dead daemon's rows are merged with their age kept and the file is deleted; a row the current store already holds is not overwritten; a file whose daemon is alive is left alone; an unreadable file is kept until it is older than 24h; the reconciler adopts one even when its own store is empty.
    • Store tests: batch upsert in one write; the processes field survives round-trips and parses per row.
    • Integration tests against real processes, POSIX-only:
      • a restart leftover is killed through the SIGKILL escalation on the second tick and retired on the third;
      • a survivor recorded on a live tick is reaped as orphaned_descendant after its root is SIGKILLed;
      • a live session is left alone;
      • a survivor left by a session that ended under this same, still-running daemon is not reaped, and its record is removed;
      • a mismatched root identity is refused;
      • Windows does nothing.
  • Ablation:
    • With the previous reap plan restored, the three regression tests (a pgid reused by an init-parented process, a pgid reused by a live session root, a root pid reused with no start time) each fail at expect(result.reap).toEqual([]). The old code reaped those processes.
    • With the previous recorder restored, the child-process import boundary and Windows console visibility tests fail (4 tests).
    • Each follow-up fix was removed on its own, with every other change kept:
      • Without the session_ended rule, the plan test and the real-process test both fail. In the real-process test the survivor was actually killed (isRunning returned false).
      • With retire turned into a no-op, the retire test fails.
      • With other-version store adoption turned off, the reconciler adoption test fails.
  • pnpm test src/main/daemon: 190 files, 2124 passed, 15 skipped.
  • pnpm run typecheck:node and typecheck:cli pass. oxlint on src/main/daemon passes. pnpm run check:code-quality:changed reports 0 new findings.
  • Platforms: macOS locally. Linux is covered by the POSIX integration tests in CI.

AI Disclosure

Implemented with Claude (Anthropic), reviewed by the author.

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

  • Cross-platform: POSIX only. On Windows the recorder and reconciler do nothing because each PTY's job object already owns its tree and teardown terminates it.
  • SSH: the reconciler runs inside whichever daemon owns the PTYs, so on a remote host it reaps that host's processes. It never judges remote work from the client side, and it never treats loss of contact as process death.
  • Backwards compatibility: a new file in the daemon runtime dir, scoped by protocol version. Files from other protocol versions are adopted once their daemons are gone, as described above. There are no wire changes. Records from older builds that are missing soft fields still parse.
  • Performance: one batched ps -p and one store write per burst of spawns, off the spawn path. One whole-host ps (without the tty column) every 5 minutes, and only while any records or other-version files exist. Each tick builds one pid/children index from that capture and every tree walk shares it.

Remaining gaps, not addressed here:

  • Records are only written for spawns after this ships. PTYs already running under an older daemon get no backstop until they are respawned.
  • A daemon started without a pid file path creates no store, so it gets no backstop.
  • Processes born and orphaned between live ticks are logged as unverified group members, not reaped.
  • Processes a session leaves behind while its daemon keeps running are out of scope here; the natural-exit sweep (fix(terminal): sweep leftover processes when a PTY exits on its own #22348) covers them.
  • An owner-death watch would shrink the leak window from minutes to immediate.

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)

The daemon now writes a durable ownership record per PTY spawn (root pid
and start time, process groups, tty, session and incarnation, owning
daemon) next to its pid file, and a periodic reconciler compares those
records against one process table every five minutes. Groups whose
session is no longer live are signalled after two consecutive
observations, with start-time and parentage screens against pid/pgid
reuse and the daemon's own ancestry protected. Records retire when their
processes are gone, when their groups turn out to hold someone else's
processes, or after 24 hours.
@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

This change adds PTY ownership tracking and periodic orphan cleanup in the daemon. It introduces a durable record format and file-backed store for PTY ownership data, records PTY process identity when sessions spawn, and adds a pure planner that classifies records from a process-table snapshot into refreshed, skipped, dropped, or reapable results. It also adds a POSIX-only reconciler that runs on a timer, reads records, captures the process table, applies the planner, signals orphaned processes, and persists record updates. Unit and integration tests cover store behavior, planner decisions, and reconciler behavior.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 5c2e7

Ownership records can be lost or become unusable, leaving surviving PTY processes behind; cleanup can also continue during shutdown. Resolve these risks before merging unless the limitations are explicitly accepted.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 43 functions across 15 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, security, performance, and limitations. However, the required Linked Issue section explicitly states that no tra… Add a valid linked issue in the required Fixes #<issue-number> format, or provide the repository-approved issue reference for this work.
✅ 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 describes the main change: reaping PTY processes left behind after their owner daemon is gone.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, platform impact, security, performance, and limitations. However, the required Linked Issue section explicitly states that no tracked issue exists.

  • 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: 6


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 5dd37278-b850-4be4-b36a-33a0d95cb1f2

📥 Commits

Reviewing files that changed from the base of the PR and between 7240368 and 1908a58.

📒 Files selected for processing (14)
  • src/main/daemon/daemon-orphan-reap-plan.test.ts
  • src/main/daemon/daemon-orphan-reap-plan.ts
  • src/main/daemon/daemon-orphan-reconciler.test.ts
  • src/main/daemon/daemon-orphan-reconciler.ts
  • src/main/daemon/daemon-pty-ownership-lifecycle.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/pty-ownership-record-store.test.ts
  • src/main/daemon/pty-ownership-record-store.ts
  • src/main/daemon/pty-ownership-record.ts
  • src/main/daemon/pty-ownership-recorder.ts
  • src/main/daemon/terminal-host-options.ts
  • src/main/daemon/terminal-host-session-create.ts
  • src/main/daemon/terminal-host.ts
  • src/main/pty-descendant-termination.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +164 to +166
const capture: ProcessTableCapture = await (this.options.readTable ?? readFreshProcessTable)(
PROCESS_TABLE_TIMEOUT_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 | ⚡ Quick win

Fence an in-flight reconciliation when stop() runs.

If stop() runs while readTable() is pending, clearing the timer does not stop that scan. When the read completes, reconcile() can still plan, send signals, and change the store during resource disposal. Check a stop flag after the await and before signalling, or make shutdown wait for the running pass to finish.

Comment on lines +38 to +41
const rows = asRecordObject(JSON.parse(text))?.records
if (!Array.isArray(rows)) {
return []
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Treat an invalid records field as an unreadable store.

If the file contains valid JSON with a missing or non-array records field, read() reports an empty, readable store. The next upsert() then replaces the file and permanently forgets its ownership records. Reject the invalid top-level shape so mutate() preserves the file, as it already does for invalid JSON.

Proposed change
   if (!Array.isArray(rows)) {
-    return []
+    throw new Error('Invalid PTY ownership records')
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const rows = asRecordObject(JSON.parse(text))?.records
if (!Array.isArray(rows)) {
return []
}
const rows = asRecordObject(JSON.parse(text))?.records
if (!Array.isArray(rows)) {
throw new Error('Invalid PTY ownership records')
}

Comment on lines +135 to +136
writeFileSync(temporaryPath, payload, { mode: PRIVATE_FILE_MODE })
renameSync(temporaryPath, this.filePath)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Sync the record file and directory before treating the replacement as durable.

The temporary file is in the correct directory, and the rename protects concurrent readers. Neither operation makes the new record durable across a power loss. Sync the temporary file before renameSync(), then sync the containing directory after the rename. Otherwise a restart can lose the only record needed to find a surviving PTY. Based on learnings, durable POSIX replacement requires both sync steps in addition to the rename.

Source: Learnings

Comment on lines +100 to +101
this.write(base)
void (this.options.probeIdentity ?? probePtyRootIdentity)(identity.pid).then((probed) => {

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Capture a usable group and root identity before the root can disappear.

If the PTY root exits after the first write but before probePtyRootIdentity() reads it, the durable record retains startedAt: null and pgids: []. A surviving child has no parent link to that root. A later tick cannot backfill the record, and planOrphanReap() drops it as settled. Preserve enough verified spawn-time identity to recover this short-lived-root case without delaying terminal creation.

The orphan reconciler used recorded process groups plus parentage heuristics
as kill authority. Groups are reissued once their leader exits and every
launchd app has ppid 1, so a stale group could match an unrelated app or a
live session's new shell, and a root recorded without a start time matched
whatever reused its pid.

Ownership is now a list of pid + start-time identities written on live
ticks, from the tree still reachable from a root the daemon drives. Only a
recorded identity with an exact start-time match, or a live descendant of
one, is ever signalled. Process groups are a pruned hint, counted in logs
but never signalled. Every live session's tree is excluded from every
candidate set.

The spawn-time probe now goes through runProcess, is batched and debounced
into one ps call and one store write, and runs off the spawn path.

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

Caution

This PR adds a background process reaper, and two of its signal paths are not fully identity-checked: a record whose spawn-time probe failed can authorize a kill of a reused pid, and a recycled secondary process group has no identity anchor at all. A third, unrelated issue: the branch fails the existing child_process import-boundary ratchet.

Reviewed changes

  • Durable PTY ownership record — pty-ownership-record.ts, pty-ownership-record-store.ts, pty-ownership-recorder.ts: a versioned JSON file beside the daemon pid file holds one record per PTY incarnation (root pid + lstart, groups, tty, session/incarnation, owning daemon pid + start time), written once synchronously at spawn and again after a ps -p probe fills in identity; reads are per-row tolerant and writes go through a temp file + rename.
  • Pure reap classifier — daemon-orphan-reap-plan.ts: given one process table, live sessions, and pending confirmations, decides per record whether to refresh, drop (settled/expired/unclaimable), skip, or reap after two consecutive observations, behind the ancestry, start-time, and parentage screens.
  • Reconciler — daemon-orphan-reconciler.ts, daemon-pty-ownership-lifecycle.ts: unref'd 30s-then-5min timer that reads the store, takes its own process-table capture, and SIGTERMs members then identity-checked SIGKILLs survivors via the shared descendant terminator.
  • Wiring — TerminalHost gains an optional onPtySpawned hook, called right after session publish; DaemonServer starts the reconciler with the server and stops it on dispose; readFreshProcessTable is exported and collectDescendantRows accepts a readonly table.
  • Tests — unit tests for the classifier and store, plus POSIX-only integration tests against real processes.

⚠️ A recycled secondary process group has no identity anchor

The record stores identity for the root only, but pgids is the union of every descendant group (refreshLiveRecord), and the reap set is that union. For any recorded group other than the root's own, there is no stored leader identity and no start-time lower bound — only the root's start time, which any post-root process trivially passes. Once such a group id is recycled by an orphaned stranger (its leader's pid reused), the ancestry, start-time, and parentage screens all pass and the group is reaped as orphaned_group. The root's own group is protected only by the structural coincidence that group N requires a live leader with pid N, which makes rootRow present and trips root_pid_reused; no equivalent check exists for a child-created group, and bash job control routinely creates one.

Technical details
# Recycled secondary process group can authorize a wrong kill

## Affected sites
- `src/main/daemon/daemon-orphan-reap-plan.ts:245-250` — `refreshLiveRecord` appends every descendant's non-root pgid to the record, so `pgids` normally holds more than the root's group.
- `src/main/daemon/daemon-orphan-reap-plan.ts:176,188` — the start-time screen uses only `record.root.startedAt`; a group whose leader reuses a pid necessarily starts after the root.
- `src/main/daemon/daemon-orphan-reap-plan.ts:197-200` — parentage accepts `ppid === 1`, i.e. any orphaned stranger.
- `src/main/daemon/daemon-orphan-reap-plan.ts:348-353` — `root_pid_reused` keys only on `record.root.pid`, so reuse of a secondary group's leader is never screened.
- `src/main/daemon/daemon-orphan-reap-plan.ts:378-380` — a reaped record keeps its confirmation, so once a record has been reaped the next tick signals a candidate on first sight; this removes the second observation for the recycled group.

## Reason it is reachable
The screen is purely negative: it rejects occupants that are the daemon's ancestry, predate the root, or are parented by a live process outside the group. A stranger orphaned to init in a recycled group passes all three. A detached daemon/systemd child is exactly such an occupant.

## Required outcome
Every group the reaper signals must be bound to a recorded identity, not merely to a recorded group number. Either store a leader pid + start time per recorded group, or refuse to signal a group whose leader is not the identity-checked root.

## Open questions for the human
Is the pgid-union reap set intentional, given those groups carry no per-group identity? If so, what anchors their identity once the root is gone?

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


function isRunning(pid: number): boolean {
try {
process.kill(pid, 0)

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.

isRunning reports a zombie as alive: process.kill(pid, 0) succeeds for a Z process, and the reaped survivor's parent is PID 1. On a host whose PID 1 does not reap orphans, waitForExit never returns true and finds a survivor the root left behind fails — I reproduced it here, where the survivor shows stat = Z after a SIGKILL that the sendSignal seam confirmed was sent. Treat Z/X as exited, or assert on the SIGKILL being sent rather than on the pid disappearing.

@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 in the delta — the prior safety findings are addressed. The one previously-noted test observation (isRunning treating a zombie as alive) is unchanged; I did not re-review it as new.

Reviewed changes (delta 5c2e7eae55 against the prior review at 1908a58)

  • Kill authority moved from process groups to exact identities — records now carry processes: OwnedProcessIdentity[] (pid + lstart), matchIdentity demands an exact start time, and pgids are discovery/reporting hints only (unverifiedGroupMembers, counted but never signalled). This closes the recycled-secondary-group path.
  • A null recorded start time can no longer authorize a signal — matchIdentity refuses a null startedAt, and a non-live record whose recorded pid is in use drops as unprovable. This closes the reused-pid path.
  • Live session trees are protected — LiveSessionIdentity.pid, reported by the host only while the root is alive, feeds protectLiveTree, excluding that whole tree and its groups from every candidate set.
  • Recorder reworked — spawns only enqueue; a 1s-debounced batch runs one ps -p probe through runProcess (which also fixes the import-boundary ratchet) and writes once, with an isLive gate and a start-time-vs-queue-time check rejecting dead or reused roots; stop() added and wired into disposeResources.
  • Store — upsertMany writes a batch in one rewrite.
  • Tests — new pty-ownership-recorder.test.ts; plan tests rewritten around identities (init-parented pgid reuse, live-session-root pgid reuse, reused root pid with no start time, unverified group members, protected process). I ran child-process-import-boundary, daemon-orphan-reap-plan, pty-ownership-recorder, and pty-ownership-record-store: 42 passed. daemon-orphan-reconciler is 4 passed / 1 failed at waitForExit(survivorPid, 15_000) — the previously-reported zombie/liveness issue, not a product defect: the process table shows the survivor as Z after a SIGKILL that the sendSignal seam confirms was sent.

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

…cords

A session that ends under a running daemon retires its ownership record,
and the plan re-derives the same rule: a record this daemon wrote is never
kill authority. Ownership files left by a previous protocol version are
merged once their daemons are gone. The process table is indexed once per
tick.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bee6cf01-05b4-4aa8-9787-9d522a41c320

📥 Commits

Reviewing files that changed from the base of the PR and between 1908a58 and 5c2e7ea.

📒 Files selected for processing (11)
  • src/main/daemon/daemon-orphan-reap-plan.test.ts
  • src/main/daemon/daemon-orphan-reap-plan.ts
  • src/main/daemon/daemon-orphan-reconciler.test.ts
  • src/main/daemon/daemon-orphan-reconciler.ts
  • src/main/daemon/daemon-pty-ownership-lifecycle.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/pty-ownership-record-store.test.ts
  • src/main/daemon/pty-ownership-record-store.ts
  • src/main/daemon/pty-ownership-record.ts
  • src/main/daemon/pty-ownership-recorder.test.ts
  • src/main/daemon/pty-ownership-recorder.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/daemon/daemon-server.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +111 to +114
this.timer = setTimeout(() => {
this.timer = null
void this.flush()
}, this.options.batchDelayMs ?? RECORD_BATCH_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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Persist ownership before the delayed batch can be lost.

If the daemon exits during this one-second delay, no probe or store write runs for a PTY that has already spawned. A surviving PTY then has no record for the next daemon to reconcile. Preserve a durable, verifiable identity before this window, or make the loss window an explicit limit of the cleanup guarantee.

@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 in this delta — it moves the reaper to identity-only kill authority for daemons that actually died and adds cross-protocol ownership-store adoption. One minor semantic note inline.

Reviewed changes (delta 1aa07b7 against the prior review at 5c2e7ea)

  • Reap only for daemons that died — daemon-orphan-reap-plan.ts gains selfStartedAtMs and writtenBySelf: a non-live record this daemon wrote is dropped as session_ended, while an earlier daemon that drew the same pid under a different start time is still reaped. owningDaemonStillAlive is now exported.
  • Prior-protocol store adoption — new pty-ownership-legacy-stores.ts lists other daemon-v<N>.pty-owners.json files, merges a file into the current store once every writer daemon is gone (per-record fail-closed liveness, recordedAt preserved, delete only after a landed write), and expires unreadable files after 24h; wired through the reconciler and daemon-pty-ownership-lifecycle.ts.
  • Shared process-tree index — new daemon-orphan-process-tree.ts extracts buildOrphanProcessTree/descendantsOf/collectProtectedAncestry/protectLiveTree, adds a duplicate-pid guard so a non-atomic capture grants a recycled root no children, and builds one index per tick.
  • Store merge/remove — insertMissing, remove, boolean mutate/write, and a shared capRecords.
  • Recorder retire — PtyOwnershipRecorder.retire(sessionId) removes an ended session's record on the next batch while keeping a live respawn.
  • Tests — plan coverage for session_ended and same-pid/different-start daemons, descendantsOf cycle and duplicate cases, legacy-store list/adopt/expire, recorder retire, and an integration test that a survivor left when a session ends under a live daemon is not reaped. The five ownership suites run 53/54 here; the one failure is the previously reported isRunning zombie behavior, unchanged by this delta. child-process-import-boundary passes 4/4.

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

Comment on lines +199 to +201
const retire = (existing: PtyOwnershipRecord): boolean =>
retiring.has(existing.sessionId) &&
!this.options.isLive({ ...existing, pid: existing.root.pid })

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.

retire(sessionId) deletes every existing record whose sessionId matches, so a record an earlier daemon left for a reused session id is also dropped, losing that leftover's pending reap. The window is narrow — the periodic reaper normally acts within a couple of ticks — but the predicate is broader than its "session ended under this daemon" contract.

Technical details
# retire() can drop an earlier daemon's still-pending record

## Affected sites
- `src/main/daemon/pty-ownership-recorder.ts:199-201` — the `retire` predicate keys on `retiring.has(existing.sessionId)`, with no daemon-identity check.
- `src/main/daemon/daemon-pty-ownership-lifecycle.ts:45` — the recorder already holds its own identity in `options.daemon`, so the gate is available.
- `src/main/daemon/daemon-server.ts` — `onSessionReaped` calls `recorder.retire(sessionId)` for the current daemon's ended session.

## Required outcome
- Retirement removes only records this daemon wrote; another daemon's record for the same session id stays for the two-observation reap path.

## Suggested approach (optional)
- Add `existing.daemon.pid === this.options.daemon.pid` to the predicate.

## Open questions for the human
- Is session-id reuse across daemon restarts (client-supplied ids, cold restore) intended? If ids are always minted fresh per daemon, the scenario is unreachable and this is moot.

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