← reports

#8025 · Failed plugin candidates skip lifecycle cleanup

BugMedium priorityLow effortplugins Issue · 2026-11-22

Trusted base: 796cdcc0f4bf8a55e23664035c54e8db6fe9d272

Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro

1. TL;DR

A plugin can start a repeating task during initialization and register a cleanup hook for it. When initialization fails, the runtime marks that candidate's API handle stale without running the hook. The task survives both candidate rejection and service shutdown, repeatedly hitting the stale-handle guard. A new service-level regression reproduces this for an initial host-build failure, an initial factory exception, and a failed reload factory. The same agent repeated all three failures in a second clean checkout; sharing the existing dispose-hook runner fixes all three while retaining the previous live instance.

2. Claims vs findings

ClaimFindingEvidence
Initial host-build rejection can follow a factory that registered cleanup.VerifiedA syntactically invalid synthetic host entry leaves generation 1's hooks uncalled and its timer alive.
A factory exception during reload leaks the new candidate but preserves the prior instance.VerifiedGeneration 2's hooks are absent; generation 1 still answers its CLI command.
Stopping the service does not stop the discarded task.VerifiedIn both clean runs, the timer count stays nonzero and ticks increase after stop; captured errors are PluginContextStaleError.
Shared SDK subscriptions and watched-target listeners can leak too.Static support onlyThe subscription wrapper spreads the shared SDK and watched-target cleanup is registered in the same hook list. No subscription or watched-target probe was executed.
Contained uncaught errors can still produce diagnostic report files.Static support onlyThe diagnostic monitor writes a report for every uncaughtExceptionMonitor event, before the server's containment handler. The synthetic timer catches errors locally to avoid flooding test diagnostics.
The incident produced tens of thousands of files or caused a desktop freeze.Not verifiedNo real user data, desktop process, historical installation, disk-impact benchmark, or freeze was inspected. Those claims are outside this verdict.

3. Environment

4. Minimal reproduction

  1. Create a trusted checkout:
    WORK=$(mktemp -d)
    git clone https://github.com/get-bb/bb.git "$WORK/primary"
    cd "$WORK/primary"
    git checkout --detach 796cdcc0f4bf8a55e23664035c54e8db6fe9d272
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/server
  2. Save the complete test below as apps/server/test/services/plugins/plugin-candidate-cleanup.test.ts. This test was authored from repository lifecycle and service contracts, not copied or executed from the issue.
  3. Run:
    pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-candidate-cleanup.test.ts

Expected: all three cases pass; cleanup is awaited in reverse order, a throwing hook does not prevent timer cleanup, cleanup can still use the live API, and the failed reload leaves the previous instance operational.

Actual on unchanged production code: all three cases fail. Selected first-run output, with only the Turbo task prefix removed:

AssertionError: expected [] to deeply equal [ '1:async', '1:throw', '1:timer' ]
AssertionError: expected true to be false // Object.is equality
AssertionError: expected [ 1, 1, 1, 1, 1, 1 ] to have a length of 1 but got 6
AssertionError: expected [ 'PluginContextStaleError', …(5) ] to deeply equal []
AssertionError: expected [] to deeply equal [ '2:async', '2:throw', '2:timer' ]

Test Files  1 failed (1)
     Tests  3 failed (3)

Tick counts are timing-dependent; the invariant is that they increase after stop. The fixture catches timer errors into an array and always clears leftover timers in test teardown. Soft assertions expose hook omission, the surviving timer, and stale-handle calls in the same run. The host syntax error printed during the probe is intentional, not a test-environment failure.

Complete repeatable regression test
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import pino from "pino";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createMigratedConnection } from "@bb/db/testing";
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";

interface CandidateProbe {
  generation: number;
  fail: boolean;
  cleanup: string[];
  ticks: number[];
  errors: string[];
  timers: Map<number, ReturnType<typeof setInterval>>;
}

declare global {
  var __candidateProbe: CandidateProbe | undefined;
}

