← reports

#6141 · Initialization probes leave atomic-save files after interrupted flushes

BugPriority: LowEffort: Lowprovidersprovider-claude-codeconfirmed-reproIssue #61412026-10-22 · base 937cca40b740b76b75411f109273117039bf28c8

Verdict: REPRODUCED · Root-cause confidence: high for the interrupted-save leak and missing bb cleanup. The exact shutdown actor is not established.

1. TL;DR

Model and command discovery start a short-lived Claude Code process. The real lockfile-pinned CLI can leave a temporary global-config save behind when shutdown interrupts a slow flush. The normal-I/O control leaves no such file. Both a first run and a second clean checkout reproduced this through bb's actual initialization probe, actual SDK, and actual native CLI, without credentials, a real bb instance, or user configuration. bb currently closes the query without tracking or cleaning that child's unfinished atomic saves.

A local PID-scoped cleanup candidate makes four focused regressions pass, but it is not pushed: the existing provider suite has five failures, also reproduced without the fix. The automation's requirement that relevant existing tests pass therefore prevents a pull request.

2. Claims vs findings

ClaimStatusEvidence
Discovery can leave global-config atomic-save files when storage stalls.VerifiedBoth real-process runs leave one PID-matched file after child exit with an interrupted 12-second fsync.
Normal I/O does not leak in the control.Verified for these runsThe normal case passes in both checkouts.
The probe closes as soon as initialization resolves.VerifiedThe trusted source's finally block aborts input and closes the query, without a process-exit cleanup.
Both model and slash-command discovery share the probe.VerifiedBoth trusted callers import and call the same helper.
Waiting for natural process exit still leaks, and a CLI-specific failsafe causes the exit.UnverifiedNo drain-mode or signal-level experiment was performed. This report does not distinguish SDK escalation from the CLI's own exit behavior.
The reporter's historical file counts and attribution identify the probe.UnverifiedThe reporter's machine and runtime data were not accessed. Our evidence is a fresh, isolated real-process reproduction.

3. Environment

4. Minimal reproduction

Run on Linux x64 with Node, pnpm and a C compiler. The helper interposes only the subprocess's fsync calls on config temporary files. It activates the delay after the actual probe returns, so initialization is not artificially slowed. The test waits until the native CLI PID no longer exists before checking the config directory. Nothing mocks the probe, SDK, CLI, or disk writes.

  1. Fetch the trusted repository and the two authored reproduction artifacts, then run the test:
    git clone https://github.com/get-bb/bb.git bb-6141
    cd bb-6141
    git checkout --detach 937cca40b740b76b75411f109273117039bf28c8
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
    curl -fsS https://get-bb.github.io/reports/issues/6141/repro/probe-delay.c -o plugins/provider-claude-code/src/bridge/probe-delay.c
    curl -fsS https://get-bb.github.io/reports/issues/6141/repro/probe-filesystem.repro.test.ts -o plugins/provider-claude-code/src/bridge/probe-filesystem.repro.test.ts
    pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- src/bridge/probe-filesystem.repro.test.ts
  2. Expected: both cases pass, with no temporary config save after child exit.
  3. Actual in the first checkout:
    {"mode":"delayed","modelCount":4,"exited":true,"events":["started pid=7589","started pid=7604","started pid=7606","started pid=7607","started pid=7610","started pid=7611","started pid=7613","started pid=7614","started pid=7612","delayed-fsync-enter pid=7589"],"leftovers":[".claude.json.tmp.7589.e604a363bd30"]}
  4. Actual in the second clean checkout:
    {"mode":"delayed","modelCount":4,"exited":true,"events":["started pid=8627","started pid=8642","started pid=8643","started pid=8644","started pid=8647","started pid=8648","started pid=8650","started pid=8651","started pid=8649","delayed-fsync-enter pid=8627"],"leftovers":[".claude.json.tmp.8627.8fc5dd256659"]}
Test Files  1 failed (1)
Tests       1 failed | 1 passed (2)

Expected: []
Received: one .claude.json.tmp.<exited-child-pid>.<12-hex> file

