Skip to content

fix(agent-core-v2): wait for in-flight auto compaction before the next step - #5454

Merged
sailist merged 1 commit into
mainfrom
fix/early-auto-compaction
Nov 26, 2026
Merged

sailist merged 1 commit into
mainfrom
fix/early-auto-compaction

Conversation

@RealKai42

Copy link
Copy Markdown
Collaborator

Requirement or Bug

把 loop_control.compaction_trigger_ratio 设得低于 0.85 的用户,自动压缩基本不生效:压缩在后台启动后和回合的下一步并发,下一步追加的回复让压缩结果被丢弃。上下文处在触发比例和 0.85 之间时,每一步都白跑一次完整的压缩请求,并弹出 "Context compaction did not finish",上下文直到 0.85 才真正缩小。更糟的是,如果上下文越过 0.85 时还有一个过期的压缩在跑,回合会以 interrupted / user_cancelled 结束,但用户并没有取消。

这个 PR 之后,压缩按配置的比例生效,回合不会再被误判为取消。默认配置(0.85)的行为不变。

Bug Reproduction Steps

  1. 在 config.toml 里设置 [loop_control] compaction_trigger_ratio = 0.7。
  2. 在一个会话里让上下文在回合中途越过 70%,例如读几个大文件。
  3. 观察 wire.jsonl:先有 full_compaction.begin,紧接着是 full_compaction.cancel,没有 context.apply_compaction;界面提示 "Context compaction did not finish";后续请求仍带着完整历史。
  4. 继续读文件,让上下文在压缩进行中越过 85%:回合以 interrupted、end_reason: user_cancelled 结束。

tests/scenarios/auto-compaction.test.ts 通过 KAP 复现第 1–3 步,新的引擎测试确定性地复现了两种现象。

Root Cause

  • 阻塞比例是 max(triggerRatio, 0.85)。触发比例更低时,beforeStep 只在 token 数达到阻塞比例时才等待压缩;在两者之间,压缩在后台跑,回合的下一步同时发出请求。
  • 压缩完成后,historySafeToCompact 只接受压缩期间追加的真实用户输入和注入消息。并发那一步追加的 assistant 和工具消息让检查失败,压缩结果在请求已经跑完、费用已经产生之后被丢弃。
  • 回合正在 block() 里等待这个压缩时,丢弃产生的 AbortError 被原样抛给回合,runStepStarting 把它当成中止,于是回合以取消结束。
sequenceDiagram
    participant Turn as 回合
    participant Compaction as 后台压缩
    Turn->>Compaction: 第 N 步后 token 越过触发比例,开始压缩
    Turn->>Turn: 第 N+1 步不等待(未到 0.85),请求并追加回复
    Compaction-->>Compaction: 摘要返回,历史已变,丢弃
    Note over Turn,Compaction: 若此时回合在 0.85 处等待它:丢弃 → AbortError → 回合以 cancelled 结束
Loading

这是根本修复:步骤不再和压缩赛跑;回合等待的压缩被丢弃时,基于当前历史重新压缩,而不是中止回合。

Code Changes

改动集中在 packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts:

 beforeStep
   checkAutoCompaction()            # 可能启动一次压缩
-  if shouldBlock(tokens)           # 只有达到 0.85 才等待
-    block()
+  block()                          # 只要有压缩在进行就等待

 block
-  wait for the active compaction; rethrow its abort to the turn
+  wait for the active compaction
+  if it was discarded because history changed
+    start a compaction of the current history and wait for it once more

compactionRound 里两处历史检查失败时,现在都通过 discardForChangedHistory 给这个压缩任务打上 historyChanged 标记并取消它本身(之前取消的是当时的 _compacting,并且没有区分"历史变化"和"被取消")。block() 只在看到这个标记、且回合本身没有被中止时才重新压缩;显式取消压缩(SDK 的 cancelCompaction)的处理不变。

决策 选择 没选 理由
怎样让并发步骤不再废掉压缩 步骤开始前等待进行中的压缩 把并发追加的 assistant 和工具消息保留在摘要之后 后者要改 context.apply_compaction 记录以及所有回放它的地方(journal、transcript、undo、replayBuilder、kap-server 的 fold),属于 wire 契约变更
回合等待的压缩因历史变化被丢弃时 重新压缩一次;再次被丢弃就不压缩直接继续这一步 直接继续;无限重试 只做第一项改动,会让更多回合去等一个已经过期的压缩然后被取消:目标续跑的 system_trigger、后台任务通知、!cmd 消息都会在回合之间追加进历史。只重试一次,避免异常情况下反复发压缩请求

阅读顺序:先看 fullCompactionService.ts 的 beforeStep、block、waitForActiveCompaction、discardForChangedHistory,再看测试。

CompactionStrategy.shouldBlock 现在不再被服务调用,阻塞比例只剩下决定"是否在每步结束后检查"的作用。为了让改动聚焦,这次没有改 strategy,可以后续简化。

Behavior Changes and Affected Users

行为 之前 之后 谁依赖旧行为 退路
compaction_trigger_ratio < 0.85,有自动压缩在进行时,回合下一步的模型请求 立即发出,与压缩并发 等压缩完成(或失败)后再发出 设置了该配置的用户:TUI、print 模式、desktop 与 web、VS Code、ACP,以及通过 SDK 设置 compactionTriggerRatio 的调用方。旧行为下压缩几乎都被丢弃,没有人能从并发中获益 不设置该配置或设为 ≥ 0.85,恢复"到 85% 才阻塞压缩"
同一配置下,上下文处在触发比例与 0.85 之间 每步发一次压缩请求然后丢弃,并提示 "Context compaction did not finish" 压缩一次并生效 无 同上
同一配置下,回合最后一步后在后台开始的压缩,下一个回合开始时 未到 0.85 时下一回合直接请求,压缩结果通常被丢弃 下一回合第一步等压缩完成;用户在压缩期间发消息时,首个请求会晚一次压缩的时长 同第一行 同第一行
回合等待的压缩因为历史变化被丢弃 回合以 cancelled(user_cancelled)结束 基于当前历史再压缩一次后继续;再次被丢弃则不压缩继续这一步 无,旧行为是误判取消 不需要
默认配置(0.85)下的自动压缩 每次都阻塞回合 不变 — —

默认配置不变的依据:触发比例等于阻塞比例时,beforeStep 原本启动压缩后一定会阻塞;beforeStep 时已有压缩在进行,只可能来自自带阻塞的上下文溢出恢复。"重新压缩"分支只在回合等待期间历史出现用户输入、注入消息以外的追加时才会触发,回合停在步骤开始阶段时 loop 不会做这种追加。显式取消压缩不会打 historyChanged 标记,处理不变。

受影响模块与测试覆盖:

  • agent-core-v2 的 full compaction 服务。
  • fullCompaction.test.ts 新增 "waits for an auto compaction started below the block ratio before requesting the step":覆盖第一、二行,断言压缩进行中没有主请求发出、压缩生效、回合正常完成。
  • fullCompaction.test.ts 新增 "compacts again instead of cancelling the turn when the compaction it waits for is discarded":覆盖第四行,用目标续跑消息让后台压缩过期,断言回合正常完成、用的是重新压缩的摘要。
  • 现有测试 "attributes background auto compaction to the turn that started it" 原先依赖后续回合的请求与压缩并发;现在改为等 compaction.blocked 后再放行压缩(第三行),断言没变。
  • 现有测试 "blocks the turn until auto compaction finishes" 继续覆盖第五行。
  • tests/scenarios/auto-compaction.test.ts:通过真实 KAP 会话(40k 窗口、触发比例 0.7)断言压缩生效、压缩后的请求带摘要且不再带旧文件内容、两个回合都正常完成。

验证:修复前,两个新引擎测试和 KAP 场景都失败;修复后都通过。没有涉及路径、子进程、shell 或终端输入,只在 macOS 上运行过。

运行记录
  • 修复前(HEAD 的服务代码):新测试 1 在压缩进行中发出了 1 个主请求;新测试 2 的目标续跑回合以 reason: cancelled、interruptReason: aborted 结束;KAP 场景第二个回合没有 compaction 条目。
  • 修复后:上述测试、更新的测试和 KAP 场景通过;pnpm lint 通过;tsc -p packages/agent-core-v2 和 tsc -p tests/scenarios 通过。
  • 整个 fullCompaction.test.ts 一起跑时,"names truncated compaction responses when retries are exhausted" 和 "honors loopControl.compactionMaxAttempts for retryable generation failures" 在高负载机器上超时(假定时器加一次 advanceTimersByTimeAsync)。它们在未改动的 main 上同样超时,单独运行能通过,与本 PR 无关。

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.

…t step

With loop_control.compaction_trigger_ratio below the 0.85 blocking ratio,
automatic compaction started in the background while the turn kept
running. The concurrent step appended its reply, so the compaction was
discarded after its request had completed, on every step until the
context reached the blocking ratio. When a turn then waited on such a
stale compaction, the discard surfaced as an abort and the turn ended as
cancelled.

Wait for an in-flight automatic compaction before starting a step, and
when the compaction a turn waits on is discarded because history changed
(for example a goal continuation or task notification appended between
turns), compact the current history once more instead of aborting the
turn.
@changeset-bot

changeset-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6a6d1b9

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 25, 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-25T17:45:24.936249Z 6a6d1b9 PR opened
🔒 Security Review ✅ Completed 2026-11-25T17:47:04.811550Z 6a6d1b9 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 25, 2026

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

commit: 6a6d1b9

@sailist
sailist merged commit 5b4fa96 into main Nov 26, 2026
22 checks passed
@sailist
sailist deleted the fix/early-auto-compaction branch November 26, 2026 02:30
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