Skip to content

fix(thread): keep the main thread when a newer Claude Code resumes it - #711

Merged
amiddavid merged 1 commit into
mainfrom
fix/thread-resume-id
Oct 25, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/thread-resume-id

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

After a resume, the main conversation now keeps its thread id. The cause was a Claude Code upgrade between quit and resume. Version 2.1.309 adds one key to an old message, and the thread fingerprint counted that key.

Fixes #708.

What we found

Live session 327ef650, from Claude Code's own request log (message hashes and key names only):

  • The user quit on 2.1.303 and resumed on 2.1.309. The resume at 11:35:00 started a new process.
  • The resumed request (11:37:24) repeated all 1,877 earlier messages and added 3.
  • Only message 1 changed. It is a system-role message. Its content is the same, byte for byte. 2.1.309 added "output_config":{"effort":"medium"} to it.
  • The provider's cache read 813,853 tokens: the whole old prefix. So the provider does not match on this key.
  • The tracker hashes every message key except cache_control. So message 1 hashed differently, no thread matched, and the tracker gave the request a new id, p:7754bf728db9.
  • The rewritten-tail rule did not help. It allows a change in the last 1 or 2 messages, and this change was at message 1.

What changed

  • internal/thread: the fingerprint leaves out a message's own output_config key, as it already leaves out cache_control.
  • The rule applies to the message object only. The same key inside a tool input or a content block still counts.
  • The Fingerprint doc comment says what is left out and why.

How it was tested

New test TestAResumeByANewerClaudeCodeKeepsTheMainThread replays the resume with the live message shapes. It also has 2 positive controls: the key inside a tool input still counts, and a content change still counts.

All runs on the eval box.

Run Result
New test, thread.go from origin/main FAIL: resumed request got p:463945e42e75
New test, this fix PASS
Mutation 1: remove the new skip FAIL: resumed request got p:463945e42e75
Mutation 2: skip output_config at every depth FAIL: "output_config inside a tool input was left out"
go test -race ./internal/thread/ PASS
go test -race ./proxy/... PASS
go vet, gofmt -l on internal/thread clean

Data dependence

No change. The thread tracker stays metadata only: it keeps message hashes and counts. It works the same at each storage level (off, metadata only, everything). docs/data-dependence.md needs no change.

Technical notes

  • Claude Code 2.1.310 logs each API request in the session transcript as a keep count plus a list of message-blob hashes. I rebuilt the last pre-resume request and the first post-resume request from that log. They differ at index 1 only.
  • A local replay with 2.1.310 (fake upstream, no real traffic) showed no other change across --resume on one version. So the version upgrade is the trigger, not resume itself.
  • A session split before this fix stays split until the proxy restarts. A compaction does not heal it: the post-compaction request takes the compacting thread's id, which is the p: id.
  • Status line follow-up: Status line follows the newest thread, so it shows a subagent and not the main conversation #709.

Claude Code 2.1.309 adds `output_config` to the system-role message it
sends second. 2.1.303 sent that message without it. A session that the
user quits on 2.1.303 and resumes on 2.1.309 then sends one old message
with a new key and the same content. The thread fingerprint hashed that
key, so no thread matched, and the main conversation moved onto a new
"p:" id. The proxy lost the thread's state (frozen_tokens 347,167 -> 0)
and nothing was marked main again.

The fingerprint now leaves out a message's own `output_config`, as it
already leaves out `cache_control`. The provider's cache read the whole
old prefix on that request, so the key is not part of what it matches.
The key still counts anywhere inside a message.

Fixes #708

Assisted-By: Claude
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 543883dc1e83 approve

Verdict: approve

Findings

None. The change is correct and scoped.

