Skip to content

Keep a supervised host daemon running when a memory killer stops it - #6159

Closed
alexandre-vl wants to merge 2 commits into
get-bb:mainfrom
alexandre-vl:fix/host-daemon-survives-oom-killer
Closed

alexandre-vl wants to merge 2 commits into
get-bb:mainfrom
alexandre-vl:fix/host-daemon-survives-oom-killer

Conversation

@alexandre-vl

@alexandre-vl alexandre-vl commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

A thread on a provider-managed Linux machine stopped with "Thread interrupted because the host daemon disconnected". After that, every follow-up waited on the host until someone restarted the daemon by hand. The machine was a rented 16 GB VM that the berth plugin lends to bb. It had run out of memory, and its earlyoom service picked bb's host daemon:

earlyoom[20326]: sending SIGTERM to process 21213 uid 1001 "node": badness 670, VmRSS 74 MiB

Three host-side defects turned that one signal into a dead machine:

  1. A kill looked like a requested stop.
    • The daemon handles SIGTERM as a graceful shutdown ("Shutting down host daemon" {"mode":"shutdown","reason":"SIGTERM"}) and exits 0 (daemon.ts).
    • bb-app host-daemon --supervise returns as soon as its daemon exits 0 (superviseHostDaemonProcess).
    • So the launcher treated the kill as a stop it had asked for, and exited too.
  2. bb's processes have no name of their own.
    • Linux names a process after the file it ran. The launcher and the daemon are therefore node, or MainThread on Node 24, like every test runner and dev server on the machine.
    • A memory killer cannot spare bb without sparing all of them.
    • The daemon ran at oom_score_adj 0, while the provider's own services ran at -900, so it was among the first candidates.
  3. The installer left a sandbox with no way to restart the daemon.
    • The berth plugin installs its sandboxes with BB_INSTALL_SKIP_SERVICE=1. In that mode, the installer left the temporary join daemon running unsupervised (install-machine.sh).
    • --start and --stop use owned_pid to recognize the daemon they recorded in install-daemon.pid, but it never matched bb's own launcher (install-machine.sh).
      • In *" $launcher "*" host-daemon "*, both literals claim the single space between bb-app and host-daemon.
      • The same happens between the port and --server-url.
    • So --stop failed on any live recorded daemon.
    • --start failed with Recorded daemon PID belongs to another process. whenever another process held the recorded PID. That can happen after a sandbox restarts: its disk survives, and the PID file with it, but its processes do not.

What changed

  • Signal exits (apps/host-daemon/src/daemon.ts, packages/config/src/machine-service.ts):
    • A signal-driven shutdown now exits 128 plus the signal number: 130 for SIGINT, 143 for SIGTERM (HOST_DAEMON_SIGNAL_EXIT_CODES in @bb/config/machine-service).
    • The supervisor already restarts a daemon that exits non-zero, with its 1 s to 30 s backoff. So a daemon stopped by a signal the launcher did not send now comes back.
  • Requested stops stay clean (packages/bb-app/src/launcher.ts):
    • When the launcher itself is told to stop, it still exits 0, with or without --supervise (toHostDaemonLauncherExitCode).
    • systemd and launchd record a clean stop, as before.
  • Process names (packages/bb-app/src/bin/bb-app.ts, packages/bb-app/src/bin/bb-host-daemon.ts, apps/host-daemon/src/index.ts):
    • On Linux, the launcher names itself bb-app and the daemon names itself bb-host-daemon, by writing /proc/self/comm once at startup (setLinuxProcessName).
    • The command line, which the installer's ps checks match, is untouched. process.title would have rewritten it.
    • The name is set in the bin entrypoints rather than in runBbApp, because tests call runBbApp in-process.
    • A memory killer can now spare bb by name, for example with earlyoom's --avoid '(^|/)(bb-app|bb-host-daemon)$'. saibai-labs/berth#196 adds exactly that to berth's machines.
  • Installer (apps/server/src/assets/install-machine.sh):
    • With BB_INSTALL_SKIP_SERVICE=1, once the machine has joined, the installer:
      • stops the temporary join daemon;
      • waits for its port to free up;
      • starts the supervised daemon in its place.
    • The closing warning now says that the daemon restarts after a crash but not after a reboot.
    • owned_pid matches <launcher> host-daemon and --host-daemon-port <port> --server-url <url>, written exactly as the installer launches them.
    • A recorded PID that runs anything other than this data directory's launcher is treated as stale: --start starts a new daemon, and --stop signals nothing.
    • A recorded launcher with another port or server URL still stops the installer, now with Recorded daemon PID runs a host daemon with another port or server URL.
  • Docs: docs/multiple-devices.md (the skip-service mode) and docs/configuration.md (--supervise).
  • No wire change, so HOST_DAEMON_PROTOCOL_VERSION is unchanged. A launcher from an older release, still running after its daemon self-updated, also restarts a daemon that exits 143, because it already restarts every non-zero exit.
  • Companion PR: Resume an active provider machine whose daemon is gone #6160 makes the server resume an active provider machine whose daemon is gone. That covers what this PR cannot, such as a stop of the launcher itself.

