Skip to content

claude-code initialization probe leaves ~/.claude.json.tmp.* files in $HOME when the disk is slow #6141

Open

Description

@seklow

Summary

On a loaded Linux host, 46 ~/.claude.json.tmp.<pid>.<hex> files (about 400 KB each) piled up in $HOME over three days. Their timing and content tie them to bb's claude-code initialization probe (model catalog / command listing). The probe starts a short-lived claude CLI and closes it right away. During shutdown the CLI starts another save of ~/.claude.json, and on a slow disk it exits before that save's rename, so the temp file is never removed (upstream: anthropics/claude-code#87677). I expected catalog refreshes to leave nothing behind in $HOME.

Versions and environment

  • bb 0.46.1, npm package bb-app installed under ~/.local/share/bb-app, running on Node 24.21.0. Code path checked on main at 93d1fc0c86a8476cb91411880a5d21e44b465908.
  • claude-code provider. Repro with Claude Code 2.1.308; the field leaks came from the 2.1.30x series, the last one on 2.1.308.
  • @anthropic-ai/claude-agent-sdk 0.3.245, the version pinned in pnpm-lock.yaml on main.
  • Debian 13, kernel 6.12, ext4 root at 95% full.

Steps to reproduce

This standalone script copies the query() options and teardown of initialization-probe.ts line for line and uses the same SDK version. I did not run bb itself under fault injection.

To simulate a slow disk, the script attaches strace to the spawned CLI just before teardown and delays its fsync/rename calls. Requirements:

  • Linux, the Claude Code CLI on PATH (tested 2.1.308), Node ≥ 18;
  • a strace with inject=...:delay_enter support (tested 6.13);
  • permission for strace to attach to a sibling process: kernel.yama.ptrace_scope must be 0, or run as root. Ubuntu defaults to 1, and the script prints strace's error if the attach fails.

No login is needed: the script uses an empty CLAUDE_CONFIG_DIR. I ran it under env -i HOME=$HOME PATH=..., with no Anthropic credentials in the environment, and it reported 5 models.

  1. mkdir probe-repro && cd probe-repro && echo '{"type":"module"}' > package.json && npm i @anthropic-ai/[email protected]
  2. Save as probe.mjs:
// Mirrors plugins/provider-claude-code/src/bridge/initialization-probe.ts (bb main).
// Usage: node probe.mjs <claude-cli> <empty-config-dir> <delay-ms> [drain]
// Right before teardown, strace is attached to the spawned CLI and delays every
// fsync and rename by <delay-ms>, simulating a slow disk while the CLI saves its config.
// With "drain", the query is drained until the CLI exits on its own before close().
import { spawn } from "node:child_process";
import { readdirSync, readFileSync } from "node:fs";
import { query } from "@anthropic-ai/claude-agent-sdk";

const [cli, configDir, delayMs, mode] = process.argv.slice(2);
const t0 = Date.now();
const log = (msg) => console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s ${msg}`);
const childPid = () =>
  readdirSync("/proc").find((d) => {
    try { return readFileSync(`/proc/${d}/stat`, "utf8").split(") ")[1].split(" ")[1] === String(process.pid); }
    catch { return false; }
  });

async function* promptWithoutMessages(signal) {
  if (signal.aborted) return;
  await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
}

const promptEnd = new AbortController();
const session = query({
  prompt: promptWithoutMessages(promptEnd.signal),
  options: {
    cwd: process.cwd(),
    env: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
    persistSession: false,
    settingSources: ["user", "project", "local"],
    pathToClaudeCodeExecutable: cli,
  },
});
try {
  log(`initializationResult: ${(await session.initializationResult()).models.length} models`);
  if (Number(delayMs) > 0) {
    const pid = childPid();
    spawn("strace", ["-f", "-qq", "-tt", "-o", "strace.log", "-e", "trace=fsync,rename,exit_group",
      "-e", `inject=fsync,rename:delay_enter=${Number(delayMs) * 1000}`, "-p", pid], { stdio: ["ignore", "ignore", "inherit"] });
    await new Promise((r) => setTimeout(r, 500));
  }
} finally {
  promptEnd.abort();
  if (mode === "drain") {
    for await (const _ of session) {}
    log("CLI exited on its own");
  }
  session.close();
  log("session.close()");
}
await new Promise((r) => setTimeout(r, 15000));
log(`config dir: ${readdirSync(configDir).join(", ")}`);
process.exit(0);
  1. Run it:
rm -rf cfg && mkdir cfg && node probe.mjs "$(command -v claude)" "$PWD/cfg" 10000          # bb's teardown
rm -rf cfg && mkdir cfg && node probe.mjs "$(command -v claude)" "$PWD/cfg" 10000 drain    # wait for exit, then close()
rm -rf cfg && mkdir cfg && node probe.mjs "$(command -v claude)" "$PWD/cfg" 0              # control

Results on this host:

delay teardown runs leaving a temp file
10 s close() (bb's teardown) 3 of 3
10 s drain, then close() 3 of 3
none close() or drain 0 of 3

In earlier runs that delayed only fsync: 0 of 2 leaked at 3 s, 1 of 2 at 6 s, and 3 of 4 at 10 s.

Expected vs actual

Expected: after the probe the config dir has no .claude.json.tmp.* files.

Actual, first command, verbatim. The dispatch_event line is strace noise from delay injection.

0.4s initializationResult: 5 models
0.9s session.close()
strace: dispatch_event: pid 502201 has delayed wait data set already
15.9s config dir: .claude.json, .claude.json.tmp.502197.aa124898f08e, .last-cleanup, backups, sessions

strace.log from the same run, filtered to the CLI's main thread (502197) and the thread doing the fsync (502201). The SIGTERM line is trimmed:

502201 02:24:01.809632 fsync(15 <unfinished ...>
502197 02:24:04.283915 --- SIGTERM {si_signo=SIGTERM, si_code=SI_USER, ...} ---
502197 02:24:08.790219 exit_group(0 <unfinished ...>
502201 02:24:08.790401 <... fsync resumed>) = ?

Second command (drain), verbatim:

0.4s initializationResult: 5 models
strace: dispatch_event: pid 503428 has delayed wait data set already
10.5s CLI exited on its own
10.5s session.close()
25.5s config dir: .claude.json, .claude.json.tmp.503361.d2b2edba5a11, .last-cleanup, backups, sessions

Evidence

Exit timing, from strace.log of all 6 leaking runs above:

  • The CLI calls exit_group(0) 6.97–6.98 s after the shutdown save's fsync starts, whether or not it received SIGTERM. In the close() runs that was 4.5 s after SIGTERM, before the SDK's SIGKILL; in the drain runs there was no signal at all.
  • No rename follows the delayed fsync.
  • This looks like Claude Code's shutdown failsafe forcing the exit (armShutdownFailsafe → forceExit in the 2.1.308 bundle). That is inferred from the fixed timing; I did not trace the shutdown code.
  • So a gentler teardown in bb does not avoid the leak by itself.

How often the probe saves. In one traced session against an empty config dir, the CLI did 9 atomic saves of .claude.json (temp file, then fsync, then rename). The last one opened its temp file about 0.1 s after close().

Field data from one host (bb 0.46.1), Oct 20–22. Method: I matched file mtimes against "Provider model catalog refresh settled" lines with providerId: "claude-code" in ~/.bb/logs/server*.log. That gives 223 refreshes logged from Oct 18 07:54 to Oct 22 22:16.

  • Of the 46 temp files, 38 fall within ±10 s of a refresh settling and 45 within ±35 s. A random instant in the same window falls within ±10 s of a refresh 1.0% of the time (Monte Carlo, 20k samples).

  • Refreshes next to a leak were slow. Median durationMs is 15.6 s within ±10 s and 18.7 s within ±35 s, against 4.3 s over all 223. 9 of the 45 matches ended with outcome: "timeout".

  • By day:

    day claude-code refreshes timeouts median duration leaked files
    Oct 20 80 18 13.2 s 36
    Oct 21 63 2 1.5 s 9 (all before a reboot at 06:46)
    Oct 22 64 7 1.5 s 1
  • 7 of the 46 files contained a clientDataCacheSlots entry with entrypoint sdk-ts, stamped within ±2.5 s of the file's mtime. bb thread sessions run with CLAUDE_CODE_ENTRYPOINT=cli, so sdk-ts points to the probe. The other 39 are attributed by timing alone.

  • 45 of the 46 files were complete copies of about 400 KB. One was cut off at exactly 128 KiB, so that process died during the write itself.

Example log lines (hostId removed). The first was the refresh nearest to one leak, which settled 32.7 s before it; the second settled 6.5 s before the Oct 22 12:51:26 leak:

{"level":40,"time":1792468206789,"component":"server","providerId":"claude-code","scope":"host","durationMs":30000,"outcome":"timeout","errorCode":"command_timeout","errorMessage":"Timed out waiting for command result","errorStatus":504,"changed":false,"msg":"Provider model catalog refresh settled"}
{"level":30,"time":1792662679982,"component":"server","providerId":"claude-code","scope":"host","durationMs":22447,"outcome":"success","modelCount":16,"changed":false,"msg":"Provider model catalog refresh settled"}

Code:

Possible fixes, all aimed at probeClaudeInitialization as a whole:

  1. Spawn the CLI less often. For example, persist the catalog and command list across provider-runtime restarts, keyed by CLI version, or read them from a session that is already running.
  2. Until #87677 is fixed upstream, clean up after the probe. With a custom spawnClaudeCodeProcess, bb owns the ChildProcess and its pid. After it exits, bb can remove .claude.json.tmp.<that pid>.<12 hex> from the directory holding .claude.json ($CLAUDE_CONFIG_DIR if set, else $HOME).
  3. Waiting for the CLI to exit before close() is not enough on its own; see the drain runs.

What you ruled out

Suggested priority and effort (optional)

Low: the files are harmless, about 400 KB each, but unbounded on loaded hosts and they land in $HOME. Workaround: delete .claude.json.tmp.* files whose PID is dead. Fix 2 is probably low effort.

Checks

  • I reproduced this on the latest release or on main, or I say above that I could not.
  • I searched open and closed issues for the same problem.
  • If an agent wrote this, the body ends with > AGENT GENERATED and links the thread or report.

Investigated by Claude Code in a bb thread on the reporter's machine. That thread is local and cannot be shared, so this issue is the complete report: the script and the evidence above.

AGENT GENERATED

Activity

  1. added theissue type on Oct 22, 2026
  2. added
    providers
    provider-claude-code
    confirmed-repro
    on Oct 22, 2026
  3. bb-slop-cop commented on Oct 22, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Low priority · Low effort; labels: providers, provider-claude-code, confirmed-repro.
    • REPRODUCED · high confidence using the real probe, SDK, and pinned native CLI in two clean trusted checkouts: normal-I/O controls pass; delayed flushes leave a PID-tagged file after process exit.
    • Reproduction and root-cause report, including repeatable tests and both run logs.
    • Root cause: shutdown interrupts a CLI config flush before its atomic save completes; the probe has no post-exit cleanup. The exact shutdown actor remains unverified.
    • No PR: a local cleanup candidate passes all four new regressions, but five existing provider tests also fail on unchanged main. The required passing-suite gate is unmet, so the fix remains unpushed.
  4. seklow commented on Oct 22, 2026

    @seklow
    Author

    To be explicit about why this is filed here: the root cause is upstream.

    AGENT GENERATED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-reproprovider-claude-codeproviders

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions