Skip to content

fix: gc dead message refs after each turn (#390) - #491

Closed
ranxianglei wants to merge 1 commit into
masterfrom
2026-09-03_fix-390-ref-gc
Closed

ranxianglei wants to merge 1 commit into
masterfrom
2026-09-03_fix-390-ref-gc

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #390

根因链

消息 id 是内容指纹(kernel wire/message-id),所以每次编辑/截断/去重都会让旧 id 死亡,但旧 id 的 byRaw/byRef 条目没有任何路径回收 → 编号单调逼近 99999,kernel allocateFreeRef 抛 ref capacity exhausted,prepare 侧 catch 退化成 "kernel transform failed, forwarding unchanged" → 该会话压缩静默停摆。tokenSnapshot(按 ref 键控)同样泄漏;orphan-gc 失活块的 effectiveMessageIds 映射也永远滞留。

关键发现:清条目即复用

kernel 的 assignRefsNode 每回合用 nextIndex: highestUsedIndex(map)+1 重算游标(不持久递增)——所以 只要清掉死条目,空槽复用自动发生,无需任何游标手术;capacity throw 只在真有 99999 个活 ref 时才触发。

修复

新增 src/ref-gc.ts gcMessageRefs(session, incoming, outgoing, log),在三条 prepare 路径(anthropic/openai/responses)的 processTurn + reapOrphanBlocks 之后执行,剪除所有 raw id 不再可达的映射。存活集 =

  1. 入站视图 id ∪ 出站视图 id(出站含渲染出的 summary);
  2. 活跃块的 effectiveMessageIds(墓碑,保 decompress 可用);
  3. 出站文本中被引用的 mNNNNN(活跃 summary 引用的标签必须保映射——否则空槽复用后旧引用会错误指向新消息,decompress 张冠李戴)。

tokenSnapshot 同步剪到幸存 ref;highestUsedIndex ≥ 90000 时 warn 一次,病态场景不再静默。

测试 tests/issue390-ref-gc.test.ts 9/9

  • 死条目剪除 / 活 id 保留;活跃块墓碑保留 + byRaw/byRef 一致性不变式
  • 被出站 summary 引用的 ref 保留(防错配复用的核心用例)
  • tokenSnapshot 剪除;kernel 真实 assignRefs 复用空槽(验收标准 2 的机制证明)
  • issue 复现:40 ref / 37 消息 / 3 幽灵 → 恰好剪 3 个
  • orphan-gc + ref-gc 同回合协作:被 reap 的块 id 同回合回收(验收标准 3 的路径)
  • 长跑压力:1000 回合混合编辑/截断,byRef 与活视图同阶、零幽灵存活(验收标准 1)
  • 90k 容量 warn

验证

typecheck ✓;全量 993/995(2 个失败为 plugin-agent.test.ts 已知环境永久失败,干净 master 同样复现);build ✓;E2E 4-phase 核心链路(codex 真客户端)PASS。

备注

Message ids are content fingerprints, so every edit/truncation/dedup orphans
the old id's byRaw/byRef entry. Nothing recycled them: the ref space
(m00001..m99999) grew monotonically toward the kernel's capacity throw, whose
prepare-side catch degrades to 'kernel transform failed, forwarding unchanged'
— compression silently stalls for the rest of the session. Dead
tokenSnapshot entries (keyed by ref) leaked the same way; orphan-gc'd blocks
kept their effectiveMessageIds mappings forever.

gcMessageRefs runs after processTurn + reapOrphanBlocks on every prepare path
(anthropic/openai/responses) and prunes every mapping whose raw id is no
longer reachable: incoming or outgoing view (outgoing includes rendered
summaries), an ACTIVE block's effectiveMessageIds (tombstones for
decompress), or cited as mNNNNN inside outgoing-view text (so a freed slot is
never re-allocated onto a tag a live summary still shows — that would
misattribute on decompress). tokenSnapshot is pruned to the surviving refs.

The kernel recomputes its allocation cursor as highestUsedIndex(map)+1 each
turn (assignRefsNode), so pruning makes freed slots reusable automatically —
no cursor surgery. The capacity throw now needs 99999 genuinely live refs; a
warn fires at 90k so the pathological case is never silent.
@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-03_fix-390-ref-gc (668cff3)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-491

Each push to this PR publishes a new version under the pr-491 npm tag.

Option B — Download artifact

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

This comment is automatically updated on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[bot] 🏷 开始审核 PR #491(fix: gc dead message refs after each turn,closes #390)。正在拉取分支、逐行审 diff、复现根因并跑全量验证(typecheck / test / build),稍后给出结论。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[bot] 🏷 审核结论:LGTM,可合并(附 3 条非阻塞小注)。

Triage 三步(先审核后实现的流程记录)

