Repository navigation
Tie each loaded plugin copy's work to that copy across reload, disable and removal - #6464
Merged
ymichael merged 1 commit intoOct 28, 2026
Conversation
…e and removal Each loaded plugin instance now tracks its own in-flight invocations and pending interactions. A reload interrupts only the old copy's forms, so requestInput forms the new copy raises while loading stay pending; disable and removal still interrupt every pending row the plugin owns, including rows with no in-memory waiter. Disposal closes WebSockets first and waits for their onClose handlers, then aborts the old copy's CLI ctx.signal and the new RPC experimental_signal (which also aborts when the request disconnects), drains for the stop timeout, and releases callers still waiting with an error before invalidating the handle. The old copy keeps serving requests during its dispose window. Hook, provider and server-access records run on the copy that listed them and are refused once it is gone. A stale-handle error is always contained and logged once per instance; other uncaught errors are contained only when plugin code is on their stack, and the plugin stays running with a status detail. callRpc keeps its 75 s timeout whether or not the caller passes a signal. Fixes #4432, #4941, #5964, #5969 Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/plugin-reload-per-instance-ownership-4432-4941-5-thr_vn27fvegwy
branch
October 28, 2026 19:32
This was referenced Oct 30, 2026
2 tasks done
This was referenced Nov 19, 2026
ymichael
pushed a commit
that referenced
this pull request
Nov 20, 2026
## Human comments ## What was wrong The server's `uncaughtException` handler exits unless the plugin runtime claims the error ([start-server.ts#L606-L612](https://github.com/get-bb/bb/blob/df9619d8e8aac4aff00c0c3ff9b8ef4e2823e4f2/apps/server/src/start-server.ts#L606-L612)). Outside a service run, the runtime claims an error only when a loaded plugin's code file appears in its stack ([plugin-runtime.ts#L610-L645](https://github.com/get-bb/bb/blob/df9619d8e8aac4aff00c0c3ff9b8ef4e2823e4f2/apps/server/src/services/plugins/plugin-runtime.ts#L610-L645)). The error in #7509 is what an aborted `fetch` rejects with. undici re-captures the stack after an `await`. The result is `AbortError: This operation was aborted` with no frames on Node 24, which the desktop app runs, and with only an `node:internal/deps/undici` frame on Node 22. undici also rewrites the stack of the shared `signal.reason`, so anything else that later throws that reason has the same stack. When plugin code leaves such a rejection unhandled, the stack names no plugin and the server exits. This is how one plugin's floating aborted fetch can restart the whole server several times a day. ## What changed - `apps/server/src/services/plugins/plugin-runtime.ts`: - A new `AsyncLocalStorage`, `pluginCodeContext`, names the plugin. It is set around the plugin's module import, its factory and `invokeWrapped`, which every handler, hook, provider, RPC, route, CLI and event call goes through. - Node runs the `uncaughtException` handler in the async context of the throwing callback or the rejected promise, so the handler can read it. - `containPluginError` still decides by stack location first. Only when the stack names no code outside `node:` internals does it fall back to that context. - A claimed error is logged as `[plugin:<id>] uncaught error from work this plugin started (its stack names no code): ...`, and the plugin's status detail is set as before. - Deviation from the issue's ask: the server still exits for core errors. A core error with frames is never claimed by context, including core work started during a plugin call (#6464's test is unchanged and passes). - Accepted risk: a stack-less error from core work that a plugin call started is attributed to that plugin and contained. Such an error carries no evidence either way, and before this change it took the server down. - Not identified: which plugin aborted the fetch in the reporter's crashes. With this change the log names it. - No wire, schema, CLI, SDK or plugin API changes. ## How you verified - New test in `apps/server/test/services/plugins/plugin-instance-lifecycle.test.ts`, "contains an aborted fetch's frameless error from work a plugin started". The fixture plugin aborts a real `fetch` to a local server that never answers and rethrows the rejection from a detached callback. **On main** it fails: 0 errors claimed. With the change, 1 is claimed and the plugin stays `running` with the message in its status detail. - New test "does not claim a frameless error from work no plugin started": the same error from test code is not claimed. - A standalone script on Node 22.23.5 and Node 24.22.1 confirms what the tests depend on: the aborted-fetch error names no code outside `node:`, and the handler sees the plugin's context. The server test suite itself only runs on the Node 24 build here. - `pnpm exec turbo run test --filter=@bb/server -- test/services/plugins test/plugins` passes (61 files, 603 tests). - `pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/server` passes, and `oxfmt` is clean. Fixes #7509 > AGENT GENERATED
This was referenced Nov 22, 2026
ymichael
added a commit
that referenced
this pull request
Nov 23, 2026
#8029) ## Human comments ## What was wrong When a plugin load fails after its server factory ran, `discardCandidate` in `apps/server/src/services/plugins/plugin-runtime.ts` throws the new instance away. It aborts `stopping`, interrupts the instance's interactions, closes its databases, aborts `released` and invalidates the handle. It never ran `handle.disposeHooks`; only `disposePluginInstance` did. So `bb.onDispose` cleanup that the factory registered never ran. Timers and `bb.sdk.subscribe` callbacks the factory started kept running against the invalidated `bb`. Each call threw `PluginContextStaleError` until the server exited. This happens on a first load whose host entry fails to build, and on a reload whose factory throws. #6464 rewrote `discardCandidate` but did not add the hooks. The reproduction is in #8025. ## What changed - `plugin-runtime.ts`: the LIFO dispose-hook loop moves out of `disposePluginInstance` into `runDisposeHooks`. `discardCandidate` now calls it after the `stopping` abort and the interaction interrupt, and before databases close and the handle is invalidated. That is the order `disposePluginInstance` already uses. A failing hook is still logged and later hooks still run. All three discard paths get this: the factory throws, the host entry has a problem, and services are still hung after the previous instance's teardown. - A failed reload does not touch the previous instance. Its hooks still run only when it is disposed. - New test `apps/server/test/services/plugins/plugin-failed-load-dispose.test.ts`. The fixture starts a real 10 ms timer and registers a sync, a throwing, and an async dispose hook. It covers a first load whose host entry fails to build, a first load whose factory throws, and a reload whose factory throws. Each case asserts the hooks ran in LIFO order, that the throwing hook did not stop later ones, and that no timer tick or `PluginContextStaleError` follows `service.stop()`. The reload case also checks that the previous instance keeps serving its CLI command and timer, and that its hooks run only at its own disposal. - Docs: the "bb.onDispose and the reload lifecycle" section of `plugins/bb-guide/skills/bb-plugin-authoring/references/backend-ui-lifecycle.md` now says that hooks also run when a load fails after the factory ran. The `onDispose` declaration comment in the Plugin SDK is unchanged, so this PR does not need an SDK version bump. - Deviation from the issue: #8025 also suggested that the `uncaughtExceptionMonitor` in `installSafeProcessDiagnostics` skip or rate-limit reports for errors the server handler claims. This PR does not change that. With this fix, a plugin that cleans up in `onDispose` no longer causes the report flood. A plugin that leaks a timer without `onDispose` still can. That can be a separate change. ## How you verified - With `main`'s `plugin-runtime.ts`, all three cases fail (`expected [] to deeply equal [ '1:async', '1:throw', '1:timer' ]`, and the same for generation 2 on reload). All three pass with the change. - `pnpm exec turbo run test --filter=@bb/server --force -- test/services/plugins/plugin-failed-load-dispose.test.ts test/services/plugins/plugin-instance-lifecycle.test.ts`: 16 passed, three runs in a row. - Live check on a `pnpm start:worktree` server: a path plugin with a 50 ms timer and an unresolvable host import logged its dispose hook 1 ms before `failed to load`, and no stale-handle errors or crash reports followed. - `pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@get-bb/plugin-sdk`: 8 tasks passed. The `@get-bb/plugin-sdk` tests pass too. - Full server suite, `pnpm exec turbo run test --filter=@bb/server -- --maxWorkers=2`: 4428 passed, 3 skipped, 1 failed. The failure was a 15 s timeout in `test/ai/commit-message.test.ts`. That file passed on rerun together with all of `test/services/plugins/` (64 files, 632 tests). This machine caps each command at 4 GiB. The kernel killed one Vitest worker for memory during the full run, so Vitest also reported one "Worker exited unexpectedly" error. Every test file still reported a result. With default workers the whole run was killed, which is why these commands pass `--maxWorkers`. - `pnpm exec oxfmt --check` on the changed files and `git diff --check`: clean. - Checks ran on Linux x86-64, Node.js v26.12.0. Fixes #8025 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Michael Yong <[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.
Human comments
What was wrong
Plugin work was tracked per plugin id, not per loaded copy. A reload runs the new copy's factory before disposing the old one, so disposal's plugin-wide interrupt cancelled forms the new copy had just raised (#4432). The drain only bounded waiting, so callers of a disposed copy could hang and its continuations kept running with an invalidated handle (#5969). The first use of that handle threw
PluginContextStaleErroroutside any service scope, andhandleUncaughtExceptionlet it exit the server (#5964). RPC handlers had no signal at all, so they could not learn their caller was gone (#4941).What changed
Each
LoadedPluginnow owns its work:stopping/releasedsignals, its own in-flight invocation set, and its host artifact snapshot.plugin-runtime.ts): close WebSockets, abortstopping, interrupt only this copy's interactions, stop host workers and services, wait (bounded) for WebSocketonClosehandlers, run dispose hooks, drain this copy's invocations for the stop timeout, then abortreleased, which rejects callers still waiting with "reloaded or disabled before … finished", and invalidate the handle.stoppingget thereleasedsignal instead of an already-aborted one.pending-interactions.ts): each waiter records its owning copy.interruptOwnedPluginInteractions(owner)handles reload and failed candidates. Disable, remove and shutdown still run the plugin-wide DB interrupt, so rows with no waiter are interrupted too.owner, which routes, RPC, WebSocket events and bb's internal RPC callers (connect revoke and status, git reads) pass toinvoke*.ExperimentalPluginRpcHandlerContext.experimental_signal: request disconnect or copy disposal.ctx.signalnow also aborts on disposal.callRpckeeps its 75 s timeout unchanged, with or without a caller signal.PluginContextStaleError(one instance per handle) is always contained and logged once.runningwith a status detail.experimental_signalto RPC handlers.docs/api_to_audit.mdhas a new entry. Guide updates:backend-sdk.md,backend-ui-lifecycle.md.Deviations from the issues:
bb.sdk.plugins.callRpcgives up after 75 s, but the handler keeps running and has no way to learn the caller is gone #4941: no caller-side timeout override; the handler signal covers "the handler is told the caller is gone".How you verified
New tests:
plugin-instance-lifecycle.test.tsandplugin-rpc-caller.test.ts.main, pass here.onCloseruns on reload and disable.callRpckeeps its timeout when a signal is passed.running.pnpm exec turbo run typecheck --filter='...[origin/main]'@bb/serverand@get-bb/plugin-sdkturbo run testfor@bb/serverand@get-bb/plugin-sdk: 3706/3708 server tests and all 407 SDK tests passed. The 2 failures are file-watcher tests inbuiltin-plugins.test.tsthat also fail on main in 2 of 4 runs.check-plugin-sdk-version.mjspnpm start:worktreeserver with a demo plugin:running (uncaught error: …);experimental_signal;Fixes #4432
Fixes #4941
Fixes #5964
Fixes #5969
🤖 Generated with Claude Code