The JSON lines above are verbatim test output. The short expected/received block summarizes the assertion; the complete verbatim output is in first-run log and second-run log. Test exit code 1 is the expected regression signal, not a setup failure. The delayed-fsync entry is present, but its return event is absent: the process exited while the intercepted flush was still outstanding.

Test source

Download the complete test.

import { execFileSync } from "node:child_process";
import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { probeClaudeInitialization } from "./initialization-probe.js";

const require = createRequire(import.meta.url);
const sdkRequire = createRequire(require.resolve("@anthropic-ai/claude-agent-sdk"));
const executable = join(
  dirname(sdkRequire.resolve("@anthropic-ai/claude-agent-sdk-linux-x64/package.json")),
  "claude",
);
let scratch: string;
let preload: string;

beforeAll(async () => {
  scratch = await mkdtemp(join(tmpdir(), "bb-probe-6141-"));
  preload = join(scratch, "delay.so");
  execFileSync("cc", [
    "-shared",
    "-fPIC",
    "-o",
    preload,
    fileURLToPath(new URL("./probe-delay.c", import.meta.url)),
    "-ldl",
  ]);
});

afterAll(async () => {
  await rm(scratch, { recursive: true, force: true });
});

describe("initialization probe filesystem lifecycle", () => {
  it.each(["normal", "delayed"])(
    "leaves no config temporary files after the CLI exits (%s)",
    async (mode) => {
      const home = join(scratch, mode);
      await mkdir(home);
      const config = join(home, "config");
      await mkdir(config);
      const trace = join(home, "trace.txt");
      const gate = join(home, "delay-enabled");
      const initialization = await probeClaudeInitialization({
        cwd: home,
        env: {
          HOME: home,
          PATH: "/usr/bin:/bin",
          CLAUDE_CONFIG_DIR: config,
          BB_CLAUDE_CODE_EXECUTABLE: executable,
          CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
          LD_PRELOAD: preload,
          BB_PROBE_TRACE: trace,
          BB_PROBE_DELAY_GATE: gate,
        },
      });
      expect(initialization.models.length).toBeGreaterThan(0);
      if (mode === "delayed") await writeFile(gate, "enabled");
      const startup = await readFile(trace, "utf8");
      const match = /^started pid=(\d+)$/m.exec(startup);
      if (!match) throw new Error("Missing CLI startup evidence");
      const pid = Number(match[1]);
      await vi.waitFor(
        () => {
          expect(() => process.kill(pid, 0)).toThrow();
        },
        { timeout: 25_000, interval: 100 },
      );
      const events = await readFile(trace, "utf8");
      const leftovers = (await readdir(config)).filter((name) =>
        name.startsWith(".claude.json.tmp."),
      );
      console.log(
        JSON.stringify({ mode, modelCount: initialization.models.length, exited: true, events: events.trim().split("\n"), leftovers }),
      );
      if (mode === "delayed") expect(events).toContain("delayed-fsync-enter");
      expect(leftovers).toEqual([]);
    },
    40_000,
  );
});

Delay helper

Download the complete helper. It is compiled into the test's temporary directory, not installed globally.

#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

static void record_event(const char *event) {
  const char *trace = getenv("BB_PROBE_TRACE");
  if (!trace) return;
  int output = open(trace, O_WRONLY | O_CREAT | O_APPEND, 0600);
  if (output < 0) return;
  dprintf(output, "%s pid=%d\n", event, getpid());
  close(output);
}

__attribute__((constructor)) static void started(void) {
  record_event("started");
}

int fsync(int descriptor) {
  static int (*original_fsync)(int);
  if (!original_fsync) original_fsync = dlsym(RTLD_NEXT, "fsync");
  const char *gate = getenv("BB_PROBE_DELAY_GATE");
  char descriptor_path[64];
  char target[4096];
  snprintf(descriptor_path, sizeof(descriptor_path), "/proc/self/fd/%d", descriptor);
  ssize_t length = readlink(descriptor_path, target, sizeof(target) - 1);
  if (length > 0) {
    target[length] = 0;
    if (gate && access(gate, F_OK) == 0 && strstr(target, ".claude.json.tmp.")) {
      record_event("delayed-fsync-enter");
      struct timespec delay = {.tv_sec = 12};
      while (nanosleep(&delay, &delay) < 0) {}
      record_event("delayed-fsync-return");
    }
  }
  return original_fsync(descriptor);
}

