Skip to content

fix: wait for the engine to finish disposing before server close resolves - #5250

Merged
RealKai42 merged 1 commit into
mainfrom
fix/await-engine-disposal-on-close
Nov 23, 2026
Merged

RealKai42 merged 1 commit into
mainfrom
fix/await-engine-disposal-on-close

Conversation

@RealKai42

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Layered QA 的 Windows 任务里,vitest 报过 3 次 Worker exited unexpectedly,当时正在跑的进程内 KAP 测试文件中途消失:两次是 tests/scenarios/replay.test.ts,一次是 packages/acp-server/test/kap-parity.test.ts,其中一次是 main 上的夜间运行。

查下来,kap-server 和 acp-server 的 close() 都在引擎释放完成之前就返回了:返回时,引擎在数据目录和工作区上开的文件监听还没关,调用方紧接着删目录或者退出进程。这个 PR 让 close() 等引擎释放完成再返回。

Bug Reproduction Steps

  1. 用 node --require 预加载一个脚本,记录每个 fs.watch 的打开和关闭,以及每次 fs.promises.rm 时目标目录里还开着的监听器。
  2. 在 main 上用这个脚本跑两遍 qa:layers 里进程内的 5 个文件:testkit 删除 KAP 测试目录时,有 4 到 7 次目录里还开着 5 到 13 个监听器(引擎自己的递归监听和 chokidar),它们在删除开始之后才关闭。
  3. 新增的两条测试在 main 上都稳定失败:服务端的 close() 在一个还没 dispose 完的引擎服务之前就返回了。

Root Cause

close() 调用的 core.dispose() 只是启动 instantiation.disposeAsync(),并不等它完成。配置、工作区、技能、指令等引擎服务是在这段异步释放里关闭各自的文件监听的,所以 close() 返回之后,监听还要再开几毫秒,负载高时更久。Node SDK 的关闭流程早就是先 this.app.dispose(),再 await this.app.instantiation.disposeAsync(),两个服务端都少了第二步。

和 Windows 上 worker 退出的关系:

  • Windows 上永久删除一个正被 fs.watch 监听的目录后,句柄不会失效,ReadDirectoryChangesW 会不停地返回事件、空转,直到句柄关闭。见 nodejs/node#61398,修复在 libuv/libuv#5013,还没进入 Node 的正式版本;CI 用的 Node 24.15.0 受影响。
  • 本机追踪显示,删除目录时还开着监听器的只有 kap-parity 和 replay 这两个测试文件,正好就是在 CI 上 worker 被杀的那两个。apiSurface 删除自己的目录时没有开着的监听器,也从来没出过事;其余文件不起 KAP 服务。
  • 但空转怎样导致 worker 退出,CI 日志里没有直接证据:vitest 不记录 worker 的退出码,日志里也没有崩溃信息。所以这个 PR 能确定的是去掉了已知的触发条件,是否根治要看合入后 Windows 上的运行记录。

这个 PR 修的是 close() 不等释放完成这个根因,不是绕过。

Code Changes

 close
   ...
   core.dispose()
+  await core.instantiation.disposeAsync()
   await appendLogStore.drainRetirements()
   ...

kap-server 和 acp-server 各加一行,和 Node SDK 的写法一致。

  • disposeAsync() 返回的是 dispose() 已经启动的同一个 promise,不会重复释放。
  • ledger 会接住每个释放步骤抛出的错误,交给 onUnexpectedError 报告,所以 disposeAsync() 不会 reject,close() 后面的清理步骤照常执行。

两条新测试用同一种写法:往引擎里注入一个 dispose 要等闸门打开才完成的服务,确认闸门关着时 close() 不会返回,打开后事件顺序是「dispose 开始 → dispose 完成 → close 返回」。测试里有一段 50 毫秒的等待,作用是给不等释放的实现一个返回的机会,从而让它失败;对正确的实现,结果不依赖等待长短。写法和 packages/agent-core-v2/test/_base/di/child.test.ts 里验证 disposeAsync 的用例一致。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
kap-server close() 返回的时机 引擎开始释放后就返回,文件监听等资源在后台陆续关闭 引擎所有服务释放完成后才返回 桌面端关闭或重启内嵌服务端、kimi web 退出、托管模式下的空闲退出,以及关闭后清理数据目录的测试和脚本 无
acp-server close() 返回的时机 同上 同上 kimi acp(Zed 等 ACP 客户端断开后进程退出),以及在测试里起 ACP 服务端的代码 无
关闭耗时 不等引擎释放 多出引擎释放所需的时间,通常是毫秒级;某个服务释放得慢,关闭也跟着慢 同上 无

