← reports

#5371 · ACP worker shutdown leaves agent processes running

BugPriority: MediumEffort: Lowproviders · host · provider-acpIssue

October 12, 2026 · trusted origin/main 4b12265e5fb82c01ea67e67cfe8d935533406937

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

The ACP bridge starts separate agent processes. Killing its worker with SIGTERM or SIGINT currently bypasses cleanup, so agents that keep working after stdin closes remain alive after their parent exits. Even the normal stdin-close cleanup misses agents used for model discovery because they are not registered thread sessions. A real worker and a small deterministic ACP fixture reproduce both paths without provider credentials. The same six-case regression fails in five cases in two clean trusted checkouts; with the contained fix, all six pass.

2. Claims vs findings

ClaimStatusEvidence
Worker signal termination leaves agent children running.VerifiedSession and discovery agent PIDs remain alive after worker exit for SIGTERM and SIGINT in both runs.
Normal close cleans registered sessions.VerifiedThe session/stdin case passes before the fix.
Normal close misses non-session discovery connections.VerifiedThe discovery/stdin case fails before the fix in both runs.
Connections can start during shutdown.Verified from code; fixed-path test passesNeither creation site has an admission guard. After the fix, a second discovery request sent while agent termination is pending produces no new agent.
The reported macOS provider process remains indefinitely under PID 1.Platform-specific detail unverifiedNo macOS or proprietary provider was available here. The Linux process-level reproduction verifies surviving children, not the reporter's exact machine history, parent PID or duration.

3. Environment

4. Minimal reproduction

  1. Clone the public repository and check out the exact trusted base:
    git clone https://github.com/get-bb/bb.git bb-5371
    cd bb-5371
    git checkout --detach 4b12265e5fb82c01ea67e67cfe8d935533406937
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the complete test below as packages/provider-bridge-acp/src/bridge/shutdown.test.ts.
  3. Run:
    pnpm exec turbo run test --filter=@bb/provider-bridge-acp -- --run src/bridge/shutdown.test.ts

Expected: all six cases pass; each worker exits only after its agent has stopped. Actual on unchanged main in both runs:

Tests  5 failed | 1 passed (6)
AssertionError: agent remains alive after bridge exits: expected true to be false

Failures: session/SIGTERM, session/SIGINT,
          discovery/SIGTERM, discovery/SIGINT, discovery/stdin
Passing control: session/stdin

Complete regression test

