Skip to content

fix: Claude Code fork 按 transcript 解析父会话,保留父会话编号空间,大量追加不再误报改写 (#2426) - #2427

Merged
ranxianglei merged 3 commits into
ranxianglei:masterfrom
darkness-A:fix/2426-claude-fork-lineage
Oct 8, 2026
Merged

ranxianglei merged 3 commits into
ranxianglei:masterfrom
darkness-A:fix/2426-claude-fork-lineage

Conversation

@darkness-A

Copy link
Copy Markdown
Contributor

Fixes #2426

问题

Claude Code 会话经 SDK forkSession 后以普通 resume 继续(opencode-claude 在额度错误后重试回合就是这样),没有 --fork-session 的 SessionStart 声明;且首个请求的尾部与父会话最后一个请求不同(resume 时的 <system-reminder>、技能差量)。字节级的 findResumeParent 因此拒绝了真正的父会话(等长且最后一条不同),采纳了一个更老的祖先:18 个块未继承、约 1871 条消息重新折叠、触发 unannounced-rewrite。详见 #2426。

改动(三处独立修复,均无新增配置项/环境变量)

  1. 按 transcript 解析父会话:新增 src/claude-transcript-lineage.ts,读取 Claude Code 写在 fork transcript 每一行的 forkedFrom,沿链找到 bili 已知的最近祖先。src/server/handle.ts 的 Claude 上 resume 导致消息错乱 #1486 resume-inheritance 块对以 x-claude-code-session-id 标识的请求(anthropic、主 lane、仅回环地址)先走它,查不到 transcript / 标记 / 已知祖先时回退到原有前缀匹配。安全限制:只读 <CLAUDE_CONFIG_DIR 或 ~/.claude>/projects/*/<id>.jsonl 头部(≤256 KB)、realpath 必须在 projects 根目录内、防环、深度上限 8。
  2. 继承后不复用编号:reserveRefsThrough 在继承时以及 applyCompactionArchive 裁剪之后,在 messageRefs.byRaw 写入 bili:ref-floor 哨兵保留父会话的编号空间(不计入改写统计),避免父会话里表示消息 X 的编号在子会话里表示另一条消息。
  3. 大量追加不再误报:detectUnannouncedHistoryRewrite 增加 knownIncoming / knownBefore < 0.5 判据,正常追加不再被报为改写,真实改写仍会报。

需要人工审阅的点(按 AGENTS.md §7.4)

测试

  • 新增 tests/claude-transcript-lineage.test.ts(12 个用例):transcript 查找各分支、symlink 越界、血缘链/环/深度上限、追加不误报与真实改写仍报、ref floor、anthropic e2e(等长尾改后按 transcript 继承且无编号复用;无 transcript 时找不到父;x-acp-session 不读 transcript)。
  • 判别性:撤掉 transcript 血缘 e2e 失败;撤掉保留编号空间则断言 ref m00015 must denote the same message in parent and child 失败。
  • 调整 tests/fork-ccr-adoption.test.ts:原用例写死子会话复用父会话编号(m00006–m00009),现断言子会话分支编号从父会话最高 ref 之上开始。
  • 在 rebase 到 d189be53 后的分支头上:npm run typecheck 通过;npm test 5097 项,5069 通过,0 失败,28 跳过(XDG_STATE_HOME 指向空目录,避免 claude-native 用例读取本机端口偏好);npm run build 通过。

未验证

  • 没有对真实 Claude Code 进行端到端 A/B(需要触发额度错误后的 fork);e2e 使用的是按真实 transcript 结构构造的夹具。
  • 仅在 Ubuntu 上验证,Windows / macOS 的 ~/.claude 路径解析没有实测。

awork added 2 commits October 8, 2026 23:49
… CI gate)

isClaudeSessionUuid / claudeConfigDirs / TranscriptParentLookup are only
referenced inside their declaring file (the test imports claudeTranscriptParent
and resolveClaudeTranscriptLineage), so they are INTERNAL_ONLY per the ranxianglei#1440
gate and must not be exported.
startRig pointed XDG_STATE_HOME at a fresh mkdtemp without restoring it;
restore the previous value in closeAll, mirroring the CLAUDE_CONFIG_DIR
handling already used by the e2e cases in this file.
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review 结论(结构化八问) — 全量读完 7 个文件 diff(+593/-16),原 issue #2426 已做方向审核,kernel/宿主编号消费面逐项审计,定向测试本地实跑,一处 CI 失败已复现并直接在分支上修复。

