← reports

#6123 · Background tasks lose their terminal event on owner exit

BugPriority: MediumEffort: Mediumhost · threads · provider-claude-code GitHub issue · October 22, 2026 · base c7a10f237eb5b941dfaf79cbb65f246c66eeddcb

Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro.

1. TL;DR

A background task can outlive the foreground turn, so an idle thread may correctly have unfinished background work. When its provider process is subsequently shut down or killed, the runtime forgets that work without emitting the terminal background-task event. Two focused cases reproduce this on unmodified main production code using the repository's real scripted-echo bridge subprocess: graceful runtime shutdown and SIGKILL of that bridge worker. Both cases fail again in a second clean checkout of the same commit. This verifies the missing lifecycle event, not the reporter's particular machine, timer screenshot, cloud billing, or resume history.

2. Claims vs findings

ClaimStatusEvidence
Idle background work is not settled when its owner shuts down.VerifiedAfter runtime shutdown, the owner is dead, internal open-work tracking is empty, and zero terminal task events were emitted. Repeated twice.
Killing the bridge while the runtime remains alive loses settlement.VerifiedAfter the real bridge worker receives SIGKILL and its exit callback runs, the same event omission occurs. Repeated twice.
Daemon shutdown and machine suspension traverse these lifecycle paths.Source-supportedThe daemon shuts down runtimes before flushing its event sink; server suspension requests daemon shutdown and contains no task reconciliation at that point.
Claude SDK stream end does not settle translator tasks.Source-supported; not live-testedThe stream-end callback resolves pending session work and reports an error, with no background-task settlement call.
The specific overnight timer, active count, edit rejection, paid-machine behavior and missed resume reconciliation.UnverifiedNo access to production runtime data was used. No real machine was suspended and no Claude CLI was run.

3. Environment

4. Minimal reproduction

  1. Clone the public target repository and select the trusted base:
    git clone https://github.com/get-bb/bb.git bb-owner-exit-repro
    cd bb-owner-exit-repro
    git checkout --detach c7a10f237eb5b941dfaf79cbb65f246c66eeddcb
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --concurrency=1
  2. Save the complete test below to packages/agent-runtime/src/runtime.owner-exit-repro.test.ts. This is newly authored from trusted source fixtures, not copied from the issue or a pull request.
  3. Run:
    pnpm exec turbo run test --filter=@bb/agent-runtime --force -- runtime.owner-exit-repro.test.ts

    Expected: each started task receives one terminal item with status: interrupted and taskStatus: stopped after its owning process has stopped.

    Actual diagnostic lines, verbatim from both runs:

    {"exitMode":"shutdown","activeTurn":null,"runtimeHasOpenWork":false,"taskStartCount":1,"taskCompletionCount":0,"ownerAlive":false}
    {"exitMode":"bridge-kill","activeTurn":null,"runtimeHasOpenWork":false,"taskStartCount":1,"taskCompletionCount":0,"ownerAlive":false}
    AssertionError: expected [] to deep equally contain ObjectContaining{…}
    Tests  2 failed (2)

    The failure is the final terminal-event assertion, not startup, invalid input, process cleanup or timeout. The test first confirms idle status, a pending task, open-work tracking, and actual owner-process death. The recorded task-start count refers to the asserted started item, not a database query.

Complete regression reproduction test
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { expect, it } from "vitest";
import type { ThreadEvent } from "@bb/domain";
import { createAgentRuntime } from "./runtime.js";
import {
  createScriptedEchoLaunch,
  createScriptedEchoProcessLog,
  fullRuntimeOptions,
  scriptedEchoBridgeModulePath,
  waitForRuntimeState,
  waitForThreadTurnCompleted,
  withBridgeLaunch,
} from "./test/runtime-test-harness.js";
import { promptTextInput } from "./test/prompt-input.js";

it.each(["shutdown", "bridge-kill"] as const)(
  "settles an idle background task after %s",
  async (exitMode) => {
    const workspacePath = mkdtempSync(join(tmpdir(), "bb-owner-exit-repro-"));
    const processLog = createScriptedEchoProcessLog();
    const launch = createScriptedEchoLaunch();
    const events: ThreadEvent[] = [];
    let processExited = false;
    const runtime = withBridgeLaunch(
      createAgentRuntime({
        workspacePath,
        bridgeBundleDir: dirname(scriptedEchoBridgeModulePath),
        env: processLog.env,
        onEvent: (event) => events.push(event),
        onProcessExit: () => {
          processExited = true;
        },
      }),
      launch,
    );
    const threadId = "owner-exit-thread";
    try {
      await runtime.startThread({
        environmentId: "env-repro",
        projectId: "project-repro",
        providerId: "fake",
        threadId,
        options: fullRuntimeOptions,
      });
      await runtime.runTurn({
        clientRequestId: "creq_abcdefghjk",
        threadId,
        input: [promptTextInput({ text: "bg_task" })],
        options: fullRuntimeOptions,
      });
      await waitForThreadTurnCompleted({ events, threadId });
      expect(runtime.getActiveTurnId(threadId)).toBeNull();
      expect(runtime.hasOpenBackgroundWork()).toBe(true);
      const started = events.find(
        (event) =>
          event.type === "item/started" && event.item.type === "backgroundTask",
      );
      if (started?.type !== "item/started") {
        throw new Error("The real provider did not start a background task");
      }
      expect(started.item.status).toBe("pending");
      const taskPidEntry = processLog
        .read()
        .find((line) => line.startsWith("bg_task/open:"));
      const taskPid = Number(taskPidEntry?.split(":")[1]);
      expect(Number.isSafeInteger(taskPid) && taskPid > 0).toBe(true);
      if (exitMode === "shutdown") {
        await runtime.shutdown();
      } else {
        process.kill(taskPid, "SIGKILL");
        await waitForRuntimeState({
          label: "background task owner exit",
          predicate: () => processExited,
        });
      }
      expect(() => process.kill(taskPid, 0)).toThrow();
      expect(runtime.hasOpenBackgroundWork()).toBe(false);
      const completions = events.filter(
        (event) =>
          event.type === "item/backgroundTask/completed" ||
          (event.type === "item/completed" &&
            event.item.type === "backgroundTask"),
      );
      console.log(
        JSON.stringify({
          exitMode,
          activeTurn: runtime.getActiveTurnId(threadId),
          runtimeHasOpenWork: runtime.hasOpenBackgroundWork(),
          taskStartCount: 1,
          taskCompletionCount: completions.length,
          ownerAlive: false,
        }),
      );
      expect(completions).toContainEqual(
        expect.objectContaining({
          item: expect.objectContaining({
            id: started.item.id,
            status: "interrupted",
            taskStatus: "stopped",
          }),
        }),
      );
    } finally {
      await runtime.shutdown();
      rmSync(workspacePath, { recursive: true, force: true });
      rmSync(dirname(processLog.path), { recursive: true, force: true });
      rmSync(launch.dataDir, { recursive: true, force: true });
    }
  },
);