packages/acp-server/ 属于契约文件的范围。使用方是 Zed 等 ACP 客户端和 kimi acp。协议、接口和配置都没有变,上一个版本的客户端照常工作;变的只是服务端进程在退出前把引擎释放做完。桌面端用 Promise.allSettled 等内嵌服务端关闭,CLI 也没有给服务端的 close() 设时限,所以不会因为关闭稍慢而超时。

测试覆盖:

  • packages/kap-server/test/boot.test.ts:resolves close only after the engine has finished disposing its services。
  • packages/acp-server/test/lifecycle.test.ts:同名用例,覆盖 ACP 服务端。
验证(macOS)
  • 两条新用例:在 main 上各跑 3 遍,全部失败;修复后各跑 3 遍,全部通过。
  • pnpm exec vitest run packages/acp-server packages/kap-server/test/boot.test.ts:179 条全部通过。
  • pnpm exec vitest run packages/kap-server packages/testkit tests/scenarios:1632 条通过,1 条失败,是 hosts.test.ts 的「lets a managed host sign in and renew with its own Kimi login」。去掉本 PR 的改动后,它在本机同样 3/3 失败;在 main 的 CI 上是通过的,属于本机环境问题,和本 PR 无关。
  • 用上面的追踪脚本在修复后跑 3 遍 pnpm qa:layers:共删除 456 次目录,其中 15 次是 KAP 测试目录,没有一次还开着监听器。修复前跑 2 遍就有 4 到 7 次。
  • pnpm exec tsc -p packages/kap-server/tsconfig.json --noEmit、pnpm exec tsc -p packages/acp-server/tsconfig.json --noEmit:通过。
  • pnpm lint:通过。

Windows:本机无法验证。是否消除了 worker 退出,要看合入后 Layered QA 在 Windows 上的运行记录;此前这类失败大约每 10 次 Windows 运行出现 1 次。

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.

…lves

kap-server and acp-server called core.dispose(), which only starts the
asynchronous teardown of the engine, so close() resolved while engine
services still held file watchers on the data and workspace
directories. Callers that removed those directories right after close
deleted watched directories, which on Windows keeps the watch handle
reporting events until it is closed.

Await the instantiation service's disposal after core.dispose(), as
the Node SDK already does. The ledger reports disposal errors instead
of rejecting, so the remaining cleanup steps still run.
@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f44402a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/kap-server Patch
@moonshot-ai/acp-server Patch

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T04:45:00.674360Z f44402a PR opened
🔒 Security Review ✅ Completed 2026-11-23T04:46:37.973468Z f44402a 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: f44402af27

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

Comment on lines +253 to +254
await new Promise((resolve) => setTimeout(resolve, 50));
expect(events).toEqual(['dispose started']);

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 Replace the fixed sleeps with deterministic shutdown checkpoints

If the cleanup steps after core.dispose() take longer than 50 ms, these regression tests can pass even without the production fix: the sleep expires before close() resolves, the test releases the disposal gate, and both final event sequences then appear correct. This affects both this test and packages/acp-server/test/lifecycle.test.ts:129–131, particularly under the slow or loaded environments motivating this change. Replace the elapsed-time assumption with explicit lifecycle/checkpoint synchronization so the tests reliably distinguish awaiting engine disposal from merely completing unrelated cleanup later. The root AGENTS.md explicitly prohibits sleep-based test synchronization.

AGENTS.md reference: AGENTS.md:L98-L98

Useful? React with 👍 / 👎.

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026

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

commit: f44402a

@RealKai42
RealKai42 merged commit e9538e3 into main Nov 23, 2026
25 checks passed
@RealKai42
RealKai42 deleted the fix/await-engine-disposal-on-close branch November 23, 2026 05:13
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Both the kap-server and ACP server now await core.instantiation.disposeAsync()
after core.dispose(), so file watchers and other DI services finish closing
before shutdown resolves (MoonshotAI#5250). Both regression tests register a
SlowToDispose service behind a release gate and assert close waits for it;
the changeset is copied.
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