Skip to content

Plugin load that fails after its server factory runs never runs bb.onDispose, so timers and subscriptions leak #8025

Closed

Description

@hemaaanth

Summary

When a plugin load fails after its server factory has already run, BB discards the new instance without running its bb.onDispose hooks. Timers and bb.sdk.subscribe callbacks the factory started keep running against the invalidated bb object, so every tick throws PluginContextStaleError. BB now contains each throw (#5964), but the process diagnostics monitor still writes one crash report file per throw. In my case that came to 43,163 report files (about 59 MB) in ~/.bb/logs.

I expected a discarded instance to get the same cleanup as a disposed one: run its dispose hooks, then invalidate the handle.

Versions and environment

  • Observed with the BB desktop AppImage 0.50.1 on Omarchy Linux (Arch-based), x86-64, kernel 7.2.15-1-omarchy.
  • Reproduction: BB checkout at 796cdcc0f4bf8a55e23664035c54e8db6fe9d272 (current main), Node.js v26.12.0, pnpm 9.15.9 (the repo pins 9.15.0).
  • Plugin involved in the incident: the traces plugin, installed from a local path: source. No provider, model, or credentials are needed for the reproduction.

Steps to reproduce

  1. From a BB checkout at 796cdcc0f4bf8a55e23664035c54e8db6fe9d272, install locked dependencies:

    pnpm install --frozen-lockfile
  2. Save this test as apps/server/test/services/plugins/plugin-failed-load-dispose.repro.test.ts. It uses the same standalone createPluginService setup as plugin-instance-lifecycle.test.ts. The fixture plugin starts a 10 ms timer that publishes, and clears it in bb.onDispose.

// Repro: a plugin instance that fails to load is discarded without running
// its bb.onDispose hooks, so a timer it started keeps calling the stale API.
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createMigratedConnection } from "@bb/db/testing";
import type { Logger } from "@bb/logger";
import { createAiServiceRegistry } from "../../../src/services/ai/ai-service-registry.js";
import {
  createPluginService,
  type PluginService,
} from "../../../src/services/plugins/plugin-service.js";
import { createNoopTelemetryService } from "../../../src/services/system/telemetry.js";
import { testLogger } from "../../helpers/test-app.js";

interface Control {
  generation: number;
  failFactory: boolean;
  ticks: number[];
  disposed: number[];
  timers: ReturnType<typeof setInterval>[];
}

declare global {
  var __failedLoad: Control | undefined;
}

// Same shape as a real plugin: start a timer, clear it in onDispose.
const SERVER = `
  export default function plugin(bb: any) {
    const control = globalThis.__failedLoad;
    const generation = ++control.generation;
    const timer = setInterval(() => {
      control.ticks.push(generation);
      bb.realtime.publish("tick", { generation });
    }, 10);
    control.timers.push(timer);
    bb.onDispose(() => {
      clearInterval(timer);
      control.disposed.push(generation);
    });
    if (control.failFactory) throw new Error("factory failed after setup");
  }
`;

const HOST = `
  import "bb-repro-package-that-is-not-installed";
  export default { experimental_apiVersion: 1, contract: {}, handlers: {} };
`;

async function writePlugin(root: string, withBrokenHost: boolean) {
  await mkdir(root, { recursive: true });
  await writeFile(
    join(root, "package.json"),
    JSON.stringify({
      name: "bb-plugin-failedload",
      version: "0.1.0",
      bb: {
        name: "Failed load repro",
        description: "Starts a timer, then fails to load.",
        branding: { icon: "Zap" },
        server: "./server.ts",
        ...(withBrokenHost ? { host: "./host.ts" } : {}),
      },
    }),
  );
  await writeFile(join(root, "server.ts"), SERVER);
  if (withBrokenHost) await writeFile(join(root, "host.ts"), HOST);
}

function captureUncaught(service: PluginService) {
  const previous = process.listeners("uncaughtException");
  process.removeAllListeners("uncaughtException");
  const claimed: unknown[] = [];
  const unclaimed: unknown[] = [];
  process.on("uncaughtException", (error) => {
    (service.handleUncaughtException(error) ? claimed : unclaimed).push(error);
  });
  return {
    claimed,
    unclaimed,
    restore() {
      process.removeAllListeners("uncaughtException");
      for (const listener of previous) process.on("uncaughtException", listener);
    },
  };
}

