Skip to content

Give everything the host daemon starts an owner that ends it - #6528

Closed
ymichael wants to merge 7 commits into
mainfrom
bb/swing-3-owner-scoped-resources-thr_v4bbq3y3mw
Closed

ymichael wants to merge 7 commits into
mainfrom
bb/swing-3-owner-scoped-resources-thr_v4bbq3y3mw

Conversation

@ymichael

@ymichael ymichael commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Nothing owned what the host daemon starts. Each subsystem (provider bridges, ACP agents, setup/teardown hooks, plugin workers, the frpc tunnel, the file watcher) tracked its own processes in memory, killed single PIDs or one process group, and forgot everything on a daemon restart. So children that moved into their own process group (Claude Code runs every Bash tool shell in its own group) survived their owner, a plugin worker's children outlived its disposal, a hook interrupted by a daemon restart left its processes running and the server retrying forever (#5962, #4158), a maintenance request that never settled kept its workers alive (#3230), and each leak was patched one site at a time.

What changed

  • One ledger of everything the daemon starts (apps/host-daemon/src/resource-ledger.ts): provider runtimes, the maintenance runtime, setup/teardown hooks, plugin host workers, frpc and the file watcher. Each entry is written to <dataDir>/host-daemon-resources/ before anything is spawned, with its owner, processes and a deadline. Ending an owner ends everything under it; a restarted daemon stops what the previous instance left behind.
  • Stop whole trees, only when provably ours (@bb/process-utils): a stop captures the owner's process tree (descendants by parent PID plus any own-group leaders) and signals a process only if its PID and its OS start token both match the record. The token is read by one probe at record time and act time (Linux boot ID + start ticks, macOS ps -o lstart under LC_ALL=C TZ=UTC0), so wall-clock jumps don't matter. Windows has no token: a recorded process there is never signalled, and processes are stopped through the handle of whoever started them, as on main. Anything that can't be matched is never signalled and never counts as stopped; it stays recorded as unverified for a later retry.
  • Plugin workers run in their own process group; stopping a worker (dispose, idle, reload, disable, forced kill) captures and stops its group and every descendant. Worker cleanup starts at exit, not when its pipes close.
  • Hooks capture their tree before the first kill on timeout or cancel, and a hook that had to be killed stops that tree when it ends, including a teardown whose failure is otherwise non-fatal.
  • A lint rule bans raw child_process, cross-spawn, execa and node-pty imports outside @bb/process-utils, test support and the two PTY owners; the existing spawn helpers keep main's signatures and record each child with the host process as owner.

No server/daemon wire change (HOST_DAEMON_PROTOCOL_VERSION stays 258) and no plugin SDK change (bundled types byte-identical to main). The ledger is daemon-local; after a restart the server learns a hook's outcome through main's existing environment.hook.cancel, which now answers terminated once the hook's processes are confirmed gone. That outcome stays on disk (30 days) so a second restart before the server asks doesn't lose it, and a cancel for the server's provision setup id (environment:<id>:<instance key>:setup) finds the daemon's provision setup record.

Visible behaviour changes

  • Stopping a provider bridge, ACP agent or plugin stops everything it launched, including children in their own process group.
  • A failed or cancelled hook stops its whole tree; a successful hook's background processes keep running, as on main.
  • Terminals are unchanged: closing one hangs up its shell's process group only, so nohup … & disown jobs survive.

Known limits (none worse than main)

  • Children of a plugin worker that crashed keep running, as on main: the daemon only reaches them through the live worker's tree. (Reporting each plugin child over IPC was cut to keep this change small.)
  • macOS start tokens have one-second precision, so a PID reused within the same second can't be told apart.
  • On Windows the restart cleanup does nothing: without a start token, a record a crashed daemon left behind is kept unverified rather than stopped, as on main. Reading start times there would need a PowerShell (CIM) probe per process, which slowed daemon startup in CI from ~5 s to 40–60 s.

How you verified

  • Every fix has a test that fails on the old code (process trees escaping, restart cleanup, PID reuse never signalled, clock jumps, hook timeouts, unverified records kept).
  • Three independent review rounds; all findings fixed (including PID-reuse kills through a stale record and through a late exit report, terminal jobs, records lost on unverified stops, crash cleanup blocked by inherited stderr, macOS time-zone-dependent tokens, and per-call ledger writes, now zero for short plugin git calls).
  • Typecheck and lint pass across the monorepo; process-utils, host-daemon, agent-runtime, provider-bridge-acp, CLI and MCP suites pass. The integration suite passes 77/77 on its own (its parallel-load timeouts also happen on main).
  • Windows CI (host-daemon, integration, tarball smoke) is the Windows check; not run on native Linux outside CI.

