Skip to content

fix(agent-core-v2): avoid quadratic cloning during session replay - #4885

Merged
7Sageer merged 3 commits into
release/2026-11-13-2from
fix/participant-mutable-replay
Nov 13, 2026
Merged

7Sageer merged 3 commits into
release/2026-11-13-2from
fix/participant-mutable-replay

Conversation

@kimi-agent-bot

@kimi-agent-bot kimi-agent-bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

打开或恢复包含大量历史轮次与工具调用的既有本地会话(例如冷启动首次打开会话,或会话经服务端空闲回收后再次切换打开)时,服务端重放 wire.jsonl 同步阻塞主事件循环数秒(450 轮 / 4,500 次工具调用的会话耗时约 5.4s–8.5s),客户端对话主区域与右侧项目栏同时停留在「加载中…」。

本 PR 在 DurableAgentRuntimeParticipant 上对齐 ReplayableStateKey 既有的显式 mutableReplay?: boolean 选入机制并在 ConversationFeed(kap.conversation)开启,同时在 restoreLoopJournal 中启用 loopEventFold 的可变折叠模式(收尾统一递归 freeze),将 450 轮 / 4,500 次工具调用会话的重放耗时从约 6.0s 降至约 0.07s(客户端完整打开由 ~8.5s 降至 ~1.2s),同时保持其余参与者原有 produce 路径与终态冻结语义完全不变。

Bug Reproduction Steps

  1. 准备一个包含多轮工具调用的本地会话(例如 280–450 轮、2,800–4,500 次工具调用,wire.jsonl 约 16,000–25,000 行)。
  2. 冷启动客户端打开该会话,或等待服务端空闲回收该会话后再次点击切换回该会话。
  3. 修复前:EventDispatcherService.restore() 与 LoopJournal.snapshot() 在重放 wire.jsonl 期间同步阻塞服务端主线程数秒,客户端首帧 turns 响应延迟,界面长时间显示「加载中…」。

Root Cause

根本修复。 服务端会话恢复路径存在两处随历史记录数呈 $O(N^2)$ 增长的拷贝热点:

  1. EventDispatcherService 未向 kap.conversation 参与者提供可变重放路径(主因):
    • packages/agent-core-v2/src/state/eventDispatcherService.ts 在 executeEvent 中仅为显式声明 mutableReplay 的 ReplayableStateKey 提供了暂存可变重放路径,而 kap.conversation(ConversationFeed)在 restore() 重放每条 wire 记录时均调用 replayImmer.produce。当 ConversationState.tools(数千键对象)、steps 与 turns 随历史增长后,每条工具或消息事件触发 Immer shallowCopy 全量拷贝属性描述符,形成 $O(N^2)$ 开销(25,652 条记录耗时约 5.3s–6.1s);attachLateNow 在逐条循环内调用 produce(structuredClone(attachment.getState()), ...)(4,572 条记录即耗时 5.37s)。
  2. restoreLoopJournal 未开启 loopEventFold 可变模式(叠加热点):
    • packages/agent-core-v2/src/agent/loop/journal.ts 的 restoreLoopJournal 在顺序折叠 context.append_message 与 context.append_loop_event 时未向 foldAppendMessage / foldLoopEvent 传入 mutable = true,导致每条事件都复制整条 ContextMessage[] 数组并对单条消息递归 freeze(25,652 条记录额外耗时约 0.46s–0.81s)。

Code Changes

与 ReplayableOptions.mutableReplay(state.ts)完全一致,在 DurableAgentRuntimeParticipant 上增加可选 mutableReplay?: boolean,并仅在纯折叠且具自定义 onUndo 的 ConversationFeed(kap.conversation)开启:重放期间在 replayMutableParticipants 暂存的独立 structuredClone 草稿上原地执行 applier,中途不提前写入 attachment.commit(失败直接丢弃暂存草稿),重放成功收尾时一次性递归 freeze 并 commit;未开启 mutableReplay 的其余参与者保持原有 produce 行为逐字不变。

 DurableAgentRuntimeParticipant