describe("failed plugin load skips bb.onDispose", () => {
  let workDir: string;
  let service: PluginService;

  beforeEach(async () => {
    workDir = await mkdtemp(join(tmpdir(), "bb-failed-load-"));
    globalThis.__failedLoad = {
      generation: 0,
      failFactory: false,
      ticks: [],
      disposed: [],
      timers: [],
    };
    service = createPluginService({
      aiServices: createAiServiceRegistry(),
      telemetry: createNoopTelemetryService(),
      db: createMigratedConnection(),
      hub: {
        getDaemonSessionIdForHost: () => null,
        notifyPluginChanged: () => {},
        onWatchedTargets: () => () => {},
        notifyPluginSignal: () => 0,
        notifySystem: () => {},
      },
      logger: testLogger as unknown as Logger,
      dataDir: join(workDir, "data"),
      appVersion: "0.9.0",
      loadTimeoutMs: 5_000,
      serviceStopTimeoutMs: 100,
    });
  });

  afterEach(async () => {
    await service.stop();
    // Test-only cleanup. BB never clears these timers.
    for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
    globalThis.__failedLoad = undefined;
    await rm(workDir, { recursive: true, force: true });
  });

  async function ticksAfterServiceStop() {
    const control = globalThis.__failedLoad!;
    await service.stop();
    const before = control.ticks.length;
    await new Promise((resolve) => setTimeout(resolve, 100));
    return control.ticks.length - before;
  }

  function state() {
    const control = globalThis.__failedLoad!;
    return {
      plugin: service.list().find((p) => p.id === "failedload"),
      generation: control.generation,
      disposed: [...control.disposed],
      ticks: control.ticks.length,
    };
  }

  it("first load: host entry fails to build after the factory ran", async () => {
    const root = join(workDir, "failedload");
    await writePlugin(root, true);
    const uncaught = captureUncaught(service);
    try {
      await service.installPath(root).catch((error: unknown) => {
        console.log("installPath rejected:", String(error).slice(0, 300));
      });
      await new Promise((resolve) => setTimeout(resolve, 300));
      const after = state();
      const stale = uncaught.claimed.filter(
        (e) => (e as Error)?.name === "PluginContextStaleError",
      ).length;
      console.log("first-load result", {
        status: after.plugin?.status,
        statusDetail: after.plugin?.statusDetail?.slice(0, 200),
        factoryRuns: after.generation,
        disposeHooksRun: after.disposed,
        timerTicksAfterDiscard: after.ticks,
        staleErrorsClaimed: stale,
        unclaimed: uncaught.unclaimed.length,
      });
      // Broken behavior: the factory ran, its onDispose never ran, and the
      // timer keeps firing against the invalidated handle.
      expect(after.generation).toBe(1);
      expect(after.disposed).toEqual([]);
      expect(stale).toBeGreaterThan(5);
      // service.stop() does not stop it either.
      const afterStop = await ticksAfterServiceStop();
      console.log("first-load ticks in 100 ms after service.stop():", afterStop);
      expect(afterStop).toBeGreaterThan(0);
    } finally {
      for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
      uncaught.restore();
    }
  });

  it("reload: new factory throws after registering cleanup", async () => {
    const root = join(workDir, "failedload");
    await writePlugin(root, false);
    await service.installPath(root);
    expect(state().plugin?.status).toBe("running");
    const uncaught = captureUncaught(service);
    try {
      globalThis.__failedLoad!.failFactory = true;
      await service.reload("failedload").catch((error: unknown) => {
        console.log("reload rejected:", String(error).slice(0, 300));
      });
      await new Promise((resolve) => setTimeout(resolve, 300));
      const after = state();
      const fromGen2 = globalThis.__failedLoad!.ticks.filter((g) => g === 2).length;
      const stale = uncaught.claimed.filter(
        (e) => (e as Error)?.name === "PluginContextStaleError",
      ).length;
      console.log("reload result", {
        status: after.plugin?.status,
        factoryRuns: after.generation,
        disposeHooksRun: after.disposed,
        gen2TicksAfterDiscard: fromGen2,
        staleErrorsClaimed: stale,
        unclaimed: uncaught.unclaimed.length,
      });
      // Generation 1 stays live (correct). Generation 2 was discarded, but its
      // onDispose never ran and its timer keeps throwing.
      expect(after.generation).toBe(2);
      expect(after.disposed).not.toContain(2);
      expect(fromGen2).toBeGreaterThan(5);
      expect(stale).toBeGreaterThan(5);
      // service.stop() disposes generation 1 but not the discarded generation 2.
      const afterStop = await ticksAfterServiceStop();
      console.log("reload ticks in 100 ms after service.stop():", afterStop, {
        disposeHooksRun: [...globalThis.__failedLoad!.disposed],
      });
      expect(globalThis.__failedLoad!.disposed).toEqual([1]);
      expect(afterStop).toBeGreaterThan(0);
    } finally {
      for (const timer of globalThis.__failedLoad!.timers) clearInterval(timer);
      uncaught.restore();
    }
  });
});
  1. Run it:

    pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-failed-load-dispose.repro.test.ts --disableConsoleIntercept

    Turbo runs the generators the server tests need. --disableConsoleIntercept shows the logged results, because the server config hides console output from passing tests.

