#6781 · Whole-transcript allocations hide fork failures
Bug High priority Effort: Low providers provider-claude-code confirmed-repro
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
A Claude Code transcript can exist on disk yet produce a misleading “Session not found” error when bb tries to fork it. The adapter reads the entire JSONL file into one JavaScript string, which fails at Node's maximum string length, then suppresses the read error and reports the session as absent. Both a checkpoint fork and a full fork fail on a synthetic 536,981,786-byte ASCII transcript; both succeed on the small control. A second clean trusted checkout reproduces the same results. The output writer also aggregates the fork into one string, so correcting only the reader would leave another size-limited allocation.
2. Claims vs findings
| Claim | Finding | Evidence / limit |
|---|---|---|
| Large existing transcripts become “not found”. | Verified | The fixture exists, stat matches its written size, direct UTF-8 read throws RangeError, and the real fork function reports absence in both runs. |
| Both edit checkpoints and ordinary forks are affected. | Verified at provider boundary | Both upToMessageId set to the first message and undefined fail. The bridge passes its source checkpoint to this function. No desktop click or HTTP endpoint was exercised. |
| Small transcripts work. | Verified for controls | Four-record controls succeed in both modes; checkpoint excludes later content while full fork preserves it. |
| The reader and writer both have whole-string limits. | Verified source + runtime primitive | Actual readFile fails; source writer joins all serialized entries; an equivalent oversized Array.join throws RangeError. The production writer is not reached by the failing large-input call. |
| The change originated with #6358. | Verified introduction, not release timing | git history introduces this adapter at commit 61b2fe770. No old desktop or earlier SDK was run. |
| Reported macOS failures, thread counts, version-specific behavior, and no workaround. | Unverified | No real transcripts or runtime data were read. Reproduction uses Linux and Node 22, not the reported desktop environment. |
3. Environment
- Target: public get-bb/bb; full base
916d684ac23d0b0de82c09cfc7553a50287d2188, fetched from trusted origin/main. A final fetch found no newer change to this adapter. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; installed @anthropic-ai/claude-agent-sdk 0.3.245.
buffer.constants.MAX_STRING_LENGTH = 536870888. This is a character limit, not a universal 512 MiB file-size limit: ASCII makes the byte/character counts equal in this reproduction.- Each checkout received its own frozen install and
pnpm exec turbo run build --filter=bb-plugin-provider-claude-code. The plugin has no build script; Turbo completed its four upstream generation tasks. No full application build was claimed. - No live app, provider login, session turn, network-facing instance, port, or real config directory was used. The harness creates and removes a fresh OS temporary config directory. Allow about 1.1 GB of disk and enough heap for a successful fixed full fork; the failing baseline uses less output disk.
4. Minimal reproduction
- Prepare the trusted base and frozen dependencies:
git clone --single-branch --branch main https://github.com/get-bb/bb.git /tmp/bb-repro-a cd /tmp/bb-repro-a git checkout --detach 916d684ac23d0b0de82c09cfc7553a50287d2188 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=bb-plugin-provider-claude-code
- Save the complete source below as
plugins/provider-claude-code/slopcop-6781-repro.mts. It was authored from trusted repository code, not copied from the issue. - Run the real adapter and SDK, without mocks:
node --experimental-strip-types --no-warnings plugins/provider-claude-code/slopcop-6781-repro.mts
Expected: all four fork operations succeed, preserve the source, and the process exits 0. Actual: small controls pass, large forks fail, and the final regression assertion exits 1. The source file's size is unchanged. Exact shared output prefix (the synthetic source UUID is normalized by the harness itself):
Node v22.19.0; MAX_STRING_LENGTH=536870888 small fixture: 1250 ASCII bytes; 4 records small checkpoint: PASS small full: PASS large fixture: 536981786 ASCII bytes; 2046 records direct UTF-8 read: RangeError: Invalid string length large checkpoint: Error: Session <source-session> not found large full: Error: Session <source-session> not found whole-output join above MAX_STRING_LENGTH: RangeError confirmed (primitive-only probe) node:internal/modules/run_main:123 AssertionError [ERR_ASSERTION]: Existing transcripts must fork in both modes exit status: 1
The last two lines identify the failing assertion and exit status; the ordinary Node assertion stack is omitted to avoid publishing machine paths.
Complete reproduction / regression source
import assert from "node:assert/strict";
import { constants } from "node:buffer";
import { randomUUID } from "node:crypto";
import { createWriteStream } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import { forkClaudeSession } from "./src/bridge/session-fork.ts";
const configDirectory = await mkdtemp(join(tmpdir(), "fork-boundary-"));
const projectDirectory = join(configDirectory, "projects", "synthetic-project");
const failures: string[] = [];
await mkdir(projectDirectory, { recursive: true });
async function exercise(large: boolean): Promise<void> {
const sourceSessionId = randomUUID();
const firstMessageId = randomUUID();
const sourcePath = join(projectDirectory, `${sourceSessionId}.jsonl`);
const payload = large ? "p".repeat(256 * 1024) : "small-control";
let bytes = 0;
let count = 0;
function* records(): Generator<string> {
let parentUuid: string | null = null;
while (large ? bytes <= constants.MAX_STRING_LENGTH : count < 4) {
const uuid = count === 0 ? firstMessageId : randomUUID();
const role = count % 2 === 0 ? "user" : "assistant";
const record = JSON.stringify({
type: role,
uuid,
parentUuid,
sessionId: sourceSessionId,
cwd: "/tmp/synthetic-project",
timestamp: new Date(1_700_000_000_000 + count * 1000).toISOString(),
isSidechain: false,
message: { role, content: `entry-${count}: ${payload}` },
}) + "\n";
bytes += Buffer.byteLength(record);
count += 1;
parentUuid = uuid;
yield record;
}
}
await pipeline(records(), createWriteStream(sourcePath, { flags: "wx" }));
const before = await stat(sourcePath);
assert.equal(before.size, bytes);
console.log(`${large ? "large" : "small"} fixture: ${bytes} ASCII bytes; ${count} records`);
if (large) {
try {
await readFile(sourcePath, "utf8");
console.log("direct UTF-8 read: unexpectedly succeeded");
} catch (error) {
assert.ok(error instanceof Error);
console.log(`direct UTF-8 read: ${error.name}: ${error.message}`);
}
}
for (const mode of ["checkpoint", "full"]) {
const label = `${large ? "large" : "small"} ${mode}`;
try {
const forkedSessionId = await forkClaudeSession({
configDirectory,
sourceSessionId,
upToMessageId: mode === "checkpoint" ? firstMessageId : undefined,
});
const forkPath = join(projectDirectory, `${forkedSessionId}.jsonl`);
assert.notEqual(forkedSessionId, sourceSessionId);
assert.ok((await stat(forkPath)).size > 0);
if (!large) {
const forkText = await readFile(forkPath, "utf8");
assert.ok(forkText.includes("entry-0:"));
assert.equal(forkText.includes("entry-3:"), mode === "full");
}
await rm(forkPath);
console.log(`${label}: PASS`);
} catch (error) {
assert.ok(error instanceof Error);
console.log(`${label}: ${error.name}: ${error.message.replaceAll(sourceSessionId, "<source-session>")}`);
failures.push(label);
}
}
assert.equal((await stat(sourcePath)).size, before.size);
await rm(sourcePath);
}
try {
console.log(`Node ${process.version}; MAX_STRING_LENGTH=${constants.MAX_STRING_LENGTH}`);
await exercise(false);
await exercise(true);
const chunk = "p".repeat(256 * 1024);
const chunks = Array(Math.ceil(constants.MAX_STRING_LENGTH / chunk.length) + 1).fill(chunk);
assert.throws(() => chunks.join(""), RangeError);
console.log("whole-output join above MAX_STRING_LENGTH: RangeError confirmed (primitive-only probe)");
assert.deepEqual(failures, [], "Existing transcripts must fork in both modes");
} finally {
await rm(configDirectory, { recursive: true, force: true });
}
This assertion is intentionally red on the trusted baseline. It also serves as an observable-success regression check for a future repair; no production-only test seam, database mock, or dependency is required. Raw logs and the script are retained outside this public repository; its policy permits inline evidence but forbids committed reproduction directories.
5. Root cause
forkClaudeSession, lines 20–30, supplies bb's custom project transcript store to the real SDK. load, lines 38–47, resolves and parses the source before the SDK can select its checkpoint. Therefore even a checkpoint at the first small message requires reading the entire oversized file.
findTranscript, lines 78–93, calls readFile(path, "utf8") inside a catch-all that continues to the next project. Node raises RangeError: Invalid string length for the synthetic ASCII file above its string cap. The adapter swallows that error, finds no other source, returns null, and the SDK reports the existing session as absent.
try {
contents = await readFile(
join(projectDirectory, `${sessionId}.jsonl`),
"utf8",
);
} catch {
continue;
}
append, lines 49–59, creates the entire output string before writing:
entries.map((entry) => `${JSON.stringify(entry)}
`).join("")
A large full fork retains that second limit even with an incremental reader. The primitive-only join probe corroborates this allocation hazard, not a completed execution of the unreachable production writer. The SDK contract also still loads entries into an array; streaming I/O removes the single-string ceiling, not all memory limits.
The bridge caller passes sourceProviderCheckpointId as upToMessageId and forwards the caught error. The introducing commit added the custom store. No SDK-only upgrade can remove the whole-string operations in this bb adapter.
6. Proposed fix
Read and parse JSONL incrementally and serialize/write individual entries with backpressure instead of concatenating the complete transcript. Preserve source-project selection, checkpoint behavior, UTF-8 correctness, exclusive creation, and private file permissions. Ignore genuinely missing candidate files but surface unexpected read failures with their cause. Test a real above-cap file in both modes, checkpoint cut-off, and output/error cleanup. No public protocol, migration, or product decision appears necessary; entry-array memory use remains a separate limit.
No new fix branch or pull request: GitHub metadata shows open PR #6782 already closes #6781, so the autopilot duplicate-PR guard stops fix work.
7. PR review — #6782 (static only)
Open, ready PR; reviewed head 7b33e8cc05cb3675fec66abb27e6fae7a9194da9. Its diff uses per-line reading and streamed serialization, addressing both verified whole-string allocations. It also moves parse/read errors outside the missing-file catch, preserving those causes. No linked branch, patch, or test was checked out or run.
Coverage limitation (medium): src/bridge/session-fork.test.ts:16 forces readFile to reject while using a small checkpoint fixture. It checks avoiding that reader API, but does not exercise a real above-cap input or large full output; a reader-only change could satisfy that fixture while retaining the output join bug. Use the real-boundary harness above to validate the complete repair. Verdict: the static approach addresses the observed causes; runtime correctness of the PR is not verified here.
8. Related issues
The trusted introducing commit references #6325, a config-directory fork problem. This reproduction explicitly supplies a fresh config directory, proves the source exists, and isolates size as the difference. PR #6782 also links #3185; compaction after a successful fork was not reproduced or assessed. Neither related number changes this direct failing read.
9. Verification — second clean checkout
The same agent repeated the reproduction, not an independent reviewer. A second checkout was cloned from committed objects with git clone --shared --no-checkout, pointed at trusted get-bb/bb origin, and detached at 916d684ac23d0b0de82c09cfc7553a50287d2188. Its initial git status --porcelain was empty. It received its own frozen install, the same Turbo upstream generation command, the identical authored harness, and a new temporary config directory.
git checkout --detach 916d684ac23d0b0de82c09cfc7553a50287d2188 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=bb-plugin-provider-claude-code node --experimental-strip-types --no-warnings plugins/provider-claude-code/slopcop-6781-repro.mts
Result: identical 1,250-byte control and 536,981,786-byte large fixture, both control forks pass, direct read raises RangeError, both large forks report absence, regression assertion exits 1. The only log difference is the expected checkout path in Node's stack. No finding required correction. Both temporary config directories are removed by the harness. No service was started.
10. Appendix / scope
- Investigation commands: repository visibility and issue properties via GitHub API; trusted clone/fetch; source/caller/history inspection; metadata and static diff read for #6782; two frozen installs and scoped Turbo generation runs; two executions of the included harness; file-size and checkpoint-content assertions.
- Untrusted-data handling: issue text and PR diffs were read only as claims. No issue-supplied script, command, branch, patch, external URL, or real transcript was executed or fetched. No instructions from issue data were followed.
- Classification: Bug / High / Low; providers + provider-claude-code. The size-limited affected population is narrow, but every edit/fork operation in that population is blocked. No data-loss claim is made.
- Limits: no desktop or HTTP end-to-end run, no real provider transcript, no Node 24-specific verification, and no linked-PR test execution. Existing full test suites were not rerun because no production fix was made.