← reports

#6858 · Retired plugin route state remains reachable after reload

BugMedium priorityLow effortplugins · perf · confirmed-reproGitHub issue

November 2, 2026 · trusted main d448d87f2033f7c253b64370c321ea9e7500c81d

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

A plugin reload stops the old instance but leaves its route-owned objects reachable. A new test installs a real plugin, reloads it three times, forces garbage collection through the local Node inspector, and checks weak references to four separately created payloads. Trusted main retains all four payloads in two clean-checkout runs, rather than only the current payload. The failure helper closes over the previous instance even though it needs only a boolean. Capturing that boolean instead releases the three retired payloads while the current HTTP route continues working.

2. Claims vs findings

ClaimFindingEvidence
Repeated reload retains old instance-owned stateVerifiedBoth trusted-base runs report [true, true, true, true] for payload reachability after collection.
The previous-instance closure is responsibleVerifiedChanging only the failure helper to capture a boolean makes the regression pass; disposal code and module loading are unchanged.
Production heap size, macOS behavior, and other reload entry pointsUnverified hereNo production data or heap snapshot was accessed. Linux/Node 22 and the real plugin-service reload boundary were exercised. Disable/enable and version changes were not measured.

3. Environment

4. Minimal reproduction

  1. Check out trusted main at the recorded commit and install frozen dependencies:
    git checkout d448d87f2033f7c253b64370c321ea9e7500c81d
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk --filter=@bb/server
  2. Save the linked test at apps/server/test/services/plugins/plugin-reload-collection.test.ts. It is newly authored from repository runtime and harness evidence, not copied from the issue.
  3. Run from the repository root:
    pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-reload-collection.test.ts

Expected reachability: only the fourth (current) payload remains. Actual assertion on unchanged main, verbatim:

AssertionError: expected [ true, true, true, true ] to deeply equal [ false, false, false, true ]

Download reproduction test. The payloads are intentionally small: this checks liveness, not a noisy process-memory estimate, and does not depend on retaining a module-level allocation.

import { mkdir, writeFile } from "node:fs/promises";
import { Session } from "node:inspector";
import { join } from "node:path";
import { setTimeout } from "node:timers/promises";
import { expect, it, vi } from "vitest";
import { createTestAppHarness } from "../../helpers/test-app.js";

it("releases retired route state while keeping the current plugin active", async () => {
  const references: WeakRef<object>[] = [];
  const harness = await createTestAppHarness();
  const inspector = new Session();
  try {
    inspector.connect();
    vi.stubGlobal("__bbObserveReloadPayload", (payload: object) => {
      references.push(new WeakRef(payload));
    });
    const root = join(harness.config.dataDir, "collection-fixture");
    await mkdir(root);
    await writeFile(
      join(root, "package.json"),
      JSON.stringify({
        name: "bb-plugin-collection-fixture",
        version: "0.1.0",
        bb: {
          name: "Collection fixture",
          description: "Exercises retired plugin state collection.",
          branding: { icon: "Zap" },
          server: "./server.ts",
        },
      }),
    );
    await writeFile(
      join(root, "server.ts"),
      `export default function plugin(bb) {
        const payload = { value: 42 };
        globalThis.__bbObserveReloadPayload(payload);
        bb.http.route("GET", "/value", context => context.json(payload));
      }`,
    );
    expect((await harness.pluginService.installPath(root)).status).toBe(
      "running",
    );
    for (let reload = 0; reload < 3; reload++) {
      expect(
        await harness.pluginService.reload("collection-fixture"),
      ).toMatchObject({
        ok: true,
      });
    }
    for (let collection = 0; collection < 3; collection++) {
      await setTimeout(0);
      await new Promise<void>((resolve, reject) => {
        inspector.post("HeapProfiler.collectGarbage", (error) => {
          if (error) reject(error);
          else resolve();
        });
      });
    }
    expect(references).toHaveLength(4);
    expect(
      references.map((reference) => reference.deref() !== undefined),
    ).toEqual([false, false, false, true]);
    const response = await harness.app.request(
      "http://127.0.0.1/api/v1/plugins/collection-fixture/http/value",
    );
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ value: 42 });
  } finally {
    inspector.disconnect();
    try {
      await harness.cleanup();
    } finally {
      vi.unstubAllGlobals();
    }
  }
});

5. Root cause

The runtime reads the previous LoadedPlugin and the nested pre-factory failure function references that object. The new plugin API receives callbacks created in the same activation. That retained closure context can therefore keep the previous LoadedPlugin, whose handle includes the retired HTTP route handler and payload, reachable. Each replacement repeats the link. This explanation is supported by trusted source and the narrowly controlled fail/pass change; a heap snapshot was not taken in this investigation.

