Repository navigation
test: check the prompt cache prefix across the test suites - #5474
Conversation
|
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: fc0ad8bd2b
ℹ️ 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".
The fake model now records every request in a prompt cache ledger that
splits it into segments in the order a provider caches them (model and
thinking settings, system, tools, messages; tools before system for
Anthropic) and compares them as the JSON text that was sent.
model.promptCache() reports each request's estimated reuse, the earlier
request it reuses and, for main and compaction requests, the first
difference from the latest main request under the same cache key.
checkPromptCache makes verify() fail on a break nobody declared;
model.expectCacheBreak(reason, { at }) declares an intended one, and the
first main request after a compaction may start a new history as long as
its header stays the same. reportCachedTokens reports the reused tokens
as cache reads in usage. Both options are off by default.
The provider scenarios run two turns with a tool call through the real
engine for every provider type with both options on.
The pinned mid-turn cold-recovery test killed the KAP server the moment the fake model received the request. Wire records are flushed asynchronously, so the kill usually landed before the prompt's context.append_message reached disk, and the restarted server had no trace of the interrupted turn. KAP only promises durability at stopping points, so the test now waits until the prompt's user message and its step.begin are in wire.jsonl before crashing. After the restart it checks that the turn is kept as interrupted with its user message, and that the next request starts with the messages of the interrupted request.
…guard The fake model now checks the prompt cache prefix unless a test passes checkPromptCache: false. A main or compaction request must extend the latest main request under the same protocol, cache key and model; a request the provider rejected with an HTTP or network error is neither checked, a baseline nor a source of reuse, because nothing was cached. model.promptCacheProblems() reports the problems for harnesses that do not call verify(). The agent-core-v2 harness forwards ctx.expectCacheBreak() and ctx.promptCache() to the model that answers the agent, reports cache problems from the legacy scripted path at the end of each test, and accepts scriptedModelChecks.checkPromptCache: false. It replaces prompt-cache-guard, which compared engine-level requests per agent object and skipped any change to the tool-name set: system, tools and history are now compared as sent on the wire for every test, model changes start their own baseline, history rewrites need a declaration, and the prepareOperation hook that restored persisted state first is kept as a plain wrapper. Every intended break in the existing suites is declared with its reason: undo, clearing the context, the dropped argument-correction message, media recovery, a truncated summary retried without the oldest message, and tests that send their own messages through the requester. The node-sdk prompt-event tests use the kimi provider type, so the role metadata keeps subagent requests out of the main thread.
fakeMcpServer(name, { tools, callLog }) returns an mcp.json server entry
that starts a real stdio MCP process built on the official SDK. Each
tool has a name, a description, a JSON Schema and a fixed reply, and
every call is appended to the call log, which readMcpCalls() reads
back. writeMcpConfig() writes mcp.json, and startKap accepts
mcpServers so a KAP test can mount servers before the server starts.
A server entry with deferred: true puts its tools behind progressive
tool loading.
The server registers tools/list and tools/call on McpServer's
underlying server so the schema a test passes reaches the client
unchanged. The fixtures tests drive it with the official MCP client.
A KAP scenario runs one session through tool calls, a retried 503, manual compaction, a restart, a subagent, MCP tool calls and a second compaction, and requires every main request to extend the cached prefix under one cache key. It runs under eight configurations: the default, every experimental feature, progressive tool loading, thinking, a mounted MCP server, a deferred MCP server behind progressive loading, and the anthropic and google-genai provider types. Each configuration asserts that it changed the requests, so a setting that stops taking effect fails instead of passing silently. Separate KAP cases turn on plan mode, swarm mode and tower mode, switch to manual approvals, write AGENTS.md between two turns, and steer a running reply; each keeps the next request on the same prefix. An E2E scenario reads a file, runs an approved shell command, restarts the product and reads again on TUI, Web, Desktop and ACP, and checks the cache ledger and the single cache key across the restart. scenarioFixtures forwards env and mcpServers to startKap.
Address the review of the prompt cache ledger: - A subagent's compaction compacts the subagent's own history, so its role is subagent: it is neither checked against the main agent nor lets the next main request restart the history. It is still scripted on the compaction lane. - Baselines, breaks and allowances are worked out when entries or problems are read, from the final rejection state, so a request that arrived while an earlier one was waiting for its step is not compared with that earlier request once the provider rejects it. - Anthropic and Google merge consecutive user messages by appending content blocks, so their messages are split into a role segment and one segment per block or part: an appended block extends the prefix, a changed block or one put in front still breaks it. - The structured output schema is part of the cached prefix, so the header now holds response_format, the Responses text settings, Anthropic output_config and Google's response MIME type and schema.
…n case The case added with the auto compaction fix pushes the context close to the window, so both compaction requests drop the oldest exchange to fit. That is the same head drop the truncated summary retry makes, so the case declares both breaks until the trimming contract is settled.
fc0ad8b to
43884da
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 43884dafe3
ℹ️ 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".
With the auto compaction race fixed, each journey lowers the trigger ratio to 0.5 and lets a turn's last reply report about 0.6 of the window. The compaction starts in the background, the next turn's first step waits for it, and the request after it carries the summary. The usage stays below the 0.875 window line where the compaction input is trimmed from the head, so the journey checks the cache across the compaction itself rather than the known head drop. The trigger sits on the last reply of a turn instead of after a tool call: compacting there makes the Google request merge the instruction in front of the filled-in tool result, which the fake model's message check rejects, and that ordering needs its own decision.
…ed cache_control - A request now counts as rejected from how its playback ended: a hold that failed before the headers, or reset the connection, answers it with an error as surely as an error step does. - Anthropic cache markers are stripped only where the protocol puts them: on tools, system blocks, message content blocks and the blocks inside a tool result. A tool schema or tool input property that happens to be called cache_control is compared like any other. - A break on a thread without a prompt cache key now says why: Google requests carry nothing that tells conversations apart, so a test that runs several of them gives each its own model.
#5474 landed on main as one squashed commit, so its files conflicted with the earlier branch commits this branch was cut from. The merge keeps main's version of every #5474 file and reapplies only this branch's change: the Google view rule, its tests and docs, and the mid-turn compaction trigger in the cache journeys.
#5474 landed on main as one squashed commit, so the prompt cache files this branch carried from it now come from main as merged, including the review fixes made after this branch forked. Two main changes met the MCP migration: - #5486 made the crash-after-connect fixture exit when the test creates a signal file instead of after a fixed delay. The fixture is gone, so the testkit's exitAfterConnect now takes whenFile in place of afterMs, crashAfterConnectServer passes it on, and both crash cases keep the signal they create once they have seen the connected state. - #5488 added hostPathClass to the MCP stubs for Windows path classes. The stubs keep it beside the testkit-based servers.
…flags port M34 (merge f643d40) ported the server-driven two-tier experimental flag system, so MoonshotAI#5333's not-applicable probe absent:experimentalFeatures started failing on main: --verify reported 316 pass / 2 skipped / 1 fail. The row is partial, not ported: the per-PR file-completeness gate counts 3 of 115 files never carried by this fork - two tests/e2e specs (the upstream Playwright suite this fork does not carry; MoonshotAI#5380 records the same) and tests/scenarios/prompt-cache.test.ts (added upstream by MoonshotAI#5474 and never carried here). 107 files are carried and 5 changesets are exempt. The landed half is the whole feature: app-core ServerMeta types and daemon mapping, the kap-server /meta wire, the app-client store writing profile buckets, and the desktop Lab UI. The flat-flag deviation PLAYBOOK:111 recorded is retired by that port. The probe is the kap-server meta case asserting /meta reports experimental_beta and experimental_features with stage, effect_timing and source; approved_by is "M45 file-level audit". No changeset: ledger bookkeeping is not user-perceivable. Verified: bun scripts/upstream-ledger.mjs --verify -> 317 probes pass, 2 skipped, 0 probe fail, 0 completeness fail; a second run leaves the ledger byte-identical (sha256 d0f17e07...). bun test --timeout 30000 scripts/test/upstream-ledger-probes.test.ts -> 29 pass / 0 fail. bun run lint and node scripts/checks/ratchet.mjs green. The branch is based on main 7e56303 and carries no spawn-snapshot WIP.
Requirement or Bug
Related #4935
最近接连出现 prompt 缓存未命中:压缩请求的工具集和普通回合不一致(2.7.2 里 39 → 29 个工具)、新建会话和恢复会话的工具集不一致、接近窗口上限时从头裁剪历史。这些都是「客户端发出的请求没有沿用上一个请求的前缀」,但测试一个都没拦住:引擎里原有的
prompt-cache-guard只在 agent-core-v2 的 harness 里生效,按 agent 对象比较、跨重启就失去基线,还在工具名集合变化时直接跳过;而且测试只在默认配置下跑,出问题的 Tower、MCP 这类配置根本覆盖不到。这个 PR 把「同一缓存键下,每个请求都必须延续之前的前缀,任何断点都必须显式声明」变成所有用到 testkit 假模型的测试默认都会检查的契约,并补上跨配置、跨产品面的缓存旅程测试。这个 PR 只改测试基建和测试,不改产品代码。
Bug Reproduction Steps
N/A(测试基建)
Root Cause
N/A(测试基建)。缓存问题为什么漏网见下面的「关键决策」。
Code Changes
核心思路:testkit 假模型在协议层模拟服务端的前缀缓存。它按服务端缓存的顺序,把每个请求切成参数、system、tools、messages 几段,按实际发出的 JSON 文本比较。主请求和压缩请求必须延续同一协议、同一缓存键、同一模型下的上一个主请求,否则
verify()失败;撤销、清空上下文这类有意改写,测试要用expectCacheBreak(reason)写明原因。因为判断点放在线上的请求体上,引擎、node-sdk、KAP 场景和四个产品面的 E2E 都共用这一套检查。概念
model.promptCache()expectCacheBreak(reason, { at })verify()失败结构图
flowchart LR subgraph Tests E[agent-core-v2 harness] --> M S[node-sdk / product tests] --> M K[KAP scenarios + cache journey] --> M X[E2E: TUI / Web / Desktop / ACP] --> M end M[testkit fake model] --> C[codec.promptPrefix: params / system / tools / messages] C --> L[PromptCacheLedger] L -->|verify / promptCacheProblems| R[undeclared breaks fail the test] L -->|reportCachedTokens| U[usage cached_tokens back to the product]所有测试层都已经通过 testkit 假模型发请求,所以把检查放在假模型里,一处实现就覆盖每一层,而不是在每个 harness 里各写一份。
关键决策
LlmRequest(旧 guard 的做法)prompt_cache_key的变化在引擎层看不到checkPromptCache: false关闭contextRevision、媒体降级等场景自动豁免fakeMcpServer,作为全仓库 MCP 假服务的唯一来源packages/agent-core-v2/test/mcpCore/fixtures/*.mjsconfig.toml里、渐进加载少了tool_use、MCP 默认不走延迟加载,这三组最初都是空转,测试照样通过旧 guard 的功能清单(替换旧路径时要求列出)
prompt-cache-guard做的事droppedCount = 0的压缩请求,都要延续上一个回合请求thinking、模型一致contextRevision变化、换分支时跳过cacheKey、extraParams、responseFormat一致responseFormat并入参数段,按各协议的写法比较:OpenAI 的response_format、Responses 的text、Anthropic 的output_config、Google 的responseMimeType和响应 schema。OpenAI 和 Anthropic 的文档都写明结构化输出的 schema 属于缓存前缀。extraParams是各 provider 自定义的透传字段,不检查promptCacheComparisons()计数ctx.promptCache()账本条目prepareOperation前先restorePersisted()阅读指南
packages/testkit/src/model/prompt-cache.ts:账本、基线、断点和声明的全部规则。packages/testkit/src/model/protocols/*.ts里的promptPrefix:各协议按服务端缓存的顺序切段。Anthropic 是 tools → system → messages,并忽略cache_control。Anthropic 和 Google 的每条消息按「角色 + 每个内容块」切段,因为这两家会把连续的用户消息合并成一条,只在后面追加块。packages/testkit/src/model/fake-model.ts:接线,包括默认开启、被拒请求、reportCachedTokens。packages/agent-core-v2/test/harness/{agent,scripted-generate}.ts:harness 转发声明,旧剧本路径也报告缓存问题;prompt-cache-guard.ts被删除。tests/scenarios/prompt-cache.test.ts:缓存旅程,8 组配置,每组都经过重试、MCP 调用、手动压缩、重启、自动压缩和子 agent;另有 5 种会话中途的变化和插话。自动压缩把触发比例设成 0.5,让回合最后一条回复报出约 0.6 倍窗口的用量:压缩在后台启动,下一回合的第一步等它完成,这正是 fix(agent-core-v2): wait for in-flight auto compaction before the next step #5454 修的路径,也低于 0.875 倍窗口的预裁剪线。tests/e2e/scenarios/conversation/keeps-one-prompt-cache-prefix-across-a-restart.spec.ts:四个产品面上的旅程。可以略读的部分:各测试文件里新增的 25 处
expectCacheBreak声明、packages/testkit/src/fixtures/mcp*.ts(基于官方 SDK 的假 stdio MCP 服务,供旅程挂载 MCP 用)、文档。25 处断点声明的原因分布
Behavior Changes and Affected Users
产品行为:无。diff 只涉及
packages/testkit(私有测试包)、各包的test/目录、tests/和测试文档,没有改动任何产品源码、配置项、协议或提示词文本。测试侧的行为变化:
verify()checkPromptCache: false;harness 里是scriptedModelChecks.checkPromptCache: falseprompt-cache-guard,按 agent 对象、在引擎请求层比较llmRequester.test.ts里对promptCacheComparisons()的断言ctx.promptCache()session-prompt-events.test.ts的假 provideropenai类型kimi类型tests/scenarios/providers.test.ts和 klient 的矩阵覆盖step.begin写进wire.jsonl再杀,并断言被打断的回合和提示词都被保留reportCachedTokens、promptCacheProblems()、fakeMcpServer、startKap({ mcpServers })、scenarioFixtures({ env, mcpServers })@modelcontextprotocol/sdk ^1.29.0(agent-core-v2 和 desktop 已在用同一版本)测试覆盖:规则单测
packages/testkit/test/prompt-cache.test.ts,用官方 OpenAI、OpenAI Responses、Anthropic、Google SDK 驱动;四种 provider 类型经真实引擎的验证在tests/scenarios/providers.test.ts;MCP 夹具用官方 MCP 客户端在packages/testkit/test/fixtures.test.ts里验证;缓存旅程在tests/scenarios/prompt-cache.test.ts和上面的 E2E 场景里。验证结论:本机(macOS)上跑过
pnpm lint、7 个项目的类型检查、agent-core-v2 全量、其余所有用到 testkit 的包和 KAP 场景,以及 E2E 的 TUI 和 ACP 全量(构建产物)。新 E2E 场景在 Web 和 Desktop 上也单独跑过。全量测试中,缓存检查报出的问题为 0。全量运行时,机器上同时跑着别的测试,负载在 60 到 130 之间,有一批计时和超时类用例失败:它们要么不经过这个 PR 改动的代码(搜索服务的主线程响应、mergeWorkspaces 的耗时、滚动控制器的随机不变量),要么是在等待模型或启动时超时,没有一条是缓存检查报错。合入前以 CI 在干净机器上的结果为准。为了确认这些检查真的会抓到问题,我临时向引擎注入了几种故障,验证完已全部还原:
tools[23] Write is missing;dynamicActiveTools.verify.test.ts拦下;providers.test.ts的 4 种 provider 都失败。这个 PR 没有修、但跑测试时暴露出来的产品问题(已分别跟进):
compaction_trigger_ratio调到 0.85 以下时,自动压缩和回合的下一步并发,结果被丢弃,每一步都白发一次完整的压缩请求,上下文也不缩小。这是在给旅程校准自动压缩时发现的,修复 fix(agent-core-v2): wait for in-flight auto compaction before the next step #5454 已合入(默认配置不受影响),缓存旅程现在包含自动压缩这一步。dropOldestMessageAndLeadingToolResults),和 自动压缩在 v2.6.0 仍产生 ~91.5 万 token 冷 prefill:单次约 107 次普通轮次,且 droppedCount=0 #4935 讨论的预裁剪一样属于从头裁剪,整段缓存失效。fix(agent-core-v2): wait for in-flight auto compaction before the next step #5454 新增的「等待的压缩被丢弃后重新压缩」用例里,上下文接近窗口上限,两次压缩请求也都为了放进窗口裁掉最老的一轮对话。这两处现在都按有意断点声明,等裁剪的契约定下来再改。验证命令与结果
pnpm lintpnpm exec tsc --noEmit -p <dir>/tsconfig.json:testkit、agent-core-v2、node-sdk、kap-server、product、tests/scenarios、tests/e2epnpm install --frozen-lockfile --offlinepnpm run check:duplication <main>pnpm exec vitest run --project agent-core-v2pnpm exec vitest run packages/{testkit,node-sdk,kap-server,acp-server,klient,product,app-core} tests/scenarios …suggestFiles在 main 合入 #5452 后已通过TESTKIT_CLI_BUILD=dist pnpm --filter @moonshot-ai/e2e exec playwright test --project=tui--project=acpChecklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.