Skip to content

fix(kap-server): append new content blocks without rescanning the turn - #5344

Merged
wbxl2000 merged 5 commits into
mainfrom
chengluyu-fix-append-log-backpressure
Nov 24, 2026
Merged

wbxl2000 merged 5 commits into
mainfrom
chengluyu-fix-append-log-backpressure

Conversation

@chengluyu

@chengluyu chengluyu commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

有用户报告:在 Windows 上用 Kimi Code Desktop 1.4.2,一个会话里同时跑主代理和 9 个子代理。长时间运行后,全局日志反复出现 append log flush is stuck; records are accumulating in memory,最后客户端被 Windows 记录为 Application Hang 并强制关闭。

排查发现,append-log 积压只是现象。真正的原因是主进程的事件循环被会话投影的同步工作反复占住几十秒。本 PR 修掉投影里的二次方开销。

Bug Reproduction Steps

  1. 让一个模型步骤产生大量内容块(数千到上万个)。实际案例中,某第三方 OpenAI 兼容 provider 在每个流式 chunk 里把同一段思考文本同时放进 reasoning_content 和 reasoning 两个字段,导致每个 token 都成为独立的内容块。
  2. 在 Desktop(内嵌 kap-server)中运行该步骤,多个子代理并发时更明显。
  3. 步骤结束时,主进程卡住的时长随块数平方增长。期间所有定时器(MCP 重连、健康日志、Remote Control 心跳、append-log 看门狗)一起延迟,最终可能被系统判定为无响应。

Root Cause

步骤结束时,journal 在一个同步循环里为每个内容块写一条记录并 dispatch ContextAppendLoopEvent。kap-server 的 ConversationFeed 在 immer produce 中处理每个 content.part,upsertItem 每次都对整轮的 turn.items 做一次 findIndex,总开销是 O(n²),并且全部发生在 Desktop 主进程上。

用户日志和这个模型吻合:一个 10657 块的步骤连续写了 45 秒,一个 9671 块的步骤写了 103 秒;期间全进程 10 个代理没有插入任何其他记录,耗时曲线也呈二次方。最后一个大步骤结束后约 1.5 分钟,Windows 就记录了 Hang。

本 PR 去掉其中的线性查找。immer 每个事件复制并冻结 turn.items 的开销仍然存在(见 Code Changes),所以这是缓解,不是彻底消除二次方。块数暴增的上游原因(provider 镜像推理字段导致内容块无法合并)不在本 PR 范围内。

sequenceDiagram
    participant J as Loop journal
    participant F as ConversationFeed (main process)
    J->>F: N × content.part, one sync loop
    Note over F: before: each part does findIndex over turn.items → O(N²)
    Note over F: after: new block → push, O(1) lookup
Loading

Code Changes

会话投影:已知是新块的 content.part 直接追加(packages/kap-server/src/services/conversation/conversationFold.ts)

 on step.begin(uuid)
   push step track
+  if no item of this step exists yet: stepNextBlock[uuid] = 0
 on content.part(stepUuid, block)
   build item `${stepUuid}:${block}`
-  upsertItem(turn, item)            # linear findIndex over turn.items
+  if stepNextBlock[stepUuid] is known and block >= it
+    push item; stepNextBlock[stepUuid] = block + 1
+  else
+    upsertItem(turn, item)          # unchanged path
 on step.end / clear
+  drop stepNextBlock entry

这里的不变式是:带 ${stepUuid}: 前缀的 item 只在 content.part 里创建,所以只要 block 不小于"该步骤下一个未出现的块",就一定不存在同 id 的 item。以下情况都回到原来的 upsertItem,语义不变:重复块、乱序块、没有 block 字段、step.end 之后才到的块、fork 继承的步骤、找不到 step.begin 的步骤。

实测(生产 fold + immer,单轮单步骤,本机):8000 块从 8.0 s 降到 1.47 s,与"只 push"的下限一致。剩下的二次方来自 immer 每个事件都会复制并冻结 turn.items,属于 dispatcher 提交实时事件的方式,本 PR 不动。

Behavior Changes and Affected Users

行为 改动前 改动后 谁依赖旧行为 退路
会话投影中新内容块的追加 upsertItem,结果是在末尾 push 直接 push,结果相同 无 无需
重复、乱序、无 block、步骤结束后到达、fork 继承的内容块 upsertItem 不变 Desktop、kimi web、经 KAP 订阅会话的客户端 —
已保存会话的恢复回放 upsertItem 新块走快路径,结果相同 旧版本写的会话 —

受影响模块:kap-server 会话投影,进而影响 Desktop(内嵌 kap-server)和 kimi web。对外协议、事件顺序和内容都不变。

测试覆盖:packages/kap-server/test/services/conversation.test.ts 新增用例,用计数 Proxy 断言追加 200 个块时对 turn.items 的元素读取次数是线性的(修复前 20102 次),并确认重复块仍会覆盖原 item。原有的重试、undo、fork、清空相关用例都通过。

验证记录
  • pnpm exec vitest run --reporter=agent packages/kap-server/test/services/conversation.test.ts:通过。
  • pnpm exec vitest run --reporter=agent packages/kap-server/test:1491 passed,1 failed(searchService.test.ts 的 "keeps a query valid when readonly refresh replaces its handle during source validation")。该用例只在全量并发运行时失败,单独运行时改动前后都通过,与本 PR 无关。
  • pnpm exec tsc -p packages/kap-server/tsconfig.json --noEmit:通过。
  • pnpm lint:通过。
  • 未验证:Windows 上的真实卡顿复现和事件循环 profile。

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 24, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 92ac847

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/kap-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 24, 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-24T09:15:48.208550Z 6ea457f 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.

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

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

@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: 60ca5819dc

ℹ️ 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 24, 2026

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

commit: a2f8f5f

@chengluyu chengluyu changed the title fix: stop mirrored reasoning keys from freezing long multi-agent sessions fix(kap-server): append new content blocks without rescanning the turn Nov 24, 2026
@wbxl2000
wbxl2000 merged commit c7d3576 into main Nov 24, 2026
17 checks passed
@wbxl2000
wbxl2000 deleted the chengluyu-fix-append-log-backpressure branch November 24, 2026 09:19
@github-actions github-actions Bot mentioned this pull request Nov 24, 2026
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Keep a per-step next-block cursor so an open step's content parts append
straight to the turn and only out-of-order rewrites fall back to upsert
(MoonshotAI#5344); a step with no items seeds the cursor and step.end drops it.
Compare and diff jsPlugins as sets so lint-guard configs are order
insensitive and a removed plugin reads as weakened (MoonshotAI#5249). Ledger: 5015
equivalent.
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.

3 participants