Fixes #5962
Fixes #3230
Fixes #4158
Fixes #4866

Partly addresses #1660, #5954 and #3820: descendants of bridges, ACP agents and plugin workers now die when their owner is stopped; memory growth, a memory-pressure reaper and stale bridges across plugin rebuilds are not covered.

🤖 Generated with Claude Code

AGENT GENERATED

ymichael added a commit that referenced this pull request Oct 29, 2026
Final review of #6528:
- runTeardownScript treats a timeout as non-fatal, so the hook wrapper
  called leaveRunning() and dropped the record while a detached child of
  the killed teardown kept running, and hook.cancel answered terminated.
  A hook whose script the runner had to kill now stops its captured tree
  when it ends.
- Provision setup is recorded under a daemon-local id, but the server
  cancels environment:<id>:<instance key>:setup, so after a restart the
  answer was unknown and cleanup stayed blocked. Lookups by a server
  setup id now also find that environment's provision setup record. No
  wire change.
- Confirmed hook outcomes were kept only in memory once reconciliation
  deleted the record, so a second restart before the server asked lost
  them. The record now stays on disk with no processes (pruned after 30
  days), and every restart answers from it.

Windows CI (packages-host, app smoke): identity reads there start
PowerShell, and concurrent reads of the same child each started their
own probe, starving the runner; probes also ran in the caller's cwd and
held the temp dir. Concurrent reads now share one in-flight probe, and
probes run from a neutral directory.

Tests (each fails before): "stops descendants a timed-out teardown hook
moved out of its process group", "answers the server's cancel for a
provision setup the previous daemon left running", "keeps a hook's
confirmed outcome across a second restart", "shares one probe between
concurrent reads of the same child".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael and others added 7 commits October 29, 2026 14:25
Process stops signalled single pids or whole process groups by number,
so children that moved to their own group escaped (Claude Code runs
every Bash tool shell in its own group), and a stale pid or group id
could hit an unrelated process after reuse.

@bb/process-utils now has one identity rule. probeProcessStart(pid)
reads the OS's own start token (boot id + start ticks on Linux,
ps lstart under LC_ALL=C TZ=UTC0 on macOS, CIM CreationDate on
Windows); the same probe is used when recording and when acting, so
time zones and the wall clock do not matter. A process is signalled
only when its current token matches the record, together with the
descendants and groups reached from a matched process
(snapshotProcessTree / stopProcessTree / stopRecordedProcesses). Any
mismatch, unreadable process, or leaderless group with live members is
never signalled and reported unverified; only a pid with no process
(and no group members) counts as gone. macOS lstart has one-second
precision, so a pid reused within the same second is a known limit.

- createProcessStop (managed processes, execPortableFile) snapshots the
  child's tree while it holds the child, sends the leader SIGTERM via
  its handle, stops the rest by token, and signals nothing once the
  child has exited. stopProcessGroupLeaderFirst is deleted; the dev
  launcher and tests use createProcessStop.