审查动作(结论前的验证)

  • PR 是干净单提交、基于当前 master(d189be5),未动 kernel/,无新增配置项/环境变量(对照 Configuration Surface Discipline 核过)。
  • 原 issue 三步审核:三处缺陷均真实且分层正确——①字节前缀猜测是「采纳错父会话」的产源;②继承后游标从继承 map 自身高水位重算,是「编号复用」的产源;③单比例稀释是「误报改写」的产源。三处修法都打在产源上,不是症状拦截。✅
  • 本地:npm ci + build 在 PR 头通过;定向跑 tests/claude-transcript-lineage.test.ts + tests/fork-ccr-adoption.test.ts → 18/18 通过(hermetic:port 0、临时目录)。
  • CI:26/27 绿。唯一红的是 unused-exports,本地复现后按「小问题直接修」直接推了两个标注 commit 到你的分支(9ff07f8d9..f0ade4691):
    • 11ede0e20:去掉三个 INTERNAL_ONLY 导出(isClaudeSessionUuid / claudeConfigDirs / TranscriptParentLookup)——测试文件只 import claudeTranscriptParent 和 resolveClaudeTranscriptLineage,去掉不影响任何引用,gate 复跑 clean;
    • f0ade4691:e2e rig 的 closeAll 里恢复 XDG_STATE_HOME(镜像同文件已有的 CLAUDE_CONFIG_DIR 处理;node --test 进程隔离下今日零行为影响,纯卫生)。
    • CI 已对新头重跑,等绿。

八问

  1. 是什么问题:Claude Code SDK forkSession 后的普通 resume(如 opencode-claude 额度错误重试)被 bili 采纳了更老的祖先当父会话,继承后又把父会话用过的编号重新发给了不同消息,还把正常的大量追加误报为「未声明的历史改写」。
  2. 什么原因导致的:三条独立机制——①父会话解析只靠字节级前缀匹配,而 resume 后的首个请求与父会话最后一个请求等长且尾部合法地不同(resume 时的 <system-reminder>、技能差量),真父不可见、老祖先胜出;②继承后 ref 游标按继承 map 自己的高水位重算(highestUsedIndex+1),落回父会话高水位之下 → 违反 id-never-reused 契约的编号复用;③改写检测只看「带旧 ref 的入站消息占入站总量的比例」,任何大追加都会稀释该比例 → 误报。
  3. 影响范围与严重程度:仅 Claude Code lane 的 SDK-fork 普通 resume 场景(触发条件明确);对命中会话严重度 HIGH——约 1871 条消息重新折叠、b15–b32 块在子会话丢失、健康会话上记 conflict + 强加 compaction boundary。其余 lane/路径不受影响(transcript 查找门控:anthropic 协议 + x-claude-code-session-id 身份精确相等 + 回环地址)。
  4. 怎么修复的:机制层三件套——从客户端自己写的权威标记解析父会话(fork transcript 每行 forkedFrom 链式上溯,歧义/环/深度上限全部 fail-closed,realpath 必须在 projects 根内、只读头部 ≤256KB、扇出有界),查不到才回退原前缀匹配;继承时用 byRaw 专用哨兵(bili:ref-floor,永不进 byRef)钉住父会话编号空间,覆盖「继承时」与 applyCompactionArchive 裁剪后两个时刻,游标只能向上走;改写判定改为两个稀释信号同时成立才算。
  5. 是否有回归问题:未发现破坏,既有行为逐项审计如下——(a) Claude 上 resume 导致消息错乱 #1486 字节前缀路径逐字节未动,transcript 查找 miss/异常时原样回退(命中时日志 via 值新增一种,仅日志);(b) 匿名 fork(Design: tree-shaped prefix affinity — forked branches inherit the shared prefix's compression state #629)、derived link([pi plugin] Prime RLM inline 派生子会话在代理模式下零继承:搜不到也解压不了父会话压缩块(billion-context-pi#531 同场景) #1333/feat: extend derived-session inheritance to remaining lanes (opencode V1, omp) — follow-up to #1333 #1362)、CCR adoption(bug(ccr): fork adoption carries covered refs without adopting their content-store entries #1341)路径未触碰,fork-ccr 套件按新编号重钉;(c) kernel 编号机制:assignRefs 跳过已有 byRaw 键(哨兵键不可能等于 SHA-256 消息 id)、allocateFreeRef 查 byRef(哨兵不在其中)、rebuildRefIndex 理论上会把哨宾泄漏进 byRef 但全仓零生产调用方、持久化按原样水合 → 哨兵跨重启存活且保护不蒸发;(d) applyCompactionArchive 的 nextBlockId/nextRunId 与裁剪语义未动,哨兵顺带关掉了本仓文档记载的理论重发窗口;(e) 有意灵敏度变更(必须披露):改写检测旧判据 knownIncoming/incomingTotal < 0.5 → 新判据再加 knownIncoming/knownBefore < 0.5;后果:「保留 ≥50% 旧消息 id 的同时大量追加」的部分改写不再触发(旧判据会因稀释而误触发)——按代码内注释的权衡有意为之(漏报代价=被改写子集的陈旧引用、块自动失活,无数据损坏;误报代价=健康会话记冲突+强边界),真实改写(大部分旧历史消失)仍触发且有测试钉住;(f) wire/消息形状、thinking 族载荷、tool-call arguments 字节:全部未触碰;(g) stats/UI 无任何表面遍历 byRaw 计数(所有 Object.keys/entries 点逐一核过),无外观漂移;(h) 安全面:非回环客户端永远不触发 transcript 读取;文件名强制严格 UUID;歧义(两处 project 指向不同父)宁缺毋猜。
  6. 是否破坏缓存:不影响——零 wire 变更,prefix cache 不动;每会话编号保持单调递增;nextBlockId/nextRunId、CCR 去重键、重试/节流策略均未触碰。可见的有意后果:fork 子会话的新消息标签现在从父会话最大 ref 之上开始(例:父到 m00010,子分支从 m00012 起,已由调整后的 fork-ccr 测试钉住),占位符引用因此始终指向父会话那条消息而非撞号。
  7. 是否改了设计方向:没有转向——在既有 Claude 上 resume 导致消息错乱 #1486 继承决策点上换用更强的信号(客户端声明标记优先于字节推断),与其他 host 专属门控同一套证据许可名单纪律;与 Fork adoption: survey + designs for the remaining lanes (claude, kimi, zcode, hermes; codex N/A) #2408 互补不重叠(Fork adoption: survey + designs for the remaining lanes (claude, kimi, zcode, hermes; codex N/A) #2408 依赖 SessionStart source:"fork" 声明,本 PR 覆盖没有该声明的 plain resume)。唯一策略位移是改写检测的 AND 条件,已在第 5(e) 披露。
  8. 是否引入新配置:无——无配置字段、无 BILI_* 环境变量、无 CLI flag;CLAUDE_CONFIG_DIR 是 Claude Code 自有变量,只读使用。

