Skip to content

fix(kap-server): avoid heartbeat timeout after scheduling stalls - #4823

Merged
wbxl2000 merged 4 commits into
release/2026-11-12from
kimi/20261111-052517-fix-kap-server-avoid-heartbeat-timeo-183593
Nov 11, 2026
Merged

wbxl2000 merged 4 commits into
release/2026-11-12from
kimi/20261111-052517-fix-kap-server-avoid-heartbeat-timeo-183593

Conversation

@wbxl2000

@wbxl2000 wbxl2000 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

服务端事件循环卡顿、系统睡眠或系统时钟向前跳变之后,KAP 的 WebSocket(/api/v1/ws)连接会被心跳检查立刻以 1001 / heartbeat timeout 断开,即使客户端一直在正常回应 pong。客户端会看到无故断线、重连。

Bug Reproduction Steps

  1. 客户端连上 /api/v1/ws,正常回应 ping。
  2. 让服务端进程卡住超过 20 秒(例如调试暂停、笔记本睡眠),或把系统时钟往前拨。
  3. 进程恢复后的第一次心跳检查,按卡顿前的最后入站时间计算已经超过两个间隔,连接被直接断开。

Root Cause

心跳检查只看「距上次收到客户端帧多久」,而且用的是墙上时间 Date.now():

  • 墙上时间向前跳(或系统睡眠后被校正),这个间隔会被算得过长;
  • 事件循环卡顿时,客户端的 pong 已经到达、但还排在未处理的输入里,检查却先跑了;
  • 卡顿期间服务端没有发 ping,客户端也就不会回 pong,卡顿结束后的第一次检查按卡顿前的入站时间判定超时。

根本修复,三点:

  1. 心跳计时全部改用单调时钟 performance.now(),墙上时间的跳变(向前或往回)不再影响心跳;系统睡眠期间单调时钟不前进,睡眠不会被误判。
  2. 心跳回调比上一次明显晚(超过 1.25 个间隔,默认即晚 2.5 秒以上)说明事件循环被卡住了,这时发一个新的 ping,给客户端一个完整的新回应窗口;普通的定时器抖动不算卡顿。
  3. 判定超时后先用 setImmediate 让出一次事件循环,让已经到达的入站帧先处理,再复查一次,仍然超时才断开。

Code Changes

 onHeartbeat
-  now = Date.now()
+  now = performance.now()
+  sinceLastHeartbeat = now - lastHeartbeatAt
   if now - lastInboundAt < 2 * interval
     send ping
+  else if sinceLastHeartbeat > 1.25 * interval
+    lastInboundAt = now
+    send ping
   else
-    close(1001, 'heartbeat timeout')
+    setImmediate: still expired after queued input ran ? close(1001, 'heartbeat timeout') : send ping

改动在 packages/kap-server/src/transport/ws/v1/wsConnectionV1.ts,测试在 packages/kap-server/test/wsConnectionV1.test.ts。

Behavior Changes and Affected Users

行为 之前 之后 谁依赖旧行为 退路
事件循环卡顿之后的第一次心跳检查 按卡顿前的入站时间判断,常常直接断开 回调晚了超过 1.25 个间隔时发新 ping,给一个完整的新窗口 无(旧行为是误断线) 无需
系统睡眠、墙上时间跳变(向前或往回) 影响超时判断,可能误断线,往回跳后还可能让死连接长期不被清理 不影响心跳 无 无需
检查时已超时、但 pong 已到达还没处理 直接断开 先处理排队的入站数据再复查,不断开 无 无需
对端真的不回应 两个间隔后断开 不变(断开发生在让出一次事件循环之后);卡顿之后最多多给一个窗口,仍然断开 — —
心跳回调只是稍微晚一点(抖动) 按超时判断 不变,仍按超时判断 — —
正常回应的客户端 每个间隔收到 ping 不变 — —

受影响的是所有使用 /api/v1/ws 的客户端:desktop、web、以及直接接服务端 API 的脚本,都只会少遇到误断线。

测试(wsConnectionV1.test.ts):

  • 检查时已超时、但 pong 排在后面:处理完 pong 后不断开(去掉延后复查时失败);
  • 长时间卡顿后给一个完整的新窗口,期间回应的客户端不断开;卡顿之后对端仍不回应,照常断开;
  • 心跳回调每次只晚 1 毫秒、对端不回应时,照常在两个间隔后断开(把容差改回不带余量的写法时失败);
  • 墙上时间前跳一小时又回拨:回应的客户端不断开,不回应的对端仍在两个间隔后断开(改回 Date.now() 时失败)。

kap-server 全部 1376 个测试通过,类型检查和 lint 通过。

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.

@changeset-bot

changeset-bot Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 3761f50

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code 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 11, 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-11T13:56:20.999903Z 3761f50 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 11, 2026 •

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

commit: 3761f50

@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: 478d465354

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

