Repository navigation
Description
Summary
Every in-place reload of a plugin (bb plugin reload, a version reload, disable + enable) keeps the instance it replaced alive, and that instance keeps the one before it, until the server restarts. Everything an old instance holds (route handlers, caches, buffers, its module state) is never freed. I expected the replaced instance to be collectable once disposePluginInstance has run.
Versions and environment
- Seen in production: bb 0.48.1 installed with npm (
bb-app), macOS 27.0.1, Node 26.7.0 - Reproduced on
mainat 9c66a55 with the server test harness, Node 26.7.0 - No provider involved
Steps to reproduce
- On
main, addapps/server/test/services/plugins/reload-retains-previous.test.ts:
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { afterEach, beforeEach, expect, it } from "vitest";
import { createTestAppHarness, type TestAppHarness } from "../../helpers/test-app.js";
declare global {
var __reloadRefs: WeakRef<object>[] | undefined;
}
let harness: TestAppHarness;
let rootDir: string;
beforeEach(async () => {
globalThis.__reloadRefs = [];
harness = await createTestAppHarness();
rootDir = join(harness.config.dataDir, "fixtures", "bb-plugin-heavy");
await mkdir(rootDir, { recursive: true });
await writeFile(join(rootDir, "package.json"), JSON.stringify({
name: "bb-plugin-heavy", version: "0.1.0",
bb: { name: "Heavy", description: "Reload retention fixture.", branding: { icon: "Zap" }, server: "./server.ts" },
}));
await writeFile(join(rootDir, "server.ts"),
"export default function plugin(bb) { const heavy = { bytes: new Uint8Array(20_000_000) }; globalThis.__reloadRefs.push(new WeakRef(heavy)); bb.http.route('GET', '/size', (c) => c.json({ size: heavy.bytes.length })); }");
await harness.pluginService.installPath(rootDir);
});
afterEach(async () => {
await harness.cleanup();
});
it("frees the instance a reload replaced", async () => {
for (let i = 0; i < 5; i++) expect((await harness.pluginService.reload("heavy")).ok).toBe(true);
for (let i = 0; i < 5; i++) { await delay(50); globalThis.gc!(); }
const alive = globalThis.__reloadRefs!.filter((ref) => ref.deref() !== undefined).length;
console.log(`instances loaded: ${globalThis.__reloadRefs!.length}, still alive: ${alive}`);
expect(alive).toBe(1);
});cd apps/server && NODE_OPTIONS=--expose-gc npx vitest run test/services/plugins/reload-retains-previous.test.ts
Did not reproduce with a plugin that hands nothing to bb (export default function plugin() {} with the buffer created inside the factory): its buffer is freed, since nothing keeps it alive.
Expected vs actual
instances loaded: 6, still alive: 6
× frees the instance a reload replaced
AssertionError: expected 6 to be 1
Expected: still alive: 1, the current instance only. With the change below the same test passes.
Evidence
Observed. The replaced instances stay alive (the test above). In a heap snapshot of a production server (0.48.1, taken with the inspector after a forced GC), one plugin had 5 live copies after 4 in-place reloads (about 30 MB for the 4 dead ones). The retainer path of each dead copy went through the context of loadOne of the next instance, through its previous slot.
Cause (checked in the code and by the fix).
plugin-runtime.ts#L1684-L1698:const previous = loaded.get(row.id)is read by the nested functionfailBeforeFactory, so V8 allocatespreviousinloadOne's heap context, not on the stack.plugin-runtime.ts#L1753-L1760: the closures given to the new instance throughcreatePluginApi(recordPluginUse,getSdk,getLoopbackBaseUrl, …) are created in that same function, so they capture that context, andpreviouswith it.plugin-runtime.ts#L2063-L2081:previousis disposed, but the binding isconstand is never cleared. The new instance therefore keeps the old one, which keeps its own predecessor, and so on.
A standalone Node script with the same shape (a nested function reading previous, the instance's closures created in the same scope) keeps 5 of 5 instances. It keeps 1 of 5 when the nested reader is removed, or when the closures are built in a function that does not see previous.
Fix that makes the test pass:
- const previous = loaded.get(row.id);
+ let previous = loaded.get(row.id);
@@
(rootUrl) => !candidateModuleRootUrls.has(rootUrl),
),
);
+ previous = undefined;
}A sturdier variant is to build the createPluginApi argument in a function outside loadOne's scope, so a future reference cannot bring the chain back.
What you ruled out
- Not
bb plugin reloadretains the previous module graph for the lifetime of the server (~73 MB per reload for apath:plugin) #4159 / Plugin reload leaks ESM module graphs for the process lifetime #920 (module graphs retained by the ESM loader orrequire.cache): this holds without any module retention. The chain goes through the instance's closures and holds anything the plugin keeps, not only its modules. The measurements inbb plugin reloadretains the previous module graph for the lifetime of the server (~73 MB per reload for apath:plugin) #4159 (+0.1 MiB per reload) used a plugin whose instance held almost nothing, which hides it. - Not specific to one plugin: reproduced with the minimal fixture above.
Suggested priority and effort (optional)
Medium. It hits anyone who reloads a plugin in place, mostly plugin authors during development. Restarting the server is the only workaround, and memory grows by one full instance per reload. Effort: Low (two lines plus a regression test).
Checks
- I reproduced this on the latest release or on
main, or I say above that I could not. - I searched open and closed issues for the same problem.
- If an agent wrote this, the body ends with
> AGENT GENERATEDand links the thread or report.
AGENT GENERATED. Found while investigating a server pinned at 100% CPU (heap snapshot analysis, then the repro above).
Activity
bb-slop-cop commentedon Nov 2, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotplugins,perf.confirmed-repro.Avoid retaining retired plugins through reload callbacks (get-bb#6861)