5. Root cause

plugins/provider-claude-code/src/bridge/initialization-probe.ts:20 starts a query with a message-free input stream and persistSession: false. On successful initialization or initialization failure, its finally block immediately aborts the input and calls session.close():

try {
  return await session.initializationResult();
} catch (error) {
  throw translateMissingClaudeCliCatalogError(error);
} finally {
  promptEnd.abort();
  session.close();
}

persistSession: false does not prevent the CLI from saving global configuration. In both experiments the native CLI opened a PID-tagged config temporary file; its fsync remained blocked when the process exited, leaving the pre-rename file on disk. The probe has neither the child PID nor a post-exit filesystem cleanup. The SDK's installed transport source also has a finite graceful-close path, so closing a query is not a guarantee that every filesystem write completes. We did not prove whether SDK escalation or a CLI-internal exit caused the observed interruption.

plugins/provider-claude-code/src/bridge/model-list.ts:5 and plugins/provider-claude-code/src/bridge/provider-commands.ts:130 both use this helper. plugins/provider-claude-code/src/bridge/bridge.ts:814 memoizes those calls for two minutes; memoization reduces frequency but does not remove the vulnerable lifecycle.

6. Proposed fix and safety gate

Track only the process created by this probe using the existing SDK spawn hook. After that child exits, best-effort remove only regular files matching its exact PID and the known 12-hex atomic-save suffix, from the effective config directory. Preserve the committed config, other PIDs, nonmatching suffixes, and non-file entries. Do not sweep the user's config directory broadly, or treat a slower/gentler close as a sufficient guarantee.

A local candidate at trusted latest-main 2884950f17e76f78b28c64ccf4a2e9a7c74188a8 changed two files / 174 text lines (41 production additions, 133 test additions, zero deletions), with no dependency, schema, protocol or generated-file change. Its focused regression creates actual child processes and actual files while substituting the upstream shutdown fault at the SDK boundary. Cases cover explicit config, HOME fallback, a relative config directory, failed initialization, and preservation of other files/directories.

No PR: relevant existing tests did not pass, so the mandatory simple-fix gate failed. Unrelated failures were not modified. The native-CLI experiment was not rerun with the candidate after that stop condition.

7. Verification

The same agent repeated the reproduction in a second clean detached checkout at 937cca40b740b76b75411f109273117039bf28c8, with a fresh frozen install, successful build, and newly created temporary HOME/config directories. Only the two authored reproduction files were copied in; production source was unchanged. The exact test command was:

pnpm exec turbo run test --force --filter=bb-plugin-provider-claude-code -- src/bridge/probe-filesystem.repro.test.ts

--force disabled cached test execution. Result: the normal case passed, and the delayed case failed solely on the nonempty temporary-file list after process exit. The second CLI PID and random suffix differ from the first run. This is a repeat by the same investigator, not an independent review. No verdict correction was necessary. Neither run claims to verify the reporter's historical counts, the newer standalone CLI, or the no-signal drain experiment.

8. Related issues and PRs

No open pull request connected to #6141 was found in issue timeline metadata or the repository PR search at investigation time. No other bb issue was established as a duplicate. External links supplied by the issue were not fetched.

9. Appendix and trust boundary

The issue body and any linked material were treated only as untrusted claims. No issue-provided script, branch, patch, binary or external URL was executed or fetched. The experiment was authored from trusted repository code and used the repository's frozen native SDK dependency. The live bb instance, credentials and unrelated runtime files were not accessed.

The command history comprised read-only GitHub metadata/label queries; authorized missing-field classification writes; git fetch origin main; detached trusted checkouts; frozen installs; Turbo builds; the two Turbo reproduction runs; a latest-main local fix branch; focused before/after tests; the full provider test/lint/typecheck attempt; the unchanged-base bridge test; and diff hygiene/line-count checks. Publication only adds this issue's report and artifacts plus the report index/summary. No screenshots apply to this filesystem bug.

Base source line links were checked against the recorded commit. Artifacts contain test-created identifiers and temporary paths, not user data. The second-run result supports verified: true.

> AGENT GENERATED