How you verified

Each new test fails on 1e80ca7b4 and passes here:

Test On 1e80ca7b4
apps/host-daemon/src/daemon.test.ts: SIGINT and SIGTERM shutdowns exit 130 and 143, including a signal during startup AssertionError: expected "vi.fn()" to be called with arguments: [ 143 ] (3 failed)
packages/bb-app/test/host-daemon-startup.test.mjs: the launcher is named bb-app; a daemon that SIGTERMs itself is restarted AssertionError: expected 'MainThread' to be 'bb-app' // Object.is equality (5 failed)
apps/server/test/app/install-machine-script.test.ts: the skip-service join daemon is replaced by a supervised one AssertionError: expected [ 'host-daemon', 'join', …(7) ] to deeply equal [ 'host-daemon', 'join', …(14) ]
same file: --start and --stop with a recycled PID, a --start then --stop round trip, a recorded launcher with another URL ✗ Recorded daemon PID belongs to another process. (4 failed)
packages/config/test/machine-service.test.ts: the name is set and /proc/self/cmdline is unchanged the export does not exist

packages/bb-app/test/host-daemon-supervision.test.ts also pins the supervisor behavior that this change relies on: a daemon that exits 143, then 130, then 0 is restarted twice, after 1 s and then 2 s.

Commands:

  • pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/host-daemon --filter=bb-app --filter=@bb/config: 10/10 tasks pass.
  • pnpm exec oxfmt --check and pnpm exec oxlint on every changed file: clean.
  • pnpm exec turbo run test --filter=@bb/host-daemon: 819 passed, 8 skipped.
  • pnpm exec turbo run test --filter=bb-app: 218 passed.
  • pnpm exec turbo run test --filter=@bb/config: 102 passed, 1 skipped.
  • pnpm exec turbo run test --filter=@bb/server -- test/app/install-machine-script.test.ts: 57 passed.

Live checks on Linux:

  • I ran the built daemon bundle. /proc/<pid>/comm read bb-host-daemon, and /proc/<pid>/cmdline was unchanged.
  • On the affected sandbox, I named the running daemon bb-host-daemon with a hard-linked node and added that name to earlyoom's --avoid. Over 45 minutes, earlyoom killed 177 processes, none of them bb's, and the machine stayed connected throughout.

AGENT GENERATED

A host daemon on a berth sandbox died for good after earlyoom sent it
SIGTERM under memory pressure. The daemon handled the signal as a
graceful shutdown and exited 0, the --supervise launcher treats exit 0
as a stop on purpose, and nothing restarted it, so its thread waited on
the host forever.

- A signal-driven shutdown now exits 128 plus the signal number (130
  for SIGINT, 143 for SIGTERM), so the supervising launcher restarts a
  daemon stopped by a signal it did not send. The launcher still exits
  0 when it was told to stop, so service managers see a clean stop.
- On Linux the launcher names its process bb-app and the daemon
  bb-host-daemon by writing /proc/self/comm, which leaves the command
  line the installer matches untouched. Memory killers such as earlyoom
  can then spare them by name; on Node 24 every main thread is
  otherwise named MainThread.
- With BB_INSTALL_SKIP_SERVICE=1, the installer replaces the temporary
  join daemon with a supervised one once it has joined, instead of
  leaving a daemon that nothing restarts after a crash or self-update.
The installer's --start and --stop matched the recorded daemon PID's
command line against patterns whose adjacent arguments both claimed the
same separating space, so they never matched bb's own launcher. Any
recorded PID that was still running made both commands fail with
"Recorded daemon PID belongs to another process.": --stop could not stop
a daemon the installer started without a service, and --start failed
whenever the PID was alive but no daemon answered.

A machine whose disk survives a reboot, such as a berth sandbox stopped
for idling, also keeps install-daemon.pid. Once another process takes
that PID, every resume failed the same way.

- The launcher and its port and server URL are matched as the installer
  writes them, so --stop stops the daemon --start launched.
- A recorded PID that runs anything other than this data directory's
  launcher is treated as stale: --start launches a new daemon and --stop
  signals nothing.
- A recorded launcher with another port or server URL still fails, now
  saying so.
alexandre-vl added a commit to alexandre-vl/bb that referenced this pull request Oct 23, 2026
ymichael added a commit that referenced this pull request Nov 4, 2026
## Human comments

## What was wrong

On Linux, provider bridge workers, the agent CLI under them, and every
tool command the agent runs inherited the host daemon's `oom_score_adj`.
When an agent's work used up the machine's memory, the kernel's OOM
killer ranked bb's own processes and the agent's processes equally and
killed the largest single process. When that memory was spread across
many processes, the largest was bb's server or host daemon, and every
thread on the machine stopped with "Thread interrupted because the host
daemon disconnected". Separately, the systemd unit that
`install-machine.sh` writes has no `OOMPolicy`, so systemd's default,
`stop`, takes the whole host-daemon service down as soon as the kernel
kills any process in it, including the correct victim. Details, kernel
logs and a standalone repro are in #7037.

## What changed

```diff
 RuntimeProviderProcessManager.spawnProvider
   spawnManagedProcess(bridge worker)
+  preferOutOfMemoryKill(child.pid)       # Linux: oom_score_adj = min(1000, daemon's + 500)
     └─ agent CLI ─ tool commands        # inherit the raised value

 install-machine.sh host-daemon unit
   Restart=always
   RestartSec=2
+  OOMPolicy=continue
```

- **`packages/process-utils/src/oom-score.ts`** (new):
`preferOutOfMemoryKill(pid)` sets the child's `oom_score_adj` to the
caller's value plus 500, capped at 1000. It does nothing off Linux, and
it ignores a child that has already exited or a `/proc` it can't write.
Raising a score needs no privileges.
- **`packages/agent-runtime/src/runtime-provider-process.ts`**:
`spawnProvider` calls it right after spawning the bridge worker, before
the worker can start the agent CLI. Everything the agent runs inherits
the raised value, so the kernel takes agent work before bb's server and
host daemon.
- **`apps/server/src/assets/install-machine.sh`**: the host-daemon unit
sets `OOMPolicy=continue`. Restart behavior is unchanged: if the daemon
itself is killed, `Restart=always` still brings it back.
- Plugin host workers, terminals and the server are unchanged. Only
provider workloads are re-ranked.
- No wire change, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.
- Complements #6159: that PR makes a daemon killed by a userspace killer
come back and gives bb's processes names that earlyoom can spare. This
PR changes which process the kernel picks, so the daemon isn't killed in
the first place.

**Merge danger:** two-way door. Reverting restores equal ranking. Blast
radius: Linux hosts only. Under memory pressure the kernel now kills
agent work (a provider's bridge, its CLI or a tool command) before bb,
so a thread whose provider is killed reports a provider exit instead of
every thread being interrupted.

## How you verified

Each new test fails on `920804af6` and passes here:

| Test | On `920804af6` |
| --- | --- |
| `packages/process-utils/test/oom-score.test.ts`: the child's score is
the parent's plus 500; an exited child is ignored | `Cannot find module
'../src/oom-score.js'` |
| `packages/agent-runtime/src/runtime.process-lifecycle.test.ts`: "ranks
provider processes ahead of bb for the out-of-memory killer" |
`AssertionError: expected +0 to be 500` |
| `apps/server/test/app/install-machine-script.test.ts`: the Linux
systemd user unit contains `OOMPolicy=continue` | `expected
'[Unit]\nDescription=bb host daemon fo…' to contain
'OOMPolicy=continue'` |

- `pnpm exec turbo run typecheck lint --filter=@bb/process-utils
--filter=@bb/agent-runtime`: 8 tasks successful, 0 lint warnings.
- `pnpm exec turbo run test --filter=@bb/process-utils`: 118 passed, 16
skipped.
- `pnpm exec turbo run test --filter=@bb/agent-runtime`: 299 passed.
- `pnpm exec turbo run test --filter=@bb/server --
test/app/install-machine-script.test.ts`: 54 passed.
- Kernel behavior, on Ubuntu 24.04 with Linux 6.8, using the standalone
script in #7037: in a 1.2 GB cgroup, a 500 MB "server" whose child keeps
starting 60 MB processes is OOM-killed when both have the same score.
With the child raised by 500, the kernel made 88–89 kills, all of them
the child's processes, and the server kept running.

Fixes #7037

> AGENT GENERATED

Co-authored-by: Michael Yong <[email protected]>
@github-actions github-actions Bot closed this Nov 6, 2026
@github-actions

github-actions Bot commented Nov 6, 2026

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant