Repository navigation
fix(core): keep append-log known length when own writes race a read - #5595
Conversation
🦋 Changeset detectedLatest commit: 7ca6aec The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
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 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 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".
| if (lengthAtStart !== undefined) { | ||
| state.knownLength = lengthAtStart; |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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.
0798aab to
7ca6aec
Compare
|
已在
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
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". |
`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.
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
SDKRpcClientV2.resumeSession/reloadSession恢复会话,使mcp.server_failed恰好在onDidRestore的task.history(或initializeLoop的reconcile)流式读取wire.jsonl期间由本进程追加落盘并完成 flush。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因此,任何本进程在
read()流式读取期间完成的自身追加(如 MCP 失败记录、后台任务通知、cron 触发),或较早开始的并发慢读取结束时,都会把已经记账的已知长度覆盖回旧值。同时,已知长度不能提前到读取开始前更新:若另一客户端已写入新记录、本会话正在重读历史,读取未完成前必须继续保持
externallyModified() === true,否则并发的SessionRunGate.tryAcquire()会在内存投影尚未纳入对方记录时提前放行。Code Changes
改动聚焦在
AppendLogStore内部记账:仍然在读取结束的finally中结算knownLength,但结算值改为“读前长度 + 读取期间本进程自身成功追加的字节数”,并用读取序号与重写序号防止慢读取覆盖并发重写或较新读取的结果。为什么这样同时守住两个方向:
drain()完成后,读完结算会把自身追加的字节计入knownLength(即使读取前knownLength为undefined);若自身追加在finally之后才恢复续体,drain()仍会在结算后的基线上累加,两种交错都不会误报。appendedBytes,读完结算不会把外部字节当成已知;而外部写入发生后、重读尚未完成的整个窗口内,knownLength保持旧值,SessionRunGate检查仍会抛出session.stale。关键决策:
finally中结算lengthAtStarttryAcquire()可能基于未更新的内存状态放行进轮appendedBytes,结算lengthAtStart + 读期间自身追加finally中直接记diskdisk会把读期间外部进程追加的未读字节当成已知,漏掉真实的多客户端冲突task.history重读与SessionRunGate检查阅读顺序:先看
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
knownLength在读取结束时被退回读前长度,后续锁检查误报session.stale,恢复或提交失败knownLength,重读进行中externallyModified()保持true、门控抛session.staletrue,完成后才解除session.stale)rewrite()时,较早的慢读取晚结束rewrite()已确认的长度回退,误报session.stalerewrite()时结算长度,慢读取不覆盖新状态受影响模块与测试覆盖:
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、读完后放行。验证命令与结果
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: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 条通过。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全部通过。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行为演进导致场景断言过期),与本改动无关。coding-win)初始化时 SSH 连接被重置(kex_exchange_identification: Connection reset by peer),未跑本地 Windows 专项;本改动仅涉及字节长度记账时机,不涉及路径、子进程、shell 或终端输入的平台差异。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.