#5964 · Plugin continuation errors escape process containment
2026-10-21 · trusted main commit 06ae8f039a7198a6aad2b9b6e030efb88f8dd923
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A plugin CLI invocation can leave asynchronous work running after the invocation returns or its instance reloads. If that work touches its old API, the runtime throws a stale-context error. The process-level containment hook recognizes background service contexts only, so it declines the error and the server's fallback exits with code 1. An isolated child-process reproduction exits the same way for both a thrown exception and an unhandled rejected promise; the same test fails again in a second clean checkout. Ordinary detached CLI errors also escape containment even without a reload.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Using an old realtime handle after reload can terminate the process. | Verified | Both reload cases produce PluginContextStaleError and child exit 1 in both clean runs. |
| Rejected promises have the same failure. | Verified | Node's default unhandled-rejection escalation reaches the same uncaught-exception dispatch; rejection case exits 1. |
| Only background-service work has asynchronous attribution. | Verified | serviceContext.run wraps service start; the common invocation wrapper has no plugin asynchronous context. |
| Any awaited CLI failure crashes the server. | Qualified | The common wrapper already catches returned/awaited failures. This reproduction deliberately schedules detached callbacks from the pending CLI continuation. |
| Two specific production incidents and launcher restart timings. | Unverified | No production logs, user data, or running user instance were accessed. |
3. Environment
- Linux x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1.
- Target repository is public. Both checkouts use the full trusted base SHA above.
- Real migrated SQLite via createMigratedConnection; no database mocks and no new dependencies.
- No HTTP listeners, browser sessions, provider sessions, or production runtime were needed. Each child gets a fresh mkdtemp directory and explicitly sets BB_DATA_DIR to it, then the parent removes it.
4. Minimal reproduction
- Prepare a clean checkout and prerequisites:
git clone https://github.com/get-bb/bb.git bb-5964 cd bb-5964 git checkout 06ae8f039a7198a6aad2b9b6e030efb88f8dd923 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build --filter=@bb/server # Save the test below as apps/server/test/services/plugins/plugin-uncaught.test.ts pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-uncaught.test.ts
The initial unfiltered monorepo build encountered an SDK/plugin build-order race; retrying the unchanged build succeeded (67 tasks). The targeted SDK-first build order above avoids that prerequisite race. The second checkout's server build passed.
The test loads a real, author-created plugin. Its CLI handler waits for a temporary gate file. Reload times out draining that invocation, disposes the old handle, then the test releases the gate. The resumed handler schedules either a timer throw or a detached rejected promise that publishes through its captured old API. A child uses the actual plugin-service containment method and the same contain-or-exit decision as the server. This is not a full HTTP server boot.
Expected: child exit 0, SURVIVED status=running after reload, and one plugin-attributed warning despite two stale attempts. For a live plugin's detached error, expect survival and degraded status. Actual on base:
PluginContextStaleError: plugin "containment" used a stale API handle — it was reloaded or disabled; re-entry happens via a fresh factory call expected child exit: 0 actual child exit: 1 Test Files 1 failed (1) Tests 4 failed (4)
The same failure occurs in the rejected-promise case. The two non-reload controls exit 1 with Error: detached CLI failure. All four cases fail for the intended containment assertion, not fixture setup.
Complete reproduction test (save at the path in the command)
import { spawn } from "node:child_process";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
const serverDir = fileURLToPath(new URL("../../../", import.meta.url));
const pluginSource = String.raw`
import { existsSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
export default function plugin(bb) {
bb.cli.register({
name: "containment",
summary: "Exercise containment",
async run([gate, kind, lifecycle]) {
while (!existsSync(gate)) await delay(5);
const fail = () => {
if (lifecycle === "reload") bb.realtime.publish("changed", {});
else throw new Error("detached CLI failure");
};
for (let attempt = 0; attempt < 2; attempt += 1) {
setTimeout(() => {
if (kind === "rejection") void Promise.resolve().then(fail);
else fail();
}, attempt * 20);
}
return { exitCode: 0 };
},
});
}
`;
const runner = String.raw`
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import pino from "pino";
import { createMigratedConnection } from "@bb/db/testing";
import { createAiServiceRegistry } from "./src/services/ai/ai-service-registry.ts";
import { createPluginService } from "./src/services/plugins/plugin-service.ts";
import { createNoopTelemetryService } from "./src/services/system/telemetry.ts";
const [workDir, kind, lifecycle, pluginSource] = process.argv.slice(1);
const db = createMigratedConnection();
const service = createPluginService({
aiServices: createAiServiceRegistry(),
telemetry: createNoopTelemetryService(),
db,
logger: pino({ level: "warn" }),
dataDir: join(workDir, "data"),
appVersion: "0.9.0",
serviceStopTimeoutMs: 10,
hub: {
getDaemonSessionIdForHost: () => null,
notifyPluginChanged: () => {},
notifyPluginSignal: () => 0,
notifySystem: () => {},
},
});
process.on("uncaughtException", (error) => {
if (service.handleUncaughtException(error)) return;
process.stderr.write(error.name + ": " + error.message + "\n");
process.exit(1);
});
const rootDir = join(workDir, "bb-plugin-containment");
await mkdir(rootDir);
await writeFile(join(rootDir, "package.json"), JSON.stringify({
name: "bb-plugin-containment",
version: "0.1.0",
bb: {
name: "Containment fixture",
description: "Exercises detached CLI continuations",
branding: { icon: "Zap" },
server: "./server.ts",
},
}));
await writeFile(join(rootDir, "server.ts"), pluginSource);
try {
const installed = await service.installPath(rootDir);
if (installed.status !== "running") throw new Error(JSON.stringify(installed));
const gate = join(workDir, "release");
const pending = service.runCliCommand("containment", [gate, kind, lifecycle], {});
if (lifecycle === "reload") await service.reload("containment");
await writeFile(gate, "ready");
await pending;
await delay(150);
const current = service.list().find((plugin) => plugin.id === "containment");
process.stdout.write("SURVIVED status=" + current.status + "\n");
} finally {
await service.stop();
db.$client.close();
}
`;
it.each([
["exception", "reload", "running"],
["rejection", "reload", "running"],
["exception", "live", "degraded"],
["rejection", "live", "degraded"],
])("contains a detached CLI %s after %s", async (kind, lifecycle, status) => {
const workDir = await mkdtemp(join(tmpdir(), "bb-plugin-uncaught-"));
try {
const result = await new Promise<{
code: number | null;
stdout: string;
stderr: string;
}>((resolve, reject) => {
const child = spawn(process.execPath, [
"--conditions=source",
"--import", "tsx",
"--input-type=module",
"--eval", runner,
workDir, kind, lifecycle, pluginSource,
], {
cwd: serverDir,
env: { ...process.env, BB_DATA_DIR: workDir },
timeout: 12_000,
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => { stdout += chunk; });
child.stderr.on("data", (chunk) => { stderr += chunk; });
child.on("error", reject);
child.on("close", (code) => resolve({ code, stdout, stderr }));
});
expect(result, result.stderr).toMatchObject({ code: 0 });
expect(result.stdout).toContain("SURVIVED status=" + status);
const warnings = result.stdout.split("\n").filter((line) => {
if (!line.startsWith("{")) return false;
const record = JSON.parse(line);
return record.level === 40 && record.msg.includes("[plugin:containment]");
});
expect(warnings).toHaveLength(1);
} finally {
await rm(workDir, { recursive: true, force: true });
}
});
5. Root cause
PluginContextStaleError is generated by assertLive and realtime.publish uses that guard. The exception therefore originates in real API lifetime enforcement, not the fixture.
Service attribution wraps only background-service starts. handleUncaughtException begins:
const instance = serviceContext.getStore(); if (instance === undefined) return false;
There is no stale-error special case. invokeWrapped catches awaited exceptions but does not preserve plugin attribution into detached asynchronous descendants. CLI dispatch uses that common wrapper, as do HTTP, RPC and event invocations.
The server fallback calls process.exit(1) when containment declines. With no unhandled-rejection listener, Node's default escalation reaches this same hook. The lifetime guard is correct; the missing attribution and containment at the process-error boundary cause the crash.
6. Proposed fix
Attach internal plugin and instance identity to the stale error, recognize it before service-context lookup, and deduplicate warnings weakly per disposed instance. Run the existing shared invocation wrapper in AsyncLocalStorage carrying the exact API handle and invocation label. Contain detached errors, mark only the still-current matching instance degraded, and do not degrade a replacement instance. Keep service restart/abort supervision unchanged and continue declining unrelated core errors.
An independently authored local candidate in the existing server plugin subsystem passed all seven final regression cases and 58 existing tests (65 total across nine files), plus the server typecheck. Coverage includes context-free stale errors and unrelated core errors. No SDK contract, wire protocol, dependency, persisted data, or packaging change was required. Candidate work stopped without a push when an open linked pull request appeared; no duplicate pull request was opened. In-flight request cancellation was not part of the candidate.
7. Linked pull request: static review
PR #5967 was found open and in draft during the final duplicate check (reviewed head e074fe4ec05eb39ea94d30fcfc2c09cfcbf69e43). Only its metadata and diff were read as untrusted data; its branch and tests were never checked out or executed.
The diff caches a typed stale error per API instance, deduplicates those errors, adds handler context to the common invocation wrapper, checks instance identity before degrading, and routes both exception and rejection events through the same server handler. Its tests cover stale CLI continuations and detached CLI/route/RPC/event work. These changes address the verified root-cause mechanisms. Static verdict: directionally addresses the bug; no confirmed blocking defect found in this bounded review. Runtime correctness and CI for that PR remain unverified here. The local candidate's passing results do not apply to the PR.
8. Verification
The same agent repeated the test in a second freshly created, detached worktree at 06ae8f039a7198a6aad2b9b6e030efb88f8dd923, with a frozen install and a successful targeted server build. Only the author-created reproduction test was copied; no production changes were present. A new temporary data directory was created for every child, and no ports were opened.
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@bb/server pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-uncaught.test.ts Result: 1 failed test file; 4 failed tests; child exit 1 in each case.
The second run supports the final verdict without correction. It is a repeat by the same agent, not independent verification. Runtime HTTP/RPC/event entry points were inspected but the direct crash reproducer uses CLI. Production incident timing and launcher behavior remain outside this test.
9. Related issues and pull requests
The initial duplicate check found no linked open pull request. A final timeline check found PR #5967, so the automation stopped its separate fix and did not push or open another pull request. Issue #2286 concerns CLI handler error reporting rather than process-level exception containment; it is not treated as this bug's fix. A later trusted-main fetch advanced to 04bdce811 with no changes in the affected plugin subsystem.
10. Appendix
Issue content was treated only as untrusted claims. No issue-provided script, branch, attachment, or external URL was executed or fetched. Evidence is embedded inline in accordance with the reports repository policy; local raw artifacts are not published. Checkout paths in the outputs below are anonymized.
First run: exact assertion and test output
@bb/server:test: ❯ |@bb/server| test/services/plugins/plugin-uncaught.test.ts (4 tests | 4 failed) 9033ms
@bb/server:test: × contains a detached CLI exception after reload 2768ms
@bb/server:test: × contains a detached CLI rejection after reload 2276ms
@bb/server:test: × contains a detached CLI exception after live 1992ms
@bb/server:test: × contains a detached CLI rejection after live 1995ms
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI exception after reload
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI rejection after reload
@bb/server:test: AssertionError: PluginContextStaleError: plugin "containment" used a stale API handle — it was reloaded or disabled; re-entry happens via a fresh factory call
@bb/server:test: : expected { code: 1, …(2) } to match object { code: +0 }
@bb/server:test: (2 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: - "code": 0,
@bb/server:test: + "code": 1,
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/plugins/plugin-uncaught.test.ts:128:35
@bb/server:test: 126| child.on("close", (code) => resolve({ code, stdout, stderr }));
@bb/server:test: 127| });
@bb/server:test: 128| expect(result, result.stderr).toMatchObject({ code: 0 });
@bb/server:test: | ^
@bb/server:test: 129| expect(result.stdout).toContain("SURVIVED status=" + status);
@bb/server:test: 130| const warnings = result.stdout.split("\n").filter((line) => {
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI exception after live
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI rejection after live
@bb/server:test: AssertionError: Error: detached CLI failure
@bb/server:test: : expected { code: 1, stdout: '', …(1) } to match object { code: +0 }
@bb/server:test: (2 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: - "code": 0,
@bb/server:test: + "code": 1,
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/plugins/plugin-uncaught.test.ts:128:35
@bb/server:test: 126| child.on("close", (code) => resolve({ code, stdout, stderr }));
@bb/server:test: 127| });
@bb/server:test: 128| expect(result, result.stderr).toMatchObject({ code: 0 });
@bb/server:test: | ^
@bb/server:test: 129| expect(result.stdout).toContain("SURVIVED status=" + status);
@bb/server:test: 130| const warnings = result.stdout.split("\n").filter((line) => {
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/4]⎯
@bb/server:test:
@bb/server:test:
@bb/server:test: Test Files 1 failed (1)
@bb/server:test: Tests 4 failed (4)
@bb/server:test: Start at 03:42:59
@bb/server:test: Duration 12.89s (transform 918ms, setup 1.65s, import 8ms, tests 9.03s, environment 0ms)
@bb/server:test:
@bb/server:test: ELIFECYCLE Test failed. See above for more details.
@bb/server#test: ERROR command (CHECKOUT) /usr/local/bin/pnpm run test test/services/plugins/plugin-uncaught.test.ts exited (1)
Tasks: 9 successful, 10 total
Cached: 0 cached, 10 total
Time: 47.788s
Failed: @bb/server#test
ERROR run failed: command exited (1)
Second clean run: exact assertion and test output
@bb/server:test: ❯ |@bb/server| test/services/plugins/plugin-uncaught.test.ts (4 tests | 4 failed) 7978ms
@bb/server:test: × contains a detached CLI exception after reload 2281ms
@bb/server:test: × contains a detached CLI rejection after reload 1920ms
@bb/server:test: × contains a detached CLI exception after live 1869ms
@bb/server:test: × contains a detached CLI rejection after live 1905ms
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI exception after reload
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI rejection after reload
@bb/server:test: AssertionError: PluginContextStaleError: plugin "containment" used a stale API handle — it was reloaded or disabled; re-entry happens via a fresh factory call
@bb/server:test: : expected { code: 1, …(2) } to match object { code: +0 }
@bb/server:test: (2 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: - "code": 0,
@bb/server:test: + "code": 1,
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/plugins/plugin-uncaught.test.ts:128:35
@bb/server:test: 126| child.on("close", (code) => resolve({ code, stdout, stderr }));
@bb/server:test: 127| });
@bb/server:test: 128| expect(result, result.stderr).toMatchObject({ code: 0 });
@bb/server:test: | ^
@bb/server:test: 129| expect(result.stdout).toContain("SURVIVED status=" + status);
@bb/server:test: 130| const warnings = result.stdout.split("\n").filter((line) => {
@bb/server:test:
@bb/server:test: Test Files 1 failed (1)
@bb/server:test:
@bb/server:test: Tests 4 failed (4)
@bb/server:test: Start at 03:43:08
@bb/server:test: Duration 11.50s (transform 940ms, setup 1.60s, import 10ms, tests 7.98s, environment 0ms)
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯
@bb/server:test:
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI exception after live
@bb/server:test: FAIL |@bb/server| test/services/plugins/plugin-uncaught.test.ts > contains a detached CLI rejection after live
@bb/server:test: AssertionError: Error: detached CLI failure
@bb/server:test: : expected { code: 1, stdout: '', …(1) } to match object { code: +0 }
@bb/server:test: (2 matching properties omitted from actual)
@bb/server:test:
@bb/server:test: - Expected
@bb/server:test: + Received
@bb/server:test:
@bb/server:test: {
@bb/server:test: - "code": 0,
@bb/server:test: + "code": 1,
@bb/server:test: }
@bb/server:test:
@bb/server:test: ❯ test/services/plugins/plugin-uncaught.test.ts:128:35
@bb/server:test: 126| child.on("close", (code) => resolve({ code, stdout, stderr }));
@bb/server:test: 127| });
@bb/server:test: 128| expect(result, result.stderr).toMatchObject({ code: 0 });
@bb/server:test: | ^
@bb/server:test: 129| expect(result.stdout).toContain("SURVIVED status=" + status);
@bb/server:test: 130| const warnings = result.stdout.split("\n").filter((line) => {
@bb/server:test:
@bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/4]⎯
@bb/server:test:
@bb/server:test: ELIFECYCLE Test failed. See above for more details.
@bb/server#test: ERROR command (CLEAN_CHECKOUT/apps/server) /usr/local/bin/pnpm run test test/services/plugins/plugin-uncaught.test.ts exited (1)
Tasks: 9 successful, 10 total
Cached: 8 cached, 10 total
Time: 13.846s
Failed: @bb/server#test
ERROR run failed: command exited (1)