Skip to content

fix(agent-core-v2): keep the cached prefix when compaction has to shrink its input - #5507

Closed
RealKai42 wants to merge 4 commits into
mainfrom
fix/compaction-keep-cached-prefix
Closed

RealKai42 wants to merge 4 commits into
mainfrom
fix/compaction-keep-cached-prefix

Conversation

@RealKai42

@RealKai42 RealKai42 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

接着 #4402 的分析继续修。#4402 已经让默认配置下正常的自动压缩不再走预裁剪,但压缩输入放不下时,仍然有三条路径会从头部砍历史:

  • 一步之内上下文直接越过「窗口减去输出预留」。1M 窗口下一步涨超过约 2.6 万 token 就会发生,262k 窗口只要涨超过约 1.7 万 token,读一个大文件就可能做到。
  • 服务端报上下文超长。
  • 摘要被截断,或者模型返回空摘要。

一旦砍头,接近窗口大小的压缩请求就从第一条消息开始和缓存对不上,整段按冷 prefill 计费。按 #4935 里的数据,代价约是普通回合的 100 倍。而且被砍掉的历史根本没进入摘要,信息直接丢了。

这个 PR 把这三条路径都改成从尾部收缩:压缩请求只带能放下的前一段历史,其余消息原样留在摘要后面。

Bug Reproduction Steps

  1. 用 1M 窗口的模型,让上下文停在自动压缩阈值以下。
  2. 让一步的输入(比如一个很大的工具输出)把上下文推过「窗口减去 1/8 输出预留」。
  3. 自动压缩的请求只带最近的消息,日志里 droppedCount > 0,这个请求几乎没有缓存命中。

测试里的复现:packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts 里的「pre-shrinks compaction history using historical assistant usage anchors」(1M 窗口、按真实用量估算,正是 #4402 的场景)。修复前,压缩请求里没有最老的两轮,droppedCount: 2。

Root Cause

fullCompactionService.ts 里,压缩输入需要变短时,三处都从头部开始删:

路径 原来的做法
预裁剪 preShrinkHistoryToWindowBudget takeRecentMessagesWithinTokenBudget,只保留最近的消息
溢出重试 shrinkCompactionHistoryAfterOverflow,按 0.7、0.5、0.35 的比例保留最近的消息
截断或空摘要的重试 dropOldestMessageAndLeadingToolResults,删掉最老的一条

压缩请求本来就是「整段历史 + 压缩指令」,天然延续主请求的前缀。从头部删,等于把这个前缀整段换掉。这次是根本性的修复。从头部删仍然保留为退回路径,只在两种情况下使用:原样保留的消息太多,比如切换到窗口小很多的模型(这正是 #3911 加预裁剪的原因);或者已经找不到更短的切分点。

Code Changes

核心思路:压缩输入放不下时,压缩能放下的前一段历史,其余原样保留。这样压缩请求是主请求的一个前缀加上压缩指令,缓存可以命中,历史也一条不丢。

flowchart TD
  start["压缩:整段历史 + 指令"] --> fits{放得下?}
  fits -- 是 --> normal["正常压缩(行为不变)<br/>保留的用户消息 + 摘要 + 续写提示"]
  fits -- "否:预裁剪 / 服务端超长 / 摘要截断或为空" --> tail{"能在切分点处收短,<br/>且原样保留的消息不超过预算的一半?"}
  tail -- 是 --> keep["压缩 [start, end)<br/>摘要 + 原样保留的 [end, …)<br/>事件带 legacyTail: true"]
  tail -- 否 --> head["退回:从头部裁剪(原有做法)"]
Loading

实现上,用 [start, end) 这个区间表示这次实际拿去压缩的历史:start > 0 表示从头部裁掉了,end 小于历史长度表示尾部原样保留。三条路径共用 shrinkFromTail:在预算内找最后一个可以切分的位置,切分规则复用 strategy.ts 里已有的 canSplitAfter。

决策 选择 没选 理由
放不下时砍哪里 从尾部收缩,被收掉的消息原样保留 缩小输出预留,让预裁剪更少发生 缩小预留只能让问题少一些,没有根除;预留太小还会让摘要截断变多
尾部保留时压缩后的形状 复用 [摘要, ...尾部] 这个「保留尾部」形状,事件里写 legacyTail: true 新定义一种「保留的用户消息 + 摘要 + 尾部」形状 legacyTail 从 agent-core-v2 最早的版本起就在 context.apply_compaction 的 schema 里,回放也认它,新旧版本打开会话都能正确重建,不需要改契约。代价见行为变化表
原样保留的上限 不超过压缩输入预算的一半 不设上限 压缩后的上下文要远低于触发阈值(允许的最小值是 0.5),不能刚压完又马上触发下一次。切换到小窗口模型时尾部可能比整个窗口还大,这时退回从头裁剪
testkit 账本怎么判压缩请求 只有在第一处不同之后又重发了基线已经发过的内容,才算断点 沿用「必须完整延续上一个主请求」 只少了末尾、接着发新指令的压缩请求,前缀能全部命中,没有任何浪费;从头裁剪会重发剩下的整段历史,照样会被报出来。主请求的规则不变
工具参数纠错 不改,只把断点声明的原因写准 把纠错消息留在历史里 重试成功后只少了末尾那一条纠错消息,前面的前缀照样命中;而「不保留失败尝试」是用例锁住的契约

阅读指南:

  1. fullCompactionService.ts 的 compactionRound:range 的变化、三处收缩、应用摘要时如何选择形状。
  2. 同一文件里的 shrinkFromTail 和 preShrinkToWindowBudget:在预算内找切分点,以及原样保留的上限。
  3. packages/testkit/src/model/prompt-cache.ts 的 resendsAfter:账本对压缩请求的新判定。
  4. fullCompaction.test.ts 里这几个用例:「retries an overflowing compaction on the leading messages…」(新增,用 testkit 模型)、「pre-shrinks compaction history using historical assistant usage anchors…」、「probes only the first compaction response after a truncated summary retries」(删掉断点声明后,它就成了缓存回归测试)。

可以略读的部分:strategy.ts 只是导出了 canSplitAfter;Anthropic 和 Google 编解码器给角色段加了标记;三个 changeset;两处断点声明改写了原因。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
压缩输入超过「窗口减输出预留」(预裁剪) 只保留最近的消息,砍掉头部,被砍的部分不进摘要 压缩能放下的前一段,其余原样保留在摘要后面;原样保留的部分超过预算一半时仍砍头 所有客户端(TUI、print、Desktop 和 Web、ACP、SDK)和所有 provider 上,一步之内越过这条线的会话 无配置开关;退回路径保留了原有做法
压缩请求被服务端判为超长 按比例保留最近的消息再试 按同样的比例从尾部收缩,保留尾部;做不到时才砍头 同上,token 估算偏小的会话 同上
摘要被截断或为空后的重试 删掉最老的一条再试 去掉被压缩部分的最后一段再试;没有可以切分的位置时才删最老的一条 同上 同上
以上三种情况下压缩后的上下文 保留的用户消息 + 摘要 + 续写提示 摘要 + 原样保留的尾部。损失:被压缩那一段里的早期用户消息不再原样保留,只在摘要里。压缩指令本来就要求摘要自成一体,并转述仍然相关的早期请求 依赖「压缩后总能看到最早的用户请求原文」的使用方 无
保留尾部时,原样保留的消息上的用量 带着压缩前 provider 报的用量 去掉;回放旧会话里同样形状的记录时也一样去掉 压缩服务用最后一条带用量的 assistant 消息估算上下文大小:保留旧用量会让刚压完的上下文看起来仍接近压缩前的大小,下一回合立刻再压一次(评审指出,用例已锁住)。回合的用量统计在消息追加时就已记下,不受影响 无需
重试最多能做几次 每次少一条消息,消息越多可重试越多次 每次去掉一段,可收缩的次数可能更少,耗尽得更早 依赖重试次数的测试和遥测 无
context.apply_compaction 事件 compactedCount 等于历史长度,砍头时带 droppedCount 保留尾部时 compactedCount 小于历史长度,并带 legacyTail: true;droppedCount 只统计从头裁掉的条数;tokensAfter 和正常形状一样计入请求开销(system 和工具定义),压缩后的 token 计数和下一个请求的 usedContextTokens 不会少算这部分 回放和恢复、读取 wire 的工具、KAP 对话条目的 compacted_count、ACP 的「Messages compacted」 字段早已存在,旧版本也能回放;各处展示的条数如实变小
遥测 compaction_finished.compacted_count 等于历史长度 保留尾部时更小 遥测看板 无
testkit 账本对压缩请求的判定 必须完整延续上一个主请求 只有重发了基线已经发过的内容才报断点 写测试的人;node-sdk 里一条只为撤销之后那次压缩而写的声明因此删掉 无需

正常压缩(输入放得下)的路径和形状没有变。提示词文本没有改动:压缩指令原样不动。契约文件也没有改:wire-manifest.d.ts 和事件 schema 都不变,这次只是用到了已有的 legacyTail 字段。

这次改变了压缩在少数情况下的行为,而且没有配置开关,所以请维护者明确确认:上表里「早期用户消息不再原样保留」这一项损失是否可以接受。

测试覆盖:

  • 1M 窗口那个预裁剪用例在压缩之后还会再发一个回合,断言不会立刻再触发一次压缩;不去掉旧用量时,这里会出现第二次压缩。
  • 修复前会失败的用例共 7 个:
    • 新增的溢出重试用例;
    • 截断重试的缓存探针用例;
    • 按新契约更新的 5 个已有用例:空摘要重试、只有 thinking 的重试、thinking 重试耗尽、截断重试耗尽、1M 窗口按用量估算的预裁剪。
  • 撤掉引擎修复后这 7 个全部失败,缓存检查还直接报出了原来的从头裁剪:request #2 (compaction) does not extend request #0 … messages[1] user became messages[1] assistant。恢复修复后全部通过。
  • 退回砍头的路径,由「pre-shrinks the summary request history to the effective window budget」等原有的预裁剪用例继续锁住,这些用例没有改动。
  • 尾部保留时会话恢复重建得是否一致,由这些用例里的 expectResumeMatches 验证。
  • 账本的新规则由 packages/testkit/test/prompt-cache.test.ts 新增的用例验证,原有的「从头裁剪的压缩请求会被报出」用例保留不变。
验证细节

只在 macOS(Node 24.21.0)上运行过。这个 PR 不涉及路径、子进程或 shell。

检查 结果
pnpm lint 通过
pnpm exec tsc -p <项目>/tsconfig.json --noEmit:testkit、agent-core-v2、node-sdk、kap-server、tests/scenarios 全部通过
packages/agent-core-v2/test/agent/fullCompaction 138 个通过
testkit、agent-core-v2、kap-server、node-sdk、product、acp-server、klient、tests/scenarios 全量 修掉 node-sdk 那条多余的声明后全部通过(约 1.1 万个)
CLI 测试(apps/kimi-code/test)加上 node-sdk 的 session-prompt-events 5383 个通过
E2E compact-builds-the-next-turn-from-the-summary、keeps-one-prompt-cache-prefix-across-a-restart(TUI、ACP) 4 个通过
pnpm run check:duplication <merge-base> 新增重复 0 处
只读 agent 检查 diff 里的内部标识 没有发现

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

A compaction request may summarize a leading part of the history and
keep the rest in the context, so stopping short of the end of its
baseline reuses the whole cached prefix and costs nothing. The ledger
now reports a compaction request only when, after its first difference
from the baseline, it sends again what the baseline already sent, as a
compaction that trims the oldest messages does. Main requests keep the
strict rule. Role segments of Anthropic and Google messages are marked
so their identical text does not count as content sent twice.

The undo declaration in the SDK prompt events case only covered the
compaction request after the undo, which left out the undone turn and
now passes, so it goes away. The two argument correction declarations
now say that the retry only drops the trailing correction message.
…ink its input

When the compaction request no longer fits, compaction used to cut the
history from the head: the pre-shrink kept only the most recent
messages, an overflow kept a shrinking recent share, and a truncated or
empty summary dropped the oldest message. Each of those changes the
start of a request the size of the window, so the provider could reuse
none of its cached prefix, and the dropped messages never reached the
summary.

Compaction now shrinks from the tail instead. It summarizes the
leading messages that fit, ending at a split point, and keeps the rest
of the history verbatim after the summary, using the kept-tail shape
that replay already rebuilds from the legacyTail flag on
context.apply_compaction. Trimming the head stays as the fallback when
the kept messages would take more than half of the compaction budget,
such as after switching to a model with a much smaller window, and when
no shorter prefix ends at a split point.
@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 57daf18

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
@moonshot-ai/agent-core-v2 Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T07:53:12.824960Z f941e34 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@57daf18
npx https://pkg.pr.new/@moonshot-ai/kimi-code@57daf18

commit: 57daf18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 11eb1edd87

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

…r the summary

An assistant message kept verbatim after the summary still carried the
provider usage of its request, which counted the history the summary
just replaced. Compaction sizes the context from the latest assistant
usage, so right after a kept-tail compaction the context still looked
as large as before and the next turn compacted again. The kept-tail
shape now drops that usage, for live compactions and for older sessions
with the same shape on replay alike; turn usage is recorded when the
message is appended and does not change.

The product changesets now say that earlier user messages survive only
in the summary on these paths, and that no setting keeps them verbatim.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f941e34300

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The kept-tail shape sized the compacted context from its messages
alone, while the normal shape adds the request overhead of the system
prompt and tool definitions. The token counting rebase took that
smaller number, so the next request reported less used context than it
had, and a Kimi request without an output limit would offer the missing
overhead as completion budget. The kept-tail shape now adds the same
overhead; replay keeps using the tokensAfter recorded on the event.
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.

2 participants