Skip to content

Commit 2ff8598

Browse files
SawyerHoodclaude
andauthored
Route plugin service uncaught exceptions to the service supervisor (#2128)
## What was wrong Plugins run inside the server process. A plugin background service is supervised only through the promise its `start(signal)` returns (`runService` → `onServiceSettled` in `apps/server/src/services/plugins/plugin-runtime.ts`). An error the service raises outside that promise — an unlistened `EventEmitter` `'error'` (ImapFlow socket timeout), a throw in a timer callback, a detached rejection — becomes a process-level uncaught exception. The server only registered an observe-only `uncaughtExceptionMonitor`, so Node exited, the process manager restarted the server, the plugin reloaded, and the crash looped; the service reported `running` the whole time and every restart replaced the host daemon session ("Thread interrupted because the host daemon disconnected"). Issue: #1746. Report: https://get-bb.github.io/reports/issues/1746.html ## What changed - `apps/server/src/services/plugins/plugin-runtime.ts`: `runService` runs each service instance inside an `AsyncLocalStorage` scope that carries `{ pluginId, service, controller }`. The store follows every timer, socket callback, and promise the service creates. New `handleUncaughtException(error)` reads that store: no store → returns `false`; a stale run (already restarted or disposed) → logs with plugin and service name, returns `true`; the live run → aborts its controller and records the error so the run's settlement takes the existing crash path (`onServiceSettled` → backoff → restart). If the run ignores the abort for `serviceStopTimeoutMs`, the plugin is marked `degraded` like `stopServices` does. - `apps/server/src/services/plugins/plugin-service.ts`: exposes `handleUncaughtException` on `PluginService`. - `apps/server/src/start-server.ts`: installs `process.on("uncaughtException")`. A claimed error restarts that one service. Anything unattributed keeps Node's default: stack to stderr, exit 1 (the diagnostics monitor in `index.ts` has already written its report). - `packages/plugin-sdk/src/backend-contract.ts`: one sentence in the `bb.background.service` doc comment stating that out-of-band errors count as a crash. No wire change. No CLI change. Deviation from the report's proposal: no attribution field in the process-utils dump and no per-plugin crash counter / auto-disable; the attributed error is logged with plugin and service name and recovery reuses the existing backoff, which already escalates to a 60 s cap. The scope covers services only (factory, schedule ticks, and handlers are not wrapped): services are the long-lived surface that owns sockets, and they are the only surface with a defined recovery. Verified the attribution mechanism outside the test too: `AsyncLocalStorage.getStore()` inside an `uncaughtException` listener returns the service's store for an unlistened emitter error, a timer throw, a detached rejection (arrives with `origin=unhandledRejection`), a `nextTick` throw and a `setImmediate` throw, and `undefined` for a throw outside the scope, on Node 24.18 (AsyncContextFrame), Node 24 with `--no-async-context-frame` (the async_hooks path Node 22 uses), and Node 26.5. ## How you verified New test `apps/server/test/services/plugins/plugin-background.test.ts` › "routes an uncaught exception from a service's async context to the supervisor": a service creates an `EventEmitter` with no `'error'` listener and emits `'error'` from a timer. The test swaps out vitest's `uncaughtException` listener for the same listener shape `start-server.ts` installs, then asserts the service was aborted once and started twice, its state is back to `running`, and nothing reached the process unclaimed. - Before (origin/main sources, listener only records): `AssertionError: expected 1 to be 2` at `expect(globals.__emitterStarts).toBe(2)` — the service is never restarted and the error reaches the process listener. (With the committed test as-is, main fails earlier because `service.handleUncaughtException` does not exist and the worker exits.) - After: the test passes; full file 15/15. - `pnpm exec turbo run typecheck --filter=@bb/server --filter=@get-bb/plugin-sdk`: pass. - `pnpm exec turbo run test --filter=@bb/server`: 1819/1820 pass; the one failure is `internal-skill-trees` mode 420 vs 436, the known local umask 0002 artifact, unrelated to this change. (A first run under load average 42 had 51 five-second timeouts spread across unrelated files; the affected files all passed on rerun.) - Manual, on my dev instance with the report's 18-line repro plugin installed: the server log shows one `Server listening`, then per cycle `service imap-poller raised an uncaught exception outside start(): Socket timeout — aborting it` followed by `service imap-poller crashed: Socket timeout — restarting in 1000ms` … `32000ms`; `GET /api/v1/plugins` reports the service as `backoff`; the dev-supervisor log has zero `Child exited` lines; `host_daemon_sessions` holds one `active` row and none closed as `replaced`; `bb plugin remove crashy-service` stops the cycle. On main the report shows the same plugin killing the server every few seconds with 14 dumps and 4 replaced daemon sessions. Known trade-off: the observe-only `uncaughtExceptionMonitor` still writes a `process-server-uncaughtException-*.json` report for every contained error (the monitor fires before the listener can attribute it). The stack is now also in the server log via `{ err }`. Suppressing the report for attributed errors would need the diagnostics hook to consult the plugin runtime; left for a follow-up if the reports turn out to be noise. Fixes #1746 > AGENT GENERATED: by Claude Opus 5 ## Independent verification Checked out `2048b0d11` (this PR's head) as `verify-1746-r1`; `origin/main` (`c9aef7514`) is an ancestor, GitHub reports MERGEABLE. **Root cause review.** Agrees with the issue and the report: `runService` only watched the `start()` promise and the server process only had the observe-only `uncaughtExceptionMonitor`. The fix is at the root (per-run `AsyncLocalStorage` scope + a `process.on("uncaughtException")` that claims attributed errors and otherwise keeps Node's exit) and in the right layer (server owns plugin runtime policy). No wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump is needed; no new public plugin API member (only a JSDoc update on `PluginBackground.service`). I independently confirmed, in an actual `uncaughtException` listener on Node 24.18, that the ALS store is visible for an unlistened emitter `'error'`, a timer throw, a detached rejection (`origin=unhandledRejection`), and a `nextTick` throw, and absent for a throw outside the scope; and that a `.then` continuation attached outside `run()` (the path `onServiceSettled` and the backoff timer take) sees no store under both the AsyncContextFrame and `--no-async-context-frame` implementations. **Fail-before / pass-after.** - `git checkout origin/main -- apps/server/src/services/plugins/plugin-runtime.ts apps/server/src/services/plugins/plugin-service.ts apps/server/src/start-server.ts packages/plugin-sdk/src/backend-contract.ts`, then `pnpm exec vitest run test/services/plugins/plugin-background.test.ts -t "routes an uncaught exception"` in `apps/server`: the test listener throws `TypeError: service.handleUncaughtException is not a function` and the vitest worker exits (the uncaught exception does reach the process). With the listener reduced to record-only: `AssertionError: expected 1 to be 2 // Object.is equality` at `expect(globals.__emitterStarts).toBe(2)` — the service is never restarted on main. - Restored PR sources: `plugin-background.test.ts` 15/15; the new test passed 5/5 consecutive runs. **Turbo.** `pnpm exec turbo run typecheck --filter=@bb/server --filter=@get-bb/plugin-sdk` passes. `pnpm exec turbo run test --filter=@bb/server --filter=@get-bb/plugin-sdk --force`: plugin-sdk 14/14 files; server 1819/1820, the single failure is `internal-skill-trees.test.ts` mode 420 vs 436 (known local umask 0002 artifact, unrelated, green in CI). **Repro on the fixed branch.** Own dev instance (`scripts/bb-dev-app current`, server :23506), installed the report's 18-line crashy plugin with `pnpm bb:dev plugin install ... --yes`. Server log: `raised an uncaught exception outside start(): Socket timeout — aborting it` followed by `crashed: Socket timeout — restarting in 1000ms`, then 2000/4000/8000ms. `Server listening` appears once; dev-supervisor `Child exited` count 0; `host_daemon_sessions` has one `active` row and no `replaced`; `/api/v1/plugins` shows `imap-poller` in state `backoff` (no longer lies as `running`). No longer reproduces. **CI.** All checks on `2048b0d11` pass (Checks, Package Smoke x2, Tests app-1/2/3, integration, packages, server on Node 22.x). **Residual risks (non-blocking).** - `uncaughtExceptionMonitor` still writes a `process-server-uncaughtException-*.json` dump per contained error (I observed 4 for 4 contained crashes) and nothing prunes that directory; a service that fails immediately every cycle produces one dump per 60s at the backoff cap. Follow-up: let the diagnostics hook consult the runtime, or rotate dumps. - Only background services are scoped; an out-of-band throw from a plugin factory, schedule tick, or handler still exits the server. Server code a service calls synchronously in-process (`bb.log`, kv, etc.; `bb.sdk` is loopback HTTP so it is unaffected) runs inside the plugin's scope and would be attributed to the plugin. - After a service ignores its abort following an uncaught exception, the plugin stays `degraded` even once the run settles and restarts (same semantics as the existing stop-timeout path), and further uncaught errors from that same claimed run are swallowed without a log line. No per-plugin crash counter / auto-disable (issue point 3) — a permanently broken service cycles at the 60s cap with a warning each time. > AGENT GENERATED: by Claude Opus 5 Co-authored-by: Claude <[email protected]>
1 parent d20638b commit 2ff8598

5 files changed

Lines changed: 182 additions & 5 deletions

File tree

‎apps/server/src/services/plugins/plugin-runtime.ts‎

Lines changed: 87 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { AsyncLocalStorage } from "node:async_hooks";
12
import { createHash, randomUUID } from "node:crypto";
23
import {
34
createReadStream,
@@ -324,6 +325,15 @@ const SERVICE_RESTART_MAX_MS = 60_000;
324325
/** A crash after this much healthy runtime resets the backoff sequence. */
325326
const SERVICE_HEALTHY_RESET_MS = 5 * 60_000;
326327

328+
/** One run of a background service, from runService to its settlement. */
329+
interface ServiceInstance {
330+
id: string;
331+
service: ServiceRuntime;
332+
controller: AbortController;
333+
/** Set once an uncaught exception from this run has been claimed. */
334+
uncaughtError: { error: unknown } | undefined;
335+
}
336+
327337
export interface PluginRuntimeContext {
328338
deps: PluginServiceDeps;
329339
nextCronRunAt: (cron: string, now: number) => number;
@@ -553,24 +563,96 @@ export function createPluginRuntime(context: PluginRuntimeContext) {
553563
return undefined;
554564
}
555565

566+
/**
567+
* The service instance whose async context is executing. Plugins run
568+
* in-process, so an error a service raises outside its start() promise
569+
* (an unlistened EventEmitter 'error', a throw in a timer callback, a
570+
* detached rejection) reaches the process as an uncaught exception, not
571+
* the promise chain runService watches. The store follows every timer,
572+
* socket callback, and promise the service creates, so
573+
* handleUncaughtException can hand the error back to the supervisor.
574+
*/
575+
const serviceContext = new AsyncLocalStorage<ServiceInstance>();
576+
556577
/** Start (or restart) one background service instance. */
557578
function runService(id: string, service: ServiceRuntime): void {
558579
const controller = new AbortController();
559580
service.controller = controller;
560581
service.state = "running";
561582
service.startedAt = Date.now();
583+
const instance: ServiceInstance = {
584+
id,
585+
service,
586+
controller,
587+
uncaughtError: undefined,
588+
};
562589
// The async wrapper normalizes sync throws from start() into rejections.
563-
const current = (async () => {
590+
const current = serviceContext.run(instance, async () => {
564591
await service.record.start(controller.signal);
565-
})();
592+
});
566593
service.current = current;
567594
current.then(
568-
() => onServiceSettled(id, service, { crashed: false }),
595+
() =>
596+
instance.uncaughtError === undefined
597+
? onServiceSettled(id, service, { crashed: false })
598+
: onServiceSettled(id, service, {
599+
crashed: true,
600+
error: instance.uncaughtError.error,
601+
}),
569602
(error: unknown) =>
570-
onServiceSettled(id, service, { crashed: true, error }),
603+
onServiceSettled(id, service, {
604+
crashed: true,
605+
// The out-of-band error came first; a rejection after the abort
606+
// is its consequence.
607+
error: instance.uncaughtError?.error ?? error,
608+
}),
571609
);
572610
}
573611

612+
/**
613+
* Claims an uncaught exception raised from a service's async context.
614+
* Returns false when no service owns it, so the caller keeps Node's
615+
* default and exits. A live instance is aborted; its settlement then
616+
* takes the crash path (backoff + restart) with this error as the cause.
617+
*/
618+
function handleUncaughtException(error: unknown): boolean {
619+
const instance = serviceContext.getStore();
620+
if (instance === undefined) return false;
621+
const { id, service, controller } = instance;
622+
const name = service.record.name;
623+
const message = error instanceof Error ? error.message : String(error);
624+
if (service.controller !== controller || service.disposed) {
625+
// A previous run (restarted or disposed) left a timer or emitter behind.
626+
logger.warn(
627+
`[plugin:${id}] service ${name} raised an uncaught exception from a stopped run: ${message}`,
628+
);
629+
return true;
630+
}
631+
if (instance.uncaughtError !== undefined) return true;
632+
instance.uncaughtError = { error };
633+
logger.warn(
634+
{ err: error },
635+
`[plugin:${id}] service ${name} raised an uncaught exception outside start(): ${message} — aborting it`,
636+
);
637+
const current = service.current;
638+
controller.abort();
639+
if (current === null) return true;
640+
void settledWithin(current, serviceStopTimeoutMs).then((settled) => {
641+
if (settled || service.controller !== controller || service.disposed) {
642+
return;
643+
}
644+
setStatus(
645+
id,
646+
"degraded",
647+
`service ${name} did not stop after an uncaught exception`,
648+
);
649+
logger.warn(
650+
`[plugin:${id}] service ${name} did not stop within ${serviceStopTimeoutMs}ms of its uncaught exception — plugin degraded until it does`,
651+
);
652+
});
653+
return true;
654+
}
655+
574656
function onServiceSettled(
575657
id: string,
576658
service: ServiceRuntime,
@@ -1789,6 +1871,7 @@ export function createPluginRuntime(context: PluginRuntimeContext) {
17891871
disposeOne,
17901872
emitThreadEvent,
17911873
handlerStats,
1874+
handleUncaughtException,
17921875
hungServices,
17931876
invokeWrapped,
17941877
isBuiltinPluginId,

‎apps/server/src/services/plugins/plugin-service.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,14 @@ export interface PluginService {
186186
start(): Promise<void>;
187187
/** Dispose all loaded plugins (server shutdown). */
188188
stop(): Promise<void>;
189+
/**
190+
* Route a process-level uncaught exception raised from a background
191+
* service's async context (an unlistened EventEmitter 'error', a timer
192+
* throw, a detached rejection) back to that service's supervisor, which
193+
* aborts and restarts it with backoff. Returns false when no service owns
194+
* the error; the caller then keeps Node's default and exits.
195+
*/
196+
handleUncaughtException(error: unknown): boolean;
189197
list(): PluginListEntry[];
190198
/** Palettes declared by currently loaded plugins, ordered by plugin id. */
191199
listThemes(): PluginThemeMeta[];
@@ -1003,6 +1011,7 @@ export function createPluginService(deps: PluginServiceDeps): PluginService {
10031011
disposeOne,
10041012
emitThreadEvent,
10051013
handlerStats,
1014+
handleUncaughtException,
10061015
hungServices,
10071016
hostArtifacts,
10081017
identities,
@@ -1603,6 +1612,8 @@ export function createPluginService(deps: PluginServiceDeps): PluginService {
16031612
notifyPluginsChanged();
16041613
},
16051614

1615+
handleUncaughtException,
1616+
16061617
list,
16071618

16081619
async install(source, selection) {

‎apps/server/src/start-server.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,21 @@ export async function runServer(serverConfig: ServerConfig): Promise<void> {
291291
return shutdownPromise;
292292
};
293293

294+
// Plugins run in-process. An error a plugin service raises outside its
295+
// start() promise (an unlistened EventEmitter 'error', a throw in a timer
296+
// callback, a detached rejection) arrives here, not in the service
297+
// supervisor; without this listener Node exits, the process manager
298+
// restarts the server, the plugin reloads, and the crash loops. A claimed
299+
// error restarts that one service. Anything else keeps Node's default:
300+
// the diagnostics monitor in index.ts has already written its report.
301+
process.on("uncaughtException", (error: unknown) => {
302+
if (pluginService.handleUncaughtException(error)) return;
303+
const message =
304+
error instanceof Error ? (error.stack ?? error.message) : String(error);
305+
process.stderr.write(`${message}\n`);
306+
process.exit(1);
307+
});
308+
294309
process.once("SIGINT", () => {
295310
void runShutdown().finally(() => process.exit(0));
296311
});

‎apps/server/test/services/plugins/plugin-background.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,71 @@ describe("plugin background services", () => {
319319
});
320320
});
321321

322+
it("routes an uncaught exception from a service's async context to the supervisor", async () => {
323+
// An unlistened EventEmitter 'error' fired from a timer never reaches the
324+
// start() promise: Node raises it as a process-level uncaughtException.
325+
// Without attribution the server exits and crash-loops (#1746).
326+
const rootDir = await writePlugin(workDir, {
327+
name: "bb-plugin-emitter",
328+
serverSource: `
329+
import { EventEmitter } from "node:events";
330+
export default function plugin(bb: any) {
331+
const g = globalThis as any;
332+
g.__emitterStarts = 0;
333+
g.__emitterAborts = 0;
334+
bb.background.service("imap", {
335+
async start(signal: any) {
336+
g.__emitterStarts += 1;
337+
if (g.__emitterStarts === 1) {
338+
const client = new EventEmitter(); // no client.on("error")
339+
setTimeout(() => client.emit("error", new Error("Socket timeout")), 5);
340+
}
341+
await new Promise<void>((resolve) =>
342+
signal.addEventListener("abort", () => {
343+
g.__emitterAborts += 1;
344+
resolve();
345+
}));
346+
},
347+
});
348+
}
349+
`,
350+
});
351+
// Stand in for the server's process listener (start-server.ts). vitest's
352+
// own listener would report the exception as an unhandled error, so it
353+
// steps aside for the duration of this test.
354+
const vitestListeners = process.listeners("uncaughtException");
355+
process.removeAllListeners("uncaughtException");
356+
const unclaimed: unknown[] = [];
357+
process.on("uncaughtException", (error) => {
358+
if (!service.handleUncaughtException(error)) unclaimed.push(error);
359+
});
360+
try {
361+
await service.installPath(rootDir);
362+
await vi.waitFor(
363+
() => {
364+
expect(globals.__emitterStarts).toBe(2);
365+
},
366+
{ timeout: 2000 },
367+
);
368+
// The first instance was aborted before the second one started.
369+
expect(globals.__emitterAborts).toBe(1);
370+
await vi.waitFor(() => {
371+
expect(
372+
service.list().find((p) => p.id === "emitter")?.services,
373+
).toEqual([{ name: "imap", state: "running" }]);
374+
});
375+
expect(unclaimed).toEqual([]);
376+
expect(service.list().find((p) => p.id === "emitter")?.status).toBe(
377+
"running",
378+
);
379+
} finally {
380+
process.removeAllListeners("uncaughtException");
381+
for (const listener of vitestListeners) {
382+
process.on("uncaughtException", listener);
383+
}
384+
}
385+
});
386+
322387
it("NeedsConfigurationError maps to needs-configuration and stops restarts", async () => {
323388
const rootDir = await writePlugin(workDir, {
324389
name: "bb-plugin-needy",

‎packages/plugin-sdk/src/backend-contract.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,10 @@ export interface PluginBackground {
226226
* factory completes and should resolve when `signal` aborts
227227
* (dispose/reload/disable/shutdown). A crash restarts it with capped
228228
* exponential backoff; throwing NeedsConfigurationError marks the plugin
229-
* `needs-configuration` and stops restarting until the next load.
229+
* `needs-configuration` and stops restarting until the next load. An
230+
* error raised outside the `start` promise (an unlistened EventEmitter
231+
* 'error', a throw in a timer callback, a detached rejection) counts as
232+
* a crash too: the run is aborted and restarted the same way.
230233
*/
231234
service(
232235
name: string,

0 commit comments

Comments
 (0)