Skip to content

Tie each loaded plugin copy's work to that copy across reload, disable and removal - #6464

Merged
ymichael merged 1 commit into
mainfrom
bb/plugin-reload-per-instance-ownership-4432-4941-5-thr_vn27fvegwy
Oct 28, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/plugin-reload-per-instance-ownership-4432-4941-5-thr_vn27fvegwy

Conversation

@ymichael

@ymichael ymichael commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

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 PluginContextStaleError outside any service scope, and handleUncaughtException let 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 LoadedPlugin now owns its work: stopping/released signals, its own in-flight invocation set, and its host artifact snapshot.

  • Disposal order (plugin-runtime.ts): close WebSockets, abort stopping, interrupt only this copy's interactions, stop host workers and services, wait (bounded) for WebSocket onClose handlers, run dispose hooks, drain this copy's invocations for the stop timeout, then abort released, which rejects callers still waiting with "reloaded or disabled before … finished", and invalidate the handle.
  • During disposal: the old copy keeps serving requests. Invocations started after stopping get the released signal instead of an already-aborted one.
  • Interactions (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.
  • Ownership:
    • Wire lookups return owner, which routes, RPC, WebSocket events and bb's internal RPC callers (connect revoke and status, git reads) pass to invoke*.
    • Hook, environment/machine provider and server-access records remember the copy that listed them. Bridges now take the record instead of a plugin id, and invocations on a released copy are refused.
    • Agent tools check that the current copy registered the record.
  • Signals:
    • New ExperimentalPluginRpcHandlerContext.experimental_signal: request disconnect or copy disposal.
    • CLI ctx.signal now also aborts on disposal.
    • callRpc keeps its 75 s timeout unchanged, with or without a caller signal.
  • Uncaught errors:
    • PluginContextStaleError (one instance per handle) is always contained and logged once.
    • Other uncaught errors are contained only when a loaded plugin's code file is on the stack. The plugin stays running with a status detail.
    • Core errors still exit the server, as before.
  • SDK: plugin SDK 0.6.96. The fake plugin host passes experimental_signal to RPC handlers. docs/api_to_audit.md has a new entry. Guide updates: backend-sdk.md, backend-ui-lifecycle.md.
  • Wire: no daemon protocol or DB schema change.

Deviations from the issues:

How you verified

New tests: plugin-instance-lifecycle.test.ts and plugin-rpc-caller.test.ts.

  • Issue tests (forms survive reload, RPC signal on disconnect and reload, stuck CLI caller released plus stale use contained, plugin uncaught error contained): fail on main, pass here.
  • Regression tests from the review of the prior attempt (bc88f139de): each fails on that commit and passes here. The provider-owner test also fails on main.
    • WebSocket onClose runs on reload and disable.
    • RPC is served during the dispose window.
    • callRpc keeps its timeout when a signal is passed.
    • Provider callbacks run only on the copy that registered them.
    • Core-created async errors are not claimed, and the plugin stays running.
    • Disable interrupts pending rows that have no waiter.
  • Checks run:
    • pnpm exec turbo run typecheck --filter='...[origin/main]'
    • lint for @bb/server and @get-bb/plugin-sdk
    • turbo run test for @bb/server and @get-bb/plugin-sdk: 3706/3708 server tests and all 407 SDK tests passed. The 2 failures are file-watcher tests in builtin-plugins.test.ts that also fail on main in 2 of 4 runs.
    • check-plugin-sdk-version.mjs
  • Manual: on a pnpm start:worktree server with a demo plugin:
    • reloads kept only the newest form;
    • a stuck CLI call was released after about 5 s;
    • the old copy's later publish was logged and the server stayed on the same pid;
    • a deliberate timer throw left the plugin running (uncaught error: …);
    • an aborted RPC request aborted experimental_signal;
    • disable cancelled the form.

Fixes #4432
Fixes #4941
Fixes #5964
Fixes #5969

🤖 Generated with Claude Code

AGENT GENERATED

…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
ymichael merged commit 747c8fd into main Oct 28, 2026
52 checks passed
@ymichael
ymichael deleted the bb/plugin-reload-per-instance-ownership-4432-4941-5-thr_vn27fvegwy branch October 28, 2026 19:32
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
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment