← reports

#7509 · Detached cancellation loses plugin ownership when its stack has no frames

Bug High Effort: Medium plugins · 2026-11-13 · GitHub issue

Trusted base: 88cf8f644c81fca797ad80bc31bb36a61ce5cc9b, fetched directly from get-bb/bb main.

Verdict: REPRODUCED · Root-cause confidence: high for the containment gap; unknown for the original source of cancellation. Reproduction label: confirmed-repro.

1. TL;DR

A plugin's detached cancellation can escape the server's plugin-error containment if the thrown exception has no stack frames. A new regression case loads a real plugin through the existing service harness, creates a native aborted signal, and throws its reason from a detached callback. With normal frames, the runtime claims the exception; with stack capture temporarily disabled during signal creation, it does not. The server's production exception listener exits with code 1 whenever that runtime returns false. Two separate clean checkouts reproduced the same gap without changing production code; neither run establishes which operation caused the reported desktop incidents.

2. Claims vs findings

ClaimStatusEvidence
A frameless detached plugin AbortError is not contained.VerifiedBoth runs: one native DOMException, one stack line, zero claimed exceptions, one unclaimed exception.
The equivalent framed plugin failure is contained.VerifiedThe new framed control passes in both runs, as does the existing ordinary plugin-timer failure test.
Unclaimed errors cause the server to exit.Verified in source; not crash-tested against a full serverThe production listener calls process.exit(1) after a false containment result. The test intercepts the real uncaughtException event so its worker survives.
Eight desktop incidents had this upstream cause.UnverifiedNo access to the reporter's runtime or diagnostic files. No original aborting call identified.
Disabling stack capture can produce the observed error shape.Verified as a possible mechanismThe test temporarily changes Error.stackTraceLimit only while creating a native aborted signal, then restores it before callback execution. It never overwrites the exception stack.
The diagnostic filename proves the process died.Refuted as an inference; reporter already notes this distinctionThe monitor records an exception before the containment listener decides whether to exit. Existing serialization already includes an available error.cause.

3. Environment

4. Minimal reproduction

The reproduction is an original extension of the trusted repository's existing lifecycle fixture and uncaught-exception collector. It is not the issue's supplied script. It exercises the real plugin loader, native AbortSignal, detached callback, process exception event, and plugin-service containment handler.

  1. Clone the public target repository and select the recorded trusted main commit:
    git clone https://github.com/get-bb/bb.git bb-7509
    cd bb-7509
    git checkout --detach 88cf8f644c81fca797ad80bc31bb36a61ce5cc9b
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@get-bb/plugin-sdk
    pnpm exec turbo run build --filter=@bb/server
  2. Save the complete patch below as repro.patch, then apply and run:
    git apply repro.patch
    pnpm exec turbo run test --filter=@bb/server -- test/services/plugins/plugin-instance-lifecycle.test.ts
  3. Inspect the failed frameless row and the successful framed/core controls. The intended invariant is that a detached plugin cancellation is claimed even without textual location frames. Current production code violates that invariant.

Complete reproduction patch against the recorded base; all dependencies and test helpers are already in the repository:

diff --git apps/server/test/services/plugins/plugin-instance-lifecycle.test.ts apps/server/test/services/plugins/plugin-instance-lifecycle.test.ts
index 90a1845330..27b03dfd32 100644
--- apps/server/test/services/plugins/plugin-instance-lifecycle.test.ts
+++ apps/server/test/services/plugins/plugin-instance-lifecycle.test.ts
@@ -83,6 +83,18 @@ const fixture = `
           }, 0);
           return { exitCode: 0 };
         }
+        if (argv[0] === "abort-framed" || argv[0] === "abort-frameless") {
+          const previousLimit = Error.stackTraceLimit;
+          let signal: AbortSignal;
+          try {
+            if (argv[0] === "abort-frameless") Error.stackTraceLimit = 0;
+            signal = AbortSignal.abort();
+          } finally {
+            Error.stackTraceLimit = previousLimit;
+          }
+          setImmediate(() => signal.throwIfAborted());
+          return { exitCode: 0 };
+        }
         if (argv[0] === "core-work") {
           control.coreWork();
           return { exitCode: 0 };
@@ -486,6 +498,39 @@ describe("plugin instance lifecycle without cooperation", () => {
     }
   });
 
+  it.each(["abort-framed", "abort-frameless"])(
+    "contains a detached cancellation from plugin code: %s",
+    async (mode) => {
+      const uncaught = withUncaughtExceptions((error) =>
+        service.handleUncaughtException(error),
+      );
+      try {
+        expect(await service.runCliCommand("lifecycle", [mode], {})).toMatchObject({
+          exitCode: 0,
+        });
+        await expect
+          .poll(() => uncaught.claimed.length + uncaught.unclaimed.length)
+          .toBe(1);
+        const failure = [...uncaught.claimed, ...uncaught.unclaimed][0];
+        expect(failure).toBeInstanceOf(DOMException);
+        expect(failure).toMatchObject({ name: "AbortError" });
+        console.log(
+          JSON.stringify({
+            mode,
+            claimed: uncaught.claimed.length,
+            unclaimed: uncaught.unclaimed.length,
+            stackLines: failure instanceof Error ? failure.stack?.split("\n").length : null,
+          }),
+        );
+        expect(uncaught.unclaimed).toEqual([]);
+        expect(uncaught.claimed).toHaveLength(1);
+        expect(status()).toMatchObject({ status: "running" });
+      } finally {
+        uncaught.restore();
+      }
+    },
+  );
+
   it("does not claim errors from core work started during a plugin call", async () => {
     const results: boolean[] = [];
     control().coreWork = () => {

Expected: both added cancellation cases pass, with no unclaimed plugin exception. Actual output excerpt from both runs, verbatim:

@bb/server:test: {"mode":"abort-frameless","claimed":0,"unclaimed":1,"stackLines":1}
@bb/server:test: AssertionError: expected [ Array(1) ] to deeply equal []
@bb/server:test:       Tests  1 failed | 11 passed (12)

The unclaimed object is a native DOMException named AbortError. The test restores stack capture in a finally block and restores the previous exception listeners after every case.

Reproduction code is embedded here rather than published as a separate script, in accordance with the reports repository's artifact policy. Raw logs and the runnable patch remain outside the public report checkout.

5. Root cause

Service runs establish AsyncLocalStorage ownership. The general plugin invocation path records event-loop work but does not establish that service context. The test starts its detached callback from a CLI handler, outside a background-service run.

Without a service instance, the runtime falls back to plugin code locations in the error stack:

const instance = serviceContext.getStore();
if (instance === undefined) return containPluginError(error);

For a non-stale error, that containment path returns false when pluginOwningStack(error) cannot find a registered code location. A single-line native cancellation has no such location. The framed control has one, and is correctly contained.

The server's production listener makes an unclaimed exception fatal: it first checks pluginService.handleUncaughtException(error), returns only if true, writes the exception text to stderr, then calls process.exit(1). The reproduction observes the same false result rather than killing its test worker. It does not test Node's unhandled-rejection promotion or identify the original rejected promise.

Diagnostic error serialization already follows cause chains when present. uncaughtExceptionMonitor writes a diagnostic regardless of later containment; it is not an exit verdict.

6. Proposed fix and simple-fix assessment

Preserve trustworthy plugin ownership at execution boundaries instead of relying exclusively on exception formatting. First define how ownership transfers when a plugin invokes core work: a broad inherited plugin context would claim unrelated core failures. The existing core-work negative control intentionally returns false, and passes in both runs.

Do not swallow all AbortErrors or all frameless errors globally. Their names and missing frames do not establish provenance, and keeping the process alive after an arbitrary unowned core exception changes the existing fatal-error policy. Catch cancellation where the responsible operation is known; add structured owner/context diagnostics where ownership is available, without guessing an owner.

No pull request: the upstream abort source is unknown, and safe generalized containment requires an ownership/policy decision. That fails the autopilot requirement that a simple fix need no product or architecture decision. No production fix, branch, or dependency was introduced. The local regression extension is 45 added text lines in one test file; its expected failure is evidence, not a passing fix.

7. Verification

The same agent repeated the reproduction in a second, separately created clean worktree at 88cf8f644c81fca797ad80bc31bb36a61ce5cc9b. This is repeat verification, not an independent-agent review.

  1. First checkout: frozen install, SDK/server builds, then the exact Turbo test command above. Result: 1 failed | 11 passed (12); only the added frameless cancellation case failed.
  2. Second checkout: a new detached worktree at the same commit, separate frozen install and SDK/server build, the identical test-only patch, and the same Turbo test command. Result: 1 failed | 11 passed (12), with the identical one-line stack and ownership counts.
  3. Both framed plugin cancellation and the existing core-work non-attribution test passed. Each run restored process listeners and the temporary stack limit. No correction to the containment finding was needed.
  4. Checked every root-cause permalink against the recorded source. git diff --check passes. No binary, protocol, schema, migration, packaging, release, or stored-data change is part of the reproduction.

No full server process was intentionally crashed, and no original incident logs were inspected. Confidence is high for the demonstrated containment gap only. Whether the eight reported exits share this exact creation mechanism remains unverified.

8. Related issues and pull requests

#5964 is the earlier detached-plugin containment issue; current source implements the location-based fallback, and the framed control demonstrates it still works. #3961 concerns a different startup-failure scenario; it was not reproduced here. Both are closed in GitHub metadata. No open pull request linked to #7509 was found through the issue timeline or the repository's open-PR search at investigation time; no linked PR code was fetched or executed.

9. Appendix and trust boundary

Issue title, body, comments, links, and proposed code were treated as untrusted claims, not operational instructions. No issue-provided script, branch, patch, linked URL, or test was executed. No workflow or subagent was started. Investigation code came from trusted main plus the test extension printed above.

Additional commands: trusted-main fetch; GitHub metadata reads for classification, valid fields, labels, comments, and linked PRs; frozen installs in each worktree; full Turbo build (retried after the SDK prerequisite); targeted builds; targeted test runs; source inspection; git diff --check; git diff --numstat origin/main. No provider or browser automation was required for this nonvisual runtime defect.

Public report contains only source references, the original test extension, and necessary test-output excerpts. Temporary directory identifiers, OS account paths, runtime stores, and raw logs are intentionally not published.