Skip to content

Forking a thread whose source has already been compacted causes the fork to immediately re-compact (claude-code) #3185

Closed

Description

@IlyaM

Summary

Forking a thread on the claude-code provider whose source thread has already undergone context compaction causes the new forked thread to immediately trigger its own compaction on its very first turn, even when the source thread's actual token usage was low (~15-20% of the context window) at the moment of the fork. Expected: a fork should start with the source's already-compacted context; actual: it reloads the full, pre-compaction history and re-compacts right away.

Versions and environment

  • bb 0.42.1, run from source at commit dba32a469fd820ff6106715db0aaf6ed297d79a5
  • Linux
  • Provider: claude-code, CLI claude --version 2.1.260 (Claude Code), vendored @anthropic-ai/claude-agent-sdk ^0.3.245
  • Nothing unusual about the setup (standard worktree environment)

Steps to reproduce

  1. Have (or create) a claude-code thread that is long-running enough to have gone through at least one auto-compaction (thread/compacted event visible via bb thread log <id> --json --all).
  2. Fork it with a trivial prompt:
    bb thread fork <source-thread-id> --prompt "This is a test fork. Do nothing, just reply 'ok'."
  3. Wait for the fork to go idle: bb thread wait <new-thread-id> --status idle
  4. Inspect the new thread's event log: bb thread log <new-thread-id> --json --all

Reproduced directly: forked a long-running coordinator-style thread (4 prior compactions over its life) with a minimal prompt. Reproduced on the first attempt.

Expected vs actual

Expected: the forked thread starts from the source's current (already-compacted) context and does not immediately re-compact.

Actual: immediately after the fork's own client/thread/start event, before any real reply, the event log shows:

turn/started
turn/input/accepted
item/started   {"item": {"type": "contextCompaction", ...}}   x5
thread/compacted
item/started   {"item": {"type": "agentMessage", "text": "ok"}}

Five separate contextCompaction items fire back-to-back and a new thread/compacted event is recorded, all before the trivial "ok" reply. The thread/tokenUsage/updated event recorded immediately afterward shows usedTokens: 164914 out of modelContextWindow: 1000000 (~16%) — well under any reasonable compaction threshold, which rules out "the source was simply near its limit" as an explanation. The source thread's own usage right before the fork was similarly low: usedTokens: 198499 / 1000000 (~20%), recorded via thread/contextWindowUsage/updated in its event log at the last turn before the fork.

The same behavior was also observed when forking into a side-chat off the same source thread, not only with a full thread fork.

Evidence

  • Fork/checkpoint resolution: resolveThreadForkPoint and resolveCheckpointForkDescriptor — this always resolves a checkpoint at or after the source's last completed turn, i.e. after any compaction. This part is not the problem.
  • Provider-level fork call: handleThreadFork, specifically the call to the SDK's forkSession(sourceProviderThreadId, { upToMessageId }) at line 2493 and startAttachedResidentThreadSession(...) at line 2530.
  • Root cause traced into the vendored @anthropic-ai/[email protected] (minified sdk.mjs, not part of this repo): forkSession's implementation copies the full transcript into a new session file and assigns a new UUID to every message (s.set(oldUuid, newUuid)), but does this via a shallow object spread that leaves compactMetadata on any copied compact_boundary system message pointing at the old session's UUIDs (anchorUuid, headUuid, tailUuid, preservedMessages.uuids[]). The SDK's own context-reconstruction routine skips a compact_boundary if any of its referenced UUIDs are not found in the transcript being read — which is guaranteed after a fork, since all UUIDs were just remapped. The forked session therefore reconstructs its context by walking the raw, unsuppressed parent chain all the way back through history that was already compacted in the source, immediately exceeding the threshold and forcing a fresh compaction. Every real copied message in the new transcript does carry a forkedFrom.messageUuid field holding its exact old UUID, so the old→new UUID map is fully reconstructible after the fact purely from the forked session's own JSONL file.

Suggested fix

Not implemented — this is a report of the diagnosis only. Two possible directions, from most to least targeted:

  1. bb-side post-processing workaround: after forkSession returns (plugins/provider-claude-code/src/bridge/bridge.ts around line 2498), before the resident session starts (line 2530), read the newly written forked .jsonl transcript file, build an old→new UUID map from each entry's forkedFrom.messageUuid field, and rewrite the UUID references inside every compact_boundary entry's compactMetadata to point at the new UUIDs. This is additive, isolated to compact_boundary lines, and can be made best-effort/no-op if the expected fields aren't present (e.g. on a future SDK release that changes the on-disk format).
  2. Upstream fix in @anthropic-ai/claude-agent-sdk: forkSession should remap the UUIDs it references inside compactMetadata using the same map it already builds for uuid/parentUuid/logicalParentUuid, since it demonstrably has that map in scope at the point it emits each copied entry.

What was ruled out

  • Not a symptom of the source thread being near its context-window threshold: measured usage was ~16-20% of a 1,000,000-token window at the time of both the fork and the immediate re-compaction.
  • Not caused by bb selecting a stale/pre-compaction checkpoint: resolveThreadForkPoint/resolveCheckpointForkDescriptor resolve to the last completed turn, which is at or after the source's last compaction.
  • Searched open and closed issues in this repo for "fork" and "compaction"/"compact" — no existing issue describes this exact mechanism. Closest are unrelated symptoms (#1939 "Autocompact is thrashing (Claude)" is a different trigger — repeated compaction during normal growth, not on fork).
  • Checked anthropics/claude-code GitHub issues for related upstream reports: #48937 (forking a compacted session opens blank/invisible to listSessions) and #48270 (resume picks a stale branch on a forked/branching JSONL, closed as stale) both touch the same general area — compaction-boundary/session-tree bookkeeping breaking under fork/resume — but neither describes the specific UUID-remap-vs-compactMetadata mismatch found here.

Suggested priority and effort

Medium — hits any user who forks a long-running/previously-compacted thread (a common pattern for parallelizing work off a coordinator thread), causes a confusing delay and wasted tokens on every such fork, but has a functional workaround (do nothing; the fork still works, just recompacts). Effort for the bb-side workaround looks Low-Medium (isolated, additive file patch); effort for an upstream SDK fix is unknown since it is outside this repo.

AGENT GENERATED

Activity

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

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    Classified as Bug · Priority: Medium · Effort: Low · labels: providers, provider-claude-code, confirmed-repro.

    Report: https://get-bb.github.io/reports/issues/3185.html

    • Verdict: REPRODUCED
    • Root-cause confidence: high
    • Root cause: The locked Claude SDK regenerates transcript entry UUIDs during fork but leaves compact-boundary UUID references pointing to the source session, so reconstruction bypasses preserved-history relinking.
    • Reproduction label: confirmed-repro — the focused UUID-integrity regression failed in two clean checkouts at the trusted base.
    • Pull request: none — the first robust implementation plus its red-first regression totaled 327 text lines across 3 files, exceeding the strict fewer-than-300-line simple-fix limit, so it was stopped and not pushed.
  4. added a commit that references this issue on Nov 2, 2026
    9dec2ae
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