Skip to content

fix(agent-core-v2): keep the prompt cache through auto compaction - #4456

Merged
7Sageer merged 7 commits into
mainfrom
fix/compaction-pre-shrink-cache
Oct 27, 2026
Merged

7Sageer merged 7 commits into
mainfrom
fix/compaction-pre-shrink-cache

Conversation

@7Sageer

@7Sageer 7Sageer commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

#3911 引入的 compaction 预裁剪,让上下文窗口大于约 195k 的模型每次自动 compaction 都会丢掉 prompt cache。这个 PR 同时补上诊断埋点,让后台能区分客户端破坏缓存前缀和服务端未命中。

Bug Reproduction Steps

1. Compaction 预裁剪

  1. 使用 256k(或 1M)窗口的模型,默认 compaction 配置。
  2. 对话增长到刚过自动 compaction 触发点(256k 下为 W − 50k = 206k,1M 下为 0.85W = 850k)。
  3. 观察 compaction 请求:最旧的几条消息被删掉,请求和上一次 loop 请求在 history[0] 处就不同了,所以只有 system prompt 和 tools 还能命中缓存,整段历史都要重新写缓存。

修复前用临时测试实测:256k 窗口下,compaction 请求从 user 8 开始,前 16 条消息被删;1M 窗口下从 user 7 开始,两者都在 history[0] 断开前缀。

Root Cause

preShrinkHistoryToWindowBudget 用的预算是 (W − min(cap, W/8)) × 0.85 − overhead。在 W ≤ 1M 时这大约是 0.744W,而自动触发点是 min(0.85W, W − 50k):

窗口 W 自动触发点 旧预裁剪预算
256k 206k ≈190k − overhead
1M 850k ≈744k − overhead

触发点一定高于预算,所以每次自动 compaction 都会走裁剪,而裁剪删的是最旧的消息,前缀必然断开。手动 /compact 只要上下文超过约 0.744W 也一样。

#3911 原本针对的是"历史已经超出当前模型窗口"(例如换成小窗口模型),但它用的安全预算比触发点还严,把正常情况也拉进了裁剪路径。这次是根本修复:把"是否预裁剪"的判断和"裁到多少"分开。

Code Changes

 preShrinkHistoryToWindowBudget(history, instruction, cap)
   outputReserve = min(cap, W / 8)
-  budget = floor((W − outputReserve) × 0.85) − overhead
-  if budget <= 0 or estimate(messages) <= budget
-    return history
+  inputLimit = W − outputReserve
+  if estimate(messages) + overhead <= inputLimit
+    return history                       # 请求放得下窗口:完整发送,保住缓存前缀
+  budget = floor(inputLimit × 0.85) − overhead
+  if budget <= 0
+    return history
   return takeRecentMessagesWithinTokenBudget(history, budget)

 compaction request (每次尝试)
   maxOutputSize = compactionMaxOutputSize