@wbxl2000
wbxl2000 changed the base branch from main to release/2026-11-12 November 11, 2026 13:34
@wbxl2000
wbxl2000 force-pushed the kimi/20261111-052517-fix-kap-server-avoid-heartbeat-timeo-183593 branch from 478d465 to 03f83d4 Compare November 11, 2026 13:42

@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: 03f83d46ab

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

@wbxl2000
wbxl2000 merged commit 7a0205c into release/2026-11-12 Nov 11, 2026
15 checks passed
@wbxl2000
wbxl2000 deleted the kimi/20261111-052517-fix-kap-server-avoid-heartbeat-timeo-183593 branch November 11, 2026 14:03
@github-actions github-actions Bot mentioned this pull request Nov 11, 2026
@wbxl2000 wbxl2000 mentioned this pull request Nov 11, 2026
4 of 6 tasks
Grapedge added a commit that referenced this pull request Nov 12, 2026
* fix(agent-core-v2): truncate oversized skill content (#4834)

* fix(kap-server): bind the main agent when a session is created (#4839)

* fix(kap-server): bind the main agent when a session is created

* fix(kap-server): reject a profile on prompt submissions

* fix(kap-server): reject a profile change through the session profile

* fix(kap-server): wait for model configuration before binding a new session

* fix(agent-core-v2): deduplicate restored task notifications (#4836)

* fix(agent-core-v2): deduplicate restored task notifications

* chore: add notification replay fix changeset

* fix(agent-core-v2): preserve task notifications after prompt-only crashes

* fix(agent-core-v2): complete prompts before ending turns

* test: align lifecycle snapshots with prompt completion order

* fix(agent-core-v2): settle all prompts during turn finalization

* fix(kap-server): drop reserved metadata keys from session profile updates (#4842)

* fix(kap-server): drop reserved metadata keys from session profile updates

* fix(kap-server): keep stored reserved metadata keys on profile updates

* docs: split and rewrite the server API reference (#4841)

* docs: split and rewrite the server API reference

* docs: redirect old server API anchors to the split pages

* docs: describe profile metadata as a replacement

* docs: mark question responses as answered-only

* fix(kap-server): avoid heartbeat timeout after scheduling stalls (#4823)

* fix(kap-server): avoid heartbeat timeout reaping after stalls or clock jumps

* fix(kap-server): grace heartbeat window for short scheduling stalls

* fix(kap-server): treat only clearly late heartbeats as scheduling stalls

* fix(kap-server): time heartbeats on a monotonic clock and drain queued input before reaping

---------

Co-authored-by: Kimi Code (Grok Bot) <[email protected]>

* fix(kap-server): undo a turn only once when requests race (#4846)

* docs: describe heartbeat stall handling (#4849)

* docs: describe heartbeat stall handling

* docs: explain the monotonic clock in the heartbeat notes

* fix(agent-core-v2): acquire session lock before loop restoration (#4848)

* fix(agent-core-v2): acquire session lock before loop restoration

* chore: add session lock lifecycle changeset

* fix(agent-core-v2): hold session lock through loop restoration

- add an operation-scoped lease to the session run gate
- hold it across loop initialization, reset, and pending drains
- cover idle timeout and release ordering

* fix(agent-core-v2): keep the output of stopped tool calls (#4854)

* fix(kap-server): drop the partial reply of a retried step (#4855)

* fix(agent-core-v2): dedupe historical tool schemas (#4862)

* fix(agent-core-v2): dedupe historical tool schemas

* chore: add duplicate tool schema changeset

* fix(agent-core-v2): preserve first tool schema declaration

* fix(agent-core-v2): remind on changed tool schemas

* fix(agent-core-v2): block stale tool schema calls

* fix(agent-core-v2): normalize registry schemas in pending checks

* fix(agent-core-v2): import registry tool metadata type

* fix(agent-core-v2): preserve abort handling during validation

* fix(agent-core-v2): refine validation hook preparation

* fix(agent-core-v2): make validation hooks synchronous

* fix(agent-core-v2): preserve tool result notes on fork (#4867)

* fix(agent-core-v2): preserve tool result notes on fork

* chore: add fork tool result note changeset

* fix(agent-core-v2): scope tool result note restoration to forks

* fix(agent-core-v2): normalize inherited tool result notes

* fix(agent-core-v2): isolate fork note restoration

* feat(tui): sweep running titles toward text and add KIMI_CODE_TUI_ANIMATION_FPS (#4843) (#4870)

* chore: sync web dist from code-app (#4871)

code-app: 8ab17294e031323186d357d121c5360b8353900e

Co-authored-by: kimi-agent-bot <[email protected]>

* ci: release packages (#4835)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore: sync web dist from code-app

code-app: 5835391dac3a2b9e0c65ffbd418f0d6042a7adb2

---------

Co-authored-by: Haozhe <[email protected]>
Co-authored-by: qer <[email protected]>
Co-authored-by: Kimi Code (Grok Bot) <[email protected]>
Co-authored-by: grapedge <[email protected]>
Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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