Skip to content

Run marketplace plugin servers in their own worker threads (experiment) - #7248

Closed
ymichael wants to merge 3 commits into
mainfrom
bb/run-marketplace-plugin-server-code-off-core-s-ev-thr_jbvai7bpud
Closed

ymichael wants to merge 3 commits into
mainfrom
bb/run-marketplace-plugin-server-code-off-core-s-ev-thr_jbvai7bpud

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Every plugin's server code runs on the bb server's event loop. In production, the third-party usage plugin (github.com/MayankBansal12/bb-plugin-usage) accounted for 15.7% of all sampled event-loop stall time (24.9 s of 158.5 s, up to 361 ms in one stall). 76% of that was its own SQLite work on its plugin data.db, and its dashboard RPC runs a 335 ms query. No change in core can make that work cheaper, because it is the plugin's own synchronous code. It can only stop stalling core if it runs somewhere else. (Investigation: O2 audit report, "Proposal: isolate plugin server work".)

What changed

A new isolatedPluginServers experiment, off by default and not on for early adopters, runs the server entry of every plugin installed from git or npm in its own worker_thread.

Design. Core still builds the plugin's real API handle with createPluginApi. Status, stats, invokeWrapped, wireLookup, services, schedules, events and dispose work exactly as before. The plugin's factory runs in the worker against a mirror of BbPluginApi:

  • Calls from the worker into core are synchronous. A worker call to bb.* blocks only the worker (Atomics.wait + receiveMessageOnPort). Core runs the real handle.api member and returns the value or the error, so registration errors still throw synchronously. A member that returns a promise resolves later.
  • Callbacks run in the worker. Callbacks the plugin registers (service start, event and settings listeners, schedules, CLI run, onDispose/onInstall, whileWatched) become proxies in core's handle records and run in the worker. Abort signals, errors (including PluginContextStaleError and RPC boundary errors), streams and Responses cross the boundary.
  • One RPC pipeline. The RPC path is a single function, runPluginRpcMethod, which validates input, runs the handler, validates and normalizes the output, and computes tags. It runs wherever the plugin's code runs. Core's in-process records and worker records both expose invoke(), and invokeRpcHandler calls it.
  • HTTP routes stream both ways. The request body and the Response body are transferred as streams, and the request's abort signal is mirrored into the worker. The worker's Hono Context gets core's c.req.path, c.req.routePath, c.req.param() and context variables (c.var / c.get). c.env (the raw Node request and response) isn't available in a worker.
  • storage.database() stays synchronous inside the worker (shared openPluginDatabase). The hourly incremental-vacuum sweep runs inside each worker (maintainIsolatedPluginDatabases).
  • bb.sdk is built in the worker with the same caller token and wrapper (plugin-sdk-wrapping.ts, moved out of plugin-api.ts).
  • Error reporting parity. Core awaits every forwarded callback kind (RPC, HTTP, services, schedules, events, CLI, onInstall, onDispose, whileWatched) except settings onChange listeners. For the awaited kinds, a worker callback that throws rejects the core-side proxy, which lands in the same catch and log line as in-process. Settings listeners are called synchronously and are fire-and-forget, so the worker wraps them: a synchronous throw comes back to core, which logs it through the same call-site message (callSettingsListener is shared by both call sites). An async rejection stays unhandled in the worker and is reported as [plugin:<id>] uncaught error, as in-process. One deliberate difference: in-process, an uncaught error whose stack isn't the plugin's exits the server; in a worker, every uncaught error is contained.
  • Crash handling. Uncaught errors in a service's async context go through the same abort-and-backoff path as in-process. Other uncaught errors are logged and shown in the status detail. If the worker exits (process.exit, OOM), core keeps running: the plugin is disposed and set to error, then restarted with the background-service backoff.
  • Timeouts. A factory that hangs times out exactly as before, and its worker is terminated, so core is never blocked.
  • Toggling the experiment (PUT /settings/experiments) reloads the affected plugins live.

Why threads rather than processes:

Start time (empty) Memory (empty)
Worker thread 12 ms ~10 MB RSS
fork 23 ms ~43 MB RSS

Threads are also what makes synchronous bb.* calls possible, because they share memory.

What stays in-process. Before evaluating the plugin, the worker scans the server entry and the files it imports relatively for the APIs it can't host yet (plugin-server-worker-preflight.ts). If it finds one, the plugin loads in-process and its setup runs only once, there. bb logs which API kept it in-process. That covers agent tools, configuration and instructions, providers, mention providers, experimental_hooks.on, environment, machine, server-access and AI-service providers, WebSocket routes, hosts.experimental_client, tunnel APIs, and settings with experimental_schema. These all need core to call synchronously into the plugin or to hold the plugin's schemas. Bundled first-party plugins are never isolated, because they rely on those in-process core objects. The scan matches member names, so it also catches destructured and aliased access. It is conservative: a match keeps the plugin in-process, as today. Only a computed member name the scan can't see, such as bb.agents["register" + "Tool"], reaches the runtime backstop. In that case the worker's partial setup is thrown away and setup runs again in-process. That second run isn't side-effect free (writes the partial setup already made, such as database migrations or KV writes, stay), which is why the scan runs first. A plugin that hits one of these APIs only after it loads is reloaded in-process.