+  readonly mutableReplay?: boolean;  // requires custom onUndo when undoable

 EventDispatcherService (silent = true)
   attachment.mutableReplay === false (default):
     unchanged produce / replayImmer.produce path
   attachment.mutableReplay === true (kap.conversation):
     stage structuredClone(attachment.getState()) in replayMutableParticipants
     apply each record in place (clone replacement if next !== current)
     discard staged draft if restore / attachLate fails
     commit(freeze(staged, true)) once at end of restore / attachLateNow

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

阅读顺序:

  1. packages/agent-core-v2/src/state/eventDispatcher.ts 与 eventDispatcherService.ts:对齐 replayMutableStates 实现 mutableReplay?: boolean 暂存重放与收尾 freeze。
  2. packages/kap-server/src/services/conversation/conversationFeed.ts:kap.conversation 开启 mutableReplay: true。
  3. packages/agent-core-v2/src/agent/loop/journal.ts:restoreLoopJournal 开启 mutable = true 并在 foldSettle 后统一 freeze。
  4. packages/agent-core-v2/test/state/eventDispatcher.test.ts 与 packages/agent-core-v2/test/agent/loop/journal.test.ts:边界与失败丢弃回归测试。

Screenshots / Recordings

同一份合成重度工具长会话(450 轮 / 4,500 次工具调用,25,652 行 wire.jsonl)冷启动点击打开对比:左侧修改前在 t = 2.0s(直至 ~8.5s)仍停留在「加载中…」,右侧修改后快速完成加载并可交互。

点击打开后 t = 2.0s 修改前后对比

点击打开全过程修改前后录屏对比

Behavior Changes and Affected Users

行为 修改前 修改后 依赖旧行为的人群 退路
kap.conversation(ConversationFeed,mutableReplay: true)历史恢复与 attachLate 逐条记录执行 Immer.produce(attachLate 另逐条 structuredClone),重放末尾再 structuredClone + freeze 在暂存独立草稿上原地折叠,失败丢弃草稿,成功收尾一次性递归 freeze 后 commit;终态数据与冻结属性逐字节一致,450 轮会话重放由 ~6.0s 降至 ~70ms 全端消费 kap-server 会话流的客户端(desktop 与 web) 无需(纯内部重放性能优化,输出状态逐字节一致)
未声明 mutableReplay: true 的 DurableAgentRuntimeParticipant 与 AgentModel 走 replayImmer.produce / produce 逐条折叠并 commit 不变 全端所有其余运行时参与者与模型 无需
restoreLoopJournal 重建循环上下文消息 默认以不可变模式逐条拷贝并冻结 ContextMessage[] 以 mutable = true 折叠并在 foldSettle 后一次性递归 freeze,返回消息及嵌套内容同样不可变 全端恢复既有会话的用户 无需
  • 受影响模块:
    • packages/agent-core-v2/src/state/eventDispatcher.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: true 要求自定义 onUndo、不污染 initial、重跑与失败原子丢弃、冻结替换克隆及 attachLate 追平后继续实时派发。
    • packages/agent-core-v2/test/agent/loop/journal.test.ts:验证多步工具调用与步骤内压缩恢复不修改输入 WireRecord 且返回消息嵌套字段已冻结。
    • 9 组梯度合成会话修复前后 ConversationFeed.turns() 与 restoreLoopJournal() 序列化 SHA-256 100% 一致。
验证与基准测试明细

合成长会话重放基准对比(同一份 wire.jsonl,3 轮均值,输出 SHA-256 全部一致)

