Skip to content

Route plugin service uncaught exceptions to the service supervisor - #2128

Merged
SawyerHood merged 1 commit into
mainfrom
bb/fix-1746-plugin-service-crash-isolation
Aug 21, 2026
Merged

SawyerHood merged 1 commit into
mainfrom
bb/fix-1746-plugin-service-crash-isolation

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 21, 2026 •

Copy link
Copy Markdown
Collaborator

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

A plugin background service is supervised only through the promise its
start() returns. An unlistened EventEmitter 'error', a throw in a timer
callback, or a detached rejection from the service never reaches that
promise: Node raises it as a process-level uncaught exception, the
server exits, the process manager restarts it, the plugin reloads, and
the crash loops while the service still reports running.

The runtime now enters an AsyncLocalStorage scope per service run, so
the process-level handler can attribute the error to the service that
raised it, abort that run, and let its settlement take the existing
crash path (backoff + restart). Unattributed errors keep Node's default
exit; the diagnostics monitor has already written its report.

Fixes #1746

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood marked this pull request as ready for review August 21, 2026 02:23
@SawyerHood
SawyerHood merged commit 2ff8598 into main Aug 21, 2026
13 checks passed
@SawyerHood
SawyerHood deleted the bb/fix-1746-plugin-service-crash-isolation branch August 21, 2026 03:06
SawyerHood added a commit that referenced this pull request Aug 21, 2026
## What was wrong

The codebase carried a lot of code that nothing reached: symbols and
files with no consumer, options that no caller passes, branches the
types make impossible, feature flags that graduated but kept their `if`
guards, pass-through wrappers that only forward arguments, barrel files
that re-export hundreds of names nobody imports through them, and the
same small helper copied into many files. This code has no effect on
behavior, but every reader must still parse it.

## What changed

Net −16k lines across 1,732 files. No behavior change. Four commits, two
per pass:

1. **Remove dead code, pass-through wrappers, and stale barrels** —
unused symbols and files, dead branches, unused params/options,
single-use wrappers inlined, dead barrel lines, tests and stories that
existed only for deleted code. Drops the unused `cronstrue` dependency
from `apps/app`.
2. **Drop export from module-private symbols** — ~900 declarations that
were exported but only used inside their own file.
3. **Remove more dead code, duplicate helpers, and unused options** —
second pass over the same ground plus repo-wide sweeps for duplicate
helpers and legacy/compat paths. Folds byte-identical helper copies into
one shared module where the consumer already depends on it (e.g.
`describeError` ×11, `createDeferred` ×15 → `@bb/test-helpers`,
`DelayedLoading` ×4 → `@bb/shared-ui`). Removes unused
`ws`/`@types/ws`/`tsx` devDependencies from `apps/connect` and an unused
`@radix-ui/react-slot` from `apps/web`.
4. **Drop export from more module-private symbols** — ~700 more.

Out of scope on purpose: `@get-bb/plugin-sdk` and `@bb/sdk` exports
(public API), CLI commands and flags, server routes, DB schema and
migrations, generated code, wire payload shapes between the server and
host daemon (`HOST_DAEMON_PROTOCOL_VERSION` is unchanged), and parsers
for persisted or legacy data.

Every removal was found by one agent, adversarially verified by a second
agent that searched the whole repo (including strings, configs, docs,
`.ladle`, and stories) for any remaining reference, and then applied by
a third. 41 proposals were rejected at verification or apply time, and I
reverted 2 more by hand.

## How you verified

- `pnpm exec turbo run typecheck` — 74/74 packages pass
- `pnpm exec turbo run lint` — passes
- `pnpm exec turbo run build` for `@bb/app`, `@bb/server`,
`@bb/host-daemon`, `@bb/cli`, and all `plugins/*` — passes
- `pnpm exec turbo run test` — all packages pass except
`internal-skill-trees.test.ts`, which fails identically on `main` on
this machine (local umask 0002; passes in CI)
- Rebased onto `main` after #2125, #2132, #2128, #2126, #2112 landed;
re-ran typecheck, lint, and tests for the touched packages

Fixes #

> AGENT GENERATED: by Claude Opus 5

---------

Co-authored-by: Claude <[email protected]>
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.

Plugin background services can kill the server: supervisor only sees the promise chain

1 participant