Skip to content

fix(core): keep append-log known length when own writes race a read - #5595

Merged
sailist merged 2 commits into
mainfrom
bug-473-11-26-append-log-read-write-stale
Nov 27, 2026
Merged

sailist merged 2 commits into
mainfrom
bug-473-11-26-append-log-read-write-stale

Conversation

@sailist

@sailist sailist commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

恢复或重载已有会话时,如果配置了连接较慢或会被服务端拒绝的 MCP server,Core 会在恢复过程中把 mcp.server_failed 持久化到会话日志;当这次自身写入与恢复流程重读历史重叠时,紧接着的 Loop 初始化会把本进程自己的追加误判为外部客户端修改,直接抛出 Session "..." was updated by another client; reload it before continuing(session.stale),导致 SDK / KAP 调用方(包括 Desktop/Web、VS Code、外部 Agent 宿主)无法打开会话。本 PR 修复该记账竞态,使自身写入不再触发误报,同时完整保留真实多客户端冲突检测(包括重读尚未完成时的并发门控检查)。

Bug Reproduction Steps

  1. 准备一个已有历史记录的会话,并配置一个可控延迟失败的 MCP server(在会话恢复开始后才返回失败,例如服务端拒绝启用或子进程延迟退出)。
  2. 通过 SDKRpcClientV2.resumeSession / reloadSession 恢复会话,使 mcp.server_failed 恰好在 onDidRestore 的 task.history(或 initializeLoop 的 reconcile)流式读取 wire.jsonl 期间由本进程追加落盘并完成 flush。
  3. 读取结束后,内存中的已知长度被退回追加前;随后 initializeLoop 调用 runGate.tryAcquire() 检查 externallyModified(),发现磁盘长度大于已知长度,恢复直接抛出 session.stale。

最小确定性复现见 packages/core/test/store/append-log.test.ts 与 packages/agent-core-v2/test/wire/persistence.test.ts 的新增回归用例(修复前失败,修复后通过)。

Root Cause

这是根本修复,不是绕过检查。

跨进程会话锁引入时,为了防住“读取日志期间另一个进程追加了未读字节,读完却直接记成当前磁盘长度,导致后续漏报 session.stale”,AppendLogStore.read() 在 finally 中做了保守回退:只要读前长度 lengthAtStart 与读完时的磁盘长度 disk 不一致,就把 state.knownLength 写回 lengthAtStart。

但这段逻辑没有区分“外部进程写入”和“本进程自身写入”:

sequenceDiagram
    participant Restore as 会话恢复 (task.history)
    participant Log as AppendLogStore
    participant Disk as wire.jsonl
    participant MCP as MCP 失败处理
    participant Gate as SessionRunGate

    Restore->>Log: read()
    Log->>Disk: lengthAtStart = L0,开始流式读取
    MCP->>Log: append(mcp.server_failed) + flush
    Log->>Disk: drain() 追加 301B,inFlightBytes 归零,knownLength += 301B
    Restore->>Log: 流式读取结束,进入 finally
    Log->>Log: disk (L0+301B) ≠ lengthAtStart (L0),knownLength 被回退为 L0
    Gate->>Log: externallyModified()
    Log-->>Gate: disk (L0+301B) > known (L0) + inFlight (0) → true(误报)
    Gate-->>Restore: 抛出 session.stale
Loading

因此,任何本进程在 read() 流式读取期间完成的自身追加(如 MCP 失败记录、后台任务通知、cron 触发),或较早开始的并发慢读取结束时,都会把已经记账的已知长度覆盖回旧值。

同时,已知长度不能提前到读取开始前更新:若另一客户端已写入新记录、本会话正在重读历史,读取未完成前必须继续保持 externallyModified() === true,否则并发的 SessionRunGate.tryAcquire() 会在内存投影尚未纳入对方记录时提前放行。

Code Changes

改动聚焦在 AppendLogStore 内部记账:仍然在读取结束的 finally 中结算 knownLength,但结算值改为“读前长度 + 读取期间本进程自身成功追加的字节数”,并用读取序号与重写序号防止慢读取覆盖并发重写或较新读取的结果。

 LogState
+  appendedBytes: number   # 本实例 drain() 成功追加的累计字节数(不依赖 knownLength 是否已初始化)
+  readEpoch: number       # 最近一次开始的 read() 序号

 drain()
   await storage.append(...)
   if knownLength is defined: knownLength += encoded.length