场景(轮数 / 工具调用 / wire.jsonl 行数) dispatcher.restore() 修改前 dispatcher.restore() 修改后 restoreLoopJournal 修改前 restoreLoopJournal 修改后 attachLate 修改前 → 修改后
80 轮 / 800 工具(4,572 行) 147.3 ms 21.4 ms (6.9×) 31.6 ms 12.3 ms 5,369.0 ms → 12.1 ms (442×)
140 轮 / 1,400 工具(7,992 行) 439.0 ms 22.1 ms (19.9×) 79.3 ms 3.5 ms —
110 轮 / 15 图 + 880 工具(5,622 行) 181.3 ms 16.7 ms (10.9×) 40.4 ms 2.4 ms —
280 轮 / 2,800 工具(15,972 行) 2,000.8 ms 42.0 ms (47.6×) 305.9 ms 7.3 ms —
450 轮 / 4,500 工具(25,652 行) 6,063.2 ms 69.3 ms (87.5×) 463.3 ms 12.1 ms —

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: 3e3dffb

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-13T08:59:07.420641Z 3e3dffb 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 12, 2026 •

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

commit: 3e3dffb

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

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

@kimi-agent-bot
kimi-agent-bot force-pushed the fix/participant-mutable-replay branch from fe18c25 to 9c464f2 Compare November 12, 2026 17:24
@kimi-agent-bot
kimi-agent-bot changed the base branch from main to release/2026-11-13 November 12, 2026 17:24

@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: 9c464f24c7

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

@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: 33aa94851a

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

@kimi-agent-bot

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 335d2571cb

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

@sailist
sailist force-pushed the fix/participant-mutable-replay branch from 335d257 to 660af3b Compare November 13, 2026 05:07
@wbxl2000 wbxl2000 closed this Nov 13, 2026
@wbxl2000 wbxl2000 reopened this Nov 13, 2026
@sailist
sailist force-pushed the fix/participant-mutable-replay branch from 660af3b to 3e3dffb Compare November 13, 2026 08:56
@sailist
sailist changed the base branch from release/2026-11-13 to release/2026-11-13-2 November 13, 2026 08:56
@WilliamLambertCN

Copy link
Copy Markdown