+  usedContextTokens = estimate(request) + ceil(W × 2%)   # provider 据此把 max_tokens 钳到 min(cap, W − used)
  • 只有估算的请求大小真的超过"窗口 − 输出预留"时才预裁剪;裁剪目标仍是原来的 0.85 安全预算。

  • 默认配置下,自动触发点加上输出预留不会超过窗口(256k:206k + 32k < 256k;1M:850k + 128k < 1M),所以正常的自动 compaction 都发送完整历史。

  • 发送完整历史后,剩余窗口会小于 compaction 请求的输出上限(例如 256k 窗口、maxOutputSize = 64k:触发点约 206k,206k + 64k > 256k)。loop 请求本来就靠 usedContextTokens 把 max_tokens 钳到 W − used,compaction 因为传了 messages override 之前拿不到这一步。现在 compaction 每次请求都显式传 usedContextTokens(请求估算 + 窗口 2% 的估算余量),由 provider 层现有的 resolveMaxCompletionCap 钳制,因此 modelOverrides.maxCompletionTokens 等任何来源的上限都会被钳住,显式 opt-out(≤ 0)保持不发送。

    • 估算余量只作用于输出上限,不进入预裁剪判断,避免 1M 窗口默认 128k 上限的模型在触发点附近重新预裁剪。
    • 钳制后的范围是 min(cap, W/8) 到 cap:128k–256k 窗口在自动 compaction 时约 30k–49k,1M 窗口基本不受影响;摘要正文通常只有几千 token。
  • AgentLLMRequestOverrides 新增可选 usedContextTokens,未传时沿用原有推导,其他调用方不变。

  • 测试方面:新增一个回归用例,256k 窗口、真实内容撑到刚过触发点,断言 compaction 请求以完整的原历史开头(撤掉修复后这个用例会失败);fix(agent-core-v2): pre-shrink compaction history to the effective model window #3911 的预裁剪夹具原本落在"旧预算 < 历史 < 窗口"这段区间,把最旧那条消息加大,使它确实超出窗口,继续覆盖超窗场景。

  • 新增 IAgentContextProjectorService.captureMediaDegradeCount:返回 max(0, 媒体数 − 2)。

  • 继承的降级状态在新图把请求再次撑到 413 时,先重新计数降级;仍然 413 才 strip。不做这一步的话,降级不再滚动之后会直接跳到 strip、删掉所有图,比原来更差。

  • 测试 harness:删掉 prompt-cache 守卫里对滚动降级的豁免(alignDegradedMedia),守卫现在对降级请求也做严格的前缀检查;fix(agent-core-v2): keep media recovery across turns and compaction #4413 的前缀用例在严格守卫下照样通过。

  • 新增回归用例:降级后下一 turn 加新图,前缀保持不变;继承降级状态后被新图再次 413,会重新降级而不是 strip(这两个用例撤掉修复后都会失败);projector 层:快照之后追加的媒体保持原样。

另外复用 prompt_cache_probe 增加 source=compaction:

compaction 首次请求创建
  固定当时的 lastTurnRequest 快照
  实际消息投影与媒体解析
  比较 model / system prompt / tools / history 前缀 hash
  首个成功响应
    上报 cache read / cache creation / input / output、baseline 输入量和请求间隔
    截断后的重试不再重复上报
  网络失败且无 usage
    保留 probe,等待下一次成功响应
  • history 比较基于 provider 实际接收的投影消息:用上一轮消息数截取本次前缀,再比较 hash;遥测只包含 hash、布尔值、token 数和时间,不包含消息正文。
  • model 或 context revision 不一致时不比较无关前缀,对应 match 和 baseline 字段缺省;没有上一轮基线也不会伪造 history_prefix_match=false。
  • 后台读取规则:任一 match 为 false 可定位客户端对应前缀变化;全部 match 为 true 但 input_cache_read 缺失或偏低时,结合 parent_request_gap_ms、provider 和模型判断缓存超时、淘汰或服务端策略,不能仅凭未命中直接断言超时。基线不可用时字段缺省,不参与归因。
  • fork 原有 probe 的发射条件和字段含义不变;parent_input_tokens / parent_request_gap_ms 在 compaction 中表示上一轮请求的对应值。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
请求估算在"0.85 × (W − 预留) − overhead"到"W − 预留"之间时,compaction 首次请求的历史 从最旧消息开始裁掉,首次请求一定能放进安全预算 发送完整历史,输出上限钳到剩余窗口;如果估算偏低导致实际超窗,交给原有的 0.7/0.5/0.35 超窗回退缩减 所有客户端(TUI、print 模式、desktop 与 web、VS Code、ACP、SDK)中窗口大于约 195k 的模型的自动 compaction,以及上下文超过约 0.744W 时的手动 /compact。旧行为对它们没有好处,只会让缓存失效 无需退路:输入加钳制后的输出上限不超过窗口,与 loop 请求的钳制规则一致
请求估算超过"W − 预留"时(例如换成小窗口模型后历史超窗) 预裁剪到 0.85 安全预算 不变 — —
compaction 请求的 max_tokens 固定为 maxOutputSize(或默认 min(W, 128k)、modelOverrides.maxCompletionTokens),不随输入收窄 min(上述上限, W − 请求估算 − 2%W),下限为 provider 的 1;显式 opt-out(≤ 0)仍不发送 所有 provider 方言的 compaction 请求;原先在"输入 + 上限 > 窗口"时会被校验窗口的 provider 拒绝 无需退路:只收窄超出窗口的部分,窗口内可用的输出空间不变
窗口未知(≤ 0)时 跳过预裁剪 不变(也不传 usedContextTokens) — —
prompt_cache_probe 遥测 只有 fork 首个 turn 请求 增加 compaction 首个成功响应的 source=compaction 样本及 model/history 对照;fork 行为不变 未按 source 过滤的缓存命中率聚合会混入 compaction 样本;只读取 fork 旧字段的查询保持兼容 按 source=fork / source=compaction 分别聚合;无基线时跳过 match 字段
docs/state-manifest.d.ts 中的 llmRequester.lastTurnRequest 类型 包含 model、revision、system/tools hash、usage 和时间 加法增加 messageCount / historyHash,仅供运行时缓存对照;不持久化消息或新增 wire 字段 使用状态检查接口的调试工具读取到两个新增字段;旧会话、旧客户端请求和状态恢复路径不变 无需迁移,未知新增字段可忽略

已知的取舍:如果估算落在上表第一行的区间、但实际已经超出窗口,首次请求会失败,要靠超窗错误被正确识别才能走回退;输出上限按估算加 2% 余量钳制,估算偏差超过余量时同理。被观测到的超窗上限(observedMaxContextTokensByModel)只参与余量计算,provider 钳制仍以配置窗口为准。

受影响模块:packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts;src/agent/contextProjector/、src/agent/llmRequester/llmRequester.ts、llmRequesterService.ts、src/app/telemetry/events.ts;契约文件 docs/state-manifest.d.ts(已重新生成)。mediaProjection 从包入口导出,degradeOlderMediaParts 改名为 degradeLeadingMediaParts、新增 countMediaParts;仓库内没有包外调用方。

测试覆盖:

  • 第 1 行:新增 sends the full history when an auto compaction request fits the window。
  • 第 2 行:fix(agent-core-v2): pre-shrink compaction history to the effective model window #3911 的预裁剪用例(夹具已调整为确实超窗),包括 pre-shrinks the auto compaction triggered before a step、falls back to reactive overflow shrinking when the pre-shrunk request still overflows、counts system prompt and tool overhead into the pre-shrink budget。
  • 第 3 行:新增 clamps the compaction completion budget to the window left by the full history(256k 窗口、maxOutputSize = 64k,断言完整历史前缀、原始上限 64k、剩余窗口在 0 与 64k 之间;撤掉修复后失败);原有 honors maxOutputSize / default 128k hardCap / env hard cap / opt-out 用例继续通过。
  • 第 4 行:does not pre-shrink when the effective context window is unknown。
  • 媒体降级前缀:keeps the media-degraded prefix when a later turn adds new media;keeps media degraded by an earlier snapshot unchanged when newer media are appended;harness 守卫对 fix(agent-core-v2): keep media recovery across turns and compaction #4413 前缀矩阵(media-degraded 场景)做严格检查。
  • 媒体降级重新计数:re-degrades instead of stripping when new media push an inherited degraded request over the limit。
  • 缓存诊断:7 个 compaction probe 用例覆盖完整前缀、预裁剪及 reactive overflow shrink 的 history mismatch(包括裁剪后消息数少于基线)、切模型、context revision 失效、无基线网络重试和截断重试;原 fork probe 用例继续通过,state manifest 已重新生成。
  • 新增诊断遥测没有用户配置或 CLI 行为,因此不增加额外 changeset 或用户文档。