1. 复现/查证 —— 根因链属实。 逐行核对了 acp-kernel 0.0.47 源码与代理侧全部 ref-map 消费点:

  • byRaw/byRef 在 kernel 管道中没有任何回收路径(assignRefsNode 只增不减;kernel 只对 tokenSnapshot 有 render 时自洽剪除,refs map 不管)。全仓唯一的既有剪除是 applyCompactionArchive(src/session.ts:359,仅 native compaction boundary 触发),确实覆盖不了编辑/截断/去重产生的常规死亡 id → 单调逼近 m99999 → allocateFreeRef 抛 ref capacity exhausted → prepare catch 退化为 forwarding unchanged。根因定位准确,不是症状层修复。
  • "清条目即复用"机制验证通过:assignRefsNode 每回合 nextIndex: highestUsedIndex(io.state.messageRefs) + 1(dist/index.js:2109),allocateFreeRef 从游标向上扫第一个空槽——剪掉死条目后空槽复用自动发生,无需游标手术。测试 5 用真实 assignRefs 证明了这一点(m00002 被复用),是验收标准 2 的硬证据。

2. 层次判断 —— 方案打到核心。 存活集设计正确且是最小充分集:入站∪出站视图 id、活跃块 effectiveMessageIds 墓碑(保 decompress)、出站文本引用的 mNNNNN(防空槽复用到活跃 summary 仍在展示的标签上导致张冠李戴——这是整个修复里最微妙也最对的一点)。我额外审计了三条 prepare 路径之外的其余 processTurn 调用点:prepareCountTokens 丢弃 turn.state(不可变管道,无泄漏)、prepareResponsesCompact 与 compress-loop refreshFolded 的瞬时死条目会在下一个正常回合被 gc 收走——没有残留的永久泄漏路径。与 applyCompactionArchive 的顺序也自洽(先窄剪后宽剪,gc 是超集语义)。

3. 方案评估 —— 成立。 放置位置(processTurn + reapOrphanBlocks 之后)保证被 reap 块的 id 同回合回收;tokenSnapshot 同步剪除与 kernel 自身行为一致;CoreMessage 所有内容都在 .text 字段,引用扫描无死角。

独立验证结果(PR 分支 668cff3)

项 结果
typecheck ✓
tests/issue390-ref-gc.test.ts 9/9 ✓
全量测试 994/995 —— 唯一失败为 tests/launcher.test.ts:22(resolveClientCommand),干净 master 同样复现,环境依赖、与本 PR 无关
build (tsup) ✓
与当前 master(4f5fe7e) 合并 git merge-tree 干净,无冲突(分支祖先含已合并的 #490,无内容重复)
E2E 本沙箱连不上默认本地 sglang upstream,无法代跑;以你报告的 4-phase PASS 为准。按 AGENTS.md §3,server.ts 改动合并前建议确认 E2E 已过(你已跑过则直接合即可)

一个数字出入:PR 写 993/995(2 个 plugin-agent 失败),我这里 plugin-agent 27/27 全过、失败的换成了 launcher.test.ts——同类环境抖动,不影响结论,但说明那 2 个"已知永久失败"实际是环境相关的。

非阻塞小注(report only,不另开 issue)

  1. warn 语义与文档不符:commit/doc 说 "warn once per threshold crossing",实现是每回合 pruned>0 && highest≥90k 都打一条(无去重标志)——病态稳态下每请求一行日志。另外 warn 检查在 if (pruned === 0) return 之后,若某回合恰好零剪除则不打 warn;鉴于 effectiveMessageIds 只存 anchor id(每块约 2 个),该场景近乎理论性,但把检查移到早退之前是一行改动,顺手更稳。
  2. 引用扫描只看出站:plugin 模式下 summary 引用活在 agent 重传历史里(入站面);块被 orphan-reap 后这些标签会悬空,直到分配游标回卷到该编号以下才可能错配——需要大规模 churn 才触发,概率低。若要严格闭环,后续把 citedRefs 扩到入站文本即可(一次正则扫描,成本可忽略)。建议作 follow-up。
  3. src/session.ts:336 注释("nextIndex is left alone so a freed ref slot is never re-allocated…")与已验证的 kernel 行为矛盾(游标每回合重算、复用自动发生);PR 备注已计划后续简化 applyCompactionArchive,届时一并修掉这句注释即可。

结论:根因真实、机制证明扎实、测试覆盖了全部三条验收标准路径,验证齐备——可以合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

按维护者指示关闭:这个宿主侧补偿层设计(三条件存活集 + 墓碑 + 文本引用扫描 + 空槽复用)被认为过于脆弱,不适合作为 kernel 行为的外部补丁合入。#390 缺陷本身仍然成立(幽灵 ref 单调膨胀、逼近 99999 时 kernel throw、orphan 块映射滞留),留待 kernel 侧根治(如加宽 ref 编号空间或稳定 id 方案)。

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.

幽灵 ref 永不回收:编号单调膨胀、逼近 99999 时 throw 并静默停摆该请求压缩;orphan-gc 失活块同样泄漏映射

1 participant