+  appendedBytes += encoded.length

 read(scope, key)
   await flushLog(scope, key)
   lengthAtStart = diskLength(scope, key)
+  appendedAtStart = state.appendedBytes
+  cutoverEpochAtStart = state.cutoverEpoch
+  readEpoch = ++state.readEpoch
   try {
     stream and parse records           # 读取进行中不提前改写 knownLength,外部修改后的重读仍保持 stale
   } finally {
-    if diskLength() !== lengthAtStart:
-      state.knownLength = lengthAtStart
+    if diskLength() is defined
+       and state.cutoverEpoch === cutoverEpochAtStart   # 不覆盖读期间完成的 rewrite()
+       and readEpoch === state.readEpoch:               # 较早的慢读取不覆盖较新读取的结果
+      state.knownLength = (lengthAtStart ?? 0) + (state.appendedBytes - appendedAtStart)
   }

为什么这样同时守住两个方向:

  • 本进程自身追加 / 重写:读期间 drain() 完成后,读完结算会把自身追加的字节计入 knownLength(即使读取前 knownLength 为 undefined);若自身追加在 finally 之后才恢复续体,drain() 仍会在结算后的基线上累加,两种交错都不会误报。
  • 外部进程追加 / 截断:外部写入不增加 appendedBytes,读完结算不会把外部字节当成已知;而外部写入发生后、重读尚未完成的整个窗口内,knownLength 保持旧值,SessionRunGate 检查仍会抛出 session.stale。

关键决策:

决策 选择 没选 理由
结算时机 读取完成的 finally 中结算 读取开始前直接赋值 lengthAtStart 读前赋值会在“外部已写入、本会话重读未完成”期间提前清除 stale,并发 tryAcquire() 可能基于未更新的内存状态放行进轮
自身写入计量 记录本实例累计 appendedBytes,结算 lengthAtStart + 读期间自身追加 在 finally 中直接记 disk 直接记 disk 会把读期间外部进程追加的未读字节当成已知,漏掉真实的多客户端冲突
上层恢复流程 不改 MCP 失败持久化、task.history 重读与 SessionRunGate 检查 恢复期间暂时跳过 stale 检查 跳过检查会放过真实冲突,且其他读写重叠路径(并发读取、后台通知)仍会误报

阅读顺序:先看 packages/core/src/store/append-log.ts 中 read() 的 finally 结算与 drain() 的 appendedBytes,再看 packages/core/test/store/append-log.test.ts、packages/agent-core-v2/test/wire/persistence.test.ts 与 packages/agent-core-v2/test/session/sessionActivity/sessionRunGate.test.ts 的交错时序用例。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
读取会话日志期间,本进程自身追加或重写落盘后的外部修改判定 knownLength 在读取结束时被退回读前长度,后续锁检查误报 session.stale,恢复或提交失败 保留读期间自身写入的字节数,不误报,会话正常恢复与继续 无(旧行为为误报;受影响人群为配置了 MCP / 插件的 TUI、Desktop/Web、VS Code、ACP 及 SDK / KAP 外部 Agent 在恢复会话时) 无需
外部客户端已写入新记录、本会话重读历史尚未完成时的并发门控检查 读取结束时才刷新 knownLength,重读进行中 externallyModified() 保持 true、门控抛 session.stale 行为不变:重读完成前继续保持 true,完成后才解除 同时用多个客户端(如 TUI + Desktop/Web/VS Code)打开同一会话的用户 N/A
读取会话日志期间,外部进程直接追加或截断(含与自身追加混合发生) 判定为外部修改(session.stale) 行为不变,仍判定为外部修改 同时用多个客户端打开同一会话的用户 N/A
并发两次读取或读期间发生 rewrite() 时,较早的慢读取晚结束 慢读取结束时把较新读取或 rewrite() 已确认的长度回退,误报 session.stale 仅最新一次开始的读取在未发生 rewrite() 时结算长度,慢读取不覆盖新状态 无(旧行为为误报) 无需

受影响模块与测试覆盖:

  • packages/core/src/store/append-log.ts:由 packages/core/test/store/append-log.test.ts 覆盖首次读取与已有 knownLength 下读期间自身追加、自身与外部混合追加、外部写入后重读进行中保持 stale、并发 rewrite()、重叠读取(自身/外部追加),以及既有外部修改/in-flight 写入用例。
  • packages/agent-core-v2(WireService 恢复读取与 SessionRunGate):由 packages/agent-core-v2/test/wire/persistence.test.ts 覆盖 readRestoreChains() 期间自身追加 mcp.server_failed,由 packages/agent-core-v2/test/session/sessionActivity/sessionRunGate.test.ts 覆盖外部写入后重读暂停期间 gate().begin() 仍抛 session.stale、读完后放行。
