Skip to content

fix: strip cache_control from prefix-affinity identity hashing (#2188) - #2191

Merged
ranxianglei merged 2 commits into
masterfrom
2026-10-05_resume-inheritance-cache-control
Oct 6, 2026
Merged

ranxianglei merged 2 commits into
masterfrom
2026-10-05_resume-inheritance-cache-control

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What

findResumeParent requires the child request's chain hash to equal the parent's stored tailHash at the parent's depth. That chain was hashed with stableStringify(message) — which includes each content block's cache_control. Claude Code stamps a cache_control breakpoint on its last message and last assistant message and moves them as the conversation grows, so a --resume <parent> --fork-session --session-id <child> replay of the parent's history differs from the parent's final live request only by where those hints sit. The shared prefix was therefore never byte-stable across a breakpoint shift, and findResumeParent returned null deterministically — every Claude Code resume/fork started at zero compression blocks (#1486 / #1834 / #1850 never fired).

Root cause & fix

src/prefix-affinity.ts: add canonicalForHash — sorted-key JSON with every cache_control field dropped — used by both chainHashes and perItemHashes. The identity chain is now invariant to breakpoint placement while still requiring actual content to match byte-for-byte. All three consumers route through these two functions, so anonymous resolution (#309), identified-session tracking (#1486), and resume-fork detection all inherit the fix; no other code path re-implements this hashing (fork-adoption.ts adopts kernel CoreMessages and relies on the resolver's match).

stableStringify is unchanged and stays exported (still used by src/tool-ring.ts for tool-call argument canonicalization).

Behavior change (flagged per policy)

One-time, self-healing: chains persisted in ~/.local/state/billion-context/prefix-affinity.json by pre-upgrade bili were hashed with cache_control; after this change they no longer match new-format incoming hashes, so such sessions fork fresh once and re-converge after their next live request re-notes the chain. No false positives are possible (a stale entry would need a sha256 collision to wrongly match). No persistence-format / schema change — I chose "accept one-time invalidation" over adding a hash-version field (the latter is a human-gated persistence change); if versioning is preferred it can be a follow-up.

Tests

  • tests/prefix-affinity.test.ts — two new regression tests pinning the mechanism:
    • identity hash is invariant to cache_control placement (same transcript, breakpoint on different trailing blocks → identical tailHash + itemHashes).
    • resume-fork survives a cache_control breakpoint shift (parent tail carries breakpoints on idx 8/9; child replay clears them and extends → findResumeParent still resolves the parent at full depth).
  • Verified teeth: under the OLD algorithm the fixture gives parent.tail ≠ child.hashes[depth-1] (MISMATCH → null); under NEW they're equal (MATCH). Mirrors the issue's minimal-repro evidence.
  • Existing prefix-affinity, affinity-persist, and resume-ref-inheritance suites pass; typecheck clean. Full suite left to CI.

Closes #2188

Claude Code stamps a cache_control breakpoint on its last message + last assistant message and moves them as the conversation grows. The prefix-affinity identity chain hashed those bytes via stableStringify, so a --resume/--fork replay of an earlier history diverged from the parent's stored chain exactly at the breakpoint position and findResumeParent returned null deterministically — every Claude Code resume/fork lost all compression inheritance (#1486/#1834/#1850).

Add canonicalForHash: sorted-key JSON with every cache_control field dropped, used by both chainHashes and perItemHashes. The identity chain is now invariant to breakpoint placement while still requiring actual content to match byte-for-byte.

Behavior change (one-time): pre-upgrade chains persisted in prefix-affinity.json were hashed WITH cache_control, so they no longer match new-format incoming hashes and fork fresh once; each session converges after its next live request re-notes its chain (self-healing, no persistence-format change).
@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-05_resume-inheritance-cache-control (61ed976)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.2259-pr.2191.c0c1c35

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr2191.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

#2191 review 完成。结论先行:可合并,需人工合并——改动触及 identity/session-binding 逻辑,按 §7.4 必须 human merge;质量上无拦点。

查重:open+closed issue/PR 检索 cache_control / prefix-affinity / resume-inheritance 关键词,无重复项;#1486/#1834/#1850 是 resume-inheritance 功能本身的工单,#2189 是独立的 preflight 问题,均与本修复不重叠。

审核证据(不只读 diff):

  • [bug] Claude Code resume/分支永远命中不了 resume-inheritance:链哈希把 cache_control 断点算进去了 #2188 根因逐行复核成立:旧算法 chainHashes/perItemHashes 经 stableStringify 把 cache_control 算进哈希 → CC 断点在 live 请求与 replay 之间移动 ⇒ 父深度处 progressive hash 必然失配,findResumeParent 确定性 null ✓
  • 三个消费方全部经由这两个函数(server.ts:2299 resolve / :2445 chainFingerprint+note(...,true) / :2619 findResumeParent),全仓无第二处独立实现该哈希;fork-adoption 不自建哈希、依赖 resolver 匹配 ✓
  • worktree 本地定向运行:prefix-affinity + affinity-persist + resume-ref-inheritance 全绿(39 tests)、typecheck clean、build OK。head@3cf8b2a CI:已完成 job 全部 success(test ubuntu×2、kernel-guard、docs-sync/coverage、version/lane-guard、registry e2e ubuntu+windows、real-client lanes ×6、build-artifact);仅 windows-latest test×2 在跑——我推的 nit commit 会触发新 head 的完整 CI,以新 head 结果为准。
  • 两个新回归测试有牙:旧算法下 test1 tailHash 必不等、test2 findResumeParent 返回 null;新算法下均通过——与 [bug] Claude Code resume/分支永远命中不了 resume-inheritance:链哈希把 cache_control 断点算进去了 #2188 的最小复现证据同形。

七问:

  1. 是什么问题:Claude Code --resume --fork-session --session-id <child>(换新 client id + 全量 replay)永远命中不了 resume-inheritance,子会话从 0 压缩块起步。
  2. 什么原因导致:identity 链哈希把传输层 cache_control 断点当成了内容;CC 在 live 请求与 replay 之间移动断点,共享前缀不再逐字节稳定 → progressive hash 在父深度必然失配。不是匹配策略问题,是哈希输入混入了非内容字节。
  3. 怎么修复的:identity 哈希用的 canonical form(sorted-key JSON)改为任意深度剥离所有 cache_control 字段,chainHashes+perItemHashes 共用 → 身份对断点位置不变,内容仍要求逐字节相等。修在 canonicalization 这个产生脏字节的源头,不是堵下游比较。
  4. 是否有回归问题:逐项清点过既有行为——匿名 prefix 解析(# [Bug/Regression] 0.1.59 关闭内容指纹会话兜底 (#286):无会话头第三方 harness 请求被直接 400,不转发上游 #309/compress rejects ranges as protected zone; stale ranges from previous sessions (ref renumbering + opener-hash conversation signal) #1262,head-anchored/最长严格前缀/identified-skip 语义不变)、identified 链 append-only 纪律(Claude 上 resume 导致消息错乱 #1486/detectUnannouncedHistoryRewrite 误判 1 条消息的侧边辅助请求(如 WebSearch),导致 Ref 映射表被洗空、编号雪崩耗尽(m99999)及 363 万 Token 溢出 #1075 不缩水规则不变)、lineage 归属(debug-only)、MIN_CANONICAL_BYTES=24 退化门(空骨架本身已 ≥24B,边界实际不可达)、持久化快照 schema(字段不变)、stableStringify 消费方(tool-ring.ts:66/72/81 原样保留)、wire/message shape(零改动,plugin/proxy 双模式均不涉及)。无意回归:无。唯一有意变更即 PR 已披露的一次性失效:升级前持久化的旧格式链不再匹配新格式 incoming hash,自愈、无误报可能(需 sha256 碰撞)。一个值得记录的 nuance:identified 父链要等父会话下一次 ≥ stored depth 的 live 请求才重新记入新格式(server.ts:2445-2451);匿名链一个请求内即收敛(每请求 note())。父会话若永不回来,其 stale entry 无害地留在表里直到 LRU 淘汰。
  5. 是否破坏缓存:上游 provider prefix-cache 不受影响(零 wire 变更)。bili 内部:affinity 快照一次性失效(上述已披露);重试/去重/增量游标逻辑未触碰。
  6. 是否改了设计方向:没有。同一机制、同一数据流,只是 canonical form 更窄。显式选择「接受一次性失效」而非 hash-version 字段,避开 human-gated 持久格式变更;如日后想要 versioning 可作 follow-up。
  7. 是否引入新配置:无。无新 env/config/默认值。

顺手小修(独立标注 commit,非本 PR 引入):src/prefix-affinity.ts MAX_TRACKED_SESSIONS 注释上方有一行重复的 JSDoc 首行(master 既存,master 与 PR head 比对确认)→ 删除一行,commit 61ed9766a 已推到 PR 分支。

diff 整洁度:2 文件 +87/-2 单一线性提交,无 lockfile/golden/生成物漂移,每行都与目的相关(外加上面 1 行注释小修)。干净。

判定:可合并,请人工 merge(identity-logic 变更按 §7.4 留给人)。合并后建议观察一次真实 CC resume/fork,确认日志出现 [resume-inheritance] N msg(s) byte-exact prefix of … — inheriting refs/blocks/lineage (#1486)(该日志措辞本 PR 未改,可直接 grep)。

@ranxianglei
ranxianglei merged commit 39c4958 into master Oct 6, 2026
19 checks passed
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.55-master.39c4958 (rolling master tag).

npm install -g billion-context@0.0.55-master.39c4958  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Claude Code resume/分支永远命中不了 resume-inheritance:链哈希把 cache_control 断点算进去了

1 participant