Repository navigation
Description
Summary
When a plugin load fails after its server factory has already run, BB discards the new instance without running its bb.onDispose hooks. Timers and bb.sdk.subscribe callbacks the factory started keep running against the invalidated bb object, so every tick throws PluginContextStaleError. BB now contains each throw (#5964), but the process diagnostics monitor still writes one crash report file per throw. In my case that came to 43,163 report files (about 59 MB) in ~/.bb/logs.
I expected a discarded instance to get the same cleanup as a disposed one: run its dispose hooks, then invalidate the handle.
Versions and environment
- Observed with the BB desktop AppImage
0.50.1on Omarchy Linux (Arch-based), x86-64, kernel7.2.15-1-omarchy. - Reproduction: BB checkout at
796cdcc0f4bf8a55e23664035c54e8db6fe9d272(currentmain), Node.jsv26.12.0, pnpm9.15.9(the repo pins9.15.0). - Plugin involved in the incident: the
tracesplugin, installed from a localpath:source. No provider, model, or credentials are needed for the reproduction.
Steps to reproduce
-
From a BB checkout at
796cdcc0f4bf8a55e23664035c54e8db6fe9d272, install locked dependencies:pnpm install --frozen-lockfile
-
Save this test as
apps/server/test/services/plugins/plugin-failed-load-dispose.repro.test.ts. It uses the same standalonecreatePluginServicesetup asplugin-instance-lifecycle.test.ts. The fixture plugin starts a 10 ms timer that publishes, and clears it inbb.onDispose.
// Repro: a plugin instance that fails to load is discarded without running
// its bb.onDispose hooks, so a timer it started keeps calling the stale API.
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createMigratedConnection } from "@bb/db/testing";
import type { Logger } from "@bb/logger";
import { createAiServiceRegistry } from "../../../src/services/ai/ai-service-registry.js";
import {
createPluginService,
type PluginService,
} from "../../../src/services/plugins/plugin-service.js";
import { createNoopTelemetryService } from "../../../src/services/system/telemetry.js";
import { testLogger } from "../../helpers/test-app.js";
interface Control {
generation: number;
failFactory: boolean;
ticks: number[];
disposed: number[];
timers: ReturnType<typeof setInterval>[];
}
declare global {
var __failedLoad: Control | undefined;
}
// Same shape as a real plugin: start a timer, clear it in onDispose.
const SERVER = `
export default function plugin(bb: any) {
const control = globalThis.__failedLoad;
const generation = ++control.generation;
const timer = setInterval(() => {
control.ticks.push(generation);
bb.realtime.publish("tick", { generation });
}, 10);
control.timers.push(timer);
bb.onDispose(() => {
clearInterval(timer);
control.disposed.push(generation);
});
if (control.failFactory) throw new Error("factory failed after setup");
}
`;
const HOST = `
import "bb-repro-package-that-is-not-installed";
export default { experimental_apiVersion: 1, contract: {}, handlers: {} };
`;
async function writePlugin(root: string, withBrokenHost: boolean) {
await mkdir(root, { recursive: true });
await writeFile(
join(root, "package.json"),
JSON.stringify({
name: "bb-plugin-failedload",
version: "0.1.0",
bb: {
name: "Failed load repro",
description: "Starts a timer, then fails to load.",
branding: { icon: "Zap" },
server: "./server.ts",
...(withBrokenHost ? { host: "./host.ts" } : {}),
},
}),
);
await writeFile(join(root, "server.ts"), SERVER);
if (withBrokenHost) await writeFile(join(root, "host.ts"), HOST);
}
function captureUncaught(service: PluginService) {
const previous = process.listeners("uncaughtException");
process.removeAllListeners("uncaughtException");
const claimed: unknown[] = [];
const unclaimed: unknown[] = [];
process.on("uncaughtException", (error) => {
(service.handleUncaughtException(error) ? claimed : unclaimed).push(error);
});
return {
claimed,
unclaimed,
restore() {
process.removeAllListeners("uncaughtException");
for (const listener of previous) process.on("uncaughtException", listener);
},
};
}
describe("failed plugin load skips bb.onDispose", () => {
let workDir: string;
let service: PluginService;
beforeEach(async () => {
workDir = await mkdtemp(join(tmpdir(), "bb-failed-load-"));
globalThis.__failedLoad = {
generation: 0,
failFactory: false,
ticks: [],
disposed: [],
timers: [],
};
service = createPluginService({
aiServices: createAiServiceRegistry(),
telemetry: createNoopTelemetryService(),
db: createMigratedConnection(),
hub: {
getDaemonSessionIdForHost: () => null,
notifyPluginChanged: () => {},
onWatchedTargets: () => () => {},
notifyPluginSignal: () => 0,
notifySystem: () => {},
},
logger: testLogger as unknown as Logger,
dataDir: join(workDir, "data"),
appVersion: "0.9.0",
loadTimeoutMs: 5_000,
serviceStopTimeoutMs: 100,
});
});
afterEach(async () => {
await service.stop();
// Test-only cleanup. BB never clears these timers.
for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
globalThis.__failedLoad = undefined;
await rm(workDir, { recursive: true, force: true });
});
async function ticksAfterServiceStop() {
const control = globalThis.__failedLoad!;
await service.stop();
const before = control.ticks.length;
await new Promise((resolve) => setTimeout(resolve, 100));
return control.ticks.length - before;
}
function state() {
const control = globalThis.__failedLoad!;
return {
plugin: service.list().find((p) => p.id === "failedload"),
generation: control.generation,
disposed: [...control.disposed],
ticks: control.ticks.length,
};
}
it("first load: host entry fails to build after the factory ran", async () => {
const root = join(workDir, "failedload");
await writePlugin(root, true);
const uncaught = captureUncaught(service);
try {
await service.installPath(root).catch((error: unknown) => {
console.log("installPath rejected:", String(error).slice(0, 300));
});
await new Promise((resolve) => setTimeout(resolve, 300));
const after = state();
const stale = uncaught.claimed.filter(
(e) => (e as Error)?.name === "PluginContextStaleError",
).length;
console.log("first-load result", {
status: after.plugin?.status,
statusDetail: after.plugin?.statusDetail?.slice(0, 200),
factoryRuns: after.generation,
disposeHooksRun: after.disposed,
timerTicksAfterDiscard: after.ticks,
staleErrorsClaimed: stale,
unclaimed: uncaught.unclaimed.length,
});
// Broken behavior: the factory ran, its onDispose never ran, and the
// timer keeps firing against the invalidated handle.
expect(after.generation).toBe(1);
expect(after.disposed).toEqual([]);
expect(stale).toBeGreaterThan(5);
// service.stop() does not stop it either.
const afterStop = await ticksAfterServiceStop();
console.log("first-load ticks in 100 ms after service.stop():", afterStop);
expect(afterStop).toBeGreaterThan(0);
} finally {
for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
uncaught.restore();
}
});
it("reload: new factory throws after registering cleanup", async () => {
const root = join(workDir, "failedload");
await writePlugin(root, false);
await service.installPath(root);
expect(state().plugin?.status).toBe("running");
const uncaught = captureUncaught(service);
try {
globalThis.__failedLoad!.failFactory = true;
await service.reload("failedload").catch((error: unknown) => {
console.log("reload rejected:", String(error).slice(0, 300));
});
await new Promise((resolve) => setTimeout(resolve, 300));
const after = state();
const fromGen2 = globalThis.__failedLoad!.ticks.filter((g) => g === 2).length;
const stale = uncaught.claimed.filter(
(e) => (e as Error)?.name === "PluginContextStaleError",
).length;
console.log("reload result", {
status: after.plugin?.status,
factoryRuns: after.generation,
disposeHooksRun: after.disposed,
gen2TicksAfterDiscard: fromGen2,
staleErrorsClaimed: stale,
unclaimed: uncaught.unclaimed.length,
});
// Generation 1 stays live (correct). Generation 2 was discarded, but its
// onDispose never ran and its timer keeps throwing.
expect(after.generation).toBe(2);
expect(after.disposed).not.toContain(2);
expect(fromGen2).toBeGreaterThan(5);
expect(stale).toBeGreaterThan(5);
// service.stop() disposes generation 1 but not the discarded generation 2.
const afterStop = await ticksAfterServiceStop();
console.log("reload ticks in 100 ms after service.stop():", afterStop, {
disposeHooksRun: [...globalThis.__failedLoad!.disposed],
});
expect(globalThis.__failedLoad!.disposed).toEqual([1]);
expect(afterStop).toBeGreaterThan(0);
} finally {
for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
uncaught.restore();
}
});
});-
Run it:
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-failed-load-dispose.repro.test.ts --disableConsoleIntercept
Turbo runs the generators the server tests need.
--disableConsoleInterceptshows the logged results, because the server config hides console output from passing tests.
The tests assert the broken behavior, so they pass when the bug is reproduced.
Both cases reproduce:
- First load, host entry fails to build. This is the incident path. The factory runs, then the
hostArtifactProblem !== nullbranch callsdiscardCandidate. - Reload, factory throws after it set up cleanup. The previous instance correctly stays live. The failed candidate's timer leaks.
In both cases service.stop() does not stop the leaked timer either. It runs the live instance's hooks (generation 1 in the reload case) and never sees the discarded one. Without the test's own clearInterval cleanup, Vitest reports the leaked timer's PluginContextStaleError as unhandled errors after the tests finish.
What did not reproduce: a host entry build failure during a reload no longer runs the factory. BB returns failBeforeFactory first when a previous instance exists. So bb plugin reload with a broken host entry is safe on main and on 0.50.1. Only a load with no previous instance (server startup, install, or re-enabling a plugin in the error state) reaches the factory and then the discard.
Expected vs actual
Expected: the discarded instance's bb.onDispose hooks run (in LIFO order, as for a normal dispose). Its timer stops. No PluginContextStaleError follows, and nothing from the discarded instance runs after service.stop().
Actual output from the test on main:
first-load result {
status: 'error',
statusDetail: 'Build failed with 1 error:\n' +
'host.ts:2:9: ERROR: Could not resolve "bb-repro-package-that-is-not-installed"',
factoryRuns: 1,
disposeHooksRun: [],
timerTicksAfterDiscard: 29,
staleErrorsClaimed: 29,
unclaimed: 0
}
first-load ticks in 100 ms after service.stop(): 9
reload result {
status: 'running',
factoryRuns: 2,
disposeHooksRun: [],
gen2TicksAfterDiscard: 29,
staleErrorsClaimed: 29,
unclaimed: 0
}
reload ticks in 100 ms after service.stop(): 9 { disposeHooksRun: [ 1 ] }
Test Files 1 passed (1)
Tests 2 passed (2)
Incident log from ~/.bb/logs/server.23.log (2026-11-20, server startup). The factory's own log line appears 1 ms before the failure, and the first stale-handle error follows 0.6 s later:
13:03:29.232 Server listening
13:03:37.454 [plugin:traces] Traces loaded (read-only BB storage)
13:03:37.455 plugin traces failed to load: Build failed with 1 error:
prompt-contract.ts:2:18: ERROR: [plugin: bb-zod-resolution] could not resolve "zod": this host entry imports it; add zod to the plugin's dependencies. ...
13:03:38.049 PluginContextStaleError: plugin "traces" used a stale API handle — it was reloaded or disabled; re-entry happens via a fresh factory call
The same sequence repeats after the next server start at 14:43:34 (Traces loaded at 14:43:41.543, failure at 14:43:41.544, first stale error at 14:43:42.187).
Evidence
discardCandidateabortsstopping, interrupts interactions, closes databases, abortsreleased, and callshandle.invalidate(). It does not runhandle.disposeHooks.disposePluginInstancerunshandle.disposeHooksin reverse before it invalidates the handle. Only this path runsbb.onDispose.discardCandidateis called after the factory has run in three places:- the factory throws;
- the host entry failed to build and there is no previous instance (the early return for reloads is here);
- services were still hung after disposing the previous instance.
invalidate()only marks the handle stale and revokes the RPC caller. It does not stop anything the plugin started.bb.sdk.subscribeis not tied to the plugin instance.wrapSdkForPluginspreads the shared SDK, andsubscribegoes straight to the realtime client. Only the plugin's ownbb.onDisposecan remove it. In the incident,tracessubscribed tothread:changedand published from a short timer on each change. The leaked subscription threw once per thread change for the rest of the process.- BB puts some of its own cleanup on the same list.
rpc.experimental_whileWatchedpushes the stop function for ahub.onWatchedTargetslistener that starts during the factory. A discarded candidate keeps that listener. I read this from the code and did not reproduce it. - The docs promise cleanup on failed loads only for the previous instance. The
bb.onDisposelifecycle section and theonDisposecontract ("the sanctioned place to clear timers") say nothing about a candidate that is dropped after its factory ran. - Report flood:
installSafeProcessDiagnosticslistens onuncaughtExceptionMonitor. Node calls that listener before the server'suncaughtExceptionhandler gets a chance to claim the error. So it synchronously writes aprocess-server-uncaughtException-*.jsonfile even for errors BB then contains.reportStaleErrorlogs a stale error once, becauseassertLivereuses one cached error object. The report writer has no such limit. - Measured counts: I counted
process-server-uncaughtException-*.jsonfiles in~/.bb/logswhose error wasPluginContextStaleErrorfortraces. There were 43,163 files (about 59 MB) between 2026-11-19 and 2026-11-21, when I deleted them. In the busiest window, 2,859 files appeared in 22 seconds right after the 13:03:37 failed load. - Investigation: BB thread
thr_3sau3cn5p3.
The leak is reproduced on main. The report flood is read from code and matches the incident files. I did not measure the disk or CPU cost of the flood on its own. I also do not claim it caused a separate desktop freeze the same evening: that freeze showed no rise in the report rate.
What you ruled out
- Not A plugin's error after reload crashes the whole server #5964. That fix contains
PluginContextStaleErrorso the server stays up, and it works here: the server did not exit. This report is about the discarded instance never being cleaned up, and about the report files written for each contained error. - Not fixed by Tie each loaded plugin copy's work to that copy across reload, disable and removal #6464. That PR gave each loaded copy its own
stoppingandreleasedsignals. It rewrotediscardCandidateto abort them and interrupt the copy's own interactions, but dispose hooks still run only indisposePluginInstance. A plugin timer orbb.sdk.subscribecallback does not watch those signals. - Not
bb plugin reloadretains the previous module graph for the lifetime of the server (~73 MB per reload for apath:plugin) #4159 (module graph kept after reload) and not Let in-flight plugin tool calls finish when the plugin reloads #7336 (in-flight tool calls during reload). Both are about a normal reload of a working instance. - Not caused by stashing
bbin module state. The plugin used only thebbpassed to the factory in the same load. The handle went stale because BB discarded that load. - The original trigger (a host entry that could not resolve
zodin apath:worktree) was a plugin packaging mistake. A clean host build avoids this instance of the leak. Any other failure after the factory runs still leaks. bb plugin reloadwith a broken host entry does not reproduce onmainor0.50.1: it fails before the factory runs.- Searched open and closed issues for
discardCandidate,onDispose,PluginContextStaleError,"dispose hooks","stale plugin API",uncaughtExceptionMonitor,"process diagnostic report", and"failed plugin load subscription", and rechecked issues and PRs on 2026-11-22. No matching report found.
Suggested priority and effort
Medium. Any plugin that starts a timer or bb.sdk.subscribe in its factory and then fails to load leaks that work until the server restarts. With busy threads it fills ~/.bb/logs with report files. The workaround is per plugin: catch PluginContextStaleError and tear down on the first throw. That is what the traces plugin now does. No user data was lost. Effort is probably low.
A possible fix: in discardCandidate, run candidate.handle.disposeHooks in reverse before handle.invalidate(), with the same per-hook error logging as disposePluginInstance. Separately, the diagnostics monitor could skip or rate-limit reports for errors that the server handler claims, for example by writing the report from the server's uncaughtException handler after handleUncaughtException returns false. A regression check: a fixture that registers bb.onDispose and then fails to load (factory throws; first load with a broken host entry). Assert that the hook ran and that no PluginContextStaleError follows.
AGENT GENERATED
Activity
bb-slop-cop commentedon Nov 22, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotplugins,confirmed-repro.origin/mainin two clean checkouts. The test is included in the report.