No screenshot is supplied: verification targets the event contract directly, not a rendered UI.

5. Root cause

The owner lifecycle and timeline lifecycle are disconnected. RuntimeBackgroundWorkState stores only task IDs and clears sets without producing events. Its state can therefore say there is no background work while the event stream still contains an unmatched start.

clear(): void {
  this.openTaskIdsByThreadId.clear();
}

clearThread(threadId: string): void {
  this.openTaskIdsByThreadId.delete(threadId);
}

The related Claude SDK stream-end callback has a comparable missing settlement operation. A resumed translator also ignores unknown task notifications. Those paths were inspected only, not executed in this report. Why the reporter's particular new daemon instance did not reconcile is not established by these tests.

6. Proposed fix

Retain the information needed to close each pending background task and emit its existing terminal event when its actual owner stops. Use the same settlement operation for runtime shutdown and provider detachment, preserve task identity and scope, and never emit a second completion for tasks already settled. Ensure daemon event flushing follows settlement. Handle a Claude CLI stream ending while its bridge remains alive separately, since the runtime has not observed bridge death in that case.

Do not treat a brief transport disconnect as proof that a process died; a machine that preserves memory can retain legitimate background work. Any server suspension fallback should require a reliable shutdown acknowledgement. Abrupt daemon loss and restart recovery require separate coverage.

7. Linked PR review

PR #6124 was open and ready against main when checked. Its metadata and diff were read as untrusted evidence only; its branch and tests were not checked out or run.

Static assessment: directionally addresses the verified root cause; not an approval. The diff changes packages/agent-runtime/src/runtime-background-work-state.ts to retain task payloads and construct terminal events, and changes runtime.ts's detach and shutdown owners to emit them. It also adds Claude stream-end settlement and a server suspension fallback gated on daemon shutdown acknowledgement. Those changes correspond to the observed omission rather than just hiding the timer.

No specific blocker is established by this trusted-base investigation. Remaining review requirements are behavior under duplicate/late completions, per-thread/process ownership, failed or memory-preserving suspension, and end-to-end event persistence. The linked PR spans multiple subsystems, so this report does not assert that it qualifies as a simple fix. No duplicate fix PR is opened because #6124 already links this issue.

8. Related issues

No duplicate was independently established. Other issue numbers mentioned in the report under investigation were not needed to reproduce this lifecycle failure; their causes are not adopted as findings here.

9. Verification

The same agent repeated the reproduction in a second clean temporary clone at the exact recorded commit, with its own frozen install and build artifacts. Before adding the newly authored test, the checkout was clean. Production files remain unchanged in both clones; only the reproduction test is untracked.

First checkout:
pnpm exec turbo run test --filter=@bb/agent-runtime -- runtime.owner-exit-repro.test.ts
Result: exit 1; 2 tests fail at the missing-terminal-event assertion.

Second clean checkout:
pnpm exec turbo run test --filter=@bb/agent-runtime --force -- runtime.owner-exit-repro.test.ts
Result: exit 1; 2 tests fail at the same assertion, with the same diagnostic counts.

Existing control suites, first checkout:
pnpm exec turbo run test --filter=@bb/agent-runtime -- runtime.recovery.test.ts runtime.process-lifecycle.test.ts
Test Files  2 passed (2)
Tests  60 passed (60)

The control suites include background-task completion during an ordinary provider turn and bridge restart deferral while background work is open. They show the new failure is specific to owner exit, not a generally broken bridge fixture. git diff --check passes in both clones. A fresh fetch found no later main change to the investigated runtime owners. No report conclusion changed after the second run.

10. Appendix and limits

Raw build/test logs and the authored test are retained outside the public report repository. The public report embeds the entire repeatable test and exact relevant output; it does not publish raw logs, local paths, temporary IDs, live account details or private runtime data. The report publisher rebuilds the site index from summary metadata.

The issue and linked PR were treated as untrusted claims. No issue commands, linked patches or PR code were executed. All executed repository code comes from trusted main plus the test authored here. The test's protocol IDs and scripted background-task request were selected from the trusted repository's schemas and fixtures. No dependencies, migrations, stored data, public protocol, or production sources were changed.

Classification rationale: this is unexpected behavior with an available stop/restart recovery path; the observed defect is not an unprompted crash or demonstrated data loss. Priority is Medium. A complete repair crosses runtime, provider and server lifecycle paths, so Effort is Medium. Labels are host, threads, provider-claude-code and, after publication, confirmed-repro.

Agent-generated investigation for SlopCop new-issue-autopilot.