← reports

#5536 · Idle provider cleanup and repeated-resume checks

Bug · High priority · Medium effort · providers / host / provider-claude-code
GitHub issue · 2026-10-15 · base d722659a2c89fdf371fdb5d9f09fdd1ba3d0cba7

Verdict: NOT REPRODUCED · Root-cause confidence: low · Reproduction label: no-repro

1. TL;DR

The reported surviving Claude runtime and duplicate actions were not reproduced on the trusted main commit below. The actual agent-runtime reaper was exercised with real bridge-worker processes using the repository's scripted provider fixture; three completed-turn, reap, and resume cycles left each old worker dead before the next worker started. Separately, the actual Claude bridge's stop/drain and replacement-serialization tests passed with a controlled SDK boundary. Both checks were repeated by the same agent in a second clean checkout, without a workflow or another agent. These Linux fixture results do not establish that the reported macOS/real-Claude behavior is absent; its root cause remains unknown.

2. Claims vs findings

ClaimStatusEvidence and limitation
Successful reaping can leave the old bridge worker running.Not observed in the tested pathThe enhanced lifecycle test checks actual worker PIDs after each of three successful reaps, not only the process registry. All old workers were dead.
The next turn starts a second worker for the same provider session while the first survives.Not observed in the tested pathTwo resumes preserve providerThreadId; before each reap there is exactly one live fixture worker, and afterward all previously started workers are dead.
A real Claude runtime survives and processes duplicate notifications.UnverifiedNo real Claude CLI, macOS desktop instance, child-completion delivery, commit, or worker-spawn action was run. The SDK is mocked in bridge tests.
The same production thread was successfully reaped repeatedly over a day.UnverifiedNo production runtime data was accessed. The repeat reap after each release returns an empty result in the isolated test.

3. Environment

4. Minimal reproduction attempt

  1. Save the inline patch below as repeated-reap.diff. It extends the existing non-Codex lifecycle test rather than introducing an alternate production implementation.
  2. Run the following on the pinned trusted checkout. The patch changes only that test. Use a fresh checkout and new temporary test directories for the second run.
git clone https://github.com/get-bb/bb.git bb-5536
cd bb-5536
git checkout --detach d722659a2c89fdf371fdb5d9f09fdd1ba3d0cba7
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
git apply /path/to/downloaded/repeated-reap.diff
pnpm exec turbo run test --force --filter=@bb/agent-runtime -- src/runtime.process-lifecycle.test.ts
pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- src/bridge/__tests__/bridge.test.ts src/bridge/__tests__/sdk-session.test.ts src/bridge/bridge.conformance.test.ts -t 'holds thread stop open|waits for an in-flight close|graceful|canonical protocol suite'
git diff --check

Expected for correct cleanup: each completed turn can be reaped; the old worker is dead when reap returns; an immediate second reap returns nothing; resuming the same provider identity starts exactly one live replacement. The Claude stop response must wait for SDK completion and a same-thread replacement must wait for the in-flight close.

Actual: those assertions passed. The reported leak did not occur in these checks.

Test Files  1 passed (1)
     Tests  1 passed | 31 skipped (32)

Second checkout, full lifecycle file:
Test Files  1 passed (1)
     Tests  32 passed (32)

Claude focused checks, both checkouts:
Test Files  3 passed (3)
     Tests  5 passed | 95 skipped (100)

The test artifact, inline:

diff --git a/packages/agent-runtime/src/runtime.process-lifecycle.test.ts b/packages/agent-runtime/src/runtime.process-lifecycle.test.ts
index 829afe854..fb1ed16ba 100644
--- a/packages/agent-runtime/src/runtime.process-lifecycle.test.ts
+++ b/packages/agent-runtime/src/runtime.process-lifecycle.test.ts
@@ -1145,7 +1145,7 @@ describe("createAgentRuntime process lifecycle", () => {
     }
   });
 