未验证(作者已披露,接受):无真实 Claude Code A/B(需现场触发额度错误 fork,e2e 用按真实 transcript 结构构造的夹具);Windows/macOS 的 ~/.claude 路径未实测(代码走 os.homedir/path.join,平台风险低)。测试有效性核查:e2e(a) 断言 derivedFromSessionId===parentId + 逐 ref 同号同消息,撤掉血缘解析或撤掉编号空间保留都会分别打红,是有牙的真回归测试,非恒真断言。

判定:可合 —— 等重跑的 CI 全绿后由人工合并(系统规则禁止我合并;当前 mergeable_state 为 blocked,合并请自行操作:#2427 )。我推的两个 commit 均为分支上的附加小修,无范围蔓延。

@ranxianglei

Copy link
Copy Markdown
Owner

Reviewed against master d189be53, then re-verified on your updated head f0ade469 (includes your unused-exports fix — same conclusion I reached locally, so nothing to add there).

Verdict: direction correct, all three defects confirmed at code level, implementation sound. Local verification green. Details below, plus the interaction checks with the recently-merged fork-adoption work.

Defect 1 — transcript lineage. Confirmed the failure mode in findResumeParent: the equal-length-but-last-message-differs case fails hashes[entry.depth-1] === entry.tailHash, and the grandparent with the deepest surviving prefix wins — exactly the #2426 report. Your gate design is right on every axis I probed:

  • anthropic + conversationHeaderSource(...).value === sessionId excludes |sub: splits and persona forks; loopback-only matches the "transcript is a local file" trust boundary; session.stats.requests === 0 bounds the readdir fan-out to once per session.
  • The safety argument holds: adoption stays content-addressed (maybeAdoptResume seeds refs only for raw ids present in the incoming request), so a wrong/stale lineage can at worst inherit nothing — a wrong ancestor contributing refs for identical content hashes is semantically correct by construction.
  • Ambiguity → refuse, cycle set, depth ≤ 8, realpath confined to the projects root, 256 KB head read — all verified in the code, with matching tests.

Defect 2 — ref floor. The bili:ref-floor sentinel is well-shaped: never matches an incoming id (raw ids are SHA-256 hex), has no byRef entry, is excluded from the rewrite denominator, and survives applyCompactionArchive pruning via the conditional re-pin. Note this also closes the "known residual" documented in AGENTS.md (kernel cursor dropping after the archive prune) — worth calling out in the merge notes. Verified reserveRefsThrough is a no-op for the §8 plugin-fork path (full namespace inherited there, floor already reached).

Defect 3 — dual ratio. Checked the shape that must KEEP firing: a codex-style local-compaction replay (2 of 14 ids retained) → knownIncoming/knownBefore = 2/14 < 0.5 on both sides → still detected, so the openai-lane archive path is unaffected. Large-append now correctly passes. The knownIncoming > 0 precondition (total rewrite not reported) is pre-existing semantics, unchanged.

Interactions with the recently-merged fork work (my review focus):

Local verification on f0ade469: typecheck clean; claude-transcript-lineage 12/12; fork/adoption family (fork-ccr-adoption, claude-fork-lineage, prefix-affinity, plugin-fork, fork-adoption-wires, resume-ref-inheritance, resume-adoption-wires, issue1333-derived-inheritance, plugin-native-binding) 109 pass / 0 fail; rewrite/conflict family (fix-1001-history-rewrite, compaction-archive, conflict-remediation, conflict-lifecycle) all pass.

Merge notes: touches message-ref numbering + session identity binding → stays human-review per §7.4 (correctly self-declared in the PR body). Base is behind master (ede3244a merged #2373 — touches prepare-responses.ts/codex-compact.ts, zero file overlap with this PR); rebase before merge or merge as-is, both clean.

One question for the record, not a blocker: when the transcript chain resolves to a KNOWN ancestor that is NOT the direct parent (fork-of-fork whose middle session never hit this proxy), the child adopts the nearest known ancestor's refs/blocks for shared ids only. That's the intended "nearest tracked ancestor" semantics and content-addressing keeps it safe — just confirming it's deliberate (the hops field in the log line will make these visible in production logs).

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 确认:「最近已知祖先」语义是有意的,理由如下(供存档):

  1. 决策时机决定了信息上限。继承必须在子会话首个请求时定案(stats.requests === 0 门控,且该请求不能被延迟)——而此刻这个 proxy 实例能引用的只有它自己知道的会话。中间会话若从未经过本实例(另一台机器、另一个实例、或已被 GC),对它而言不存在;「等 P 出现再链」意味着要么推迟整个继承决策、要么永远不继承。取最近已知祖先是该时刻的最大可用信息。
  2. 内容寻址把风险封顶。采纳只对入站请求中真实存在的 raw id 种 ref、块只在全部 effectiveMessageIds 在场时才整体采纳、bili:ref-floor 把游标钉在祖先高水位之上——从更老的祖先继承,对相同内容哈希而言语义上就是正确的(你第 8 行的论证我完全同意)。
  3. 退化子情形不劣于修复前基线。真正的损失窗口是「A 与 fork 点之间 P 独有的折叠块」——这些从 A 看不到,子会话拿不到,会自己重新折叠一遍。这正是无继承(fresh session)的行为,即该子情形回落到修复前基线而不是更差;常见形态([bug] Claude Code fork(forkSession)后未匹配到真正的父会话:采纳了错误祖先、18 个块被重新折叠、ref 编号可能复用、误报 unannounced-rewrite #2426:直接父会话已知)拿到完整继承。
  4. 一个已知的、可接受的残留:derivedFromSessionId 在首请求钉在最近的已知祖先上,即使 P 之后又出现在本 proxy 下也不会改链到 P。[pi plugin] Prime RLM inline 派生子会话在代理模式下零继承:搜不到也解压不了父会话压缩块(billion-context-pi#531 同场景) #1333 的 fallback 是只读优化,子会话自身的压缩使其自足,所以这不影响正确性,只影响跨会话检索的覆盖面;hops > 1 的日志行让这类案例在生产里可审计。若未来生产日志显示这种案例频繁出现,再考虑「P 出现后补链」也不迟——现在不做是刻意的克制。

其余无异议:merge notes 收到(rebase 或原样合并都干净,交给你定);f0ade4691 的 CI 正在跑,当前 21/27 绿、零失败,剩 6 个长 e2e lane,全绿后这里补一行确认。

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 确认:f0ade4691(含两个附加小修)上 27/27 全部通过、零失败,包括之前红的 unused-exports。分支已就绪,等人工合并:#2427

@ranxianglei
ranxianglei merged commit 64ca1ef into ranxianglei:master Oct 8, 2026
27 checks passed
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.161-master.64ca1ef (rolling master tag).

npm install -g billion-context@0.0.161-master.64ca1ef  # 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

2 participants