Non-blocking

  • expand/anchor.go:67 — the anchor fingerprint still counts output_config, so the same upgrade-resume can disable a recorded anchor. expand.Fingerprint strips only cache_control. An anchor recorded before the upgrade stores the hash of the message without output_config. After the resume, that message carries the key, Anchor.Usable returns false, and the restored copy is no longer inserted. The model then sees the bare <<cg:HASH>> marker again and can re-expand it every turn — the loop the anchor exists to stop (#201). The path fails open (the compaction stays, nothing is lost), and the blast radius is small: only an anchor whose fingerprinted message is the one that gained the key, which the PR says is message 1 only. This is a defect in main, not in this PR, so by repo rule it needs its own issue, not a change here. Recommend a follow-up issue linked to #708.
  • internal/thread/thread_test.go:886 — no test for output_config inside a content block. The test covers the key inside a tool input. A content block ({"type":"text",...,"output_config":...}) goes through the same canon call with message=false, so the code is right. One more control would pin the doc's "never inside one" claim to the block path too.
  • Comment nit, internal/thread/thread.go:637 — the skip condition reads asymmetric without a word why. cache_control is skipped at every depth, output_config only at message level. That is correct: cache_control legitimately lives on content blocks, output_config does not. A half-line comment would save the next reader the re-derivation.

What I checked

  • The full diff of #711 (internal/thread/thread.go, internal/thread/thread_test.go) and the code around every change.
  • The canonAt refactor: all four canon call sites are nested values or the bare-string input, so only elements of messages/input get the message-level skip. The skip cannot leak inside a tool input or a content block.
  • Hash stability across the fix: with the skip, a message that gains output_config hashes the same, key order aside (the skipped key writes nothing). I traced the new test by hand: the resumed request's first five cumulative sums equal the thread's, longestPrefix matches, and Resolve returns the primary id. Without the skip, message 1 hashes differently, no thread matches, newID returns a p: id — so the test is a real regression test. Live tests were not approved, so this is a read-only trace; the PR reports the same result from mutation runs on the eval box.
  • The claim the fix rests on — the provider cache does not match on this key — matches issue #708 and the PR body (cache read 813,853 tokens after the change). The package's rule is to group as the cache groups, so the skip follows the evidence.
  • Side effects of skipping the key: two requests that differ only by effort now share a thread id. That is consistent with the cache-grouping rule and with how cache_control is already treated.
  • Every other user of a message fingerprint in the repo: expand/anchor.go (see Non-blocking), apply/restore.go (uses expand.Fingerprint), internal/extract (per-request keys, not cross-turn). The keep-alive resends the stashed body verbatim, so it is unaffected.
  • Repo rules: fail-open is untouched (no error path changed); data dependence is unchanged — the tracker keeps hashes and counts only — and the PR states this; docs/data-dependence.md needs no row for a non-component package. No library/proxy boundary change. Commit is DCO-signed with an Assisted-By line.
  • CLAUDE.md, docs/design.md (package map, session keying, fail-open pipeline), issue #708, and the PR description.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.310 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 543883dc1e83 approve

Verdict: approve

Findings

None. The change does what the PR says, and nothing else.

Non-blocking

  • expand/anchor.go:67 — the anchor Fingerprint strips only cache_control, so it still counts a message-level output_config. The same 2.1.303 → 2.1.309 upgrade this PR fixes can retire an anchor whose At-1 message is the upgraded system message: Usable then fails on every later turn, the restored copy stops being inserted, and RecordAnchor's same-id rule (anchor.go:120) blocks a replacement anchor, so the model can re-expand the same marker once per turn for the rest of the session. The trigger is narrow (in-band anchors fingerprint the request's last message; repair anchors fingerprint the message before the expand call, which is that system message only when the expand call sits in the first assistant turn) and the failure direction is fail-open (cost, no corruption). Suggest a follow-up issue that mirrors the message-level skip here.
  • internal/thread/thread.go:637 — the skip is by key name only. A deliberate effort change mid-session (same messages, a different output_config value) also keeps the thread now. This agrees with the PR's own evidence (adding the key did not miss the provider cache), so it is a consequence to know about, not a defect.

What I checked

  • The full diff (internal/thread/thread.go, internal/thread/thread_test.go) and the code around each change.
  • The canon → canonAt refactor, every call site: cache_control is still skipped at every depth (the condition is not gated on message), output_config is skipped only where message is set — the top-level elements of the messages/input array in fingerprint (thread.go:565). The bare-string Responses input and all recursion into values pass message=false. No other behavior changed.
  • The new test, traced by hand: the resumed request's first five messages hash exactly as the pre-upgrade request's (the skip makes message 1 identical, the string-content normalization makes content:"go on" hash as the array form), so longestPrefix matches the 5-message thread and the request keeps Primary. Both positive controls (key inside a tool input, content change under output_config) exercise the message=false recursion and the un-skipped fields loop.
  • Every other consumer of cross-turn message hashes, for the same upgrade trigger: expand/anchor.go (see Non-blocking), dash/toolinventory.go usedFrom (hashes the last tool-using assistant message — never the system message at index 1, unaffected), modes/tracker.go (hashes session keys, not bodies), apply/prefixsplit.go (operates on system, not messages), proxy/agentcompaction.go (phrase match, not a hash), internal/compactionpoint (comment only).
  • The Fingerprint doc comment matches the code, and no other doc describes the exclusion list.
  • Data dependence: no change — the tracker stays metadata only; the PR body states this and docs/data-dependence.md needs no row (thread tracking is not a registered component).
  • The PR body (title and description only; no comments or other reviews read).

@amiddavid
amiddavid merged commit ef94a3c into main Oct 25, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 25, 2026
amiddavid added a commit that referenced this pull request Oct 25, 2026
- A ping the sweep's question replaced uses no output-budget step (#712), so the next plain
  pings differ.
- A failed question is not a transport failure of a ping: it does not set #710's retry flag,
  the ordinary ping goes out in its place, and a question that billed asks once per idle period.
