Skip to content

test: move every fake model onto testkit with strict checks - #5422

Merged
RealKai42 merged 21 commits into
mainfrom
test/consolidate-fake-models
Nov 25, 2026
Merged

RealKai42 merged 21 commits into
mainfrom
test/consolidate-fake-models

Conversation

@RealKai42

@RealKai42 RealKai42 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

仓库里的假模型原来是各包各写一份:引擎 harness 自带四套协议编码,klient、node-sdk、kap-server、VS Code、TUI 各自起 HTTP 服务或手写 SSE。这些假模型都很宽松:剧本用完就回一个错误,剧本没用完也不检查,测试自己并不知道发出了几次请求。这个 PR 把它们全部换成 testkit 的假模型,并让引擎测试在每个用例结束时对账。这是「假模型收束到 testkit」的第 1 轮,前置的 #5385、#5386、#5392、#5393 已合入。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路:所有层的测试共用 testkit 的一个假模型,用同一套剧本步骤、挂起点和 verify()。引擎这块不改测试的写法,只换底座:mockNextResponse、llmCalls 这些旧接口留着,harness 把每条旧剧本翻译成 testkit 步骤,请求照常经过真实的协议编码和解析。换完以后,打开严格检查:没写剧本的请求、写了剧本却没人请求、不合法的消息序列,都会让用例失败。这次检查暴露出来的用例也一并修好。

flowchart LR
  subgraph tests[测试]
    E[引擎存量用例<br/>mockNextResponse]
    N[引擎新用例<br/>testkitAgentFixtures]
    K[klient / node-sdk / kap-server]
    V[VS Code / TUI]
    A[acp-server / tests/scenarios / tests/e2e]
  end
  E -->|旧剧本翻译成步骤| H[harness<br/>scripted-generate.ts]
  H --> M
  N --> M
  K --> M
  V --> M
  A --> M
  M[testkit 假模型<br/>步骤 · 挂起点 · 通道 · verify] --> P[OpenAI / Anthropic / Google 编码<br/>Kimi 文件接口]
  P --> R[产品里真实的 provider 请求链]
Loading

所有箭头最后都汇到同一个假模型。所以假模型补一个能力(比如文件上传),每一层都能用;加一项检查,每一层都受约束。

关键决策

决策 选择 没选 理由
引擎存量用例怎么迁 旧接口不变,底下换 testkit 逐个文件改写 557 处 mockNextResponse 实验里 457/472 条不改就能通过,剩下的原因都已查清。逐个改写的成本高一个量级,换来的覆盖却差不多
「调用的工具是否在请求里提供过」这项检查 引擎 harness 默认关,可以用 scriptedModelChecks 打开 全部打开 引擎在 loop 启动时就定下请求里的工具列表(loopService.ts 的 initialTools())。之后注册的工具、经 select_tools 加载的工具只通过对话告诉模型。testkit 只看工具列表,所以会误报 42 处,这些在测试里修不掉。剧本对账和消息检查照常打开
故意构造的重复消息、故意调用不存在的工具 单条用例关掉检查(scriptedModelChecks),或者在调用上加 invalid: true 全局放宽 只有 4 条用例需要,放宽的范围就只限这 4 条
严格检查在哪里报错 harness 模块级的 afterEach;上下文关闭时先结算再释放 让 557 处调用各自调用 verify() 不用改调用点。另外以前检查闭包从不释放,同一文件里所有用例的假模型一直留在内存里,这次一起修了
klient 错误矩阵 每条用例起一个假模型,注册指向它的 provider 整个文件共用一个 一条用例失败时,剩下的剧本不会串到后面的用例
阅读指南
  1. packages/agent-core-v2/test/harness/scripted-generate.ts:旧接口怎样翻译成 testkit 步骤。请求和剧本靠一个队列配对,挂起改用 held(),异常改用断连或网络错误,最后在 afterEach 里对账。
  2. packages/testkit/src/model/uploads.ts、fake-model.ts:新加的 Kimi 文件接口(uploads()、holdUploads())。
  3. packages/testkit/src/model/fetch-transport.ts:进程内断流时,已发出的数据不会丢。
  4. packages/agent-core-v2/test/agent/task/idle-notification-repro.test.ts:严格检查暴露问题后,用例怎么改成确定性的写法。
  5. packages/klient/test/e2e/invalid-input-matrix.test.ts:协议层用例每条起一个模型的写法。
  6. packages/node-sdk/test/session-prompt-events.test.ts:按用户消息分流(route),用 held() 拖住流,用步骤函数根据实际请求生成 TaskStop 调用。

