Repository navigation
fix(agent-core-v2): keep the prompt cache through auto compaction - #4456
Conversation
…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.
|
There was a problem hiding this comment.
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.
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 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) }; |
There was a problem hiding this comment.
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 👍 / 👎.
| const historyPrefixMatch = | ||
| compared && cacheProbeBaseline.messageCount <= input.messages.length | ||
| ? fingerprint( | ||
| JSON.stringify(input.messages.slice(0, cacheProbeBaseline.messageCount)), | ||
| ) === cacheProbeBaseline.historyHash | ||
| : undefined; |
There was a problem hiding this comment.
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 👍 / 👎.
| cacheProbeBaseline !== undefined && | ||
| cacheProbeBaseline.modelAlias === request.modelAlias && | ||
| cacheProbeBaseline.contextRevision === request.contextRevision; |
There was a problem hiding this comment.
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 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 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; |
There was a problem hiding this comment.
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 👍 / 👎.
| readonly media: /* MediaProjection — packages/agent-core-v2/src/agent/contextProjector/contextProjector.ts */ { | ||
| readonly degradeCount: number; | ||
| } | { |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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 👍 / 👎.
commit: |
There was a problem hiding this comment.
💡 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)), |
There was a problem hiding this comment.
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.
Signed-off-by: 7Sageer <[email protected]>
RealKai42
left a comment
There was a problem hiding this comment.
把 #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; |
There was a problem hiding this comment.
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)的夹具实测值很小,需要把实测总量也调到确实超窗。
| const usedContextTokens = | ||
| effectiveMaxTokens > 0 | ||
| ? estimatedCompactionRequestTokens + | ||
| Math.ceil(effectiveMaxTokens * COMPLETION_BUDGET_ESTIMATE_MARGIN_RATIO) |
There was a problem hiding this comment.
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() 加上指令的估算;裁剪之后实测值已经对不上子集,再退回启发式。
) (#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]>
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).
Requirement or Bug
#3911 引入的 compaction 预裁剪,让上下文窗口大于约 195k 的模型每次自动 compaction 都会丢掉 prompt cache。这个 PR 同时补上诊断埋点,让后台能区分客户端破坏缓存前缀和服务端未命中。
Bug Reproduction Steps
1. Compaction 预裁剪
W − 50k = 206k,1M 下为0.85W = 850k)。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):触发点一定高于预算,所以每次自动 compaction 都会走裁剪,而裁剪删的是最旧的消息,前缀必然断开。手动
/compact只要上下文超过约 0.744W 也一样。#3911 原本针对的是"历史已经超出当前模型窗口"(例如换成小窗口模型),但它用的安全预算比触发点还严,把正常情况也拉进了裁剪路径。这次是根本修复:把"是否预裁剪"的判断和"裁到多少"分开。
Code Changes
只有估算的请求大小真的超过"窗口 − 输出预留"时才预裁剪;裁剪目标仍是原来的 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 因为传了messagesoverride 之前拿不到这一步。现在 compaction 每次请求都显式传usedContextTokens(请求估算 + 窗口 2% 的估算余量),由 provider 层现有的resolveMaxCompletionCap钳制,因此modelOverrides.maxCompletionTokens等任何来源的上限都会被钳住,显式 opt-out(≤ 0)保持不发送。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:history_prefix_match=false。input_cache_read缺失或偏低时,结合parent_request_gap_ms、provider 和模型判断缓存超时、淘汰或服务端策略,不能仅凭未命中直接断言超时。基线不可用时字段缺省,不参与归因。parent_input_tokens/parent_request_gap_ms在 compaction 中表示上一轮请求的对应值。Behavior Changes and Affected Users
/compact。旧行为对它们没有好处,只会让缓存失效max_tokensmaxOutputSize(或默认min(W, 128k)、modelOverrides.maxCompletionTokens),不随输入收窄min(上述上限, W − 请求估算 − 2%W),下限为 provider 的 1;显式 opt-out(≤ 0)仍不发送usedContextTokens)prompt_cache_probe遥测source=compaction样本及 model/history 对照;fork 行为不变source过滤的缓存命中率聚合会混入 compaction 样本;只读取 fork 旧字段的查询保持兼容source=fork/source=compaction分别聚合;无基线时跳过 match 字段docs/state-manifest.d.ts中的llmRequester.lastTurnRequest类型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;仓库内没有包外调用方。测试覆盖:
sends the full history when an auto compaction request fits the window。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。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 用例继续通过。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。验证:最新提交基于
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-v2typecheck 与无注释检查通过,oxlint 无新增告警。补充验证:reactive overflow shrink 短历史回归在修复前因
history_prefix_match缺失失败、修复后通过;fullCompaction.test.ts122 个测试通过,agent-core-v2typecheck 与无注释检查通过。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.