验证:最新提交基于 2c8e2416,typecheck、无注释检查、目标 oxlint、6 个 probe 用例及包含媒体降级在内的 108 个相关测试通过。最终全量为 7457 通过、2 失败:returns the spawned agent id when a foreground subagent times out 在基线 e4eb803c 上也稳定复现 30 秒超时;rescans the workspace source when a project agent file changes on disk 单独重跑通过。lint:imports 在基线与当前分支均有相同 4 条未改动文件报错,本次没有新增 import 违规。

输出上限钳制:fullCompaction、llmRequester、usage 共 238 个测试通过,agent-core-v2 typecheck 与无注释检查通过,oxlint 无新增告警。

补充验证:reactive overflow shrink 短历史回归在修复前因 history_prefix_match 缺失失败、修复后通过;fullCompaction.test.ts 122 个测试通过,agent-core-v2 typecheck 与无注释检查通过。

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.

…st overflows the window

The pre-shrink budget (~0.74 of the window) sat below the auto-compaction trigger (min(0.85W, W-50k)), so every auto compaction on windows above ~195k dropped the oldest messages and broke the prompt-cache prefix. Gate pre-shrinking on the real input limit (window minus output reserve) and keep the safety budget as the shrink target.
Copilot AI balanced review requested due to automatic review settings October 27, 2026 03:39
@changeset-bot

changeset-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 629f19d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

Media degradation recomputed 'keep the 2 most recent' on every request, so each new image after a 413 replaced an older kept image and broke the prompt-cache prefix. Record how many leading media were degraded when the provider rejected the request, re-capture only when an inherited degraded request is rejected again with more than 2 visible media, and drop the prompt-cache guard's tolerance for rolling degradation.
@7Sageer 7Sageer changed the title fix(agent-core-v2): only pre-shrink compaction history when the request overflows the window fix(agent-core-v2): keep the prompt cache through auto compaction and degraded media Oct 27, 2026
@7Sageer 7Sageer changed the title fix(agent-core-v2): keep the prompt cache through auto compaction and degraded media fix(agent-core-v2): keep the prompt cache through auto compaction Oct 27, 2026
@7Hanrui

7Hanrui commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-27T06:35:02.610136Z 629f19d 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.

@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: 42b06183e9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