其余测试文件、文档、基线 JSON 可以略读。

旧 harness 的功能清单,以及每一项在新路径里的位置
旧 harness 能做的事 新路径
OpenAI chat、Anthropic、Google 三种协议的流式和非流式回复 由 testkit 的编码器产生,请求经过真实的协议解析
OpenAI Responses 协议(旧实现只支持纯文本回复) 现在没有测试用到。harness 遇到这种请求会给出明确的报错,并把问题记下来让用例失败(test/harness/scripted-generate.test.ts 固定这个行为)。testkit 的 Responses 编码器另开 PR 补
parts、message、usage、finish reason、response id、request id 翻译成 testkit 的 reply、withUsage、finishWith、withResponseId;request id 写进响应头
httpError testkit 的 httpError,错误体沿用旧格式
流到一半失败(error 加 parts) disconnect(可以选择断流前先发 usage)或 streamError
error 是一个 Promise:流挂起,直到请求被中止 一个不释放的 held()
onStream 回调:旧实现先等一个 setTimeout(0) 再调用 删除。用到它的 4 条用例改成 held() 拖住流,测试里等引擎发出 AssistantDelta 或 ToolCallDelta 事件,需要放行时用 createMockProvider(...).hold(name).release()。改成只靠「消费方在等下一块数据」这个信号的话,这 4 条用例必然失败:SDK 把已解析的事件交给引擎之前,就先去读下一块字节了
handler 抛出的异常 原样作为传输层故障交给引擎
剧本用完时回一个错误 记一个问题,用例结束时失败
严格检查暴露的问题和处理方式
类型 处数 处理
调用了请求没提供的工具 42 见关键决策第 2 行
发出了没写剧本的请求 30 后台任务启动后的下一步、任务结束后的通知回合、目标续跑回合都补上剧本。目标续跑会在用例结束后才发出,导致问题被记到下一条用例上,所以改成让模型在回合里调用 UpdateGoal 完成目标
写了剧本却没被请求 26 「This step should never run」这类诱饵直接删掉,这些测试本来就断言了请求次数。根本到不了模型的(autoConfigure: false,或者模型目录桩没写 protocol),删掉剧本或补上配置
连续两条相同的用户消息 11 都是测试输入造成的,改成不同的文字。只有两条用例是故意的(同一句话插话三次、同一批次里两次调用同一个 skill),在这两条里关掉消息检查

另外修了两处测试时序。后台 agent 原来用 Promise.resolve 让它一启动就完成,通知落进哪个回合要看竞态;现在改成启动回合结束之后再完成。三条「任务结束」的用例改用可控的进程或者 drain,等通知回合跑完再结束。

