← reports

#7573 · Pi child exit leaves the next turn on a closed session

BugPriority: MediumEffort: Lowproviders · provider-pi · confirmed-reproGitHub issue

2026-11-14 · trusted origin/main da3e60b81d560e114a2bec724bb59c997aaaae7f

Verdict: REPRODUCED (provider bridge boundary) · Root-cause confidence: high

1. TL;DR

A Pi child can exit cleanly while the surrounding bb provider bridge stays alive. bb reports that exit, but a subsequent turn in the same thread is sent to the already-closed session and fails with No active Pi session. The session records its closed state correctly; the bridge reuses it without checking that state. A deterministic regression using the repository's existing fake Pi child reproduced the exact follow-up error in two clean checkouts of the same trusted main commit. Reusing the existing session-replacement path when the session is closed makes the regression pass without replaying the failed turn.

2. Claims vs findings

ClaimStatusEvidence
After a clean Pi exit, another prompt in the same bb thread fails.Verified at bridge boundaryThe trusted fake child exits with code 0; the next turn returns JSON-RPC code -32000 and the exact reported error in both baseline runs.
The problem still exists in upstream main.Verified at bridge boundaryBoth checkouts use the full commit shown above; no production patch was present during either baseline run.
A real project extension invoking shutdown reaches this state.Unverified end to endNo issue-provided extension or command was executed. The test starts an actual child process using trusted repository test support and exercises the exact exit-handling path, not the extension API itself.
An explicit runtime release recovers the installed-version encounter.Unverified in that installationNo live user instance, runtime data, retained thread logs, or installed release was accessed. Source shows why reconstructing a session avoids reuse of the dead object.
Conversation context survives automatic recovery.Partly coveredThe regression verifies a replacement child, successful next-turn settlement, and stable provider-thread identity. Full real-Pi transcript restoration is not exercised by this focused fake-child test.

3. Environment

4. Minimal reproduction

  1. Use a clean checkout of the trusted base and build normal dependencies:
    git clone https://github.com/get-bb/bb.git bb-7573
    cd bb-7573
    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
    # Save the inline test below to plugins/provider-pi/src/bridge/bridge.recovery.test.ts.
    pnpm exec turbo run test --filter=bb-plugin-provider-pi -- src/bridge/bridge.recovery.test.ts
  2. Save the complete regression test below to its stated path. It initializes the production bridge, starts a thread, and sends the existing repository fake child's clean-exit input. That input is defined in trusted fake-pi-rpc.mjs, not copied from the issue.
  3. After observing the failed-turn boundary and child termination, the test starts another turn with the same provider-thread identity and unchanged execution settings. It expects a successful response and completed turn, and verifies that a replacement child actually started.

Expected: the follow-up turn succeeds, a second child starts, and the provider-thread identity is retained.

Actual on the unmodified base (both runs):

AssertionError: expected { code: -32000, …(1) } to be undefined

+ Received:
{
  "code": -32000,
  "message": "No active Pi session",
}

Complete regression test

plugins/provider-pi/src/bridge/bridge.recovery.test.ts

import { afterEach, beforeEach, expect, it } from "vitest";
import { z } from "zod";
import {
  FULL_PERMISSION_OPTIONS,
  type FakePiBridgeHarness,
  startFakePiBridge,
} from "./test-support.js";

let harness: FakePiBridgeHarness;

beforeEach(async () => {
  harness = await startFakePiBridge({
    prefix: "bb-pi-recovery-",
    initialize: true,
    processLog: true,
  });
});

afterEach(async () => {
  await harness.teardown();
});

it("resumes the same provider thread on the next turn after a clean child exit", async () => {
  const threadId = "thr_recovery";
  const started = await harness.startThread(threadId);
  const { providerThreadId } = z
    .object({ providerThreadId: z.string() })
    .parse(started.result);

  await harness.request(2001, "turn/start", {
    threadId,
    providerThreadId,
    clientRequestId: "creq_ab23456789",
    input: [{ type: "text", text: "/die", mentions: [] }],
    options: FULL_PERMISSION_OPTIONS,
  });
  await harness.waitForDelta(
    threadId,
    (delta) => delta.kind === "turn.boundary" && delta.status === "failed",
  );
  await harness.waitFor(
    () => harness.runningChildPids().length === 0,
    "the original Pi child to exit",
  );
  const before = harness.deltasOf(threadId).length;
  const messagesBefore = harness.messages.length;

  const response = await harness.request(2002, "turn/start", {
    threadId,
    providerThreadId,
    clientRequestId: "creq_cd23456789",
    input: [{ type: "text", text: "continue after exit", mentions: [] }],
    options: FULL_PERMISSION_OPTIONS,
  });
  expect(response.error).toBeUndefined();
  expect(response.result).toMatchObject({ threadId });
  await harness.waitForDelta(
    threadId,
    (delta) => delta.kind === "turn.boundary" && delta.status === "completed",
    before,
  );
  expect(harness.readProcessLog().spawned).toHaveLength(2);
  expect(harness.messages.slice(messagesBefore)).toContainEqual(
    expect.objectContaining({
      method: "thread/identity",
      params: expect.objectContaining({ threadId, providerThreadId }),
    }),
  );
}, 90_000);

