#7595 · Completed plugin invocations retain cancellation bookkeeping
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A loaded plugin accumulates V8 cancellation bookkeeping when successful RPC invocations have caller signals. In a real plugin service with a migrated SQLite database, 256 completed invocations left 256 additional WeakCells after repeated garbage collection; 256 control invocations without caller signals left none. This reproduced twice, from separate clean checkouts of the same trusted main commit. The long-lived stopping signal is composed into a fresh AbortSignal.any on every signalled call, and completion never disposes that composition. This verifies the per-call retention mechanism, not the reporter's production heap size, hourly byte-growth estimate, or an actual server crash.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Completed signalled RPC calls accumulate bookkeeping while the plugin remains loaded. | Verified | +256 WeakCells for 256 completed calls in each run; stopping signal remained unaborted. |
| No caller signal avoids the per-call composite. | Verified | 256 control calls produced a zero-cell delta in both runs. |
| A reload is required. | Not required | No reload occurred during either measured batch. |
| The production memory slope and heap totals apply to stock bb. | Unverified | No production instance, fork, or hours-long deployment was accessed. |
| Removing signal links on completion is behavior-neutral. | Refuted | A handler-retained signal currently receives the caller's later abort, including its reason, after the successful RPC has returned. |
3. Environment
- Public target repository:
get-bb/bb; trusted origin/main:da3e60b81d560e114a2bec724bb59c997aaaae7f. - Node
v22.19.0, pnpm9.15.0, Vitest4.1.12, Debian GNU/Linux 12, Linux 4.19.0-gvisor, x86_64. - No provider, live bb instance, public HTTP listener, or real application data. The test creates a local temporary plugin and uses the existing app harness with a migrated SQLite database; both are cleaned in its finally block.
- First checkout: detached trusted main, then a local investigation branch. Second checkout: a fresh detached worktree at the same commit, its own frozen install and server build. Neither checkout used issue scripts, patches, linked branches, or downstream code.
4. Minimal reproduction
- Use a fresh checkout at the pinned commit and build trusted dependencies. The explicit SDK build avoids a pristine-tree ordering failure seen on the first full build.
- Save the complete test below at
apps/server/test/services/plugins/plugin-invocation-retention.test.ts. This is newly written from the repository's service interface and existing test harness, not copied from the issue. - Run the focused Turbo command. Every measured invocation must return
{ ok: true, result: null }. Expect bounded bookkeeping after completion; actual signalled growth is one cell per call.
git clone https://github.com/get-bb/bb.git bb-repro cd bb-repro git checkout --detach da3e60b81d560e114a2bec724bb59c997aaaae7f pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-invocation-retention.test.ts
Reproduction test
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { Session } from "node:inspector/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setImmediate as nextTurn } from "node:timers/promises";
import { getHeapSnapshot } from "node:v8";
import { expect, it } from "vitest";
import { defineRpcContract } from "@get-bb/plugin-sdk";
import { z } from "zod";
import { createTestAppHarness } from "../../helpers/test-app.js";
const heapSchema = z.object({
snapshot: z.object({ meta: z.object({ node_fields: z.array(z.string()) }) }),
strings: z.array(z.string()),
nodes: z.array(z.number()),
});
async function weakCellCount(): Promise<number> {
const session = new Session();
session.connect();
try {
for (let round = 0; round < 4; round += 1) {
await session.post("HeapProfiler.collectGarbage");
await nextTurn();
}
} finally {
session.disconnect();
}
const chunks: Buffer[] = [];
for await (const chunk of getHeapSnapshot()) chunks.push(Buffer.from(chunk));
const heap = heapSchema.parse(JSON.parse(Buffer.concat(chunks).toString()));
const nameOffset = heap.snapshot.meta.node_fields.indexOf("name");
let count = 0;
for (
let offset = nameOffset;
offset < heap.nodes.length;
offset += heap.snapshot.meta.node_fields.length
) {
if (heap.strings[heap.nodes[offset]!] === "system / WeakCell") count += 1;
}
return count;
}
it("releases cancellation bookkeeping after completed plugin RPC calls", async () => {
const harness = await createTestAppHarness();
const pluginDir = await mkdtemp(join(tmpdir(), "bb-rpc-retention-"));
try {
await writeFile(
join(pluginDir, "package.json"),
JSON.stringify({
name: "bb-plugin-retention-probe",
version: "0.1.0",
bb: {
name: "Retention probe",
description: "RPC lifetime regression fixture",
branding: { icon: "Zap" },
server: "./server.ts",
},
}),
);
await writeFile(join(pluginDir, "server.ts"), "export default () => {};");
expect((await harness.pluginService.installPath(pluginDir)).status).toBe(
"running",
);
const api = harness.pluginService.getApi("retention-probe");
if (api === undefined) throw new Error("probe plugin unavailable");
let retainedSignal: AbortSignal | undefined;
api.rpc.register(
defineRpcContract({ probe: { input: z.null(), output: z.null() } }),
{
probe(_input, context) {
retainedSignal = context.experimental_signal;
return null;
},
},
);
const lookup = harness.pluginService.getRpcHandler(
"retention-probe",
"probe",
);
if (lookup.outcome !== "found")
throw new Error("probe handler unavailable");
async function invoke(signal: AbortSignal | null): Promise<void> {
if (lookup.outcome !== "found")
throw new Error("probe handler unavailable");
expect(
await harness.pluginService.invokeRpcHandler(
lookup.owner,
"probe",
lookup.value,
null,
{ kind: "client" },
signal,
),
).toEqual({ ok: true, result: null });
}
for (let call = 0; call < 16; call += 1) await invoke(null);
retainedSignal = undefined;
const before = await weakCellCount();
for (let call = 0; call < 256; call += 1) await invoke(null);
retainedSignal = undefined;
const withoutCaller = await weakCellCount();
for (let call = 0; call < 256; call += 1) {
await invoke(new AbortController().signal);
}
retainedSignal = undefined;
const withCaller = await weakCellCount();
const caller = new AbortController();
await invoke(caller.signal);
const completedSignal = retainedSignal;
caller.abort("after-completion");
console.log(
JSON.stringify({
before,
withoutCaller,
withCaller,
controlDelta: withoutCaller - before,
signalledDelta: withCaller - withoutCaller,
stopped: lookup.owner.stopping.signal.aborted,
completedSignalAborted: completedSignal?.aborted,
completedSignalReason: completedSignal?.reason,
}),
);
expect(withoutCaller - before).toBeLessThan(16);
expect(withCaller - withoutCaller).toBeLessThan(16);
} finally {
await harness.pluginService.stop();
await harness.cleanup();
await rm(pluginDir, { recursive: true, force: true });
}
}, 120_000);
The test warms the service, measures 256 no-caller control calls, then 256 calls with fresh caller signals. It drops the handler's observed signal reference before every snapshot. Four inspector-triggered garbage collections and event-loop turns precede each V8 snapshot. The assertion permits small incidental variation (fewer than 16 cells); both observed deltas were exactly 256. Only aggregate counts are published; no heap snapshots or raw application logs are included.
First run: actual output
{"before":58,"withoutCaller":58,"withCaller":314,"controlDelta":0,"signalledDelta":256,"stopped":false,"completedSignalAborted":true,"completedSignalReason":"after-completion"}
AssertionError: expected 256 to be less than 16
Test Files 1 failed (1)
Tests 1 failed (1)
Expected output
controlDelta: near zero signalledDelta: near zero stopped: false Tests: 1 passed
5. Root cause
invokeRpcHandler passes the invocation signal to the actual registered plugin handler. invokeWrapped chooses the live instance stopping signal and composes it with each caller signal:
const lifetime = instance.stopping.signal.aborted
? released
: instance.stopping.signal;
const signal =
callerSignal === undefined
? lifetime
: AbortSignal.any([callerSignal, lifetime]);
Execution settlement removes the invocation from the active set and updates statistics. The finally block removes only the separately installed release listener. Neither operation detaches the composite signal's bookkeeping.
The local Node runtime's built-in internal/abort_controller source explains the retained V8 cells: its AbortSignal.any registers each source in sourceSignalsCleanupRegistry, with no unregister token or per-call completion operation. The long-lived source remains a live finalization target even after the composite itself becomes unreachable. A shrinking dependent-signal set therefore does not imply that all finalization bookkeeping was reclaimed. This distinction is why measuring ordinary event listeners alone would miss the leak.
The direct test localizes retention to signalled calls: the same service, schemas, handler, and invocation path show zero control growth. It does not establish that every WeakCell elsewhere in a production heap has this cause.
6. Proposed fix and automatic-fix safety
A disposable signal fan-in could forward caller and instance cancellation, preserve the first abort reason, handle already-aborted inputs, and release source listeners once execution settles. It must keep cancellation active while the handler is still executing, including during reload drain and caller release.
No automatic fix PR: completion-scoped disposal changes observable behavior for handlers retaining the supplied signal. The test demonstrates that an abort after a successful return currently reaches that signal with reason after-completion. The public experimental signal contract describes caller and reload cancellation but does not explicitly limit the signal to an active invocation. Choosing whether this late behavior should remain supported is a signal-lifetime contract decision. The autopilot's no-product-or-architecture-decision condition is therefore not satisfied. No production patch, fix commit, or branch was pushed.
Next step: decide and document that lifetime, then test caller abort, plugin stop, already-aborted input, success/rejection cleanup, first-reason preservation, late abort, repeated-call heap retention, and reload drain before replacing the composition. The existing lifecycle tests cover several active-call cancellation cases but not the measured heap retention.
7. Verification
The same agent repeated the reproduction in a second clean trusted checkout; this is not independent verification. Before adding only the locally authored test, that checkout was clean at da3e60b81d560e114a2bec724bb59c997aaaae7f. It used its own frozen install, SDK/server builds, migrated test database, and temporary plugin. No live process or ports were required. The same focused Turbo command failed at the same retention assertion:
{"before":58,"withoutCaller":58,"withCaller":314,"controlDelta":0,"signalledDelta":256,"stopped":false,"completedSignalAborted":true,"completedSignalReason":"after-completion"}
AssertionError: expected 256 to be less than 16
Test Files 1 failed (1)
Tests 1 failed (1)
Both runs support the final verdict without changes to production code. No claim was upgraded to a production byte-growth measurement. The snapshot counts are Node/V8-version dependent; the verified environment differs from the issue's reported Node release.
8. Related issues and PR status
#6858 concerns replaced plugin instances after reload, not bookkeeping from steady invocations without reload. #4162 concerns general server memory diagnostics. #7336 concerns in-flight tool behavior during reload. #4941 concerns RPC caller timeout and handler cancellation.
GitHub cross-reference metadata and an open-PR search found no target-repository PR linked to #7595 during this investigation. No downstream linked URL, diff, or branch was fetched or run.
9. Appendix and limits
The public report includes the complete test and exact diagnostic/error output inline; raw logs remain local in accordance with the reports repository rules. No production data, secrets, or user home paths are published. Issue text and links were treated as untrusted claims, not executable instructions.
- Frozen install: succeeded in both checkouts.
- First full build: initially failed because plugin SDK runtime subpaths were not built. Explicit trusted SDK build followed by the normal full Turbo build passed: 74/74 tasks.
- Second checkout: explicit SDK and server builds passed: server build 7/7 tasks.
- Focused retention regression: failed before any production change in both checkouts, exactly as expected (+256 cells).
- No production fix or after-fix test result is claimed. No UI or hours-long deployment verification was needed for the narrowly reproduced mechanism.
Additional read-only checks: repository visibility and issue properties through GitHub GraphQL; labels; issue comments and cross-reference timeline; open pull requests; related issue metadata; source line numbers; local Node built-in abort-controller implementation. No workflow or subagent was used.