plugin-runtime.ts:1684

    const previous = loaded.get(row.id);
    function failBeforeFactory(
      status: PluginRuntimeStatus,
      detail: string,
    ): string {
      if (previous !== undefined) {
        setStatus(row.id, "running", `reload failed: ${detail}`);
        logger.warn(
          `plugin ${row.id} reload failed (kept previous instance): ${detail}`,
        );
        return `${detail} (${PREVIOUS_INSTANCE_KEPT})`;
      }
      setStatus(row.id, status, detail);
      logger.warn(`plugin ${row.id} not loaded (${status}): ${detail}`);
      return detail;

plugin-runtime.ts:1753

    const handle = createPluginApi({
      recordPluginUse: () => capturePluginUse(deps, row.id),
      pluginId: row.id,
      logger: deps.logger,
      db: deps.db,
      dataDir: deps.dataDir,
      getSdk: () => boundSdk,
      getMachineEnrollments: () => {
        if (!context.machineEnrollments)
          throw new Error(
            "Machine enrollment is unavailable in this plugin host",
          );
        return context.machineEnrollments.forOwner(row.id);
      },
      getAppUrl: deps.getAppUrl ?? (() => null),
      getLoopbackBaseUrl: () => boundLoopbackBaseUrl,
      rpcCaller: rpcCallers.issue(row.id),
      invalidateRpc: (tags) => deps.hub.notifyPluginChanged(row.id, tags),
      whileRpcWatched: (method, handler) => {
        const active = new Map<string, AbortController>();
        const isWatchedRead = (target: PluginReadSubscriptionTarget) =>
          target.pluginId === row.id && target.method === method;
        const stop = deps.hub.onWatchedTargets(["plugin-read"], (change) => {

plugin-runtime.ts:2063

    if (previous !== undefined) {
      await disposePluginInstance(previous);
      const hungAfterDispose = hungServices.get(row.id);
      if (hungAfterDispose !== undefined && hungAfterDispose.size > 0) {
        for (const rollback of rollbackGenerations.reverse()) rollback();
        loaded.delete(row.id);
        deps.sharedPorts?.clearDeclarationsForOwner(row.id);
        discardCandidate(plugin);
        return hungServicesDetail(hungAfterDispose);
      }
      releaseMutableRoots(
        [...previous.moduleRootUrls].filter(
          (rootUrl) => !candidateModuleRootUrls.has(rootUrl),
        ),
      );
    }
    disposeUnavailableProviderRegistrations(row.id);
    deps.hub.notifyPluginChanged(row.id, null);
    loaded.set(row.id, plugin);
    appBundles.set(row.id, appBundleCandidate.snapshot);
    if (hostArtifactCandidate === null) hostArtifacts.delete(row.id);

Disposal invalidates the old handle and stops work; it does not make an otherwise strongly reachable object collectable. The relevant code is the API method retaining its options callback, the retained route records, and instance disposal.

6. Proposed fix and verification

Keep the previous instance available locally for disposal and rollback, but compute const isReload = previous !== undefined and let the failure helper capture only that boolean. This preserves failed-reload behavior without introducing mutable lifecycle state, public APIs, or protocol changes. The production patch is two added lines and one removed line in the existing plugin runtime.

The focused regression passes after the change, including a successful response from the current route. Existing plugin tests and the server typecheck/build were run through Turbo:

@bb/server:test:  Test Files  59 passed (59)
@bb/server:test:       Tests  588 passed (588)
 Tasks:    10 successful, 10 total

7. Verification: second clean run

The same agent created a second clean detached worktree at the exact base commit, installed frozen dependencies, built the SDK/server, and copied only the newly authored regression test. Production code remained unmodified; git status showed only the untracked test. The exact command below failed for the same four-live-payload assertion. This is a repeat clean run, not an independent-agent verification.

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-reload-collection.test.ts

Second-run log. No verdict correction was needed.

8. Related issues and pull requests

No linked open pull request was present in issue timeline metadata or the issue-number PR search before implementation. #4159 concerns module-graph retention; this regression instead observes per-factory route payload liveness and is corrected without changing module loading. The production/macOS measurements in the issue are not used as evidence here.

9. Appendix

Issue content was treated as untrusted claims. No issue-provided command, test, patch, linked branch, or external URL was executed or fetched. Repository and numeric issue identity came from the trusted caller.

Initial all-package build encountered an already-unbuilt SDK runtime entry in the GitHub plugin; the SDK runtime build and relevant server build then succeeded. No dependency was added.

Validation commands, in addition to the frozen installs and reproduction commands above:

pnpm exec turbo run build
pnpm exec turbo run build --filter=@get-bb/plugin-sdk
pnpm exec oxfmt apps/server/test/services/plugins/plugin-reload-collection.test.ts apps/server/src/services/plugins/plugin-runtime.ts
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins
pnpm exec turbo run lint typecheck build --filter=@bb/server
git diff --check

No visual claim is made, so screenshots are not applicable.