- A held answer and its drop records stay on their own thread key, so a thread that moves to
  another id (#711 prevents it for a resume) does not carry them.

Tests only.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
amiddavid added a commit that referenced this pull request Oct 25, 2026
… what it earns (#404 PR C) (#695)

feat(sweep): apply the held answer on the next cold request, and book what it earns

The sweep asked at the keep-alive ping and held the answer, and nothing used it.
This change applies it. The sweep now saves money.

- Cold apply (point 3): on the next cold request of a thread, rechecks the held
  answer and replaces each valid output with a shape descriptor and a <<cg:HASH>>
  marker. The original is stashed, so expand returns it byte for byte. Each drop
  writes a record (cg:swd:), and every later request of the thread replays the
  same bytes. A warm request with an unchanged conversation never changes (H1).
- Changed prefix (point 4): a rewind, an edited turn or a fork applies only the
  held drops after the first changed message. The ones before it stay held.
  Counted apart as sweep_applied_changed_prefix.
- Fail open: a store that cannot hold an original refuses that drop. A panic in
  the apply restores every message it touched, writes no record, and forwards the
  request unchanged.
- Dashboard (point 9): the answer cost is booked once, on the ping row the
  question replaced, in its own column (sweep_answer_usd). The expands of sweep
  markers come off the sweep's credit at the write rate.
- Quality signals (point 7): an expand of a sweep marker is charged to the sweep,
  and a later turn that uses something a dropped output introduced counts as a
  false drop. False-drop rate per thread and overall, in the Components tab and in
  /stats (keepalive.sweep_drops). Ids, hashes and counts only.
- The ping carries the forwarded body after a cold apply (point 15), by test.
- The shadow-only ask gate is gone. shadow stays a setting and applies nothing.
- xhigh runs the sweep again. The other presets are unchanged.
- From the #508 notes: registerPing no longer keeps a conversation copy for a
  thread with no candidate and prunes on every registration (D); the sweep reads
  its own cg:swd: record, not cg:res: (F); BuildFallbackAsk and the sweep-only
  pricing in prefix_econ.go are removed (coref keeps what it uses).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): serialise putHeld, claim before the cold apply, retry a panicked apply once

- putHeld takes heldMu and never overwrites a newer AskedAtMs, so a claim that read an old
  answer cannot overwrite a new one, and two asks of one thread cannot land out of order.
- The cold apply claims the held answer first. A panic in the apply or the recheck restores
  every message, is counted (sweep_apply_panic), and hands the answer back once. A second
  panic leaves it spent.
- The ask-level slot refusal counts as sweep_concurrency_full, not sweep_ask_failed.
- The cold test now uses the summary reserve's ColdApplyPhase.
- The sweep row carries the net saving and the cold-apply cache numbers for L1 and C2.
- docs/data-dependence.md: the sweep row now says it stashes originals for expand. PENDING.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
docs(sweep): fix the xhigh and housellm preset rows; record the data-dependence approval

presets.md: xhigh and housellm now describe the sweep as it is: it asks at the keep-alive
ping and removes content only on a cold request. The old max_calls and "adjudicates at
depth on an expired cache" text is gone.

data-dependence.md: Decided by records David Amid's approval of 2026-10-25 (#695).

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): round 1 review fixes for the false-drop signal and the commit window

- A marker shared by two threads lists every owner. An expand credits the thread that
  made it, and only a thread that carries the marker. With no thread known (the
  request-path repair), every owner is credited.
- The reference scan, the expand note and the commit take dropMu, so a flag is not lost.
- The commit is atomic in effect. A panic after the first record tombstones every record
  and marker owner this attempt wrote. Applied and sweep_applied_* are counted last.
- The change point is computed from the answer the claim returns.
- Shadow mode keeps replaying drops that already exist. It only stops new applies.
- Rename AppliedChangedPrefx; fix the stale selectAffordableDrops hint; document the
  next-warm imprecision.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
fix(sweep): release dropMu when the reference scan panics, and close the panic paths

- scanReferences held dropMu with a plain Unlock inside a function that recovers panics.
  A panic in the Store or the ledger left the lock held for good, and every later scan,
  expand note and commit blocked. The locked part is now a closure with a deferred unlock.
- The extraction savings metrics are booked after the commit, with the events and ledger.
- A panic at the held trim gives back the untrimmed answer, so the drops after the change
  point are not lost.
- An expand of a marker with no thread known counts once in the total.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
test(sweep): pin the sweep question against #710, #711 and #712

- A ping the sweep's question replaced uses no output-budget step (#712), so the next plain
  pings differ.
- A failed question is not a transport failure of a ping: it does not set #710's retry flag,
  the ordinary ping goes out in its place, and a question that billed asks once per idle period.
- A held answer and its drop records stay on their own thread key, so a thread that moves to
  another id (#711 prevents it for a resume) does not carry them.

Tests only.

Part of #404.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Thread tracker: a resumed session loses its main thread id

1 participant