Repository navigation
Route plugin service uncaught exceptions to the service supervisor - #2128
Merged
Merged
Conversation
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
marked this pull request as ready for review
August 21, 2026 02:23
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]>
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.
What was wrong
Plugins run inside the server process. A plugin background service is supervised only through the promise its
start(signal)returns (runService→onServiceSettledinapps/server/src/services/plugins/plugin-runtime.ts). An error the service raises outside that promise — an unlistenedEventEmitter'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-onlyuncaughtExceptionMonitor, so Node exited, the process manager restarted the server, the plugin reloaded, and the crash looped; the service reportedrunningthe 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:runServiceruns each service instance inside anAsyncLocalStoragescope that carries{ pluginId, service, controller }. The store follows every timer, socket callback, and promise the service creates. NewhandleUncaughtException(error)reads that store: no store → returnsfalse; a stale run (already restarted or disposed) → logs with plugin and service name, returnstrue; 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 forserviceStopTimeoutMs, the plugin is markeddegradedlikestopServicesdoes.apps/server/src/services/plugins/plugin-service.ts: exposeshandleUncaughtExceptiononPluginService.apps/server/src/start-server.ts: installsprocess.on("uncaughtException"). A claimed error restarts that one service. Anything unattributed keeps Node's default: stack to stderr, exit 1 (the diagnostics monitor inindex.tshas already written its report).packages/plugin-sdk/src/backend-contract.ts: one sentence in thebb.background.servicedoc 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 anuncaughtExceptionlistener returns the service's store for an unlistened emitter error, a timer throw, a detached rejection (arrives withorigin=unhandledRejection), anextTickthrow and asetImmediatethrow, andundefinedfor 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 anEventEmitterwith no'error'listener and emits'error'from a timer. The test swaps out vitest'suncaughtExceptionlistener for the same listener shapestart-server.tsinstalls, then asserts the service was aborted once and started twice, its state is back torunning, and nothing reached the process unclaimed.AssertionError: expected 1 to be 2atexpect(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 becauseservice.handleUncaughtExceptiondoes not exist and the worker exits.)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 isinternal-skill-treesmode 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.)Server listening, then per cycleservice imap-poller raised an uncaught exception outside start(): Socket timeout — aborting itfollowed byservice imap-poller crashed: Socket timeout — restarting in 1000ms…32000ms;GET /api/v1/pluginsreports the service asbackoff; the dev-supervisor log has zeroChild exitedlines;host_daemon_sessionsholds oneactiverow and none closed asreplaced;bb plugin remove crashy-servicestops 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
uncaughtExceptionMonitorstill writes aprocess-server-uncaughtException-*.jsonreport 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
Independent verification
Checked out
2048b0d11(this PR's head) asverify-1746-r1;origin/main(c9aef7514) is an ancestor, GitHub reports MERGEABLE.Root cause review. Agrees with the issue and the report:
runServiceonly watched thestart()promise and the server process only had the observe-onlyuncaughtExceptionMonitor. The fix is at the root (per-runAsyncLocalStoragescope + aprocess.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 noHOST_DAEMON_PROTOCOL_VERSIONbump is needed; no new public plugin API member (only a JSDoc update onPluginBackground.service). I independently confirmed, in an actualuncaughtExceptionlistener on Node 24.18, that the ALS store is visible for an unlistened emitter'error', a timer throw, a detached rejection (origin=unhandledRejection), and anextTickthrow, and absent for a throw outside the scope; and that a.thencontinuation attached outsiderun()(the pathonServiceSettledand the backoff timer take) sees no store under both the AsyncContextFrame and--no-async-context-frameimplementations.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, thenpnpm exec vitest run test/services/plugins/plugin-background.test.ts -t "routes an uncaught exception"inapps/server: the test listener throwsTypeError: service.handleUncaughtException is not a functionand 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 equalityatexpect(globals.__emitterStarts).toBe(2)— the service is never restarted on main.plugin-background.test.ts15/15; the new test passed 5/5 consecutive runs.Turbo.
pnpm exec turbo run typecheck --filter=@bb/server --filter=@get-bb/plugin-sdkpasses.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 isinternal-skill-trees.test.tsmode 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 withpnpm bb:dev plugin install ... --yes. Server log:raised an uncaught exception outside start(): Socket timeout — aborting itfollowed bycrashed: Socket timeout — restarting in 1000ms, then 2000/4000/8000ms.Server listeningappears once; dev-supervisorChild exitedcount 0;host_daemon_sessionshas oneactiverow and noreplaced;/api/v1/pluginsshowsimap-pollerin statebackoff(no longer lies asrunning). No longer reproduces.CI. All checks on
2048b0d11pass (Checks, Package Smoke x2, Tests app-1/2/3, integration, packages, server on Node 22.x).Residual risks (non-blocking).
uncaughtExceptionMonitorstill writes aprocess-server-uncaughtException-*.jsondump 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.bb.log, kv, etc.;bb.sdkis loopback HTTP so it is unaffected) runs inside the plugin's scope and would be attributed to the plugin.degradedeven 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.