import { spawn } from "node:child_process";
import {
  existsSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
import { expect, it } from "vitest";

const workerEntry = fileURLToPath(
  new URL(
    "../../../provider-bridge-protocol/src/bridge-worker-entry.ts",
    import.meta.url,
  ),
);
const bridgeModule = fileURLToPath(new URL("./bridge.ts", import.meta.url));

function isAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

async function waitFor(predicate: () => boolean): Promise<void> {
  const deadline = Date.now() + 10_000;
  while (!predicate()) {
    if (Date.now() >= deadline)
      throw new Error("Timed out waiting for process state");
    await delay(25);
  }
}

const shutdowns = ["SIGTERM", "SIGINT", "stdin"] as const;
const connections = ["session", "discovery"] as const;

it.each(
  connections.flatMap((connection) =>
    shutdowns.map((shutdown) => ({ connection, shutdown })),
  ),
)(
  "reaps $connection agents on $shutdown and refuses new agents during shutdown",
  async ({ connection, shutdown }) => {
    const dir = mkdtempSync(join(tmpdir(), "bb-acp-shutdown-"));
    const readyFile = join(dir, "ready");
    const stoppingFile = join(dir, "stopping");
    const lateFile = join(dir, "late");
    const agentFile = join(dir, "agent.mjs");
    writeFileSync(
      agentFile,
      `
import { writeFileSync } from "node:fs";
import { createInterface } from "node:readline";
setInterval(() => {}, 1000);
process.on("SIGTERM", () => writeFileSync(process.env.STOPPING_FILE, "stopping"));
const input = createInterface({ input: process.stdin });
input.on("line", (line) => {
  const message = JSON.parse(line);
  if (message.method === "initialize") {
    writeFileSync(process.env.READY_FILE, String(process.pid));
    if (process.env.HANG_INITIALIZE === "1") return;
    process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { protocolVersion: 1 } }) + "\\n");
  }
  if (message.method === "session/new") {
    process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { sessionId: "shutdown-session" } }) + "\\n");
  }
});
`,
    );
    const worker = spawn(
      process.execPath,
      [
        "--conditions=source",
        "--import",
        import.meta.resolve("tsx"),
        workerEntry,
        bridgeModule,
        "provider-acp",
        dir,
      ],
      { stdio: ["pipe", "pipe", "pipe"] },
    );
    let stdout = "";
    let stderr = "";
    worker.stdout.setEncoding("utf8").on("data", (chunk: string) => {
      stdout += chunk;
    });
    worker.stderr.setEncoding("utf8").on("data", (chunk: string) => {
      stderr += chunk;
    });
    const exited = new Promise<void>((resolve, reject) => {
      worker.once("exit", () => resolve());
      worker.once("error", reject);
    });
    function providerOptions(ready: string, hang: boolean) {
      return {
        acpLaunchSpec: {
          displayName: "Shutdown fixture",
          command: process.execPath,
          args: [agentFile],
          env: {
            READY_FILE: ready,
            STOPPING_FILE: stoppingFile,
            HANG_INITIALIZE: hang ? "1" : "0",
          },
        },
      };
    }
    function send(method: string, params: object, id: number) {
      worker.stdin.write(
        JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n",
      );
    }
    try {
      if (connection === "session") {
        send(
          "thread/start",
          {
            threadId: "shutdown-thread",
            cwd: dir,
            instructionMode: "append",
            options: {
              permissionMode: "full",
              permissionScope: "full",
              approvalReviewer: null,
              permissionEscalation: null,
              providerOptions: providerOptions(readyFile, false),
            },
          },
          1,
        );
        await waitFor(() => stdout.includes('"id":1'));
        expect(stdout, stderr).not.toContain('"error"');
      } else {
        send(
          "model/list",
          { providerOptions: providerOptions(readyFile, true) },
          1,
        );
      }
      await waitFor(() => existsSync(readyFile));
      const pid = Number(readFileSync(readyFile, "utf8"));
      expect(isAlive(pid)).toBe(true);
      if (shutdown === "stdin") worker.stdin.end();
      else worker.kill(shutdown);
      await waitFor(
        () =>
          existsSync(stoppingFile) ||
          worker.exitCode !== null ||
          worker.signalCode !== null,
      );
      if (
        shutdown !== "stdin" &&
        worker.exitCode === null &&
        worker.signalCode === null
      ) {
        send(
          "model/list",
          { providerOptions: providerOptions(lateFile, true) },
          2,
        );
      }
      await Promise.race([
        exited,
        delay(10_000).then(() => {
          throw new Error("Bridge did not exit");
        }),
      ]);
      expect(isAlive(pid), "agent remains alive after bridge exits").toBe(
        false,
      );
      expect(existsSync(lateFile), "shutdown admitted a new agent").toBe(false);
      expect(worker.exitCode, stderr).toBe(0);
    } finally {
      worker.stdin.destroy();
      if (worker.exitCode === null && worker.signalCode === null)
        worker.kill("SIGKILL");
      await exited;
      for (const file of [readyFile, lateFile]) {
        if (existsSync(file)) {
          const pid = Number(readFileSync(file, "utf8"));
          if (isAlive(pid)) process.kill(pid, "SIGKILL");
        }
      }
      worker.stdout.destroy();
      worker.stderr.destroy();
      rmSync(dir, { recursive: true, force: true });
    }
  },
  30_000,
);

The fixture implements only initialization and session creation. Its lifetime deliberately remains independent of stdin EOF; otherwise a cooperative agent could mask the missing parent cleanup.

5. Root cause

The worker bootstrap installs signal handlers only when the bridge exports them. The ACP bridge export supplies only onClose. Node's default signal action therefore exits the worker without running agent cleanup.

export const experimental_providerBridge = experimental_defineProviderBridge({
  handleLine,
  onClose: () => {
    void stopAllSessions().finally(() => {
      process.exit(0);
    });
  },
});

stopAllSessions() enumerates only sessionsByBbThreadId. The model-discovery connection is separate and has an empty exit callback, so that cleanup misses it even on normal close. Both creation sites call the underlying connection factory directly, with no shutdown admission check.

The connection already exposes managed process termination. The missing responsibility is bridge-wide lifecycle ownership, not a new process-control mechanism.

6. Proposed fix

Track all ACP connections in one bridge-owned set, removing them on exit. Gate the shared factory once shutdown starts. Route EOF, SIGTERM and SIGINT into one idempotent shutdown routine. Release registered sessions and stop every tracked connection concurrently with all-settled handling, report cleanup failures to stderr, close the tool bridge, then exit. Reuse the existing managed termination/escalation implementation.

The implemented candidate changes only two files in the ACP subsystem, with 245 additions and 11 deletions: 256 changed text lines. It adds no dependency, generated file, stored-data change, or public protocol/schema change. It leaves thread stop behavior alone.

7. Related issues

No open linked pull request was present in GitHub cross-reference metadata or the issue-number PR search when investigated. Other timeout and unrelated process-leak reports are not required to reproduce this distinct cleanup defect.

8. Verification

The same agent repeated the test in a second clean temporary checkout at the exact recorded base, after a separate frozen install and full build. It uses fresh per-test directories and fixture processes; there are no ports. The repeated command is the Turbo command in section 4. Both runs produce the same five lifecycle failures and one passing session/EOF control. This is a second clean run, not independent-agent verification. No root-cause correction was necessary.

After the fix, all six regression cases pass, including termination escalation and the refusal of late discovery requests. The full relevant suites pass: 391 ACP tests passed, 4 skipped; 309 agent-runtime tests passed. Typecheck and lint pass for ACP, agent-runtime and bridge-protocol. Full build succeeded before reproduction; diff whitespace checks pass.

A broader bridge-protocol suite has eight failures in existing Claude permission-change cases. The identical eight failures also occur on the second checkout with unchanged production code. These unrelated failures were not modified; relevant ACP and runtime suites were run separately and passed.

9. Appendix

Before fix, first clean checkout: 5 failed, 1 passed (6).
Before fix, second clean checkout: 5 failed, 1 passed (6).
After fix, focused regression: 6 passed (6).
After fix, relevant suites: 391 + 309 tests passed; 4 ACP tests skipped.
Broader protocol suite: 8 Claude contract failures, also present on unchanged main.

pnpm exec turbo run test typecheck lint --filter=@bb/provider-bridge-acp --filter=@bb/agent-runtime
pnpm exec turbo run test typecheck lint --filter=@bb/provider-bridge-acp --filter=@bb/provider-bridge-protocol --filter=@bb/agent-runtime
pnpm exec turbo run test --filter=@bb/provider-bridge-protocol -- --run src/contract-tests/permission-changes.test.ts
git diff --check origin/main
git diff --numstat origin/main

Issue text and its proposed implementation were treated as untrusted claims. No issue-supplied command, patch, branch, binary or external link was executed or fetched. The regression and fix were derived from the trusted repository. No visual evidence is necessary for this process-lifecycle defect. Raw build/test logs remain private; complete repeatable evidence is inline.

> AGENT GENERATED