验证命令与结果
  • m0-dev(Linux,Node 24):
    • corepack pnpm --filter @moonshot-ai/core --filter @moonshot-ai/agent-core-v2 typecheck:两包均通过。
    • @moonshot-ai/core 全量(corepack pnpm --filter @moonshot-ai/core test):37 个测试文件、409/409 条通过。
    • @moonshot-ai/agent-core-v2:
      • 首轮全量:8424 条通过、19 条跳过;仅 test/app/git/gitService.test.ts 中 2 条 git sparse-checkout init --cone 用例因远端机器 git CLI 未生成 config.worktree 报 ENOENT(直接断言 git CLI 的磁盘布局,与本改动无关)。
      • 本轮受影响目录(test/wire、test/session/sessionActivity、test/agent/mcp):17 个文件、253/253 条通过。
    • 修复前对照:首轮 Core 新增 3 条竞态用例失败;本轮新增的 2 条“重读进行中保持 stale”用例(Core + SessionRunGate)在首版提交上失败(54 条中 2 失败 52 通过),加固后全部通过。
  • 本地 .workspace/lint-pool.sh run bug-473-11-26-append-log-read-write-stale:pnpm lint(含 type-aware oxlint、注释、导入边界、测试桩、固定等待检查)与 check:duplication 全部通过。
  • 自定义 E2E(工作区 custom-e2e/mcp-startup-lifecycle/run.mts,macOS 进程内 SDKRpcClientV2 + testkit + 真实 stdio MCP 子进程):
    • resume-mcp-failure-race:修复前连续 3/3 抛出 Session "..." was updated by another client; reload it before continuing;修复后持续通过,mcp.server_failed 只落盘一次、后续回合正常。
    • live-reread-stale-gate(本轮 Codex P1 新增):首版提交上复现“重读暂停期间 tryAcquire() 未抛 stale”,加固后通过;两个场景连续 3 轮(6/6)全部通过。
    • 存量 slow-stdio-dynamic / slow-stdio-static / stdio-startup-failure 在当前未修改的 origin/main(d98f858e)上以相同断言失败(MCP 披露与重连 nextRetryAt 行为演进导致场景断言过期),与本改动无关。
  • 未验证项:Windows 开发机(coding-win)初始化时 SSH 连接被重置(kex_exchange_identification: Connection reset by peer),未跑本地 Windows 专项;本改动仅涉及字节长度记账时机,不涉及路径、子进程、shell 或终端输入的平台差异。

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

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7ca6aec

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

This PR includes changesets to release 4 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
kimi-code Patch
@moonshot-ai/core 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 27, 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-27T02:45:15.435480Z 7ca6aec Manual request
ℹ️ 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 27, 2026 •

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

commit: 7ca6aec

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

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