The tests assert the broken behavior, so they pass when the bug is reproduced.

Both cases reproduce:

  • First load, host entry fails to build. This is the incident path. The factory runs, then the hostArtifactProblem !== null branch calls discardCandidate.
  • Reload, factory throws after it set up cleanup. The previous instance correctly stays live. The failed candidate's timer leaks.

In both cases service.stop() does not stop the leaked timer either. It runs the live instance's hooks (generation 1 in the reload case) and never sees the discarded one. Without the test's own clearInterval cleanup, Vitest reports the leaked timer's PluginContextStaleError as unhandled errors after the tests finish.

What did not reproduce: a host entry build failure during a reload no longer runs the factory. BB returns failBeforeFactory first when a previous instance exists. So bb plugin reload with a broken host entry is safe on main and on 0.50.1. Only a load with no previous instance (server startup, install, or re-enabling a plugin in the error state) reaches the factory and then the discard.

Expected vs actual

Expected: the discarded instance's bb.onDispose hooks run (in LIFO order, as for a normal dispose). Its timer stops. No PluginContextStaleError follows, and nothing from the discarded instance runs after service.stop().

Actual output from the test on main:

first-load result {
  status: 'error',
  statusDetail: 'Build failed with 1 error:\n' +
    'host.ts:2:9: ERROR: Could not resolve "bb-repro-package-that-is-not-installed"',
  factoryRuns: 1,
  disposeHooksRun: [],
  timerTicksAfterDiscard: 29,
  staleErrorsClaimed: 29,
  unclaimed: 0
}
first-load ticks in 100 ms after service.stop(): 9
reload result {
  status: 'running',
  factoryRuns: 2,
  disposeHooksRun: [],
  gen2TicksAfterDiscard: 29,
  staleErrorsClaimed: 29,
  unclaimed: 0
}
reload ticks in 100 ms after service.stop(): 9 { disposeHooksRun: [ 1 ] }
 Test Files  1 passed (1)
      Tests  2 passed (2)

Incident log from ~/.bb/logs/server.23.log (2026-11-20, server startup). The factory's own log line appears 1 ms before the failure, and the first stale-handle error follows 0.6 s later:

13:03:29.232  Server listening
13:03:37.454  [plugin:traces] Traces loaded (read-only BB storage)
13:03:37.455  plugin traces failed to load: Build failed with 1 error:
              prompt-contract.ts:2:18: ERROR: [plugin: bb-zod-resolution] could not resolve "zod": this host entry imports it; add zod to the plugin's dependencies. ...
13:03:38.049  PluginContextStaleError: plugin "traces" used a stale API handle — it was reloaded or disabled; re-entry happens via a fresh factory call

The same sequence repeats after the next server start at 14:43:34 (Traces loaded at 14:43:41.543, failure at 14:43:41.544, first stale error at 14:43:42.187).