@kimi-agent-bot Independent high-impact 2.6.0 reproduction and version-bisect evidence: #4917.

  • Exact released 2.6.0, isolated forced late conversation attachment: 88.873 s,
    including 67.880 s in 7,439 structuredClone calls.
  • Same input with normal early attachment: latest-page HTTP 4.199 s.
  • An experimental no-per-event-deep-clone copy reduced late attach to 2.519 s;
    this is cost isolation, not a production-ready replacement or an undo/failure-safety guarantee.
  • The per-event deep clone is absent in actual npm 2.5.2 / 2.5.3 and introduced by b263e80 (refactor(agent-core-v2): port agent loop runtime core #4630).
  • A separate real 2.6.0 trace had a 61.928 s local upstream-header wait and overlapping 42.670 s WS handshake.
    We have not proved that incident naturally entered attachLateNow; a later coordinated refresh was fast.

I confirmed #4888 / #4893 already shipped the kap.conversation mutable-replay fix in 2.6.1.
Please reconcile this still-open follow-up with the shipped fix and advise affected 2.6.0 users accordingly.
The remaining default/non-opt-in late-participant deep-clone path should be triaged separately;
I have not runtime-tested 2.6.1 or demonstrated a remaining user-visible stall on it.

No private session data, IDs, credentials, raw profiles, or logs were uploaded.
I am not opening a duplicate fix PR; a focused follow-up can be prepared after maintainer /approve if needed.

@7Sageer
7Sageer merged commit ec35f9a into release/2026-11-13-2 Nov 13, 2026
26 of 27 checks passed
@7Sageer
7Sageer deleted the fix/participant-mutable-replay branch November 13, 2026 09:57
@github-actions github-actions Bot mentioned this pull request Nov 13, 2026
wbxl2000 pushed a commit that referenced this pull request Nov 16, 2026
* fix(agent-core-v2): avoid quadratic cloning during session replay (#4885)

* fix(agent-core-v2): avoid quadratic cloning during session replay

* fix(agent-core-v2): isolate replay assignments and preserve rollback order

* refactor(agent-core-v2): make participant mutable replay explicit opt-in

---------

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

* fix(agent-core-v2): validate Kimi media upload status (#4905)

* fix(agent-core-v2): reject failed Kimi image extraction

* chore: add Kimi image extraction changeset

* fix(agent-core-v2): validate Kimi media upload status

* fix(kap-server): forward swarm member task events (#4922)

* test(agent-core-v2): make zero-timeout task wait deterministic (#4925)

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

* feat(registry): support search_url and feedback_url on custom registry providers (#4875)

* feat(registry): support search_url and feedback_url on custom registry providers

* fix(sdk): honor provider.env credentials and custom_headers for feedback_url

* refactor(core): submit feedback through the engine

Web and desktop reach this machine through kap-server, so feedback submission resolves the active model's provider in the engine and is exposed on the same route and klient method. The SDK facade keeps the managed OAuth path and no longer re-derives provider credentials.

* refactor(sdk): drop the unused feedback facade

Product clients submit feedback through the engine. The SDK facade and oauth toolkit no longer keep a second managed-only submission path.

* refactor(feedback): share engine schemas across route and klient

The HTTP body uses the engine field names, so the route forwards it and the klient contract imports the same schemas.

* refactor(feedback): drop unused kap and klient surfaces

TUI reaches IFeedbackService through the harness. The HTTP routes, klient facade, and the schemas that only served them have no caller.

* refactor(feedback): package and upload feedback attachments in the engine

* refactor(feedback): keep FeedbackService internal to agent-core-v2

* test(cli): provide execFile in node:child_process mocks

The feedback codebase scanner added in this branch calls
promisify(execFile) at module scope and is now reachable from the
agent-core-v2 index, so partial child_process mocks in these suites
failed module evaluation.

* feat(feedback): disclose submitted files, attach request_id, and drop text-only option (#4876)

* feat(registry): support search_url and feedback_url on custom registry providers

* fix(sdk): honor provider.env credentials and custom_headers for feedback_url

* refactor(core): submit feedback through the engine

Web and desktop reach this machine through kap-server, so feedback submission resolves the active model's provider in the engine and is exposed on the same route and klient method. The SDK facade keeps the managed OAuth path and no longer re-derives provider credentials.

* refactor(sdk): drop the unused feedback facade

Product clients submit feedback through the engine. The SDK facade and oauth toolkit no longer keep a second managed-only submission path.

* refactor(feedback): share engine schemas across route and klient

The HTTP body uses the engine field names, so the route forwards it and the klient contract imports the same schemas.

* refactor(feedback): drop unused kap and klient surfaces

TUI reaches IFeedbackService through the harness. The HTTP routes, klient facade, and the schemas that only served them have no caller.

* refactor(feedback): package and upload feedback attachments in the engine

* refactor(feedback): keep FeedbackService internal to agent-core-v2

* test(cli): provide execFile in node:child_process mocks

The feedback codebase scanner added in this branch calls
promisify(execFile) at module scope and is now reachable from the
agent-core-v2 index, so partial child_process mocks in these suites
failed module evaluation.

* feat(feedback): disclose submitted files, attach request_id, and drop text-only option

* fix(session-export): keep SESSION_NOT_FOUND for missing non-empty session ids

The global-log-only fallback exists for feedback submissions without an
active session (empty id). Scoping it to empty ids restores the 40401
envelope that kap-server's export route promises for unknown sessions.

* test(agent-core-v2): pin retained request id semantics in llmRequester assertions

* chore: sync web dist from code-app

code-app: 11563df26b92f0035659083327976a2e9b8e6727

code-app-release: b0b6d9c7a45c96ca48039ff05789c6e90f76ef20

code-app-local-build: 005d2b437493b7ab04d01f70542f3b6356699f4d

* ci: release packages (#4918)

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

* fix(agent-core-v2): align request id back-sync with main

---------

Co-authored-by: kimi-agent-bot <[email protected]>
Co-authored-by: Haozhe <[email protected]>
Co-authored-by: 7Sageer <[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.

5 participants