Sandboxing. Worker isolation doesn't sandbox the filesystem, network or child processes; a worker plugin has the same access as an in-process one today. The usage plugin, for example, writes a scan cache under the host's ~/.cache/bb-plugin-usage/. All benchmark and end-to-end runs used a host daemon with HOME pointed at APFS clones inside the dev data dir.

Other changes:

  • @bb/db/sqlite-maintenance is a new drizzle-free module holding the raw SQLite vacuum helpers, so the worker bundle doesn't load the schema.
  • New build entry dist/plugin-server-worker.js.
  • Settings → Experiments label and description.
  • docs/configuration.md.
  • bb guide customization and bb guide plugins.

There is no daemon wire change.

How you verified

New tests in apps/server/test/services/plugins/plugin-server-isolation.test.ts (11, passing), all using real git-sourced installs on a real HTTP server:

  • RPC, HTTP, storage, settings, services, SDK and caller identity in both modes, checking the worker's threadId.
  • Streaming plus client-disconnect abort and cancel.
  • Core stays responsive while a handler spins for 600 ms.
  • process.exit in a worker: the plugin restarts on a new thread.
  • An uncaught service error restarts the service.
  • A factory hang times out without blocking core.
  • Uninstall closes the worker's database.
  • A plugin calling an unsupported API falls back in-process.
  • The worker API surface has the same shape as the in-process one.
  • Toggling the experiment moves plugins in both directions.
  • A route's Hono context (params, path, routePath, variables, query, headers, body) has the same shape in a worker as in-process.
  • Every callback kind's errors produce identical log lines in both modes: settings listener (both call sites), onInstall, onDispose, service crash, CLI, RPC.
  • A plugin whose code uses an unsupported API runs its setup once. Without the preflight, this test sees two runs.
  • Preflight unit tests: an unsupported API in an imported chunk, destructured access, and no false positive on ordinary words.

Existing plugin, route, internal, public and catalog suites (155 files):

  • Experiment off: all pass.
  • Experiment defaulted on locally: 1548/1553 pass. Four failures read plugin state through globalThis or vi.stubGlobal from the test thread, which a worker can't share by design: prebuilt-server-loading ×2, plugin-native-server-loading, and the plugin-update stabilization-crash test. The fifth, builtin-plugins hot-reload, involves a builtin (never isolated) and also flaked with the experiment off.

Checks: turbo run typecheck lint for server, db, domain, app and templates, plus the db and domain test suites.

End-to-end with the real usage plugin (v0.3.27, installed from its git URL into a start:worktree instance on an empty data dir): the host daemon ran with HOME set to APFS clones of the session history inside that data dir. Core main-thread event loop and CPU were measured with an injected probe (5 ms timer lateness, process.threadCpuUsage()). Runs were interleaved A/B on a machine with load average 5–12.

Metric (core main thread) In-process Worker
Full first scan (11,546 events, ~60 s): stall time (lateness ≥ 20 ms) 315 / 273 ms 0 / 0 ms
Full scan: max event-loop delay 179 / 168 ms 16 / 13 ms
Full scan: core CPU 1.87 / 1.63 s 1.01 / 0.89 s
20 × dashboard RPC: stall time 669 / 667 ms 0 / 0 ms
20 × dashboard: max delay 43 / 48 ms 9 / 19 ms
20 × dashboard: core CPU 763 / 757 ms 238 / 243 ms
dashboard latency p50 49 / 48 ms 58 / 57 ms
Tiny RPC round trip p50 / p99 (400 calls) 1.78 / 2.14–2.25 ms 1.85–1.90 / 2.39–2.47 ms
Plugin reload (client-observed) ~70 ms ~86 ms
Worker start incl. factory n/a 74–80 ms (ping), 143 ms (usage)
Server RSS, usage + ping plugins 704–825 MB 819–902 MB (+77–145 MB for 2 workers; RSS is noisy)

Official plugins with the experiment on. connect-next, github-pr-status, prompt-library and storage-retention are always installed as builtin (bb-official lists them as bundled), so isolation never applies to them. A git install with the same id is refused while the builtin exists, and a git install from source fails on their workspace:* dependencies. To exercise their real server code anyway, I installed their prebuilt bundles as standalone git repos under renamed ids in the dev instance:

  • github-pr-status and storage-retention fell back in-process at preflight (bb.hosts.experimental_client) and ran with their services up.
  • connect-next fell back in-process at preflight (bb.server.internal_DO_NOT_USE_openTunnelIngress) and ran with its tunnel service up.
  • prompt-library ran in a worker (started in 103 ms). star, search (with prompt history through bb.sdk) and the CLI list --json all worked.

Scan wall time was unchanged (58–62 s in both modes). Bundle cost per worker, measured separately: 66 ms and ~23 MB heap, versus 12 ms and 6 MB for an empty worker. Most of that is the plugin SDK client and its schemas.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 3 commits November 9, 2026 13:21
…experiment

The isolatedPluginServers experiment moves the server entry of git and npm
plugins into a worker thread per plugin. Core keeps building the plugin API
handle; the worker gets a mirror whose calls cross synchronously through
Atomics, and its callbacks, RPC methods and HTTP routes are proxied back
into the same records core already dispatches. storage.database() opens in
the worker. Plugins that use APIs a worker cannot host load in-process.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/run-marketplace-plugin-server-code-off-core-s-ev-thr_jbvai7bpud branch from c196e7d to aac8a7c Compare November 9, 2026 21:22
@ymichael ymichael closed this Nov 9, 2026
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.

1 participant