return media;
};
const captureMediaDegradePolicy = (): { readonly degradeCount: number } => {
const media = { degradeCount: this.projector.captureMediaDegradeCount(shaped) };

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 Count media after applying the active structural projection

When a structure error is followed by a 413, this callback counts media using the normal projection, while the retry applies that count after projectStrict has potentially dropped leading non-user messages. For example, two images in a leading assistant message plus two in the following user message produce degradeCount: 2; strict mode drops the assistant message and then degrades both remaining user images, retaining none instead of the intended two newest. The former degraded policy counted after strict projection, so those images survived; capture the count using the active structure policy instead.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

Comment on lines +503 to +508
const historyPrefixMatch =
compared && cacheProbeBaseline.messageCount <= input.messages.length
? fingerprint(
JSON.stringify(input.messages.slice(0, cacheProbeBaseline.messageCount)),
) === cacheProbeBaseline.historyHash
: undefined;

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 Report shortened histories as cache-prefix mismatches

When compaction pre-shrinks the request below the baseline's messageCount, the baseline is valid but this condition leaves history_prefix_match undefined. A shorter history cannot contain the baseline history as a prefix, so the new diagnostic incorrectly makes this case indistinguishable from having no usable baseline and cannot attribute exactly the prefix break it was added to detect; return false when compared is true but the message count is smaller.

Useful? React with 👍 / 👎.

Comment on lines +500 to +502
cacheProbeBaseline !== undefined &&
cacheProbeBaseline.modelAlias === request.modelAlias &&
cacheProbeBaseline.contextRevision === request.contextRevision;

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 Compare the resolved model instead of its reusable alias

If provider configuration is hot-reloaded under the same alias between the last turn and compaction, the catalog resolves a new model or endpoint but this check still reports a model match and emits prefix comparisons against a request whose cache cannot be shared. This undermines the new attribution telemetry for custom-model users; store and compare the resolved model/provider endpoint identity rather than only modelAlias.

Useful? React with 👍 / 👎.

@7Hanrui

7Hanrui commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

@codex review

@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: 0ee9d42d34

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

this.tokenCounting.estimateMessages(history) +
this.tokenCounting.estimateMessage(createUserMessage(instruction));
if (messageBudget <= 0 || estimatedMessagesTokens <= messageBudget) return history;
if (estimatedMessagesTokens + overheadTokens <= inputLimit) return history;

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 Reserve the full completion budget before skipping pre-shrink

When max_output_size exceeds one eighth of the context window and the provider enforces input + max completion <= context, this new early return can send a request that cannot fit. For example, with a 256k window and a configured 64k output cap, outputReserve is capped at 32k, so a 206k auto-compaction request bypasses pre-shrink even though the requester sends maxCompletionTokens: 64000; the provider rejects roughly 270k requested tokens, and reactive overflow shrinking then drops the cached prefix. The previous 0.85 safety budget kept this configuration near 190k input and within the window, so either account for the actual completion cap here or lower the cap passed with the full-history request.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

Comment on lines +1003 to +1005
readonly media: /* MediaProjection — packages/agent-core-v2/src/agent/contextProjector/contextProjector.ts */ {
readonly degradeCount: number;
} | {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the media recovery state contract

When a previous-release debug/state-inspection client reads an agent after media degradation, this replaces the documented media: 'degraded' value with an object, so consumers that branch on the old literal silently stop recognizing the degraded state. Unlike the additive messageCount and historyHash fields described by the PR, this is a breaking replacement in a contract explicitly consumed by the external inspector and other clients; retain a compatible representation or version the contract and update the named consumers.

AGENTS.md reference: AGENTS.md:L123-L125

Useful? React with 👍 / 👎.

"@moonshot-ai/kimi-code": patch
---

Fix automatic compaction discarding the prompt cache whenever the conversation still fit the model's context window.

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 Restore the media-recovery changeset

This PR also fixes a separate user-visible bug where adding new media after a 413 discards the prompt-cache prefix, but the sole changeset only mentions automatic compaction. As a result, that shipped media-recovery fix will be absent from the generated release notes; keep its separate changeset rather than folding two independent fixes into this compaction-only sentence.

AGENTS.md reference: AGENTS.md:L90-L91

Useful? React with 👍 / 👎.

@7Sageer
7Sageer marked this pull request as ready for review October 27, 2026 05:14
@pkg-pr-new

pkg-pr-new Bot commented Oct 27, 2026 •

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

commit: 629f19d

@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: 0ee9d42d34

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

toolsHash: recorded.toolsHash,
systemPromptHash: recorded.systemPromptHash,
messageCount: input.messages.length,
historyHash: fingerprint(JSON.stringify(input.messages)),

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 Defer hashing until a compaction probe is needed

When a successful turn contains a long history or inline media, this synchronously serializes and hashes the entire provider-visible message array—even though the digest is only used if a later compaction probe runs. The media resolver permits up to 20 MiB of media per request, so image-heavy sessions can incur tens of megabytes of temporary allocation on every turn or step, adding event-loop stalls and memory pressure; compute the digest only when a probe needs it or hash incrementally.

Useful? React with 👍 / 👎.

…ng window

Sending the full history leaves less room than the configured output cap,
so pass the estimated request size as usedContextTokens and let the
provider clamp max_tokens to the window that is actually left.

@RealKai42 RealKai42 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

把 #4452(收紧后的 prompt-cache guard,加上默认触发点的复现用例)合到 629f19d 本地验证过:

  • #4452 在当前 main 上的 13 个预期失败全部通过,相关测试文件也都通过。
  • 两边只在 test/harness/prompt-cache-guard.ts 冲突。解法是保留 #4452 的收紧逻辑,同时去掉本 PR 删除的降级媒体豁免。
  • 这个 PR 先合,我再 rebase #4452。

行内两条是同一个问题。触发 compaction 用的是 tokenCountWithPending()(provider 实测值,加上还没计量部分的估算),而"是否预裁剪"和"completion budget 收缩"用的是纯启发式(ASCII 每 4 字符 1 token、非 ASCII 每字符 1 token、每张图 2000)。两者一有偏差,默认触发点的余量就不够用了。

实验方法:fake provider 按"启发式 × s"上报 usage,用真实 turn 把实测值撑到默认触发点,再分别做手动和自动 compaction。两种方式结果一致:

窗口 s(实测 / 启发式) compaction 请求
256k 1.3 完整历史,但实际输入 221k + max_tokens 86.9k = 308k,超过 262k
256k 1.0、0.97 完整历史 ✓
256k 0.9、0.7 从 history[0] 断开
1M 1.3、1.0 完整历史 ✓
1M 0.97、0.9、0.7 从 history[0] 断开(0.97 时丢了最旧的 16 条)

s < 1 对应中文和图片偏多的会话,s > 1 对应代码偏多的会话。所以 PR 描述里"默认配置下……正常的自动 compaction 都发送完整历史"这句,只在启发式和实测基本一致时成立。

#4452 的 guard 判定裁剪时用的是 max(启发式, 实测),同样没拦住这种情况,这是我那边的漏洞。如果这里改成实测口径,我会把 guard 收紧成只看实测,并把上面这组用例加进 #4452。

this.tokenCounting.estimateMessages(history) +
this.tokenCounting.estimateMessage(createUserMessage(instruction));
if (messageBudget <= 0 || estimatedMessagesTokens <= messageBudget) return history;
if (estimatedMessagesTokens + overheadTokens <= inputLimit) return history;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

P1 这里判断"放不放得下"用的是启发式,和触发用的口径(tokenCountWithPending())不一致。

1M 窗口下默认触发点是 891,290,inputLimit 是 917,504,余量只有约 2.9%。启发式只要比实测高 3%,就会走下面的裁剪,原 bug 原样复现(数据见 review 正文的表)。256k 窗口的余量约 8.1%。

建议改成和触发同一个口径:

const requestTokens =
  this.tokenCountWithPending() +
  this.tokenCounting.estimateMessage(createUserMessage(instruction));
if (requestTokens <= inputLimit) return history;
  • historyForModel 进来时就是完整的 context.get(),和 tokenCountWithPending() 覆盖的是同一份历史。这段前缀上一次 turn 请求刚被 provider 接受过,实测值就是它的真实大小。
  • 默认配置下,min(0.85W, W − 50k) + min(128Ki, W/8) ≤ 0.975W。改完之后,不管窗口多大、内容是什么,默认触发点都不会再预裁剪。
  • 真超窗时,裁剪目标可以继续用启发式(takeRecentMessagesWithinTokenBudget),因为那时只能估子集的大小。
  • fix(agent-core-v2): pre-shrink compaction history to the effective model window #3911 那几个用 appendExchange(..., 20/40/80) 的夹具实测值很小,需要把实测总量也调到确实超窗。

Comment on lines +668 to +671
const usedContextTokens =
effectiveMaxTokens > 0
? estimatedCompactionRequestTokens +
Math.ceil(effectiveMaxTokens * COMPLETION_BUDGET_ESTIMATE_MARGIN_RATIO)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

P1 同一个口径问题,方向相反:这里用启发式估算请求大小来收缩 max_tokens,代码偏多时启发式偏低,收缩就不够。

256k 窗口、s = 1.3 时,实际输入 221k,发出的 max_tokens 是 86.9k,合计 308k,超过 262k。如果 provider 校验"输入 + max_tokens ≤ 窗口",请求就会走超窗回退,cache 照样丢。

还要注意和上一条的联动:如果只把预裁剪判断改成实测、这里还用启发式,就会出新问题。中文为主时,完整历史的启发式值可能超过 W(实验里 1M、s = 0.7 时启发式是 1.27M),resolveMaxCompletionCap 会把 max_tokens 压到 1。

建议:历史没被裁剪时,这里用 tokenCountWithPending() 加上指令的估算;裁剪之后实测值已经对不上子集,再退回启发式。

@7Sageer
7Sageer merged commit 68a2838 into main Oct 27, 2026
16 checks passed
@7Sageer
7Sageer deleted the fix/compaction-pre-shrink-cache branch October 27, 2026 10:59
7Sageer added a commit that referenced this pull request Oct 27, 2026
) (#4471)

* fix(agent-core-v2): only pre-shrink compaction history when the request overflows the window

The pre-shrink budget (~0.74 of the window) sat below the auto-compaction trigger (min(0.85W, W-50k)), so every auto compaction on windows above ~195k dropped the oldest messages and broke the prompt-cache prefix. Gate pre-shrinking on the real input limit (window minus output reserve) and keep the safety budget as the shrink target.

* fix(agent-core-v2): pin degraded media to the count captured at the 413

Media degradation recomputed 'keep the 2 most recent' on every request, so each new image after a 413 replaced an older kept image and broke the prompt-cache prefix. Record how many leading media were degraded when the provider rejected the request, re-capture only when an inherited degraded request is rejected again with more than 2 visible media, and drop the prompt-cache guard's tolerance for rolling degradation.

* feat(agent-core-v2): probe compaction prompt cache prefixes

* chore: drop duplicate degraded media changeset

* fix(agent-core-v2): report prefix loss after compaction shrinks history

* fix(agent-core-v2): clamp compaction completion budget to the remaining window

Sending the full history leaves less room than the configured output cap,
so pass the estimated request size as usedContextTokens and let the
provider clamp max_tokens to the window that is actually left.

* Delete .changeset/fix-compaction-pre-shrink-cache.md



---------


(cherry picked from commit 68a2838)

Signed-off-by: 7Sageer <[email protected]>
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 3, 2026
Port of upstream MoonshotAI/kimi-code 68a2838 (MoonshotAI#4456).

Auto compaction now pre-shrinks the summary request history to the
effective window budget before the first request, so the compaction
request stays on the prompt-cache prefix, and the compaction probe
reports cache usage plus prefix parity (model/tools/system prompt/
history) against the baseline turn request, with the cacheProbePending
guard so only the first attempt probes.

This replaces the fork's earlier equivalent implementation (4eb8d59)
with upstream's baseline-shaped snapshot and telemetry payload, per the
alignment rule for equivalent-but-different implementations.

Fork features re-applied on upstream's llmRequesterService:
- proactive media eviction (estimateLlmRequestBytes, sizeProbe,
  ProactiveMediaEscalation, resolveRequestByteBudget) with the
  logRequestFailure/trackApiError estimated_request_bytes fields;
- IAgentMicroCompactionService compaction before toolSelect shaping;
- IHostTimers-based retry sleeps (keeps the fake-timer tests instant);
- CacheObservation kept as an additive optional field on the new
  snapshot so the fork's cacheBreak feature and the TurnStepCompleted
  wire event keep their shape.

Other adaptation points:
- cacheProbeService taken verbatim from upstream (its empty catch for
  unknown model aliases is deliberate; recorded in the silent-catch
  baseline).
- fullCompaction probe test fixtures use the fork harness's window and
  fixture sizes (80k window, 200k/80k-char exchanges) to trigger the
  same pre-shrink upstream's smaller fixtures trigger in its harness;
  one probe assertion uses parent_request_gap_ms because the fixture
  requester reports no usage for the baseline request.
- usage.test.ts AgentCacheProbeService block replaced with upstream's
  version (bun:test mock instead of vi.fn, IModelCatalog import added).
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.

5 participants