- On Windows a stopped root whose 'exit' arrives late is accepted once
  its pid is gone (#4866).
- processesOwnedBy(owner) returns the spawn helpers bound to an owner
  that records each child (TrackedProcess with a lazily read start
  token, cached only once read). The existing spawnHostProcess,
  execHostFile, spawnManagedProcess, ... exports keep their signatures
  and record children with hostProcessOwner, which a host process binds
  through bindHostProcessOwner (global symbol, so plugin bundles with
  their own copy report to the same owner). The plugin SDK surface is
  unchanged: its bundled types are byte-identical to main's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The daemon tracked its children only in memory and stopped them by pid
or group, so a restart lost running hooks, bridges and plugin children,
plugin workers ran in the daemon's own group and were SIGKILLed by pid,
and idle shutdowns were separate timers outside any owner.

- apps/host-daemon/src/resource-ledger.ts: every daemon-started
  resource (provider runtimes, maintenance runtime, setup/teardown
  hooks, host plugin workers, connect-next frpc, file watcher, short
  host commands) has a daemon-local typed owner and a deadline (fixed,
  idle with leases, or owner lifetime) and is persisted under
  <dataDir>/host-daemon-resources/. Records hold each process's OS
  start token; a restarted daemon stops what a previous instance left
  running and keeps any record it cannot verify or read.
- Ending an owner (DaemonResource.end) captures its process tree, runs
  the owner's graceful stop, then stops the rest of the tree by token.
  Failed or cancelled hooks stop their tree (captured before the first
  kill); a successful hook leaves its processes running, as before.
  Unverified stops keep the record for the next start.
- Host plugin workers run in their own process group, are stopped
  through their resource, clean up at exit rather than pipe close, and
  idle out through the resource's idle deadline. Workers report
  children with their token (detached ones immediately, others after a
  second) and the daemon records them under the plugin.
- hostProcessOwner is bound to a host-command resource; its children
  are written to disk only if still running after a second. Lease
  changes are not written.
- environment.hook.cancel can now answer "terminated" for a hook a
  previous daemon instance left running once its processes are
  confirmed gone (#5962). Provision setup keeps a daemon-local ledger
  key, so the server/daemon wire is unchanged: no protocol bump.
- Terminals are unchanged: closing one hangs up its shell's group only.
- Lint bans child_process, cross-spawn, execa and node-pty value
  imports outside @bb/process-utils, test support and the PTY owners.
- Maintenance requests and the provider install run hold leases with
  deadlines, so a request that never settles cannot pin the maintenance
  bridges (#3230).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Final review of #6528:
- runTeardownScript treats a timeout as non-fatal, so the hook wrapper
  called leaveRunning() and dropped the record while a detached child of
  the killed teardown kept running, and hook.cancel answered terminated.
  A hook whose script the runner had to kill now stops its captured tree
  when it ends.
- Provision setup is recorded under a daemon-local id, but the server
  cancels environment:<id>:<instance key>:setup, so after a restart the
  answer was unknown and cleanup stayed blocked. Lookups by a server
  setup id now also find that environment's provision setup record. No
  wire change.
- Confirmed hook outcomes were kept only in memory once reconciliation
  deleted the record, so a second restart before the server asked lost
  them. The record now stays on disk with no processes (pruned after 30
  days), and every restart answers from it.

Windows CI (packages-host, app smoke): identity reads there start
PowerShell, and concurrent reads of the same child each started their
own probe, starving the runner; probes also ran in the caller's cwd and
held the temp dir. Concurrent reads now share one in-flight probe, and
probes run from a neutral directory.

Tests (each fails before): "stops descendants a timed-out teardown hook
moved out of its process group", "answers the server's cancel for a
provision setup the previous daemon left running", "keeps a hook's
confirmed outcome across a second restart", "shares one probe between
concurrent reads of the same child".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Windows CI still timed out across the plugin host and thread-stop
suites (afterEach shutdowns over 10 s) and the tarball smoke left its
temp dir busy: every identity read starts PowerShell (CIM), and stops
waited on those reads even when nothing needed them.

- Windows start-token probes requested within 50 ms share one
  PowerShell query (Windows PowerShell 5.1 compatible output).
- A Windows stop answers "exited" without probing when the pid no
  longer exists, and confirms termination by the pid's absence instead
  of a second probe.
- Ledger stops first drop records whose pid no longer exists (ESRCH),
  then read identities only for what is left; captureTree skips the
  read on Windows, where tree snapshots are empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Windows CI still failed: daemon join in the tarball smoke took 39-61 s
(4.7 s on main) and host/integration tests timed out. Every tracked
process and every host command alive for a second triggered a
PowerShell (CIM) identity probe, and the probe batch waited on a
setTimeout that fake timers never fire.

- On Windows the ledger reads a process's start token only when a
  stop needs it, while it still holds the child; tracking and adoption
  no longer probe. A record a crashed daemon leaves behind therefore
  has no token on Windows and is kept unverified rather than signalled
  (main never stopped those either).
- Windows probe batching collects requests made in the same microtask
  instead of waiting on a timer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Windows the two force-kill tests still hung: killWorker stopped the
worker only through its token, and reading that token on Windows needs
a PowerShell probe that did not finish in time. A worker the daemon
still holds unreaped is now killed through its own handle, the same
rule the managed-process stop uses for its leader, after its tree is
captured; the rest of the tree is then stopped by token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shrinks the change to what users need from it:

- Host plugin workers no longer report each child over IPC. The worker
  runs in its own process group and the daemon stops that group and
  its descendants when it stops the worker (dispose, idle, reload,
  disable, forced kill). Children of a worker that crashed keep
  running, as on main.
- Windows no longer reads process start times through PowerShell
  (CIM). A recorded process there is never signalled; processes are
  stopped through the handle of the process that started them, as on
  main. readProcessIdentity is back to main's implementation.
- .oxlintrc.json keeps main's em dashes instead of — escapes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

This is an automated message. We have closed this pull request because it has been open for more than two weeks.

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