断言改动(和 #5393 一样逐条说明)
改动 原因
5 处快照里,工具调用的第一个增量变成「只有名字、参数为空」,参数在后面的增量里分块到达 testkit 和真实 OpenAI 流的发法一样。旧编码器一次发完整个调用,那是旧假模型的形状,不是契约
llmRequester.test.ts 的切点断言改成:第一块只有名字,后面每块拼起来等于完整参数 原断言写死的是旧编码器的切点
5 条中途打断的用例改用 held() 旧写法靠旧编码器的逐块节奏,testkit 改用命名挂起点
idle-notification-repro 的请求次数 2→3、3→4 后台任务启动后的下一步现在有了真实回复,多出来的那次就是它。以前这一步拿不到剧本,回合以 400 结束
coreLoopService 的「靠错误处理器重试」用例,请求次数 1→2 第一次失败原来靠「没写剧本」触发,现在显式写成 providerHttpError(500),这次失败请求也计入了请求记录
删掉 5 条 not.toContain('This step should never run.') 这类断言 对应的诱饵剧本删掉之后,它们恒为真。「不该多发请求」现在由请求次数断言和严格检查一起保证

Behavior Changes and Affected Users

None。产品代码没有改动。改动的范围是:各包的测试、引擎测试 harness、私有包 testkit、冻结检查脚本和基线、测试相关的文档。apps/vscode、packages/klient、packages/product 的 package.json 只多了 testkit 这一个开发依赖。VS Code 的 vsix 打包测试确认它不会进安装包。

测试覆盖:迁移之后,原来每条用例覆盖的行为都还在,请求现在会经过真实的协议编码,用例结束时还会多一层对账。VS Code 的 fake-provider-harness.ts 和它的自测已删除:它测的是这个假 provider 本身,假 provider 删了,这个自测也就没有意义了。

冻结检查(scripts/checks/test-doubles.mjs):

  • 删掉 vscode-fake-provider 规则,因为它对应的文件已经删了。
  • product 的 survey-turns.test.ts 加进 ENGINE_HARNESS_IMPORTERS 白名单,并写明原因:这个问卷通过引擎服务统计回合、压缩和恢复,这些服务只有 harness 里的 agent 才暴露。
  • 其余计数全部下降。有 4 个文件的 mockNextResponse 计数上升,合计 +8:这些都是给存量用例补上本来就会发出、但之前没写剧本的那一步,每一处对应一次真实请求。基线用 --update --allow-increase 更新,经过维护者确认。

没有 changeset:只改了测试和文档;testkit 是私有包,以往改它的源码都没写过 changeset。

验证

macOS 本机,分支合入 main c6dec96ae 之后按套件跑全量,和同一台机器上 main 的结果逐条比对:

套件 用例 失败 main 上的失败 新增失败
packages/agent-core-v2 8,235 4 11 1
packages/klient 155 0 0 0
packages/product 257 0 0 0
packages/node-sdk 284 1 1 0
packages/kap-server 1,571 0 0 0
packages/acp-server 181 1 1 0
packages/testkit 174 0 0 0
tests/scenarios 50 0 2 0
apps/vscode/test 402 0 0 0
apps/kimi-code/test/tui 3,805 0 0 0
  • 引擎新增的 1 条是 agentProfileLoader.test.ts 的文件监听用例,它在 main 上刚刚加入。这个分支没有改动它用到的任何代码。单独运行时,分支上 3 次失败 1 次,main 上 4 次全部通过。它用真实的文件监听器,写文件前只等 300ms,后台同时在跑全量时会偶尔超时。
  • 其余失败在 main 上同样存在:引擎 tool.test.ts 的 3 条子 agent 截止时间超时、node-sdk 1 条、acp-server 的 session/delete 1 条。
  • 引擎全量开着严格检查,没有剩余报告。
  • pnpm exec tsc --noEmit:agent-core-v2、klient、node-sdk、kap-server、product、testkit、apps/vscode、apps/kimi-code 全部通过。
  • 之后又合入了 main fdd8d245a。新进来的 2 个提交和本 PR 没有共同改动的文件;它们改到的 3 个测试文件(93 条)重新跑过,全部通过,agent-core-v2 的类型检查也通过。
  • 按评审意见删掉 onStream 及其计时器、给 Responses 请求加上明确报错之后,在干净的 worktree 里重跑了引擎全量:8,239 条,失败 8 条(main 上 11 条),没有新增。8 条都是负载下会超时的用例。改动涉及的 promptService、forkParity 两个文件连跑 5 次全部通过。
  • pnpm lint:通过。
  • pnpm run check:duplication <main>:没有新增重复。
  • 平台:只验证了 macOS,Linux 由 CI 覆盖,Windows 没有验证。产品代码没有改动;但 VS Code、klient、kap-server 的测试现在会在本机开端口起假模型。

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.

…xtras

- Answer POST .../files with a ready file object and GET .../files/<id>
  with the stored one; model.uploads() lists the uploads, and
  holdUploads() keeps them open until the client gives up.
- Let call() carry extras: OpenAI tool calls send them as `extras`, and a
  thought_signature_b64 becomes a Google thoughtSignature.
- Hand non-HTTP URLs such as the SDK's data: probe to the native fetch.
- An in-process disconnect now lets the client read the chunks already
  sent before the read fails, as a real connection drop does.
- disconnect(step, { afterUsage: true }) reports usage before dropping
  the connection, for scripts where a provider counted tokens and then
  lost the stream.
createMockProvider, createScriptedGenerate and createMockProviderRequester
keep their API but now script a testkit fake model per provider, so every
engine test reply goes through the same protocol encoders as the rest of
the repository. The harness's own OpenAI, Anthropic, Responses and Google
encoders are gone.

- Translate scripted parts, usage, finish reasons, IDs, request IDs and
  HTTP errors into testkit steps; a response can also pass a testkit
  step directly.
- Keep transport faults: a thrown error fails the fetch with that error,
  and an error after parts drops the stream and then raises it.
- Keep hang-until-abort replies and onStream callbacks with testkit
  holds, calling onStream only once the engine has read what was sent.
- Skip replies prepared for attempts that were cancelled before their
  request went out.
- Tests: hold the interruption replies before their second part, check
  the tool-call delta contract instead of fixed cut points, and update
  the five snapshots whose tool-call delta now starts with the name and
  empty arguments, as OpenAI streams do.
The survey-turn tests keep the engine harness agent but now script
their replies on a testkit fake model instead of the harness's legacy
mockNextResponse queue, and verify the model after each test.
Every engine harness model now reports its problems after each test:
a request with no scripted reply, a scripted reply nobody requested,
or a conversation the fake model rejects, such as a user message that
repeats the previous one. A context retires its checks when it closes,
so finished contexts no longer stay in memory for the rest of the file.

The harness leaves the "tool was offered" check off by default. The
engine fixes the request's tools array when the loop starts, and tools
registered later or loaded through select_tools reach the model through
the conversation, which that check cannot see. Tests can opt back in
with scriptedModelChecks.

Fixes in the tests that the checks exposed:
- background task starts and task notifications now script the step
  that follows instead of letting it fail on an empty queue
- replies that were never meant to be requested are removed; the tests
  already assert the request count
- deliberate failures are written as explicit HTTP errors
- races between a finished background agent and the next request are
  removed by finishing the agent after the starting turn settles
- goal re-injection tests complete the goal so no continuation turn
  runs after the test ends
- fixtures that sent the same user text twice now send distinct text;
  the two tests that steer or call with duplicates on purpose turn the
  message check off
- a catalog stub returns a model with a protocol so its turns reach the
  scripted model
The invalid-input matrix started its own HTTP server and wrote OpenAI,
Anthropic and Google streams by hand. Each case now starts a testkit
fake model, registers a provider that points at it, and verifies it
after the case. Uploads and cancelled uploads come from the testkit
files API instead of a hand-written files endpoint.

The kosong conformance check stubbed fetch with a hand-written chunk
and swapped the protocol registry's requester for the engine harness
double. It now stubs fetch with a testkit model, so every request goes
through the real kimi protocol adapter, and it no longer imports the
engine harness.
The session prompt tests spied on fetch and answered every request
with the same hand-written OpenAI stream, so a test never learned how
many requests it caused. Each test now scripts its replies on a testkit
model and verifies it afterwards. The cancelled-subagent replay test
routes the parent, child and background worker by their user text,
holds the child and worker streams with held(), and builds the TaskStop
call from the task id the parent actually received.

The model-switch resume test reads the requested model id from the
testkit request log instead of a hand-written stream.
The side-chat and wait tests spied on global fetch and wrote OpenAI
streams by hand, gating them with promises. Both now start a testkit
model over HTTP, point the provider's base_url at it, hold the gated
reply with held(), and verify the model when the test ends.
The test replaced the OpenAI client with an object that yielded
pre-parsed chunks. It now keeps the real OpenAI client and passes it a
testkit model's fetch, so the tool call reaches the normalizer through
the actual SSE decoder.
The VS Code integration tests ran their own HTTP fake provider with
per-route handlers that answered every chat request the same way. They
now start a testkit model, script one step per request the extension
should make, and verify it when the rig is torn down, so an extra or
missing request fails the test. The blocked-reply cases use held(),
provider rejections use httpError(), and the replay tests script the
multi-call and subagent replies directly.

fake-provider-harness.ts and its self-test are deleted.
The upload-abort TUI test ran an inline HTTP server that wrote the
ReadMediaFile tool call by hand and watched the files socket close. It
now holds uploads on a testkit model, scripts the single tool call, and
waits for the testkit upload record to turn aborted.
…trict harness

The VS Code fake provider is gone, so its freeze rule and exclusion go
with it. The product survey test is listed in ENGINE_HARNESS_IMPORTERS
with the reason it drives the engine harness agent directly, and the
checker's tests cover that exemption. The test-double baseline drops
every count the migrations removed.

tests/AGENTS.md and the testkit model guide now say that the engine
harness replies come from the testkit model, which problems fail a test,
why the offered-tool check is off by default, and how scriptedModelChecks
changes the checks.
…-models

# Conflicts:
#	packages/kap-server/test/sessions.test.ts
#	packages/node-sdk/test/sdk-rpc-client-v2.test.ts
#	packages/product/test/survey-turns.test.ts
#	scripts/checks/baselines/oxlint-ratchet.json
Four existing engine test files now script steps their tests always
requested but never scripted: the follow-up after a background task
starts, a task notification turn, and the final message after a goal
completes. Each added mockNextResponse answers a real request, so the
frozen counts for those files rise by eight in total.
@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5b0ea5f

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

@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-25T13:24:13.220773Z 5b0ea5f New commits
🔒 Security Review ✅ Completed 2026-11-25T12:02:47.728773Z ef0bc81 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.

@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: ef0bc8107d

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

@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@5b0ea5f
npx https://pkg.pr.new/@moonshot-ai/kimi-code@5b0ea5f

commit: 5b0ea5f

…ests

The engine harness invoked onStream callbacks after a zero-delay timer,
carried over from the old harness, to guess that the engine had read
the streamed text. Waiting only for the consumer's next read is not
enough, because the SDK asks for the next bytes before it hands the
parsed events to the engine. The four tests that used onStream now
hold the reply with held() and wait for the engine's AssistantDelta or
ToolCallDelta event; one releases the hold through the provider's new
hold(name). onStream and the timer are removed from the harness.

A request on the OpenAI Responses protocol now fails with a named
problem instead of an unexpected-endpoint error, because the testkit
model has no Responses codec yet. No existing test sends one.
The test cancelled the turn right after submitting it. When the cancel
won before the turn persisted its prompt, the live context kept the
user message while the resumed one did not, and the resume check at
the end of the test failed. That happens on main too whenever the test
runs alone. The test now waits until the request reaches the model and
then cancels, which still aborts the turn mid-request, the case the
loop error handlers must skip.
@RealKai42
RealKai42 merged commit e242f10 into main Nov 25, 2026
25 checks passed
@RealKai42
RealKai42 deleted the test/consolidate-fake-models branch November 25, 2026 13:41
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
…tAI#5422)

Port the testkit half of upstream e242f10: fetch transport rejects
non-http schemes, playback supports split stream writes and the
usage-before-disconnect ending, uploads can be stored, held and aborted,
and the protocol codecs carry the new model types. The model and protocol
suites pass 72 / 2 skip with typecheck clean.

The consumer test migration and the test-doubles/AGENTS gates are recorded
as remaining on the ledger row: those checks do not exist in this fork and
the affected tests have diverged.
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 26, 2026
…ed harness

The testkit model is ported and used by eight consumers; the rest use scripted-generate, which enforces the same strict scripted-response and input-snapshot contract. Record the equivalence instead of rewriting 30+ suites.
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.

1 participant