Comment thread packages/core/src/store/append-log.ts Outdated
Comment on lines +199 to +200
if (lengthAtStart !== undefined) {
state.knownLength = lengthAtStart;

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 Delay acknowledging the disk length until the read completes

When a reload is still iterating a log changed by another client, assigning knownLength before the first record is yielded makes externallyModified() return false for the entire in-progress read. A concurrent prompt or other path through SessionRunGateService.tryAcquire() can consequently acquire the run gate and write using state that has not yet incorporated the other client's records; previously the finally block kept the session stale until iteration finished. Preserve own-write accounting without acknowledging the starting length until the reader has completed, and cover a gate check while the stream is paused.

AGENTS.md reference: AGENTS.md:L111-L116

Useful? React with 👍 / 👎.

@@ -0,0 +1,5 @@
---
"@moonshot-ai/kimi-code": patch

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add a VS Code product changeset

The VS Code extension depends on @moonshot-ai/kimi-code-sdk and uses the same session resume/reload path, so extension users receive this user-visible fix too, but the added changesets cover only Core, CLI, and Desktop. Without a kimi-code product changeset, the VS Marketplace/Open VSX release notes will omit the fix; add the corresponding short extension-facing entry.

AGENTS.md reference: AGENTS.md:L169-L170

Useful? React with 👍 / 👎.

AppendLogStore.read() rolled knownLength back to lengthAtStart in finally
whenever the file grew while streaming, clobbering bytes appended or
rewritten by the same store during the read and falsely raising
session.stale on the next lock check (for example when an MCP server fails
during session restore).

Record the on-disk length before streaming starts and drop the finally
rollback so own appends accumulate on top of the read baseline while
external appends during a read still surface as external modifications.
Settle knownLength in read()'s finally as lengthAtStart plus the bytes
appended by this store during the read, guarded by cutoverEpoch and the
latest readEpoch, instead of assigning lengthAtStart before streaming.
This keeps externallyModified() true while an external update is still
being re-read, prevents slow reads from clobbering concurrent rewrites or
newer reads, and adds run-gate coverage plus the VS Code changeset.
@sailist
sailist force-pushed the bug-473-11-26-append-log-read-write-stale branch from 0798aab to 7ca6aec Compare November 27, 2026 02:34
@sailist

sailist commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

已在 7ca6aec563ee 中处理 Codex Review 的两条反馈:

  • P1(读期间提前清除 stale):改为在 read() 的 finally 中结算 knownLength = lengthAtStart + 读期间本进程自身追加字节数,并通过 cutoverEpoch / readEpoch 防止慢读取覆盖并发 rewrite() 或较新读取的结果;外部写入后的重读未完成前保持 externallyModified() === true。已补 Core 单测、SessionRunGate 集成测试与 live-reread-stale-gate E2E 场景(加固前复现失败,加固后通过)。
  • P2(VS Code changeset):已新增 .changeset/append-log-read-own-append-vscode.md("kimi-code": patch)。

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 7ca6aec563

ℹ️ 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 merged commit 42dc696 into main Nov 27, 2026
21 checks passed
@sailist
sailist deleted the bug-473-11-26-append-log-read-write-stale branch November 27, 2026 03:19
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Dec 2, 2026
`bun scripts/upstream-ledger.mjs --refresh` at upstream/main 4eb2919
added 126 rows, so every open upstream commit and every PR it references
now has a ledger row: 0/596, down from 125 at 8bf8ba3 and 126 at the
fetched tip. The refresh only reads `upstream/main ^ main`, so the three
release-2.6.2 commits named by the mission (MoonshotAI#4875/MoonshotAI#4905/MoonshotAI#4922) gained
rows with the refresh's row shape.

Settled with live probes in this tree:

- ported: MoonshotAI#5533 (docs 2.8.1 changelog), MoonshotAI#4875 (registry search_url and
  feedback_url plus the feedback service), MoonshotAI#4905 (Kimi upload status
  validation in packages/core), MoonshotAI#4922 (swarm task events in
  sessionTaskFeed), MoonshotAI#5438 (unload only declared dynamic tools), MoonshotAI#5592
  (dynamic tool replacement order), MoonshotAI#5595 (append-log known length),
  MoonshotAI#5573 (skill roots for every work dir), MoonshotAI#5576 (date reminder cwd
  comparison), MoonshotAI#5618 (session titles for skill openers), MoonshotAI#5638 (frozen
  loop tool baseline), MoonshotAI#5626 (legacy turn-input origins)
- partial: MoonshotAI#5505 (processLiveness source and consumers present; the
  upstream unit test file was never carried), MoonshotAI#5571 (program-resume and
  OSC 7577 present; the upstream test helper was never carried), MoonshotAI#5532
  (gitService half present; fsService still leaks the environment lease
  at fsService.ts:1133 and :1267), MoonshotAI#5557 (app-client icon registry kept;
  the move to app-ui was never carried)
- not-applicable: MoonshotAI#4655 (upstream reverted auto review in MoonshotAI#5649), MoonshotAI#5333
  (PLAYBOOK:111 deliberate flat experimental flags)

M39's "likely present" list was checked, not trusted: MoonshotAI#5438 is present
(upstream test passes), MoonshotAI#5487 is not (nativeStartSettleMs/leg.nativeSettled
absent), MoonshotAI#5635 is not (ToolsSettled absent), MoonshotAI#5429 needs a visual probe.
The remaining 194 pending rows stay open with their reasons; no feature
was ported and no upstream-drift allowlist entry was added.

Verification: verify -> 332 closed rows, 332 carry every file of their
PR; 317 probes pass, 2 foreign-runner skips, 0 fail; a second verify is
byte-identical (ledger sha256 cbf53638...). Probe tests 29 pass; bun run
lint and node scripts/checks/ratchet.mjs green.
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.

2 participants