Evidence

  • discardCandidate aborts stopping, interrupts interactions, closes databases, aborts released, and calls handle.invalidate(). It does not run handle.disposeHooks.
  • disposePluginInstance runs handle.disposeHooks in reverse before it invalidates the handle. Only this path runs bb.onDispose.
  • discardCandidate is called after the factory has run in three places:
  • invalidate() only marks the handle stale and revokes the RPC caller. It does not stop anything the plugin started.
  • bb.sdk.subscribe is not tied to the plugin instance. wrapSdkForPlugin spreads the shared SDK, and subscribe goes straight to the realtime client. Only the plugin's own bb.onDispose can remove it. In the incident, traces subscribed to thread:changed and published from a short timer on each change. The leaked subscription threw once per thread change for the rest of the process.
  • BB puts some of its own cleanup on the same list. rpc.experimental_whileWatched pushes the stop function for a hub.onWatchedTargets listener that starts during the factory. A discarded candidate keeps that listener. I read this from the code and did not reproduce it.
  • The docs promise cleanup on failed loads only for the previous instance. The bb.onDispose lifecycle section and the onDispose contract ("the sanctioned place to clear timers") say nothing about a candidate that is dropped after its factory ran.
  • Report flood: installSafeProcessDiagnostics listens on uncaughtExceptionMonitor. Node calls that listener before the server's uncaughtException handler gets a chance to claim the error. So it synchronously writes a process-server-uncaughtException-*.json file even for errors BB then contains. reportStaleError logs a stale error once, because assertLive reuses one cached error object. The report writer has no such limit.
  • Measured counts: I counted process-server-uncaughtException-*.json files in ~/.bb/logs whose error was PluginContextStaleError for traces. There were 43,163 files (about 59 MB) between 2026-11-19 and 2026-11-21, when I deleted them. In the busiest window, 2,859 files appeared in 22 seconds right after the 13:03:37 failed load.
  • Investigation: BB thread thr_3sau3cn5p3.

The leak is reproduced on main. The report flood is read from code and matches the incident files. I did not measure the disk or CPU cost of the flood on its own. I also do not claim it caused a separate desktop freeze the same evening: that freeze showed no rise in the report rate.

What you ruled out

Suggested priority and effort

Medium. Any plugin that starts a timer or bb.sdk.subscribe in its factory and then fails to load leaks that work until the server restarts. With busy threads it fills ~/.bb/logs with report files. The workaround is per plugin: catch PluginContextStaleError and tear down on the first throw. That is what the traces plugin now does. No user data was lost. Effort is probably low.

A possible fix: in discardCandidate, run candidate.handle.disposeHooks in reverse before handle.invalidate(), with the same per-hook error logging as disposePluginInstance. Separately, the diagnostics monitor could skip or rate-limit reports for errors that the server handler claims, for example by writing the report from the server's uncaughtException handler after handleUncaughtException returns false. A regression check: a fixture that registers bb.onDispose and then fails to load (factory throws; first load with a broken host entry). Assert that the hook ran and that no PluginContextStaleError follows.

AGENT GENERATED

Activity

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

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority: Medium · Effort: Low. Labels: plugins, confirmed-repro.
    • Report: https://get-bb.github.io/reports/issues/8025.html — REPRODUCED, high root-cause confidence.
    • Root cause: Failed-candidate teardown skips registered dispose hooks before invalidating the API, leaving plugin-created timers alive even after service shutdown.
    • Reproduction: An independently authored service-level regression covers initial host-build failure, initial factory failure, and failed reload. All three fail on unchanged origin/main in two clean checkouts. The test is included in the report.
    • Fix: Run cleanup hooks before discarding failed plugin candidates #8028 — ready, not merged. Shares the existing LIFO cleanup runner; preserves the prior live instance. Two files, 207 changed text lines.
    • Verification: 175 tests pass across 10 files; server lint, typecheck, and diff checks pass. Historical diagnostic-file counts and desktop behavior were not verified; diagnostics rate limiting is outside this fix.

    AGENT GENERATED

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-reproplugins

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions