Skip to content

fix(agent-core-v2): send the whole history to compaction and drop its head-trimming retries - #5538

Merged
7Sageer merged 1 commit into
mainfrom
fix/compaction-drop-preshrink
Nov 26, 2026
Merged

7Sageer merged 1 commit into
mainfrom
fix/compaction-drop-preshrink

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

没有单独的 issue,接着 #4402 和已关闭的 #5507 继续处理同一个问题。压缩请求「放不下」时,现在有三条路径会把历史从头部砍掉:预裁剪、服务端报超长后的重试、摘要被截断或为空后的重试。头部一变,接近窗口大小的压缩请求就和缓存对不上,整段按冷 prefill 计费,被砍掉的历史也不会进入摘要。

其中最常触发的是预裁剪:它给摘要预留了 min(128k, 窗口/8) 的输出,1M 窗口下压缩请求的输入上限只有约 875k,而自动压缩在 850k 触发,一步涨超过约 25k 就会砍头。预裁剪当初是为「在 1M 模型上攒了大上下文,再切到 256k 模型」加的(#3911),现在模型都是 1M 窗口,这个场景已经不存在。这个 PR 删掉预裁剪和截断/空摘要的专属重试,只保留服务端报超长后的收缩。

Bug Reproduction Steps

  1. 用 1M 窗口的模型,让上下文停在自动压缩阈值(850k)以下。
  2. 让一步的输入(比如一次很大的工具输出)把上下文推过约 875k,但仍在窗口内。
  3. 自动压缩的第一个请求就只带最近的消息,droppedCount > 0,几乎没有缓存命中。

用例里的复现:fullCompaction.test.ts 的「sends the whole usage-anchored history when it fits the window but not a full completion budget」(1M 窗口、用量锚点约 903k),以及「compacts again instead of cancelling the turn when the compaction it waits for is discarded」(1M 窗口、900k 用量,testkit 的缓存账本检查压缩请求是否接上主请求的前缀)。修复前前者的压缩请求缺了最早一轮,后者需要声明两处缓存断点才能通过。

Root Cause

fullCompactionService.ts 的压缩循环在输入需要变短时,三处都从头部删:

路径 原来的做法 触发条件
预裁剪 preShrinkHistoryToWindowBudget 一次砍到 (窗口 − 输出预留) × 0.85 以内 本地估算超过「窗口 − min(128k, 窗口/8)」
超长重试 依次只保留最近的 70%、50%、35%(累乘) 服务端报上下文超长
截断/空摘要重试 删掉最早一条再试 摘要被截断、为空或只有 thinking

预裁剪的线算上了一份远超实际需要的输出预留,所以在窗口还放得下时就砍头。这其实没有必要:LLM 层的 legalOutputCap 本来就会把 max_tokens 压到「窗口 − 已用」,整段历史原样发出也能留出写摘要的空间。截断/空摘要重试删最早一条,对缓解截断几乎没有作用(近 1M 的历史少一条,摘要该多长还是多长),却让每次重试都丢掉缓存。

这是根本修复:放得下时不再改动压缩请求的前缀;只有服务端真的拒绝,或者窗口确实没有给摘要留下空间时,才收缩。

Code Changes

核心思路:压缩请求第一次总是原样发出整段历史,由 LLM 层按剩余空间压低 max_tokens。之后只认两种「需要收缩」的信号,都交给现有的超长重试:服务端报超长;或者 max_tokens 被窗口压过、摘要又被截断。其余的截断直接失败,空摘要用同一个请求重试。

 compactionRound
-  history = preShrinkToWindowBudget(history)
   loop
     send(history + instruction)
     on context overflow
       observe a smaller window
       shrink history (70% → 35% → 12%)
+    on truncated summary and max_tokens was squeezed by the window
+      shrink history the same way, without learning a smaller window
-    on truncated or empty summary
-      drop the oldest message and retry
+    on truncated summary otherwise
+      fail
+    on empty or thinking-only summary
+      retry the same request (regular retryable path)
     on other retryable errors
       retry the same request
决策 选择 没选 理由
预裁剪和超长重试留哪个 留超长重试 留预裁剪、只把输出预留调小 超长重试兜的是事先算不出来的情况(本地估算偏低、实际窗口比配置小),预裁剪用的是同一个估算,发现不了;预裁剪能兜的情况都能改成事后发现,多发一个基本走缓存的请求
截断怎么处理 直接失败,只有输出被窗口压过时按超长收缩 保留删最早一条再试 删一条对截断几乎没用;opencode 和 pi 遇到截断也都直接失败。但输入约在 960k~1M 时 max_tokens 会被压到几千甚至 1,这时截断是没地方写,不是模型写得太长,直接失败会卡住会话
「输出被压过」怎么判断 压缩服务按 窗口 − usedTokens < 申请的输出上限 计算 让 core 透出实际生效的 max_tokens LlmOutcome 不带生效的 max_tokens,llm.requested 发生在 legalize 之前;为此改 core 的输出类型不值得
被压过的截断要不要记住更小的窗口 不记 和超长一样记 服务端没有拒绝请求,记下来会让这个会话之后都按更小的窗口提前压缩
空摘要 删掉专属分支,落进普通的可重试路径 保留删最早一条 APIEmptyResponseError 本来就可重试;同一个请求重试,前缀不变,缓存能命中

阅读指南:

  1. packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts 的压缩循环:删掉的预裁剪调用、新的 outputSqueezedByWindow 和 truncatedForLackOfRoom、删掉的截断/空摘要分支。
  2. packages/agent-core-v2/test/agent/fullCompaction/fullCompaction.test.ts 的 FullCompaction request window 一组:新的回归用例。

可以略读:删掉的 preShrinkHistoryToWindowBudget、dropOldestMessageAndLeadingToolResults 和 HistoryTokenProfile.overheadTokens(只有预裁剪在用);scripts/checks/baselines/test-doubles.json 是测试里遗留 mock 用量减少后按 lint 要求下调的基线;三份 changeset。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
压缩输入超过「窗口 − min(128k, 窗口/8)」但仍在窗口内 第一次请求前从头部砍掉,被砍的部分不进摘要 整段原样发出,max_tokens 压到剩余空间 所有客户端(TUI、print、Desktop 和 Web、ACP、SDK)上一步之内越过这条线的会话 无需:旧行为是要修的问题
压缩输入估算超过窗口,包括切到窗口小得多的模型 第一次请求前一次砍到预算以内,不依赖服务端怎么报错 先原样发出;服务端报超长后按 70% → 35% → 12% 收缩,三步之后仍放不下就失败 切到小窗口模型的用户;超长错误识别不了的 provider(shouldRecoverFromContextOverflow 只认 context_overflow 和 ≥50% 窗口的 413),这类 provider 上压缩会直接失败 无,请维护者确认。前提是现在只有 1M 窗口的模型
主请求报超长后触发的压缩 先记住更小的窗口,预裁剪按新窗口砍好再发 第一次压缩请求原样发出,会再被拒一次,之后才收缩 主请求超长的会话:多一次失败请求和一点延迟 无
摘要被截断,窗口留出了完整的输出预算 删最早一条再试,直到 compactionMaxAttempts 压缩直接失败 thinking 很重、或摘要写得很长的模型 无,请维护者确认
摘要被截断,max_tokens 被窗口压过 同上 按超长收缩后重试,不记住更小的窗口 输入接近窗口的会话 无需
摘要为空或只有 thinking 删最早一条再试 退避后用同一个请求重试,次数上限仍是 compactionMaxAttempts 只返回 thinking 的模型 无需
compaction.completed 的 droppedCount、遥测 dropped_count 预裁剪、超长重试、截断/空摘要重试都会累加 只有超长收缩(含被压过的截断)会累加 读取 wire 的工具、遥测看板 无
遥测 compaction_failed.retry_count(空摘要耗尽时) 每次删消息后归零,耗尽时是 1 按退避次数累计,默认上限下耗尽时是 4 遥测看板 无

正常压缩(输入放得下、摘要一次成功)的路径和压缩后的上下文形状都没有变。没有改提示词,也没有改契约文件(wire-manifest.d.ts、事件 schema、kap.md)。

测试覆盖:

  • 第 1 行:「sends the whole usage-anchored history when it fits the window but not a full completion budget」断言整段历史发出、没有 droppedCount、剩余空间小于旧的 125k 预留;「compacts again instead of cancelling the turn…」去掉了两处缓存断点声明,由 testkit 账本校验压缩请求接上主请求的前缀。
  • 第 2 行:「auto-compacts over-window context by shrinking after the provider rejects the full history」断言第一次请求是整段历史,被拒后收缩;原有的超长重试用例不变。
  • 第 4 行:「fails a truncated compaction without retrying when the window left room for the summary」断言只发一次请求。
  • 第 5 行:「shrinks and retries a summary truncated because the window left no room for it」:80k 窗口、约 70k 历史,第一次截断后收缩重试成功。关掉这条判断时这个用例会失败。
  • 第 6、8 行:空摘要、只有 thinking 的重试和重试耗尽三个用例,改为断言每次请求的输入完全相同,耗尽时 retry_count 为 4。
  • 上面 8 个用例在 main 的实现上全部失败,在这个分支上全部通过。
  • 第 3 行没有单独的用例:主请求超长后,压缩请求的超长收缩仍由已有的超长重试用例覆盖。
删掉的用例
用例 原来覆盖什么 删除原因
pre-shrinks the summary request history to the effective window budget before the first request 预裁剪按窗口预算砍头 行为已删除
counts system prompt and tool overhead into the pre-shrink budget 预裁剪预算扣掉 system 和工具开销 同上
reports pre-shrunk messages in the compaction droppedCount 预裁剪计入 droppedCount 同上;超长收缩计入 droppedCount 由 413 收缩等用例继续覆盖
falls back to reactive overflow shrinking when the pre-shrunk request still overflows 预裁剪后仍超长时的超长收缩 改为由「auto-compacts over-window context by shrinking…」和已有的 413 收缩用例覆盖
does not pre-shrink when the effective context window is unknown 窗口未知时跳过预裁剪 行为已删除
sends the full history when the newest message alone exceeds the budget 预裁剪在最新一条就超预算时不砍 同上
fails a truncated compaction immediately when compactionMaxAttempts is 1 compactionMaxAttempts = 1 时截断不重试 截断不再重试,和改写后的截断用例重复;compactionMaxAttempts 由其余三个用例继续覆盖
probes only the first compaction response after a truncated summary retries 截断重试后只探测第一次压缩响应的缓存 截断不再重试;「重试后只探测第一次」由「reports unknown usage for the first successful response after a network failure」继续覆盖

另外两个预裁剪用例改写成了上面第 1、5 行的回归用例。

验证细节

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

检查 结果
pnpm lint 通过
pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmit 通过
packages/agent-core-v2 全量 8415 个通过
packages/testkit、packages/node-sdk、tests/scenarios 228、297、71 个通过
packages/kap-server 1571 个通过;test/search/searchService.test.ts 有 2 个失败,在 main 上同样失败,与本 PR 无关
pnpm run check:duplication <merge-base> 没有新增重复
tests/e2e 的 TUI、ACP 压缩场景 未验证:需要构建产物,这次没有跑

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.

… head-trimming retries

Compaction no longer trims the oldest messages before its first request.
The LLM layer already lowers max_tokens to the room the window leaves,
so the whole history goes out and keeps the cached prefix.

A truncated summary fails the compaction unless the window squeezed its
output, in which case it shrinks like a context-overflow rejection.
Empty or thinking-only summaries are retried with the same request.
@changeset-bot

changeset-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 19a8526

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-26T12:32:35.636213Z 19a8526 PR opened
ℹ️ 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@19a8526
npx https://pkg.pr.new/@moonshot-ai/kimi-code@19a8526

commit: 19a8526

@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: 19a8526a85

ℹ️ 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".

Comment on lines +744 to +745
if (isContextOverflow || truncatedForLackOfRoom) {
if (isContextOverflow) this.observeContextOverflow(estimatedCompactionRequestTokens);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep a fallback for unrecognized overflow responses

When a custom or smaller-window model’s provider returns an overflow response that shouldRecoverFromContextOverflow does not recognize, this gate is false and the full-history request falls through to the non-retryable error path; the removed pre-shrink used to send a fitting suffix instead. The changeset describes this loss, but there is no escape hatch or maintainer approval, so preserve a local fallback or add a gated legacy mode with a guard test.

AGENTS.md reference: AGENTS.md:L195-L197

Useful? React with 👍 / 👎.

Comment on lines +742 to +743
const truncatedForLackOfRoom =
error instanceof CompactionTruncatedError && outputSqueezedByWindow;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep recovery for truncation when the window has room

When a model returns a truncated summary even though the local estimate says the window left the configured output budget, truncatedForLackOfRoom is false and this error now falls through to immediate failure; before this change, compaction dropped the oldest message and retried. The new test locks in that loss, but there is no escape hatch or maintainer approval; preserve the old recovery behind a setting or obtain approval and test the affected users’ path.

AGENTS.md reference: AGENTS.md:L195-L197

Useful? React with 👍 / 👎.

@7Sageer
7Sageer merged commit 2def6b4 into main Nov 26, 2026
22 checks passed
@7Sageer
7Sageer deleted the fix/compaction-drop-preshrink branch November 26, 2026 12:39
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
Compaction (MoonshotAI#5538):
- Send the whole history to the summary request, drop the pre-shrink and
  the drop-oldest retries, shrink a truncated summary only when the window
  squeezed its output, and retry empty or thinking-only summaries with the
  same history. Keep flushReminders, applyCompactionRound and
  historyFromContextPreservingToolNotes.
- Fix two pre-existing 2.7-alignment gaps the suite exposed: recognise the
  serialized { kind: 'context_overflow' } payload in
  shouldRecoverFromContextOverflow, and remove the duplicate
  runWithCredentialRecovery around the requester's own credential recovery
  so a replayed 401 surfaces instead of being retried.
- fullCompaction 124 pass / 0 fail; agent-core-v2 typecheck clean.

Built-in tool settings (MoonshotAI#5489):
- Keep MoonshotAI#5351's KAP catalog/config/agent-state fields, the four mode guards
  and the desktop/Web UI as a fork-only capability.
- Replace the 22 per-tool userConfigurable flags with the central
  USER_CONFIGURABLE_BUILTIN_TOOL_NAMES list in kap-server. The catalog still
  returns the same 39 entries (26 core + 13 Tower), now pinned by
  tools.test.ts.
- Ledger: MoonshotAI#5351 marked fork-only, MoonshotAI#5489 not-applicable with the keep-both
  approval, both in B2; the PLAYBOOK records the invariant.
- kap-server tools 8 pass; agent-core-v2 and kap-server typecheck clean.

Loop baseline:
- max_steps no longer marks a completed step as interrupted.
- Goal creation accepts UpdateGoal when it is loadable through
  isToolActiveForDisclosure.
- Refresh the three loop inline snapshots for the intentional
  continuation, loadable-tools and step.begin shape.
- test/agent/loop 175 pass / 3 fail; the three remaining failures are the
  pre-existing cancelled-partial preservation, recorded as the first
  acceptance of the MoonshotAI#5541 requester migration.

Ledger refresh adds 87 upstream rows; MoonshotAI#5538 and MoonshotAI#5489 are triaged, 85 remain
pending.
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