Skip to content

fix(agent-core-v2): stage opt-in mutable replay for conversation participant - #4888

Merged
wbxl2000 merged 1 commit into
release/2026-11-13from
fix/staged-participant-mutable-replay
Nov 12, 2026
Merged

wbxl2000 merged 1 commit into
release/2026-11-13from
fix/staged-participant-mutable-replay

Conversation

@wbxl2000

Copy link
Copy Markdown
Collaborator

Requirement or Bug

重新打开包含大量历史轮次与工具调用的本地会话时,服务端重放 wire.jsonl 触发 $O(N^2)$ 对象浅拷贝与重复深拷贝,阻塞主事件循环数秒。

Bug Reproduction Steps

  1. 准备包含多轮工具调用的本地会话(例如 450 轮、4,500 次工具调用,约 2.4 万行 wire.jsonl)。
  2. 冷启动打开该会话,或在服务端回收会话后重新加载 / attachLate 订阅该会话。
  3. 修复前:EventDispatcherService.restore()(约 4.3s)与 attachLate()(150 轮即约 29.6s)在重放期间同步阻塞服务端主线程。

Root Cause

根本修复。 会话恢复路径有两处未对齐 PR #4313 的可变重放机制:

  1. EventDispatcherService 仅为显式声明 mutableReplay: true 的 ReplayableStateKey 提供了暂存可变重放路径,而 DurableAgentRuntimeParticipant(如 kap.conversation)在 restore() 中对每条记录调用 Immer.produce(当 ConversationState.tools 增长至数千键时每次写入均触发全表属性描述符浅拷贝,呈 $O(N^2)$),在 attachLate() 中更对每条记录额外执行 structuredClone(attachment.getState())。
  2. restoreLoopJournal 折叠 context.append_message 与 context.append_loop_event 时未传入已有的 mutable = true 参数,导致每条记录复制整条 ContextMessage[] 并逐条递归冻结。

Code Changes

对齐 ReplayableStateKey 已有的 mutableReplay 设计:在 DurableAgentRuntimeParticipant 上增加显式 opt-in 开关 mutableReplay?: boolean(启用时要求 undoable 参与者提供自定义 onUndo 并禁止使用 checkpoint),仅对 kap.conversation 开启;重放期间在隔离的暂存草稿上原地折叠,重放成功收尾时一次性递归 freeze 并 commit,异常时直接丢弃暂存草稿。未开启开关的参与者与 AgentModel 保持原 Immer.produce 路径不变。

export interface DurableAgentRuntimeParticipant<State = any> {
  ...
  readonly mutableReplay?: boolean;
}
 EventDispatcherService (restore / attachLate, silent = true)
   attachment.mutableReplay === false (default)
     unchanged: per-record Immer.produce + per-record commit
   attachment.mutableReplay === true (kap.conversation)
-    every record -> Immer.produce / produce(structuredClone(state)) + commit
+    first mutating record -> replayImmer.produce + structuredClone into replayMutableParticipants
+    subsequent records -> applier(stagedDraft) in place (structuredClone only on replacement return)
+    end of replay -> attachment.commit(freeze(stagedDraft, true)) once
+    on replay failure -> discard replayMutableParticipants (caller state untouched)

 restoreLoopJournal
-  foldAppendMessage(context, message)
-  foldLoopEvent(context, event)
-  context = foldSettle(context)
+  foldAppendMessage(context, message, true)
+  foldLoopEvent(context, event, true)
+  context = freeze(foldSettle(context), true)

本机合成长会话实测(修改前后 ConversationFeed.turns() SHA-256 100% 一致):

场景 修改前 修改后 加速比
110 轮 / 880 工具(4,730 行)restore() 548.0 ms 50.1 ms 10.9×
280 轮 / 2,800 工具(14,840 行)restore() 2,620.3 ms 33.0 ms 79.5×
450 轮 / 4,500 工具(23,850 行)restore() 4,313.2 ms 51.3 ms 84.1×
150 轮 / 1,500 工具(7,950 行)attachLate() 29,627.4 ms 16.5 ms 1,796×

Behavior Changes and Affected Users

行为 修改前 修改后 依赖旧行为的人群 退路
kap.conversation 在 restore() 与 attachLate() 期间的状态重放 逐条执行 Immer.produce(attachLate 另逐条 structuredClone)并逐条 commit 在隔离暂存草稿上原地折叠,重放结束时一次性递归 freeze 并 commit;重放失败丢弃暂存草稿 使用 desktop、web 等通过 kap-server 恢复既有长会话的用户:终态与异常恢复语义一致,消除多秒阻塞 无需(输出状态 SHA-256 一致)
未设置 mutableReplay: true 的 DurableAgentRuntimeParticipant 与 AgentModel 逐条执行 Immer.produce 与 commit 不变 全端所有其他运行时参与者与模型 无需
restoreLoopJournal 重建循环上下文消息 逐条不可变复制并递归冻结 ContextMessage[] 以 mutable = true 折叠并在 foldSettle 后一次性递归 freeze 全端恢复既有会话的用户(TUI、print 模式、desktop 与 web、VS Code、ACP、SDK) 无需(输出消息内容与冻结性一致)
  • 受影响模块:
    • packages/agent-core-v2/src/state/eventDispatcher.ts
    • packages/agent-core-v2/src/state/state.ts
    • packages/agent-core-v2/src/state/eventDispatcherService.ts
    • packages/agent-core-v2/src/agent/loop/journal.ts
    • packages/kap-server/src/services/conversation/conversationFeed.ts
  • 测试覆盖:
    • packages/agent-core-v2/test/state/eventDispatcher.test.ts:覆盖 mutableReplay 缺少自定义 onUndo 与违规调用 checkpoint 报错、首次变更克隆隔离与单次冻结提交、替换对象(含带冻结子属性的外层未冻结对象)隔离、重跑 restore()、外层包装容器 box 的 attachLate()、重放异常丢弃暂存草稿不污染原状态,以及 restore() 读取期间实时 dispatch() 共存。
    • packages/agent-core-v2/test/agent/loop/journal.test.ts:覆盖多步工具调用与步骤内压缩恢复不修改输入记录且嵌套消息内容已冻结。
    • packages/kap-server/test/services/conversation.test.ts 与 conversationContract.e2e.test.ts:全量通过。

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 12, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 8c9297f

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 12, 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-12T18:44:52.597648Z 8c9297f 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 12, 2026

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

commit: 8c9297f

@wbxl2000
wbxl2000 merged commit 0341ca4 into release/2026-11-13 Nov 12, 2026
15 checks passed
@wbxl2000
wbxl2000 deleted the fix/staged-participant-mutable-replay branch November 12, 2026 18:47
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 18, 2026
MoonshotAI#4663 and MoonshotAI#4789 now describe the recorded-event fold that serves the pinned
bundle: task links come from persisted TaskStarted records, and the feed no
longer rebuilds from the model-context view. MoonshotAI#4730 moves from partial to
ported (record-driven items seal once, with the recorded reasoning duration),
and MoonshotAI#4772's probe follows the feed suite it now lives in.

MoonshotAI#4893 is unblocked: `kap.conversation` stages its replay, publishes once after
rehydration, and gates live dispatch only while a mutable participant
restores. The PLAYBOOK note on the release-branch commits carries the
correction for MoonshotAI#4888 for the same reason.
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