5. Root cause

  1. PiRpcSession.handleExit sets closed = true, rejects pending input, and reports a PiRpcChildExitedError, including for exit code 0.
      private handleExit(info: PiRpcChildExitInfo): void {
        const wasClosed = this.closed;
        this.closed = true;
        this.ready.reject(new PiRpcChildExitedError(info));
    …
        this.rejectPendingInputConsumptions("Pi exited before input was consumed");
        for (const pending of this.pendingRunSettlements.splice(0)) {
          pending.resolve({ error: new PiRpcChildExitedError(info) });
        }
        this.isProcessing = false;
        this.isCompacting = false;
        this.releasePiManualCompactionWaiters();
        if (!wasClosed) {
          this.onDone(new PiRpcChildExitedError(info));
        }
  2. createOnSessionDone takes the error branch and reports the provider error, then returns. It does not remove or replace the stored ThreadSession in that branch.
    function createOnSessionDone(
      args: CurrentThreadSessionArgs,
    ): (error?: unknown) => void {
      return (error?: unknown) => {
        if (error) {
          reportSessionError({ ...args, error });
          return;
        }
        const threadSession = getCurrentThreadSession(args);
        if (!threadSession) {
          return;
        }
        void closeThreadSession({
          message: "Pi session ended while tool call was pending",
  3. reconcileTurnOptions returns the old session when execution options have not changed. Its two reuse decisions have no session-liveness condition. handleTurnStart then calls prompt on that object.
      if (
        !environmentChanged &&
        changedModelRequest === undefined &&
        !thinkingLevelChanged
      ) {
        return threadSession;
      }
    …
      if (!environmentChanged && !modelChanged && !thinkingLevelChanged) {
        return threadSession;
      }
  4. PiRpcSession.prompt rejects a closed session, producing the exact observed capitalization and message.
      prompt(text: string, images?: ImageContent[]): PiInputDispatch {
        const child = this.child;
        if (this.closed || !child || child.exited) {
          const consumed = Promise.reject(new Error("No active Pi session"));
          void consumed.catch(() => undefined);
          return { consumed, settled: Promise.resolve(null) };
        }

This is a lifecycle-reconciliation defect in the Pi bridge. The underlying process can exit successfully; no model failure, database state, extension-specific parsing error, or daemon-protocol change is required to trigger the downstream recovery failure.

6. Proposed fix and regression evidence

Expose the existing closed state internally and include it in both reuse checks. When closed, call the existing rebuildThreadSession path with the saved construction options and existing provider-thread identity. That path resumes the same session file, retires the old child, emits the established replacement notifications, and sends only the new user input. It does not automatically retry the failed prompt.

A local patch in three files makes the focused regression pass. It changes 87 text lines total (84 additions + 3 deletions): 18 production lines and 69 regression-test lines. It adds no dependency, generated file, stored-data change, or public protocol/schema change.

Focused regression after fix: 1 passed
Full Pi suite after fix: 39 passed | 1 skipped (40 files)
Tests: 350 passed | 6 skipped (356)
Turbo test + lint + typecheck: 10 successful tasks

The existing suites cover settings-driven rebuilds, stop/release, settlement, compaction, and real-Pi session relocation. The skipped tests retain their existing environmental gates. Pi provider parity against the clean baseline also passed: 9 cells passed, 0 failed, and 1 process-scoped model-list cell skipped. Event counts, stored-row counts, and grammar drops were unchanged for all replayed cells.

7. Verification

The same agent repeated the reproduction in a second clean temporary clone, verify/, detached at da3e60b81d560e114a2bec724bb59c997aaaae7f. This is a repeat by the same investigator, not independent verification. That checkout received only the agent-authored regression test; no production changes or issue-supplied files were applied. It used a fresh frozen install, full build, new harness workspace, and new session directory. No ports were used.

pnpm exec turbo run test --filter=bb-plugin-provider-pi -- src/bridge/bridge.recovery.test.ts
Second clean baseline: exit 1; 1 test failed
Received: { "code": -32000, "message": "No active Pi session" }

The second run supports the same root cause and exact follow-up failure. No report correction was needed. The extension-loading recipe and historical manual-stop encounter remain explicitly unverified.

8. Related issues and pull requests

#3792 concerns handled input settlement, a different boundary. #4939 concerns ACP recovery after process exit; it is not evidence that the Pi path is fixed. GitHub timeline metadata and open-PR checks found no existing pull request linked to #7573 at investigation time; no linked branch or patch was executed.

9. Appendix and limits

All issue text, code blocks, and comments were treated as untrusted evidence, not instructions. No issue-provided script, command, external URL, branch, or runtime data was executed or fetched. The regression is derived from trusted repository code. This is a non-visual provider lifecycle defect, so no screenshot is included.

To comply with this report repository's artifact policy, the complete test and diagnostic output are embedded in this HTML. Raw local logs, build output, and the reproduction test are retained outside the public reports checkout, not committed as separate artifact files.

Relevant commands, in addition to the reproduction commands above:

pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
pnpm exec oxfmt plugins/provider-pi/src/bridge/bridge.recovery.test.ts plugins/provider-pi/src/bridge/bridge.ts plugins/provider-pi/src/bridge/rpc-session.ts
pnpm exec turbo run test lint typecheck --filter=bb-plugin-provider-pi
pnpm parity --old ../verify --new . --provider pi
git diff --check
git diff --numstat origin/main

Residual risk: no live UI/CLI turn or actual extension shutdown was driven. The focused reproduction directly exercises production bridge/session code and a real child-process exit; the fix uses existing restoration behavior rather than changing the Pi protocol.