-  it("reaps a restorable non-Codex session", async () => {
+  it("reaps a restorable non-Codex session across repeated resume cycles", async () => {
     const events: ThreadEvent[] = [];
     const processLog = createScriptedEchoProcessLog();
     const runtime = createScriptedEchoRuntime({
@@ -1156,7 +1156,7 @@ describe("createAgentRuntime process lifecycle", () => {
       },
       launch: {
         pluginId: "provider-claude-code",
-        scripted: { sessionRestorable: true },
+        scripted: { sessionRestorable: true, identifyProcess: true },
       },
     });
     try {
@@ -1167,19 +1167,69 @@ describe("createAgentRuntime process lifecycle", () => {
         providerId: "claude-code",
         options: fullRuntimeOptions,
       });
-      const result = await runtime.reapIdleProviderSessions({
-        idleForMs: 0,
-        nowMs: Date.now(),
-      });
-      expect(result.reapedSessions).toEqual([
-        expect.objectContaining({
-          providerId: "claude-code",
+      const initialSession = runtime.getProviderSession("t1");
+      if (!initialSession) {
+        throw new Error("Expected a restorable provider session");
+      }
+      for (let cycle = 0; cycle < 3; cycle += 1) {
+        const previousEventCount = events.length;
+        await runtime.runTurn({
+          clientRequestId: `creq_553622222${cycle + 2}`,
           threadId: "t1",
-        }),
-      ]);
-      expect(runtime.hasThread("t1")).toBe(false);
-      expect(runtime.listRunningProviders()).toEqual([]);
-      expect(stoppedProcessPids(processLog.read())).toHaveLength(1);
+          input: [promptTextInput({ text: `cycle ${cycle}` })],
+          options: fullRuntimeOptions,
+        });
+        await waitForRuntimeState({
+          events,
+          providerId: "claude-code",
+          runtime,
+          label: `completed cycle ${cycle}`,
+          predicate: () =>
+            events
+              .slice(previousEventCount)
+              .some(
+                (event) =>
+                  event.type === "turn/completed" && event.threadId === "t1",
+              ),
+        });
+        const started = processLog
+          .read()
+          .filter((line) => line.startsWith("spawn:"));
+        expect(started).toHaveLength(cycle + 1);
+        expect(stoppedProcessPids(processLog.read())).toHaveLength(cycle);
+        const result = await runtime.reapIdleProviderSessions({
+          idleForMs: 0,
+          nowMs: Date.now() + 60 * 60 * 1000,
+        });
+        expect(result.reapedSessions).toEqual([
+          expect.objectContaining({
+            providerId: "claude-code",
+            providerThreadId: initialSession.providerThreadId,
+            threadId: "t1",
+          }),
+        ]);
+        expect(runtime.hasThread("t1")).toBe(false);
+        expect(runtime.listRunningProviders()).toEqual([]);
+        expect(stoppedProcessPids(processLog.read())).toHaveLength(cycle + 1);
+        expect(
+          (
+            await runtime.reapIdleProviderSessions({
+              idleForMs: 0,
+              nowMs: Date.now() + 60 * 60 * 1000,
+            })
+          ).reapedSessions,
+        ).toEqual([]);
+        if (cycle < 2) {
+          await runtime.resumeThread({
+            environmentId: "env-1",
+            threadId: "t1",
+            projectId: "p1",
+            providerId: "claude-code",
+            providerThreadId: initialSession.providerThreadId,
+            options: fullRuntimeOptions,
+          });
+        }
+      }
     } finally {
       await runtime.shutdown();
     }

5. Root cause assessment

Not established; root-cause confidence: low. No failing lifecycle assertion supports a production fix. The current source already awaits the relevant shutdown path:

  1. The reaper awaits stopThread and excludes failed releases from its success list.
  2. stopThread awaits the bridge response, forgets the attachment, and releases an idle provider process.
  3. A bridge is shut down only when its attachment set becomes empty. A shared bridge can intentionally survive another thread's release; bridge survival by itself is not sufficient evidence of a leak. This does not explain the reported duplicated actions.
  4. Provider shutdown awaits process termination and finalization; unverified descendant cleanup produces a diagnostic.
  5. The Claude stop handler awaits closeThreadSession before replying; SDK shutdown interrupts and drains, with abort/close fallback on timeout.
  async function releaseIdleProviderProcess(
    proc: ProviderProcess,
  ): Promise<void> {
    if (proc.identity.threadIds.size > 0) {
      return;
    }
    await providerProcesses.shutdownProvider({
      processKey: proc.processKey,
      providerId: proc.providerId,
    });
  }
          const result = await sendCommand({
            proc,
            message: cmd,
            resultSchema: providerThreadStopResultSchema,
          });
          forgetThreadRuntimeStateForProviderState(proc.identity, threadId);
          await releaseIdleProviderProcess(proc);

The tested mechanism therefore does not support the hypothesis that main merely forgets a sole live worker and immediately reports success. It does not rule out macOS-specific process-tree behavior, detached descendants, real SDK behavior, shared-attachment interactions, or a production-version mismatch.

6. Proposed next experiment

No speculative production change is proposed. Repeat on an isolated macOS desktop instance using the exact daemon build and Claude SDK/CLI versions from the affected machine. Record sanitized bridge/CLI PID, PPID, PGID, and attachment ownership before/after each successful reap and resume, plus any descendant-cleanup diagnostic. Include one sole-thread case and one shared-bridge case. Correlate provider-session identity with actual attachment ownership rather than treating inherited process environment as proof of ownership. Only after a focused regression fails should termination or attachment handling be changed.

7. Verification

The same agent created a second clean detached worktree at d722659a2c89fdf371fdb5d9f09fdd1ba3d0cba7, checked its empty Git status, repeated the frozen install and 66-task build, applied only the published test patch, and ran both test commands with --force so Turbo could not substitute cached results. The full lifecycle file passed all 32 tests, including three reap/resume cycles; the five focused Claude checks also passed. Fresh test temporary directories were used; no ports or persistent app store were involved. This is a repeated check, not independent verification.

Corrections and limits: an early draft of the harness used invalid client-request IDs and failed boundary validation before exercising the scenario. Those IDs were corrected to the repository's allowed protocol alphabet before either final reproduction run. The final report makes no real-Claude/macOS claim and does not label the issue already fixed.

8. Related work

The issue timeline contained no linked pull request, and the open pull-request metadata search for issue 5536 returned none at investigation time. No linked branch was checked out or executed. No prior issue was established as the same root cause.

9. Appendix: checks and artifacts

The unmodified runtime lifecycle file initially passed 32/32 tests. An initial broader Claude run had 95 passes and five failures in installation-path discovery, Plan-preset permission setup, and live permission refresh. These failures occurred on unchanged production code; they were not treated as proof of the reported idle-reaper defect and were not fixed here. The stop/drain, close-serialization, and protocol checks were then selected for the two final runs.

Reproduction artifacts and full logs are retained locally, not published as separate files, in accordance with the reports repository's public-output policy. The complete test patch is inline above; relevant output excerpts follow.

runtime-baseline.log
@bb/agent-runtime:test:      ✓ does not wait for an already-exited provider during shutdown  465ms
@bb/agent-runtime:test:      ✓ waits for an exited provider to finalize before replacing it  506ms
@bb/agent-runtime:test:      ✓ starts a single replacement for concurrent callers after an exit  656ms
@bb/agent-runtime:test:      ✓ cuts off inherited provider output before starting a replacement  1367ms
@bb/agent-runtime:test:      ✓ treats shutdown process errors as expected without carrying state to replacement processes  759ms
@bb/agent-runtime:test:      ✓ gives a changed declaration its own bridge process at the same artifact hash  806ms
@bb/agent-runtime:test:      ✓ fails fast when the bridge artifact does not exist  341ms
@bb/agent-runtime:test: 
@bb/agent-runtime:test:  Test Files  1 passed (1)
@bb/agent-runtime:test:       Tests  32 passed (32)
@bb/agent-runtime:test:    Start at  03:17:47
@bb/agent-runtime:test:    Duration  11.92s (transform 776ms, setup 0ms, import 1.11s, tests 10.63s, environment 0ms)
@bb/agent-runtime:test: 

 Tasks:    6 successful, 6 total
Cached:    0 cached, 6 total
  Time:    14.529s 
claude-baseline.log
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/5]⎯
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test:  Test Files  1 failed | 2 passed (3)
bb-plugin-provider-claude-code:test:       Tests  5 failed | 95 passed (100)
bb-plugin-provider-claude-code:test:    Start at  03:18:02
bb-plugin-provider-claude-code:test:    Duration  3.77s (transform 1.70s, setup 0ms, import 2.88s, tests 2.80s, environment 0ms)
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test:  ELIFECYCLE  Test failed. See above for more details.
bb-plugin-provider-claude-code#test:  ERROR  command (<work>/base/plugins/provider-claude-code) /usr/local/bin/pnpm run test src/bridge/__tests__/bridge.test.ts src/bridge/__tests__/sdk-session.test.ts src/bridge/bridge.conformance.test.ts exited (1)

 Tasks:    5 successful, 6 total
Cached:    0 cached, 6 total
  Time:    6.167s 
Failed:    bb-plugin-provider-claude-code#test

 ERROR  run failed: command  exited (1)
repro-first.log
@bb/agent-runtime:test: > vitest run --config vitest.config.ts "src/runtime.process-lifecycle.test.ts" "-t" "reaps a restorable non-Codex session across repeated resume cycles"
@bb/agent-runtime:test: 
@bb/agent-runtime:test: 
@bb/agent-runtime:test:  RUN  v4.1.1 <work>/base/packages/agent-runtime
@bb/agent-runtime:test: 
@bb/agent-runtime:test:  ✓ |@bb/agent-runtime:isolated| src/runtime.process-lifecycle.test.ts (32 tests | 31 skipped) 443ms
@bb/agent-runtime:test:      ✓ reaps a restorable non-Codex session across repeated resume cycles  441ms
@bb/agent-runtime:test: 
@bb/agent-runtime:test:  Test Files  1 passed (1)
@bb/agent-runtime:test:       Tests  1 passed | 31 skipped (32)
@bb/agent-runtime:test:    Start at  03:19:56
@bb/agent-runtime:test:    Duration  1.69s (transform 746ms, setup 0ms, import 1.06s, tests 443ms, environment 0ms)
@bb/agent-runtime:test: 

 Tasks:    6 successful, 6 total
Cached:    3 cached, 6 total
  Time:    3.503s 
claude-focused-first.log
bb-plugin-provider-claude-code:test: claude-code bridge: Invalid params for thread/stop: params.threadId: Invalid input: expected string, received undefined; params.providerThreadId: Invalid input: expected string, received undefined; params.intent: Invalid option: expected one of "interrupt"|"release"; params.activeTurnId: Invalid input: expected string, received undefined
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: bb/conformance/alive-probe
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: bb/conformance/alive-probe
bb-plugin-provider-claude-code:test:  ✓ |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts (91 tests | 89 skipped) 30ms
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: thread/archive
bb-plugin-provider-claude-code:test:  ✓ |bb-plugin-provider-claude-code| src/bridge/bridge.conformance.test.ts (1 test) 312ms
bb-plugin-provider-claude-code:test:    ✓ passes the canonical protocol suite against the scripted claude session  311ms
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test:  Test Files  3 passed (3)
bb-plugin-provider-claude-code:test:       Tests  5 passed | 95 skipped (100)
bb-plugin-provider-claude-code:test:    Start at  03:19:12
bb-plugin-provider-claude-code:test:    Duration  1.54s (transform 1.73s, setup 0ms, import 2.81s, tests 349ms, environment 0ms)
bb-plugin-provider-claude-code:test: 

 Tasks:    6 successful, 6 total
Cached:    0 cached, 6 total
  Time:    3.976s 
repro-second.log
@bb/agent-runtime:test:      ✓ waits for an exited provider to finalize before replacing it  503ms
@bb/agent-runtime:test:      ✓ starts a single replacement for concurrent callers after an exit  653ms
@bb/agent-runtime:test:      ✓ cuts off inherited provider output before starting a replacement  1366ms
@bb/agent-runtime:test:      ✓ treats shutdown process errors as expected without carrying state to replacement processes  787ms
@bb/agent-runtime:test:      ✓ gives a changed declaration its own bridge process at the same artifact hash  802ms
@bb/agent-runtime:test:      ✓ reaps a restorable non-Codex session across repeated resume cycles  409ms
@bb/agent-runtime:test:      ✓ fails fast when the bridge artifact does not exist  329ms
@bb/agent-runtime:test: 
@bb/agent-runtime:test:  Test Files  1 passed (1)
@bb/agent-runtime:test:       Tests  32 passed (32)
@bb/agent-runtime:test:    Start at  03:20:17
@bb/agent-runtime:test:    Duration  12.21s (transform 784ms, setup 0ms, import 1.11s, tests 10.91s, environment 0ms)
@bb/agent-runtime:test: 

 Tasks:    6 successful, 6 total
Cached:    0 cached, 6 total
  Time:    14.8s 
claude-focused-second.log
bb-plugin-provider-claude-code:test: claude-code bridge: Invalid params for thread/stop: params.threadId: Invalid input: expected string, received undefined; params.providerThreadId: Invalid input: expected string, received undefined; params.intent: Invalid option: expected one of "interrupt"|"release"; params.activeTurnId: Invalid input: expected string, received undefined
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: bb/conformance/alive-probe
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: bb/conformance/alive-probe
bb-plugin-provider-claude-code:test:  ✓ |bb-plugin-provider-claude-code| src/bridge/__tests__/bridge.test.ts (91 tests | 89 skipped) 30ms
bb-plugin-provider-claude-code:test: claude-code bridge: Unknown method: thread/archive
bb-plugin-provider-claude-code:test:  ✓ |bb-plugin-provider-claude-code| src/bridge/bridge.conformance.test.ts (1 test) 316ms
bb-plugin-provider-claude-code:test:    ✓ passes the canonical protocol suite against the scripted claude session  315ms
bb-plugin-provider-claude-code:test: 
bb-plugin-provider-claude-code:test:  Test Files  3 passed (3)
bb-plugin-provider-claude-code:test:       Tests  5 passed | 95 skipped (100)
bb-plugin-provider-claude-code:test:    Start at  03:20:32
bb-plugin-provider-claude-code:test:    Duration  1.57s (transform 1.75s, setup 0ms, import 2.89s, tests 354ms, environment 0ms)
bb-plugin-provider-claude-code:test: 

 Tasks:    6 successful, 6 total
Cached:    0 cached, 6 total
  Time:    3.961s 
typecheck.log
@bb/plugin-build:generate: cache hit, replaying logs 1e2ff4b7374c17d4
@bb/templates:generate:templates: 
@bb/plugin-build:generate: 
@bb/plugin-build:generate: > @bb/plugin-build@0.0.1 generate <source-cache>
@bb/plugin-build:generate: > node ./scripts/generate-plugin-theme.mjs && node ./scripts/generate-runtime-export-manifest.mjs
@bb/plugin-build:generate: 
@bb/plugin-build:generate: wrote packages/plugin-build/src/generated/plugin-theme.generated.ts
@bb/plugin-build:generate: wrote <source-cache> (react@19.2.4)
@bb/agent-runtime:typecheck: cache miss, executing b5caeb90766d04a2
@bb/agent-runtime:typecheck: 
@bb/agent-runtime:typecheck: > @bb/agent-runtime@0.0.1 typecheck <work>/base/packages/agent-runtime
@bb/agent-runtime:typecheck: > tsc --noEmit
@bb/agent-runtime:typecheck: 

 Tasks:    4 successful, 4 total
Cached:    3 cached, 4 total
  Time:    3.203s 

Additional checks: pnpm exec turbo run typecheck --filter=@bb/agent-runtime and git diff --check. No production patch, dependency, database migration, public protocol change, or pull request was created.

Issue content was treated solely as untrusted claims. No supplied script, command, linked code, attachment, or external URL was executed or fetched.