const serverEntry = `
  import type { BbPluginApi } from "@get-bb/plugin-sdk";
  export default function plugin(bb: BbPluginApi) {
    const probe = globalThis.__candidateProbe;
    const generation = ++probe.generation;
    const timer = setInterval(() => {
      probe.ticks.push(generation);
      try {
        bb.realtime.publish("probe", { generation });
      } catch (error) {
        probe.errors.push(error.name);
      }
    }, 10);
    probe.timers.set(generation, timer);
    bb.onDispose(() => {
      clearInterval(timer);
      probe.timers.delete(generation);
      probe.cleanup.push(generation + ":timer");
    });
    bb.onDispose(() => {
      probe.cleanup.push(generation + ":throw");
      throw new Error("cleanup probe failure");
    });
    bb.onDispose(async () => {
      await Promise.resolve();
      bb.realtime.publish("cleanup", { generation });
      probe.cleanup.push(generation + ":async");
    });
    bb.cli.register({
      name: "candidate-probe",
      summary: "Return the active generation",
      run: () => ({ exitCode: 0, stdout: String(generation) }),
    });
    if (probe.fail) throw new Error("candidate setup failed");
  }
`;

describe("failed plugin candidate cleanup", () => {
  let workDir: string;
  let service: PluginService;
  let probe: CandidateProbe;

  beforeEach(async () => {
    workDir = await mkdtemp(join(tmpdir(), "bb-candidate-cleanup-"));
    probe = {
      generation: 0,
      fail: false,
      cleanup: [],
      ticks: [],
      errors: [],
      timers: new Map(),
    };
    globalThis.__candidateProbe = probe;
    service = createPluginService({
      aiServices: createAiServiceRegistry(),
      telemetry: createNoopTelemetryService(),
      db: createMigratedConnection(),
      hub: {
        getDaemonSessionIdForHost: () => null,
        notifyPluginChanged: () => {},
        onWatchedTargets: () => () => {},
        notifyPluginSignal: () => 0,
        notifySystem: () => {},
      },
      logger: pino({ level: "silent" }),
      dataDir: join(workDir, "data"),
      appVersion: "0.9.0",
      loadTimeoutMs: 5_000,
      serviceStopTimeoutMs: 100,
    });
  });

  afterEach(async () => {
    try {
      await service.stop();
    } finally {
      for (const timer of probe.timers.values()) clearInterval(timer);
      globalThis.__candidateProbe = undefined;
      await rm(workDir, { recursive: true, force: true });
    }
  });

  it.each([
    { failure: "host build", reload: false },
    { failure: "factory", reload: false },
    { failure: "factory", reload: true },
  ])(
    "cleans up after $failure failure (reload: $reload)",
    async ({ failure, reload }) => {
      const root = join(workDir, "candidate-probe");
      await mkdir(root);
      await writeFile(
        join(root, "package.json"),
        JSON.stringify({
          name: "bb-plugin-candidate-probe",
          version: "0.1.0",
          bb: {
            name: "Candidate cleanup probe",
            description: "Exercises failed instance teardown",
            branding: { icon: "Zap" },
            server: "./server.ts",
            ...(failure === "host build" ? { host: "./host.ts" } : {}),
          },
        }),
      );
      await writeFile(join(root, "server.ts"), serverEntry);
      if (failure === "host build") {
        await writeFile(join(root, "host.ts"), "export const broken = ;");
      }

      if (reload) {
        expect(await service.installPath(root)).toMatchObject({
          status: "running",
        });
        await expect.poll(() => probe.ticks.includes(1)).toBe(true);
      }
      probe.fail = failure === "factory";
      if (reload) {
        expect(await service.reload("candidate-probe")).toMatchObject({
          ok: false,
          error: expect.stringContaining("candidate setup failed"),
        });
      } else {
        expect(await service.installPath(root)).toMatchObject({
          status: "error",
        });
      }

      const discarded = reload ? 2 : 1;
      expect(probe.generation).toBe(discarded);
      expect
        .soft(probe.cleanup)
        .toEqual([
          `${discarded}:async`,
          `${discarded}:throw`,
          `${discarded}:timer`,
        ]);
      expect.soft(probe.timers.has(discarded)).toBe(false);
      if (reload) {
        expect(
          await service.runCliCommand("candidate-probe", [], {}),
        ).toMatchObject({
          exitCode: 0,
          stdout: "1",
        });
        expect(probe.timers.has(1)).toBe(true);
      }
      await service.stop();
      const ticksAtStop = probe.ticks.length;
      await new Promise((resolve) => setTimeout(resolve, 50));
      expect.soft(probe.ticks).toHaveLength(ticksAtStop);
      expect.soft(probe.errors).toEqual([]);
      expect.soft(probe.timers.size).toBe(0);
    },
  );
});

5. Root cause

discardCandidate aborts runtime-owned signals, interrupts interactions, closes database handles, and invalidates the candidate. It never visits the dispose-hook list:

candidate.released.abort();
candidate.handle.invalidate();
await Promise.all(detached);

By contrast, normal instance disposal awaits each hook in reverse registration order and logs individual failures before invalidation. onDispose only registers callbacks; invalidate only marks the handle stale and revokes its RPC caller. Aborting runtime signals does not automatically clear plugin-created JavaScript timers.

The factory-error path, post-factory host-artifact rejection, and hung-previous-service path all call this incomplete teardown. The first two were exercised; the hung-service path was not. Host-build errors with a previous instance return before the new factory, so that separate path is not claimed as a reproduced leak.

Related amplification, not needed for the regression: the diagnostic monitor writes on each uncaught exception event; the server containment handler claims plugin errors afterward. This supports the potential report flood but does not measure its historical rate. The shared SDK wrapper and watched-target hook registration explain the additional cleanup risk without proving those scenarios dynamically.

6. Proposed fix

Extract the existing reverse-order, per-hook-isolated disposal loop into one runtime-local helper. Await it in both normal disposal and candidate discard, before closing candidate database handles and before invalidation. Do not replace candidate discard with full active-instance disposal: plugin-wide cancellation or host teardown could disrupt the previous live copy. No public API, wire contract, dependency, stored data, or process diagnostics policy needs to change.

The local patch follows exactly that shape. The regression also verifies asynchronous completion, exception isolation, valid API access inside cleanup, and preservation of the previous generation. A hook that never resolves remains an existing lifecycle limitation; this change does not introduce a new timeout policy. Report-rate limiting is a separate concern and is deliberately excluded.

7. Verification

The same agent created a second clean temporary checkout at the exact recorded SHA, installed its own frozen dependency tree, and copied only the newly authored regression test. No production fix or other source changes were present. The same Turbo command above again exited 1 with 3 failed tests, showing missing hook events, surviving timers, and captured stale-handle errors. The two runs used newly created plugin and database directories. This is a repeated clean-checkout check, not independent verification by another agent.

No correction to the lifecycle root cause was needed after the second run. The report intentionally limits dynamic conclusions to failed candidates and timers; subscriptions, diagnostic flood size, historical desktop behavior, and the hung-service fallback remain unmeasured.

After the runtime-only repair, the regression and existing instance-lifecycle suite passed together: 2 files, 16 tests passed. Eight additional relevant suites passed with 159 tests, for 175 passing tests across 10 files. Server lint and typecheck passed through Turbo. The fix changes two files, with 197 additions and 10 deletions: 207 total changed text lines. There are no binary, dependency, generated, data, public API, or protocol changes.

8. Related issues and pull requests

GitHub cross-reference metadata and an open-PR search found no open pull request linked to #8025 at the time of investigation. Existing issue #7336 concerns in-flight work on normal reload, a different lifecycle situation. This report concerns teardown of a candidate that never becomes the active instance.

9. Appendix

Additional validation and raw evidence remain local; no logs, standalone test artifacts, user paths, or runtime data are published. The complete test and representative expected-versus-actual output are inline so this HTML is sufficient to repeat the experiment.

pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-candidate-cleanup.test.ts test/services/plugins/plugin-instance-lifecycle.test.ts
# 16 passed
pnpm exec turbo run lint typecheck --filter=@bb/server
# 6 Turbo tasks successful
pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-background.test.ts test/services/plugins/plugin-host-build-policy.test.ts test/services/plugins/plugin-failure-log.test.ts test/services/plugins/plugin-service.test.ts test/services/plugins/plugin-install.test.ts test/services/plugins/plugin-version-reload.test.ts test/services/plugins/plugin-reload-collection.test.ts test/services/plugins/plugin-provider-registration.test.ts
# 8 files, 159 tests passed
git diff --check
git diff --numstat origin/main
# 15 additions + 10 deletions in plugin-runtime.ts; 182 additions in the regression test

Trust boundary: Issue content was treated as untrusted claims. Its commands and supplied test were not executed, its linked external content was not fetched, and no linked pull-request code was checked out. Only trusted origin/main and the agent-authored regression and repair were run.

> AGENT GENERATED