Repository navigation
Let the OOM killer take agent work before bb - #7039
Merged
Merged
Conversation
When a Linux machine ran out of memory, the kernel killed bb's server or host daemon instead of the agent command that used the memory, and every thread on the machine stopped with "Thread interrupted because the host daemon disconnected". The provider bridge worker, the agent CLI under it, and every command the agent runs inherited the daemon's oom_score_adj, so the OOM killer ranked them all equally and picked the largest single process, usually bb's server. The host daemon now raises each provider bridge worker's oom_score_adj by 500 (capped at 1000) right after spawning it, on Linux only. The agent CLI and its tool commands inherit the value, so the kernel kills runaway agent work first and bb keeps serving the other threads. The systemd unit that install-machine.sh writes for a host daemon now sets OOMPolicy=continue. With systemd's default, OOMPolicy=stop, killing any process in the unit stopped the whole service, so even a correctly chosen victim took the daemon down with it.
Contributor
|
Thanks for the pull request, @scowalt. It was closed automatically because it does not meet the requirements below yet. This is an automated check, not a review of the change. Contributor approval. bb reviews pull requests only from approved contributors, and you are not on the list yet. Join the #contributors channel in Discord (https://discord.gg/kvBU6tJhcJ), post a link to your pull request, and explain what it changes and why. A maintainer then adds you to the list and reopens the pull request. See CONTRIBUTING.md for details. |
Collaborator
|
/approve @scowalt |
Contributor
|
Approved @scowalt for PRs. The name now stays on the allow list. The author can open a PR now. |
ymichael
pushed a commit
that referenced
this pull request
Nov 5, 2026
…7117) ## Human comments ## What was wrong When two threads of one provider whose injected skill catalogs differ start or resume their sessions at the same time in one environment runtime, each one's `ensureProvider` retires the other's freshly spawned bridge, and both commands fail. Skill roots are part of the process key (`packages/agent-runtime/src/runtime.ts:365-380`), so the two threads get two bridge processes. `ensureProvider` ends with `retireStaleBridgeProcesses` (`packages/agent-runtime/src/runtime-provider-process.ts:254-273`), which shuts down every other process of the same provider with no registered thread. A thread is registered only after `ensureProvider` returns (`packages/agent-runtime/src/runtime.ts:1549-1574`), and that return waits for the sweep's own shutdowns, so each sweep sees the other's new bridge with zero threads. The victim either dies from SIGTERM while still initializing (`exited unexpectedly (signal SIGTERM)`) or exits gracefully once initialized (`exited unexpectedly (code 0)`, or `has exited (code 0)` when the lookup lands between exit and close); the other command then reports `is not running`. In practice this hits Claude Code threads with Composer Predictions installed: its hidden helper gets `skills: []`, every other thread gets its skill, and the helper starts about a second after a watched thread goes idle. A message sent to that thread, or to another idle thread in the same environment, about 0.5 to 4 s after the idle is rejected. On one server this lost 7 sends on long-lived threads in four days, and 6 of 10 sends in a controlled repro. The sweep exists to retire bridges superseded by a plugin update (a new artifact hash). Bridges for another skill catalog of the same bridge launch are not superseded; they are released when their last thread ends. #6479 makes the same change to this filter as part of its larger session-config rework ("main killed a sibling catalog's freshly spawned process before its thread arrived"). This PR takes only that filter, so the crash can be fixed while #6479 is open; it applies to `main` on its own and the hunk matches #6479's, so either can rebase over the other. ## What changed - `packages/agent-runtime/src/runtime-provider-process.ts`: each process records its bridge launch key (`bridgeLaunchProcessKey`: artifact digest, capabilities, bridge options) when it is spawned. `retireStaleBridgeProcesses` retires only a threadless process of the same provider whose bridge launch key differs from the one being ensured. Processes of the same launch with another skill catalog are left to the existing release-after-last-thread path. - `packages/agent-runtime/src/runtime.process-lifecycle.test.ts`: - "retires a threadless bridge process superseded by a new artifact hash" now ensures the fresh key with a launch whose digest differs (`SUPERSEDING_BRIDGE_LAUNCH`, as in #6479). Before, it only changed the process key string while reusing the same launch, which no longer counts as superseded. - New "starts threads of two skill catalogs at once without retiring either bridge": two concurrent `startThread` calls on one runtime with different `skillRoots`; both must be hosted afterwards. - No daemon wire change, no `HOST_DAEMON_PROTOCOL_VERSION` change. ## How you verified - New test without the production change (`main`'s `runtime-provider-process.ts`): fails with `ProviderProcessExitedError: Provider "scripted" exited unexpectedly (signal SIGTERM)`; the other 35 tests in the file pass. With the change: 36/36. - `pnpm exec turbo run test --filter=@bb/agent-runtime --force`: 23 files, 307 tests passed. - `pnpm exec turbo run typecheck lint --filter=@bb/agent-runtime --filter=@bb/host-daemon --force`: 7/7 tasks passed. - `oxfmt --check` on the test file reports the existing `oom_score_adj` test from #7039, unchanged on `main`; the new code is formatter output and that hunk is left alone. - Standalone reproduction at the same code path, ten fresh runtimes per run, on `main` at `fa30b0a7d`: 0/10 without the change (every run lost one or both threads with `exited unexpectedly (code 0)`, `(signal SIGTERM)` or `is not running`), 10/10 with it. ```sh pnpm exec turbo run generate:test-bridges --filter=@bb/agent-runtime cd packages/agent-runtime ../../node_modules/.bin/tsx /tmp/sibling-start-race.mts "$PWD/../.." 10 ``` <details><summary>/tmp/sibling-start-race.mts</summary> ```ts import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; const root = process.argv[2]!; const trials = Number(process.argv[3] ?? 10); const { createAgentRuntime } = await import(`${root}/packages/agent-runtime/src/runtime.ts`); const harness = await import(`${root}/packages/agent-runtime/src/test/runtime-test-harness.ts`); function stage(dir: string, name: string) { const path = join(dir, name); mkdirSync(join(path, name), { recursive: true }); writeFileSync(join(path, name, "SKILL.md"), `---\nname: ${name}\n---\n`); return [{ id: `skills:${name}`, path, skills: [{ name, description: name }] }]; } let passed = 0; for (let trial = 1; trial <= trials; trial++) { const dir = mkdtempSync(join(tmpdir(), "sibling-start-race-")); const runtime = createAgentRuntime({ workspacePath: dir, onEvent: () => {}, onToolCall: async () => ({ contentItems: [], success: true }), }); const bridgeLaunch = harness.createScriptedEchoLaunch(); const start = (threadId: string, skillRoots: unknown) => runtime.startThread({ bridgeLaunch, skillRoots, environmentId: "env-1", threadId, projectId: "p1", providerId: "scripted", options: harness.fullRuntimeOptions, }); const results = await Promise.allSettled([ start("coordinator", stage(dir, "with-predictions-skill")), start("prediction-helper", stage(dir, "no-skills")), ]); const errors = results.flatMap((r) => (r.status === "rejected" ? [String((r.reason as Error).message ?? r.reason).split("\n")[0]] : [])); const hosted = ["coordinator", "prediction-helper"].filter((t) => runtime.hasThread(t)); const ok = errors.length === 0 && hosted.length === 2; if (ok) passed++; console.log(`trial ${trial}: ${ok ? "PASS" : "FAIL"} hosted=${hosted.join(",") || "none"}${errors.length ? ` errors=${JSON.stringify(errors)}` : ""}`); await runtime.shutdown(); rmSync(dir, { recursive: true, force: true }); } console.log(`${passed}/${trials} passed`); process.exit(0); ``` </details> - Live, on a bb-app 0.48.2 nightly (upstream `298e5d0`): the daemon bundle built from `298e5d0` without the change is byte-identical to the shipped `host-daemon/dist/daemon-bundle.mjs`; with the change it differs only by this filter. The live reproduction (send to a watched Claude Code thread the moment it goes idle, Composer Predictions installed) failed 6 of 10 sends before. The patched daemon has not been deployed there yet. Fixes #7116 > AGENT GENERATED Co-authored-by: Claude Opus 5.5 <[email protected]>
albrand
added a commit
to alb-hold/bb
that referenced
this pull request
Nov 25, 2026
#573) * Add OOMPolicy=continue drop-in to installed host daemon units on start Units installed before get-bb#7039 default to OOMPolicy=stop, so one OOM-killed child stops the whole daemon. On start, a systemd user unit that sets no OOMPolicy gets a 50-oom-policy.conf drop-in and a daemon-reload, with no restart and no other drop-in touched. test-change-reason: new module covered by a new test file; no existing test changed. * Respect an OOMPolicy set by any sibling drop-in before adding ours A drop-in such as 10-custom.conf with OOMPolicy=kill would be overridden by the later 50-oom-policy.conf. The migration now skips when any .conf in the unit's drop-in directory sets OOMPolicy. test-change-reason: new test for the sibling drop-in case; existing tests unchanged. * Never overwrite an existing 50-oom-policy.conf that sets other directives When the target drop-in name exists without an OOMPolicy directive, write the policy to the first free 50-oom-policy-N.conf instead of renaming over it. test-change-reason: new regression test for the pre-existing unrelated drop-in; existing tests unchanged. * Remove the OOM policy drop-in when daemon-reload fails so the next start retries The drop-in alone made later starts report already-current without a reload. test-change-reason: new regression test for reload failure then retry; existing tests unchanged. * Honor OOMPolicy only in [Service] when deciding whether the unit needs the drop-in A directive under [Unit], [Install] or a comment is ignored by systemd, so it must not suppress the migration. test-change-reason: new regression tests for misplaced-section and comment cases; existing tests unchanged. * Create the OOM policy drop-in exclusively so a file appearing after the scan is never overwritten or removed test-change-reason: new deterministic collision-race tests (file created between scan and write, and reload failure with a colliding file); existing tests unchanged. * Withdraw the OOM policy drop-in when a sibling sets OOMPolicy after the scan test-change-reason: new deterministic interleaving test (sibling OOMPolicy appears after the scan); existing tests unchanged. * Roll back the OOM policy drop-in only while it is still the file this call created test-change-reason: new test where a replacement file appears before a failed reload; existing tests unchanged. * Own one drop-in file for the OOM policy and drop the free-name search and rollback test-change-reason: owner ruling on PR 573 simplifies the migration (one bb-owned file, reload keyed on systemctl show); tests rewritten for the new contract and the race and rollback tests removed with their code. * Decide the OOM policy skip from systemctl cat so drop-ins in every search path count test-change-reason: Hermes found drop-ins outside the unit directory were missed; the skip decision now reads systemctl cat output, with new tests for a non-adjacent admin drop-in and a failing cat. * Recognise systemctl cat file headers whose path contains spaces test-change-reason: Hermes found a drop-in path with a space was not recognised as a header, so its OOMPolicy was missed; new regression test fails at df103ea.
ymichael
pushed a commit
that referenced
this pull request
Dec 1, 2026
…them (#8298) ## Human comments ## What was wrong `install-machine.sh` writes `OOMPolicy=continue` (#7039) and `ManagedOOMPreference=avoid` (#7823) into the host daemon's systemd unit. But only a new install writes the unit. A unit from before 2026-11-04 keeps the systemd default `OOMPolicy=stop`, so one kernel OOM kill of an agent process stops the whole service. Every thread on the machine stops with it. No part of bb updates a unit that exists, and `--auto-update` changes only the bb-app package. ## What changed ```diff host daemon startup (apps/host-daemon/src/app.ts) + serverMove.updateServiceDefinition() # add missing [Service] settings, daemon-reload serverMove.resumeActivation() # unchanged, now runs after the update ``` - **`packages/host-daemon-contract/src/server-move.ts`**: one list, `HOST_DAEMON_SYSTEMD_SERVICE_DIRECTIVES`, holds the two settings. The daemon and the installer tests both read it. - **`apps/host-daemon/src/server-move/service-definition.ts`**: `addMissingSystemdServiceDirectives(content)` adds each missing setting at the end of `[Service]`. A setting that the unit sets already stays as it is, also `OOMPolicy = stop` with spaces. `systemdDirective` now accepts spaces around `=`, as systemd does. - **`apps/host-daemon/src/server-move/service.ts`**: `updateServiceDefinition()` finds the daemon's own unit with the same lookup a server move uses (`BB_DATA_DIR` must match this data dir), writes the file, and runs `systemctl <scope> daemon-reload`. It does not restart the service. The update uses the same queue as server-moved notices, so the two never write the unit at the same time. A launchd plist and `BB_SERVER_MOVE_SERVICE_MANAGER=none` are not changed. - **`apps/host-daemon/src/server-move/service-manager.ts`**: `reloadSystemdService` comes out of `restartService`, which now calls it. - **`apps/server/test/app/install-machine-script.test.ts`**: the user and system unit tests compare the `[Service]` settings of the generated unit with the shared list, in both directions. A new setting in the installer that is not in the list fails the test. - No wire change, so `HOST_DAEMON_PROTOCOL_VERSION` does not change. Choice: the daemon updates the unit at startup. Precedent: the daemon already rewrites the same file on a server move (`switchToMovedServer`, `writeServiceDefinition`). The alternative is to tell users to rerun the installer, as #7823 does. That restarts the daemon and most users do not know they need it. A maintainer can ask for the other choice in a comment or push commits to this branch. ## How you verified | Check | Before (`main` b0ddaad) | After | | --- | --- | --- | | `service-definition.test.ts`: 6 cases for `addMissingSystemdServiceDirectives` (old unit, partial, other section, spaces, CRLF, no `[Service]`) | fail: `addMissingSystemdServiceDirectives is not a function` | pass | | `service-update.test.ts`: old unit gets the settings and one `daemon-reload`, no restart, file mode kept; failed reload is logged; a server move during the update keeps both changes; unit settings are kept; `none` service manager is not touched | fail | pass | | Installer test with `MemoryHigh=90%` added only to `install-machine.sh` | - | fails as expected | Live check on systemd 262 (Arch Linux), with a scratch user unit `bb-host-daemon-oom-live-check.service` (`ExecStart=/usr/bin/sleep infinity`, no OOM settings) and the real `ServerMoveService`: ```text before: MainPID=3079403 OOMPolicy=stop ManagedOOMPreference=none info Added the current OOM settings to the bb service definition after: MainPID=3079403 OOMPolicy=continue ManagedOOMPreference=avoid ``` A second run changed nothing. The script removed the scratch unit. On the machine that found this, an old unit restarted the daemon on each of four OOM kills of agent processes in nine minutes. With the same two settings in a drop-in, five more OOM kills did not restart it. `pnpm exec turbo run typecheck test lint lint:type-aware --continue --filter=@bb/host-daemon --filter=@bb/host-daemon-contract --filter=@bb/server`: all typecheck and lint tasks pass with 0 warnings. `@bb/server` tests pass. Two tests fail locally and also fail on unchanged `main` on this machine: `payload-size.test.ts` (Node 26 gzip sizes) and `protocol-self-update.test.ts` (Arch keeps npm outside the Node directory). CI uses Node 22. An Opus review found no blocking defect. Its points are fixed here: the update now runs before `resumeActivation` and on the server-moved queue, a failed reload is logged as such, settings with spaces are kept, and the drift test checks both directions. Not covered by a test: the one `app.ts` line that starts the update. `resumeActivation` at the same place has no test either. Fixes #8297 > AGENT GENERATED
scowalt
pushed a commit
to scowalt/bb
that referenced
this pull request
Dec 1, 2026
…them (get-bb#8298) ## Human comments ## What was wrong `install-machine.sh` writes `OOMPolicy=continue` (get-bb#7039) and `ManagedOOMPreference=avoid` (get-bb#7823) into the host daemon's systemd unit. But only a new install writes the unit. A unit from before 2026-11-04 keeps the systemd default `OOMPolicy=stop`, so one kernel OOM kill of an agent process stops the whole service. Every thread on the machine stops with it. No part of bb updates a unit that exists, and `--auto-update` changes only the bb-app package. ## What changed ```diff host daemon startup (apps/host-daemon/src/app.ts) + serverMove.updateServiceDefinition() # add missing [Service] settings, daemon-reload serverMove.resumeActivation() # unchanged, now runs after the update ``` - **`packages/host-daemon-contract/src/server-move.ts`**: one list, `HOST_DAEMON_SYSTEMD_SERVICE_DIRECTIVES`, holds the two settings. The daemon and the installer tests both read it. - **`apps/host-daemon/src/server-move/service-definition.ts`**: `addMissingSystemdServiceDirectives(content)` adds each missing setting at the end of `[Service]`. A setting that the unit sets already stays as it is, also `OOMPolicy = stop` with spaces. `systemdDirective` now accepts spaces around `=`, as systemd does. - **`apps/host-daemon/src/server-move/service.ts`**: `updateServiceDefinition()` finds the daemon's own unit with the same lookup a server move uses (`BB_DATA_DIR` must match this data dir), writes the file, and runs `systemctl <scope> daemon-reload`. It does not restart the service. The update uses the same queue as server-moved notices, so the two never write the unit at the same time. A launchd plist and `BB_SERVER_MOVE_SERVICE_MANAGER=none` are not changed. - **`apps/host-daemon/src/server-move/service-manager.ts`**: `reloadSystemdService` comes out of `restartService`, which now calls it. - **`apps/server/test/app/install-machine-script.test.ts`**: the user and system unit tests compare the `[Service]` settings of the generated unit with the shared list, in both directions. A new setting in the installer that is not in the list fails the test. - No wire change, so `HOST_DAEMON_PROTOCOL_VERSION` does not change. Choice: the daemon updates the unit at startup. Precedent: the daemon already rewrites the same file on a server move (`switchToMovedServer`, `writeServiceDefinition`). The alternative is to tell users to rerun the installer, as get-bb#7823 does. That restarts the daemon and most users do not know they need it. A maintainer can ask for the other choice in a comment or push commits to this branch. ## How you verified | Check | Before (`main` a8c3228) | After | | --- | --- | --- | | `service-definition.test.ts`: 6 cases for `addMissingSystemdServiceDirectives` (old unit, partial, other section, spaces, CRLF, no `[Service]`) | fail: `addMissingSystemdServiceDirectives is not a function` | pass | | `service-update.test.ts`: old unit gets the settings and one `daemon-reload`, no restart, file mode kept; failed reload is logged; a server move during the update keeps both changes; unit settings are kept; `none` service manager is not touched | fail | pass | | Installer test with `MemoryHigh=90%` added only to `install-machine.sh` | - | fails as expected | Live check on systemd 262 (Arch Linux), with a scratch user unit `bb-host-daemon-oom-live-check.service` (`ExecStart=/usr/bin/sleep infinity`, no OOM settings) and the real `ServerMoveService`: ```text before: MainPID=3079403 OOMPolicy=stop ManagedOOMPreference=none info Added the current OOM settings to the bb service definition after: MainPID=3079403 OOMPolicy=continue ManagedOOMPreference=avoid ``` A second run changed nothing. The script removed the scratch unit. On the machine that found this, an old unit restarted the daemon on each of four OOM kills of agent processes in nine minutes. With the same two settings in a drop-in, five more OOM kills did not restart it. `pnpm exec turbo run typecheck test lint lint:type-aware --continue --filter=@bb/host-daemon --filter=@bb/host-daemon-contract --filter=@bb/server`: all typecheck and lint tasks pass with 0 warnings. `@bb/server` tests pass. Two tests fail locally and also fail on unchanged `main` on this machine: `payload-size.test.ts` (Node 26 gzip sizes) and `protocol-self-update.test.ts` (Arch keeps npm outside the Node directory). CI uses Node 22. An Opus review found no blocking defect. Its points are fixed here: the update now runs before `resumeActivation` and on the server-moved queue, a failed reload is logged as such, settings with spaces are kept, and the drift test checks both directions. Not covered by a test: the one `app.ts` line that starts the update. `resumeActivation` at the same place has no test either. Fixes get-bb#8297 > AGENT GENERATED
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 thatinstall-machine.shwrites has noOOMPolicy, 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
packages/process-utils/src/oom-score.ts(new):preferOutOfMemoryKill(pid)sets the child'soom_score_adjto 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/procit can't write. Raising a score needs no privileges.packages/agent-runtime/src/runtime-provider-process.ts:spawnProvidercalls 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 setsOOMPolicy=continue. Restart behavior is unchanged: if the daemon itself is killed,Restart=alwaysstill brings it back.HOST_DAEMON_PROTOCOL_VERSIONis unchanged.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
920804af6and passes here:920804af6packages/process-utils/test/oom-score.test.ts: the child's score is the parent's plus 500; an exited child is ignoredCannot 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 500apps/server/test/app/install-machine-script.test.ts: the Linux systemd user unit containsOOMPolicy=continueexpected '[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.Fixes #7037