Skip to content

fix: detect reused pids when checking lock holders - #5505

Merged
7Sageer merged 3 commits into
mainfrom
fix/lock-pid-reuse
Nov 26, 2026
Merged

7Sageer merged 3 commits into
mainfrom
fix/lock-pid-reuse

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

Resolve #5448

锁文件比持有它的进程活得更久时,只要系统把记录里的 pid 分配给了别的进程,这把锁就会被一直当作「仍被持有」:kimi web --remote-control 一直报 Remote Control 已在运行,自动更新的安装锁一直卡住,会话一直报被占用。重启之后 pid 从小号重新分配,最容易撞上;Windows 回收 pid 很快,同一次开机内也会出现(这正是 #5448 的场景,pid 被更晚启动的 sshd.exe 复用)。这个 PR 之后,POSIX 和 Windows 上 pid 被复用的锁都会被识别为失效并回收。

Bug Reproduction Steps

  1. 运行 kimi web --remote-control,然后强杀这个进程,~/.kimi-code/server/rc.json 会留在磁盘上。
  2. 让 rc.json 里的 pid 指向一个正在运行、但不是原持有者的进程(POSIX 上为启动时间晚于 started_at 的进程,Windows 上为同一次开机内复用该 pid 的其他进程)。
  3. 再次运行 kimi web --remote-control:一直提示 Remote Control is already running on this machine (pid …),只能手动删文件。

~/.kimi-code/updates/install.lock 的复现方式相同,表现是更新一直拿不到安装锁:持有者 pid 还活着时,30 分钟超时不生效。会话锁 ~/.kimi-code/locks/sessions/<id>.lock 和会话 presence 标记在同一次开机内 pid 被复用时,表现为一直报会话被占用或 worktree 被占用。

Root Cause

这几把锁判断持有者是否还活着,用的都是「这个 pid 现在有没有进程」,但 pid 还活着不代表还是原来那个进程:

锁 改动前的判活
Remote Control 单实例锁(rc.json) 只看 kill(pid, 0)
更新安装锁(install.lock) 只看 kill(pid, 0),30 分钟超时只在锁里没有 pid 时生效
会话锁、会话 presence 标记 kill(pid, 0),加僵尸进程检查,加「记录时间不早于本次开机」。重启后的复用能识别,同一次开机内的复用识别不了

这次是根本修复,按平台采用各自最可靠且零原生依赖的机制:

  • macOS / Linux:锁里本来就记了写入时间,真正的持有者一定在写锁之前就已经启动。通过 ps 获取该 pid 的启动时间,如果晚于锁的写入时间,这个 pid 就一定已经换了主人。
  • Windows:纯 Node.js 下无法同步低开销地读取其他进程的启动时间,且 Windows 快速启动下 os.uptime()(GetTickCount64())不归零。改成由持有者进程提供一个只在它存活期间存在的内核命名管道(\\.\pipe\kimi-code-live-<pid>-<随机 16 字节十六进制>),把管道裸名写入锁的可选字段 liveness。进程无论以何种方式退出(包括强杀或崩溃),内核都会立刻回收该管道;判活时直接检查 \\.\pipe\ 中是否仍有同名管道,不再依赖 pid 未复用,也绕开了 os.uptime()。

Code Changes

改动都在已有结构里:agent-core-v2 已经有一个给会话锁和 session presence 共用的判活函数,这个 PR 把它从 persistence/backends/node-fs/ 上移到 _base/utils/ 并补强,新增 Windows 进程级存活凭证 currentProcessLiveness(),再让 Remote Control 和 CLI 的更新锁也改用它。

判活逻辑的变化:

 processStampAlive(stamp)
   if stamp is on another host → alive
+  if pid is not a positive integer or timestamp is not finite → gone
   if kill(pid, 0) fails with anything but EPERM → gone
+  if on Windows and stamp.liveness is non-empty:
+    probe = readdirSync('\\.\pipe\') contains stamp.liveness (case-insensitive)
+    if pipe directory available → return probe
+    # pipe directory unavailable → fall through to boot-time check and alive
-  if ps says zombie → gone
-  if stamp.startedAt < boot time → gone
+  if stamp.startedAt < boot time - 5s → gone
+  on Windows → alive                                          # legacy lock without liveness
+  probe = ps -o stat= -o etime= -p pid
+  if probe unavailable → alive
+  if probe says zombie → gone
+  if process start time (now - etime) > stamp.startedAt + 5s → gone   # pid reused
   alive

Windows 进程级存活凭证:

currentProcessLiveness(): string | undefined
  on POSIX → undefined
  on Windows (lazy once per process):
    create net.Server on '\\.\pipe\kimi-code-live-<pid>-<16 random bytes hex>'
    destroy any incoming socket immediately (with socket error handler)
    server.unref()
    verify server.listening && probeWindowsPipe(name) === true synchronously
    cache and return bare pipe name; reset to undefined on error/close

调用方的变化:

 Remote Control lock (acquire / inspect)
-  pidAlive(pid)
+  write optional liveness = currentProcessLiveness()
+  processStampAlive({ pid, startedAt, liveness })
 update install lock (createLockFile / isStaleLock)
-  isProcessAlive(pid)
+  write optional liveness = currentProcessLiveness()
+  processStampAlive({ pid, startedAt, liveness })
 session lock, session presence
+  write optional liveness = currentProcessLiveness()
   processStampAlive(stamp)            # reads optional liveness, stronger check

ProcessStamp.hostname 和 ProcessStamp.liveness 均为可选字段:

  • Remote Control 和更新锁的文件里没有 hostname,不传时按本机处理。
  • 锁文件格式在四个入口均仅新增一个可选字段 liveness(仅 Windows 写入,POSIX 上不写)。旧版本都用 Partial<...> 按字段读取,会忽略 liveness;新版本读旧锁(没有 liveness)时退回 kill(pid, 0) + 开机时间比较,新旧版本可并存运行。
决策 选择 没选 理由
POSIX 上怎么识别 pid 复用 用 ps 报告的进程启动时间和锁里已有的写入时间比较 在锁里新增「进程启动时间」字段 不依赖新字段,旧版本写的锁也能直接判断
Windows 上怎么识别 pid 复用 持有者进程懒创建一个内核命名管道并把裸名写入可选 liveness 字段,判活时检查 \\.\pipe\ 调 PowerShell 查启动时间;引入原生模块;继续放任同次开机复用 wmic 在 Win11 24H2 已移除,PowerShell 冷启动耗时数百毫秒不适合同步判活;命名管道零原生依赖、同步、进程崩溃即由内核回收,实测 readdirSync('\\.\pipe\') 约 0.29ms,同时绕开快速启动下 os.uptime() 不归零的问题
currentProcessLiveness() 为什么同步校验 server.listening 而不是等 'listening' 事件 listen() 后同步检查 server.listening 与 \\.\pipe\ 可见性 等 'listening' 触发前返回 undefined Node.js 的 'listening' 事件在 nextTick 异步触发,若等该事件会导致进程里第一把锁(rc.json、install.lock 及同步会话锁)必然漏写 liveness;Windows 实测确认 uv_pipe_bind 同步创建管道,成功时 server.listening 立刻为 true 且立即可见,失败时立刻为 false
Remote Control 和 CLI 怎么复用判活函数 把 processLiveness 上移到 @moonshot-ai/agent-core-v2/_base/utils/processLiveness 并通过子路径引用 新建一个共享包;在各包里放副本;直接穿透 persistence/backends/node-fs/ 副本会被 CI 的新增重复检查(jscpd)拦下,而且副本各自演化正是这次 bug 的来源;上移到 _base/utils/ 与已有的 _base/utils/proxy 保持同层且保持零内部依赖,后续处理 minidb 锁时再按需要抽独立基础包
读不到进程信息或管道目录时 当作还活着 当作已失效 和原来的行为一致(例如 busybox 的 ps 不支持 -p);误判为失效会抢走活着的持有者的锁,后果更严重

阅读顺序:

  1. packages/agent-core-v2/src/_base/utils/processLiveness.ts:跨平台判活规则与 Windows 命名管道存活凭证的全部实现。
  2. packages/remote-control/src/lock.ts、apps/kimi-code/src/cli/update/install-lock.ts、packages/agent-core-v2/src/persistence/backends/node-fs/sessionLockService.ts、packages/agent-core-v2/src/app/sessionPresence/sessionPresenceService.ts:四处锁读写透传 liveness 并共用 processStampAlive。
  3. 测试:packages/agent-core-v2/test/_base/utils/processLiveness.test.ts 是规则与 Windows 命名管道的单测;另外四个入口各有 pid 复用的回归测试。

Behavior Changes and Affected Users

行为 改动前 改动后 谁依赖旧行为 退路
Remote Control 锁的 pid 被复用(macOS / Linux,以及 Windows 上新写的锁) 当作仍在运行,拒绝启动 回收旧锁,正常启动 无:真正的持有者一定早于写锁启动或仍持有对应命名管道 无需
Remote Control 锁写于本次开机之前,pid 恰好还活着(所有平台) 当作仍在运行 回收 同上 无需
Remote Control 锁的持有者是僵尸进程(macOS / Linux) 当作仍在运行 回收 同上 无需
更新安装锁的 pid 被复用,或锁写于本次开机之前 永久挡住更新:pid 活着时 30 分钟超时不生效 视为失效并接管 同上 无需
会话锁、presence 标记在同一次开机内 pid 被复用(macOS / Linux,以及 Windows 上新写的锁) 报会话或 worktree 被占用 回收 同上 无需
Windows 快速启动「关机」前写的锁(新写的锁) 依赖 os.uptime(),可能识别不了 凭命名管道回收 无 无需
Windows 上旧版本遗留的锁(无 liveness 字段) 走 kill(pid, 0) + 开机时间比较 不变(仅过渡期存在) 升级期间共存的旧版本进程 无需
Windows 新版本进程常驻一个命名管道 无 首次写锁时懒创建一个 unref() 的本地命名管道,进程退出时由系统回收 无 无需
会话锁、presence 的开机时间比较 记录时间必须不早于开机时间 允许 5 秒容差 开机后几秒内写入的锁,原来可能被 os.uptime() 的取整误判为失效 无需
持有者 pid 还活着时的开销(Remote Control、更新锁) 只调 kill(pid, 0) POSIX 额外同步执行一次 ps;Windows 额外同步列举一次 \\.\pipe\(实测 284 个管道平均 0.29ms) kap-server 启动 Remote Control 和登出时,每 100ms 读一次 rc.json,最多 5 秒 无
ps 失败时的 stderr ps 的报错会打到宿主进程的 stderr 不再输出 无 无需

受影响的人群:

  • Remote Control:CLI 的 kimi web --remote-control,以及 Desktop、Web 内嵌的 kap-server 的 Remote Control 开关。
  • 更新安装锁:CLI 的自动更新。
  • 会话锁和 presence:CLI、Desktop、Web、VS Code 等所有通过 agent-core-v2 打开会话的客户端。

已知边界:

  • POSIX 时钟跳变:如果在锁写入之后、判活之前,系统时钟向前跳了 5 秒以上,活着的持有者可能会被误判为 pid 被复用。
  • Windows 升级过渡期:旧版本遗留在磁盘上的锁没有 liveness 字段,升级后首次遇到旧锁仍退回 kill(pid, 0) + 开机时间比较;新版本写出的锁全部带 liveness。

测试覆盖:

  • 判活规则:packages/agent-core-v2/test/_base/utils/processLiveness.test.ts 覆盖了真实子进程(存活、已退出、启动晚于记录时间),记录早于开机,非法 pid/时间戳,僵尸进程,跨天 etime 格式,读不到进程信息,跨主机,以及 Windows 专属命名管道测试(跨进程强杀后模拟 pid 复用、不存在管道、绕过 os.uptime() 且大小写不敏感、管道目录不可读保守判活、token 稳定性)。
  • 四个入口各有 pid 复用的回归测试(POSIX 与 Windows 均运行):
    • packages/remote-control/test/remote-control.test.ts:reaps a lock whose pid now belongs to a process started after it
    • apps/kimi-code/test/cli/update/install-lock.test.ts:sweeps an aged lock whose pid now belongs to a process started after it
    • packages/agent-core-v2/test/persistence/backends/node-fs/sessionLockService.test.ts:reclaims a lock whose pid now belongs to a process started after it
    • packages/agent-core-v2/test/app/worktree/worktreeService.test.ts:counts a session whose marker pid was reused as closed
  • install-lock 有一个旧用例「does not treat an aged lock as stale while its holder process is alive」,它用当前进程的 pid 配一个「1 小时前写入」的锁来模拟长期持有。这个组合在新规则下恰好就是 pid 复用的形状,所以夹具改成:锁按当前时间写入,再让第二个申请者以 1 小时后的时间来判断。原来的断言没有改。
验证记录

在 macOS 上实际运行过的命令:

  • pnpm exec vitest run --reporter=agent packages/agent-core-v2/test/_base/utils/processLiveness.test.ts packages/agent-core-v2/test/persistence/backends/node-fs/sessionLockService.test.ts packages/agent-core-v2/test/app/worktree/worktreeService.test.ts packages/remote-control/test/remote-control.test.ts apps/kimi-code/test/cli/update/install-lock.test.ts:5 个测试文件全部通过(190 passed | 5 skipped,跳过的 5 条为 Windows 专属用例),实测验证了 macOS BSD ps -o stat= -o etime= -p <pid> 输出解析。
  • pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmit、packages/remote-control、apps/kimi-code、packages/kap-server:全部通过。
  • pnpm lint:全量通过(0 warnings, 0 errors)。
  • pnpm run check:duplication 25c5e56745:通过,无新增重复。

在 Windows 11(10.0.22621 x64,Node v24.22.1)上实际运行过的验证:

  • 独立脚本实测确认:
    • readdirSync('\\.\pipe\') 返回裸名(287 个管道,含系统服务进程管道),连续 100 次总耗时 29.03ms(平均 0.29ms,P95 0.326ms);
    • server.listen(pipe) 返回瞬间 server.listening === true 且管道立即可见于 \\.\pipe\,绑定冲突/非法时同步为 false;
    • 跨进程强杀后管道在 4.83ms 内消失;
    • 父进程建管道并 spawn 长期存活的 detached 子进程后强杀父进程,子进程存活但父进程管道立即消失(无句柄继承泄漏)。
  • pnpm exec vitest run --reporter=verbose packages/agent-core-v2/test/_base/utils/processLiveness.test.ts packages/agent-core-v2/test/persistence/backends/node-fs/sessionLockService.test.ts apps/kimi-code/test/cli/update/install-lock.test.ts:3 个文件全部通过(45 passed | 2 skipped,含全部 5 条 Windows 命名管道专项用例;2 条跳过为 POSIX 专属)。
  • pnpm exec vitest run --reporter=verbose packages/remote-control/test/remote-control.test.ts -t "Remote Control single-instance lock":6/6 通过(整文件 52 条中,仅 2 条既有 chmod 0o555 用例因 Windows/管理员权限特性失败,与本改动无关)。
  • pnpm exec vitest run --reporter=verbose packages/agent-core-v2/test/app/worktree/worktreeService.test.ts -t "sessions in the worktree":7/7 通过(含新增 presence marker pid 复用回归用例)。

在 Linux 上实际运行过的命令(此前提交验证):

  • pnpm exec vitest run --reporter=agent 跑了 packages/agent-core-v2/test/persistence、sessionLifecycleService.test.ts、worktreeService.test.ts、packages/kap-server/test/remoteControl.test.ts、apps/kimi-code/test/cli/update、apps/kimi-code/test/cli/web、apps/kimi-code/test/tui/commands/web.test.ts、packages/remote-control(2 个既有的 chmod 0o555 用例因 root 环境失败)。

未验证:

  • 全量测试套件,以及本次新增 Windows 改动后在 Linux 上重跑(Linux 路径与此前验证一致,未改动行为)。

后续(不在本 PR 范围内):ensure-daemon.lock、tower 的状态锁、minidb 的 db.lock、kap-server 的实例注册表也只看 pid 判活,后续可直接复用 processStampAlive 和 currentProcessLiveness。

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.

A lock file that outlives its holder kept Remote Control, update installs
and sessions blocked whenever another process reused the recorded pid.
The holder check now compares the pid's process start time against the
lock's timestamp, alongside the existing boot-time and zombie checks, and
Remote Control and the CLI update lock now use the same check as session
locks.
@changeset-bot

changeset-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4cc9708

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

This PR includes changesets to release 6 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
@moonshot-ai/remote-control Patch
kimi-code Patch
@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

@7Sageer
7Sageer marked this pull request as ready for review November 26, 2026 08:43
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 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-26T08:55:38.822833Z abda9ec Draft marked ready
ℹ️ 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 26, 2026 •

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

commit: 4cc9708

@7Sageer
7Sageer merged commit d98f858 into main Nov 26, 2026
22 checks passed
@7Sageer
7Sageer deleted the fix/lock-pid-reuse branch November 26, 2026 13:51
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.

Remote Control cannot start: stale rc.json + recycled PID causes false "running in another process" error

2 participants