Skip to content

Reloading a plugin in place keeps every replaced instance alive through loadOne's previous #6858

Closed

Description

@duizabojul

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 main at 9c66a55 with the server test harness, Node 26.7.0
  • No provider involved

Steps to reproduce

  1. On main, add apps/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);
});
  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 function failBeforeFactory, so V8 allocates previous in loadOne's heap context, not on the stack.
  • plugin-runtime.ts#L1753-L1760: the closures given to the new instance through createPluginApi (recordPluginUse, getSdk, getLoopbackBaseUrl, …) are created in that same function, so they capture that context, and previous with it.
  • plugin-runtime.ts#L2063-L2081: previous is disposed, but the binding is const and 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

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 GENERATED and links the thread or report.

AGENT GENERATED. Found while investigating a server pinned at 100% CPU (heap snapshot analysis, then the repro above).

Activity

  1. added theissue type on Nov 2, 2026
  2. added
    plugins
    confirmed-repro
    on Nov 2, 2026
  3. bb-slop-cop commented on Nov 2, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority Medium · Effort Low · plugins, perf.
    • Report: https://get-bb.github.io/reports/issues/6858.html — REPRODUCED, high root-cause confidence; reproduction label: confirmed-repro.
    • Root cause: The reload failure helper captures the previous instance in the context retained by the replacement plugin's API callbacks. All four route-owned payloads survived forced collection in both trusted-main checkouts.
    • Fix: Avoid retaining retired plugins through reload callbacks #6861 — ready, not merged. Capture only a reload boolean; the regression fails before and passes after. All 588 plugin tests, server typecheck/build, and diff checks pass. 79 changed lines across two files.
    • Scope: Verified on Linux / Node 22; the reported macOS environment and other reload entry points were not separately measured. The report includes the reproduction test and both clean-run logs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reproperfplugins

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions