Repository navigation
fix(agent-core-v2): send the whole history to compaction and drop its head-trimming retries - #5538
Conversation
… 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 detectedLatest commit: 19a8526 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
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 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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".
| if (isContextOverflow || truncatedForLackOfRoom) { | ||
| if (isContextOverflow) this.observeContextOverflow(estimatedCompactionRequestTokens); |
There was a problem hiding this comment.
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 👍 / 👎.
| const truncatedForLackOfRoom = | ||
| error instanceof CompactionTruncatedError && outputSqueezedByWindow; |
There was a problem hiding this comment.
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 👍 / 👎.
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.
Requirement or Bug
没有单独的 issue,接着 #4402 和已关闭的 #5507 继续处理同一个问题。压缩请求「放不下」时,现在有三条路径会把历史从头部砍掉:预裁剪、服务端报超长后的重试、摘要被截断或为空后的重试。头部一变,接近窗口大小的压缩请求就和缓存对不上,整段按冷 prefill 计费,被砍掉的历史也不会进入摘要。
其中最常触发的是预裁剪:它给摘要预留了
min(128k, 窗口/8)的输出,1M 窗口下压缩请求的输入上限只有约 875k,而自动压缩在 850k 触发,一步涨超过约 25k 就会砍头。预裁剪当初是为「在 1M 模型上攒了大上下文,再切到 256k 模型」加的(#3911),现在模型都是 1M 窗口,这个场景已经不存在。这个 PR 删掉预裁剪和截断/空摘要的专属重试,只保留服务端报超长后的收缩。Bug Reproduction Steps
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以内预裁剪的线算上了一份远超实际需要的输出预留,所以在窗口还放得下时就砍头。这其实没有必要:LLM 层的
legalOutputCap本来就会把 max_tokens 压到「窗口 − 已用」,整段历史原样发出也能留出写摘要的空间。截断/空摘要重试删最早一条,对缓解截断几乎没有作用(近 1M 的历史少一条,摘要该多长还是多长),却让每次重试都丢掉缓存。这是根本修复:放得下时不再改动压缩请求的前缀;只有服务端真的拒绝,或者窗口确实没有给摘要留下空间时,才收缩。
Code Changes
核心思路:压缩请求第一次总是原样发出整段历史,由 LLM 层按剩余空间压低 max_tokens。之后只认两种「需要收缩」的信号,都交给现有的超长重试:服务端报超长;或者 max_tokens 被窗口压过、摘要又被截断。其余的截断直接失败,空摘要用同一个请求重试。
窗口 − usedTokens < 申请的输出上限计算LlmOutcome不带生效的 max_tokens,llm.requested发生在 legalize 之前;为此改 core 的输出类型不值得APIEmptyResponseError本来就可重试;同一个请求重试,前缀不变,缓存能命中阅读指南:
packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts的压缩循环:删掉的预裁剪调用、新的outputSqueezedByWindow和truncatedForLackOfRoom、删掉的截断/空摘要分支。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
shouldRecoverFromContextOverflow只认context_overflow和 ≥50% 窗口的 413),这类 provider 上压缩会直接失败compactionMaxAttemptscompactionMaxAttemptscompaction.completed的droppedCount、遥测dropped_countcompaction_failed.retry_count(空摘要耗尽时)正常压缩(输入放得下、摘要一次成功)的路径和压缩后的上下文形状都没有变。没有改提示词,也没有改契约文件(
wire-manifest.d.ts、事件 schema、kap.md)。测试覆盖:
droppedCount、剩余空间小于旧的 125k 预留;「compacts again instead of cancelling the turn…」去掉了两处缓存断点声明,由 testkit 账本校验压缩请求接上主请求的前缀。retry_count为 4。删掉的用例
droppedCountdroppedCount由 413 收缩等用例继续覆盖compactionMaxAttempts = 1时截断不重试compactionMaxAttempts由其余三个用例继续覆盖另外两个预裁剪用例改写成了上面第 1、5 行的回归用例。
验证细节
只在 Linux(Node 24)上运行过。这个 PR 不涉及路径、子进程或 shell。
pnpm lintpnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmitpackages/agent-core-v2全量packages/testkit、packages/node-sdk、tests/scenariospackages/kap-servertest/search/searchService.test.ts有 2 个失败,在 main 上同样失败,与本 PR 无关pnpm run check:duplication <merge-base>tests/e2e的 TUI、ACP 压缩场景Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.