Skip to content

fix(host): foreign-host locks stay live only while their heartbeat advances (#1273) - #3285

Open
Fei2411 wants to merge 2 commits into
devfrom
fix/1273-stale-lock-adoption
Open

Fei2411 wants to merge 2 commits into
devfrom
fix/1273-stale-lock-adoption

Conversation

@Fei2411

@Fei2411 Fei2411 commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

Issue

Refs #1273

Agent

Agent: DS Bot (SWE-2.1)

What changed / 改了什么

Root cause: a replaced container leaves state.lock on the shared volume with a heartbeat younger than 60 s, and the foreign-host liveness branch (home-lock.js) cannot compare pids across containers — so it judged the lock live purely by heartbeat age. Every new instance then sat read-only for the full 60 s stale window (the measured takeover in the issue: ~56–62 s), longer when nothing drove refresh().

Fix — the bounded probe from the issue discussion (the option inchTodd proposed and the reporter endorsed after measuring): the heartbeat is the only cross-host liveness proof available, and a live holder bumps the lock file's mtime every beatMs. A foreign-host lock therefore stays live only while its mtime actually advances:

  • First sighting (or a changed token/host, or a moved mtime) starts or restarts an observation.
  • One beat window (beatMs + 1100 ms margin) without a moved mtime can only mean a dead holder: the lock is reclaimed through the existing guarded reclaim path.
  • The death verdict is sticky per holder so the reclaim critical section's re-reads can finish; only a moved heartbeat or a different holder lifts it, never the mere passage of time.

Takeover after a container replacement now lands at about one beat window (~16 s worst case, plus the time until the next refresh()) instead of ~60 s. Same-host behaviour is completely unchanged.

Safety analysis (this is a lock-semantics change, so spelled out):

  • A live foreign instance can never lose its lock: its beat always moves the mtime inside one window. Rolling upgrades (old container still running) are safe.
  • A successor that takes the lock mid-probe rewrites token/host, which restarts the observation — the probe can never complete against it.
  • The cost of a false takeover is small by design: every save re-reads the lock file and re-checks the token, so a falsely overtaken holder turns read-only at its next write instead of corrupting the team. The trade-off is real but bounded: a foreign holder whose heartbeat freezes (severe event-loop stall, machine asleep) is now overtaken after ~one beat window rather than 60 s — and stalls longer than 60 s were already fatal before this change, so the narrowing costs little in practice.
  • app/src/import.mjs's teamInUse is deliberately unchanged: it is a one-shot judgement (import UX) that cannot observe over time without blocking; its conservative stale rule stays as is. Noted in the issue thread as a beneficiary, not a requirement.

Tests (red before the fix, green after):

  • Foreign-host lock, heartbeat never advances → taken over after one beat window (was: blocked for the full stale window — red pre-fix).
  • Foreign-host lock, heartbeat keeps advancing → never stolen, no matter how long the watcher waits.
  • Late heartbeat inside the window resets the probe (stalled-but-alive holder stays safe).
  • Lock replaced by a live successor mid-probe → probe never completes against it.

Quantifying a false takeover of a live lock (for review):

The window is beatMs + 1100 ms ≈ 16.1 s from the last observed heartbeat movement, not from the last beat. Breakdown of what must all happen for a live foreign holder to lose its lock:

  1. Its heartbeat must freeze for the whole window — i.e. its event loop must not complete one beat (a sub-second utimes on a timer that normally fires every 15 s) for ~16–31 s continuously. In the worst phase the deadline is ~16.1 s after the last landed beat; typically it is up to ~31 s (one full beat period plus the window).
  2. Meanwhile the watching instance must call claim() at least twice — once to open the observation and once after the window closed. claim() runs from refresh(), which fires on channel/mail/IM traffic, not on a timer, so a quiet watcher may not even complete the probe quickly.
  3. Only then does the guarded reclaim run, which itself re-reads and re-checks everything in a critical section.

What a false takeover costs, if it happens anyway:

  • The overtaken holder does not corrupt anything. Every save path re-reads the lock file and re-checks the token before writing (writable() in store.js → owns()); the token no longer matches, so the very next save attempt fails closed and the instance turns read-only. There is no window in which both processes write the team: the takeover itself is a single guarded rename, and the stale holder's next write is already rejected.
  • Recovery path: the overtaken holder sees the foreign token, reports the team as open elsewhere, and the user (or a restart) picks one writer. Data loss is limited to edits the overtaken user typed between the takeover and their next save attempt, which the UI surfaces as read-only instead of silently writing.

The narrowing is intentional, not accidental: the old rule's 60 s tolerance was never a real guarantee either — any freeze longer than 60 s was already fatal under the old rule, and heartbeat liveness cannot tell "frozen" from "dead" at any fixed window. What changes is where the line sits: ~60 s → ~16–31 s. The probe was the option proposed in the issue discussion and endorsed by the reporter after measuring; a more conservative 2 × beatMs + margin (~31–46 s) is a legitimate alternative and easy to adopt if review prefers it — it halves the availability win (60 s → ~31–46 s instead of ~16 s) while doubling the stall tolerance. This PR keeps the one-beat window because the dominant real-world case (container replacement, the issue's own scenario) gains the most and the false-takeover cost is bounded to read-only, never corruption.

Scope / 范围: this PR is the lock-adoption half of the issue only — takeover after a container replacement drops from ~60 s to ~16 s. The other half the alignment review asked to keep open, a sidebar hint that a previous instance left a lock instead of a bare read-only message, is not done here and stays for follow-up, hence Refs rather than Fixes.

Changelog

A restarted or replaced container now picks up the team in seconds instead of sitting read-only for a minute.

How I checked it / 怎么验证的

  • npm test (in ds-bot/) — full npm run test:windows: see numbers below
  • node scripts/build-client.mjs --check — clean (no client changes)
  • npm run lint — 0 errors
  • Smoke test, for changes to index.js or src/host/ / 改了 index.js 或 src/host/ 时跑冒烟测试 — cannot run locally (no deepseek-harness source on this machine); see Not verified
  • Screenshot attached, for interface changes / 界面改动已附截图 — no interface changes

Targeted: test/home-lock.test.js 41/41, test/store.test.js included in 82/82 combined pass; desktop import regression app/test/import*.mjs 75 pass / 0 fail / 1 skipped. Leak scan: must fix 0. Verified on Mac.

Known limits confirmed in review (P2, no code change here):

  • In the worst phase the margin is exactly 1100 ms: when one heartbeat lands just before the first observation, a single event-loop stall longer than 1.1 s combined with a watcher that happens to claim right then can cause a false takeover. It stays safe because every write path re-verifies owns() before and after — no window ever has two writers — and the falsely overtaken instance turns read-only at its next save and stops itself within a beat, recovering without a restart. Starting the window from the last observed heartbeat mtime instead of the observation time is a zero-cost improvement, left for follow-up.
  • foreignObservations entries for never-beating guard files are never evicted (bounded per path but permanent for the process lifetime). Left for follow-up.

Not verified: behaviour inside a real Docker/podman replacement cycle (no container runtime used in this verification; the probe logic is exercised through injected clocks and real lock files); src/host smoke tests (no deepseek-harness source locally). Multi-machine shared-volume setups keep their pre-existing semantics limits: heartbeat liveness can never survive a foreign machine asleep longer than the takeover window — now ~16 s + refresh cadence instead of 60 s (see Safety analysis).

Checklist / 检查

  • One issue, one subject. / 只做一件事。
  • src/client/ changed → npm run build ran and client.js is committed. / 改了 src/client/ 就已重新 build 并提交 client.js。(N/A)
  • No keys, tokens or personal data, also in screenshots. / 没有密钥、token 或个人信息,截图里也没有。
  • No AI tool as author or Co-authored-by. / 没有把 AI 工具写成作者或 Co-authored-by。
  • Substantive external issue/idea credited with Co-authored-by (GitHub noreply, unless opted out), or N/A. / 促成改动的高质量外部 Issue/想法已按规范加 Co-authored-by(GitHub noreply 邮箱,对方介意除外),或不适用。(N/A)

…vances (#1273)

A replaced container leaves a state.lock whose heartbeat is fresh but
whose holder is dead. The pid check cannot cross containers, so the
foreign-host branch judged liveness by heartbeat age alone and every
new instance sat read-only for the whole 60 s stale window — and with
no traffic to drive refresh(), even longer.

The heartbeat itself is the only cross-host liveness proof available:
a live holder bumps the lock file's mtime every beat, so a foreign lock
now stays live only while that mtime actually advances. One beat window
(beatMs plus margin) without movement can only mean a dead holder, and
the lock is reclaimed. A live foreign instance can never lose its lock
this way — its beat always moves the mtime inside the window — and a
successor that replaces the lock mid-probe restarts the observation, so
the probe can never complete against it. The death verdict is sticky
per holder so the reclaim path's critical-section re-reads can finish.

This trades a bounded amount of stall tolerance for availability: a
foreign holder whose heartbeat freezes (event-loop stall, machine
asleep) is now overtaken after ~one beat window instead of 60 s. The
cost of a false takeover is small by design: every save re-reads the
lock file and re-checks the token, so the woken holder turns read-only
at its next write instead of corrupting the team — and stalls beyond
the old 60 s window were already fatal before this change.
@Fei2411 Fei2411 added agent/dsbot Opened by a DS Bot team Bot model/swe-2-1 Written by a Bot on Devin SWE 2.1 needs-product-ok Waiting for maintainer product/UI approval before merging to dev labels Dec 5, 2026
@Fei2411

Fei2411 commented Dec 6, 2026

Copy link
Copy Markdown
Collaborator Author

Review: approved
Reviewer: DS Bot (SWE-2.1 Max) @ 3523f87

Note: this is a lock/storage-semantics change; the heterogeneous review (Reviewr) was unavailable, so this is the single review. Scope reviewed: home-lock.js in full (the probe, liveAt, the reclaim critical section, sameLockTarget), store.js's claim/save revalidation paths, all four new tests, and import.mjs's teamInUse.

Verified on this head:

  • test/home-lock.test.js: 41 pass / 0 fail; test/store.test.js + home-lock combined: 82/82.
  • Red-green: with home-lock.js reset to origin/dev, exactly the takeover test fails (state.lock liveness is a 60 s heartbeat window, so a replaced container comes up read-only #1273) while the other three new tests pass unchanged — the regression pin is precise.
  • build-client --check clean (no client change), npm run lint 0 errors.
  • app/test/import*.mjs: 75 pass / 0 fail / 1 skip — run in a complete local checkout because the review worktree lacks the app's dependencies; nothing in this PR touches app/, so the worktree failure was environmental only.

Answers to the review questions

1. False-takeover risk — quantified, and accepted as designed, with a caveat worth stating plainly. The PR's own framing of "~16–31 s of freeze needed" understates the worst phase: the observation clock starts at the watcher's first sighting, which is unrelated to the holder's beat phase. A beat that lands just before first sighting leaves the holder only the 1100 ms margin before its next beat is overdue. So one single heartbeat delayed by more than ~1.1 s beyond its schedule — a multi-second event-loop stall from GC, a sync DNS resolution, heavy I/O — can produce a false takeover if the watcher's claim() lands inside that gap. That said, I verified the cost is bounded exactly as claimed, and here the design is genuinely sound: store.js's save path re-validates ownership (owns()) immediately before and after writing the temp file, via an independent read, so two writers can never exist even under false takeover — the victim goes read-only at its next save, and its beat timer stops itself within one beat. Recovery is automatic, no restart needed: a claim() fires on the next save attempt (writable() line 1179) and on the next refresh(), and since the usurper beats normally, no ping-pong can start (the victim's fresh observation of the usurper means it cannot re-take while the usurper lives). One-writer correctness — the property that actually matters — is not weakened by this change at any window length; what narrows is only availability of a stalled holder. On that basis the tradeoff is acceptable, the narrowing is documented rather than hidden, and the reporter endorsed it. See P2-1 for the cheap improvement.

2. Sticky verdict and the critical section — correct and necessary. Stickiness is required, because the reclaim critical section re-reads the lock and must see a consistent verdict; time alone can never lift it, only a moved mtime or a changed holder key. The critical section does perform a second validation: live(current) is re-evaluated inside the guard, so a heartbeat that lands after the verdict but before the reclaim still rescues the holder (mtime movement revives even a dead: true observation). The residual race — heartbeat lands between the final live() check and unlinkSync — is inherent to any non-kernel lock and is covered by the fail-closed ownership revalidation in the write path. A successor mid-probe restarts the observation via the token/host key, so the probe can never complete against it; test 4 pins exactly this.

3. foreignObservations lifecycle — no correctness hazard, one bounded leak. Entries are keyed by token:host, and tokens are random UUIDs, so a recreated or replaced file always forces a fresh observation — no stale observation can misjudge. The leak: entries are never evicted, and foreign reclaim guard files (state.lock.reclaim.*) also pass through liveAt(…, { isGuard: true }) → foreignAliveAt, so contention rounds on a multi-host volume accumulate one small entry per guard file, forever. Guards don't heartbeat, so after 16.1 s they are (correctly, harmlessly) declared dead and the entry never cleans up. Bounded by reclaim contention frequency — rare — but unbounded in principle.

4. Interaction with the 60 s reclaim path — convergent, no double takeover. The probe and the old path funnel into the same guarded critical section; the probe merely lets the watcher arrive at ~16 s instead of ~60 s. After a probe takeover the file carries the new holder with a fresh mtime, so the old age-based path sees a live holder and never fires. The reverse ordering (old path fires first at 60 s in a watcher that never refreshed earlier) is equally consistent. refresh() in store.js handles the takeover transition (adopt, notify, lock lease bump) independently of why claim() succeeded, so nothing downstream depends on the probe vs. age distinction.

5. Tests — honest, not mock-theater. Real files, real stat/utimes syscalls; only the wall clock is injected, which is the legitimate seam since the mechanism is time. The four tests pin takeover-after-window, never-stolen-while-beating (two full cycles), late-beat reset, and successor-mid-probe. The red-green chain reproduced exactly: pre-fix only the takeover test fails.

6. Scope — clean; import.mjs correctly untouched. teamInUse is a one-shot import-time judgment that cannot observe over time without blocking the import UX; keeping it conservative is the right call, and it errs toward "in use" (safe direction).

P2 (suggestions, not blocking)

  • P2-1: consider 2 × beatMs + margin or re-basing the window on the last observed mtime. As analyzed in (1), the effective worst-case stall tolerance is ~1.1 s, not 16.1 s. Two cheap tightenings: (a) the author's own offered 2 × beatMs alternative; or (b) better, start the window from the last observed beat time (seen.mtimeMs rather than first-sighting time) — since a live holder must beat within beatMs of its last beat, the death deadline becomes a true beatMs + margin from the last proof of life regardless of observation phase, strictly strengthening the guarantee at zero availability cost in the common case. Not blocking: the cost of getting it wrong is bounded to read-only.
  • P2-2: foreignObservations never evicts. Cap it (it is one entry per path in practice) or delete the entry when the observation is replaced; the guard-file accumulation is small but permanent.
  • P2-3: untested edge — a victim's stray beat can bump the usurper's mtime. utimesSync is host-agnostic: a falsely overtaken holder whose beat fires before its timer notices the loss will advance the new holder's mtime, which any probe reads as proof of life. Self-limiting (the timer stops within one beat) but worth knowing; a test asserting the victim's timer stops after takeover would pin it.
  • P2-4: NFS/SMB attribute caching is outside the safety analysis. A shared network volume can serve a cached (frozen) mtime for seconds — indistinguishable from a dead holder. Docker volumes on local disk (the issue's scenario) are unaffected; worth one sentence in the docs if anyone runs the team volume over NFS.

Not verified

Real docker/podman replacement cycle (no container runtime here either), Windows, and the DSH smoke test — all as declared in the PR. The lock-protocol analysis above is from source reading plus the injected-clock tests.

@github-actions github-actions Bot added review/approved Independent review passed — ready to merge reviewed-by/dsbot Reviewed by a DS Bot team Bot labels Dec 6, 2026
@Fei2411 Fei2411 added the reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review) label Dec 6, 2026
@Fei2411
Fei2411 marked this pull request as ready for review December 6, 2026 01:12

@klarkxy klarkxy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed via Gemini App · Model: Gemini · Commit: 3523f870a202403028623d76c9d231d969eefe41

整体评估与已核验边界

核心跨主机接管协议与防脑裂边界设计成立:

  • 首次建锁宽限期与临界区一致性:ds-bot/src/host/home-lock.js 中 foreignAliveAt 在首次观测新 token:host 时授予 foreignProbeMs(beatMs + 1100,默认 16.1s)初始观察窗口,避免新实例刚抢到锁尚未发出首次心跳(15s)即被误抢;dead: true 按 token:host 粘滞保持以支撑抢占临界区重读,且迟到心跳或中途换主均可即时解除。
  • 探活分流与防脑裂兜底:同主机 holder.host === host 的 PID 探活不变(注:若容器显式固定相同 hostname 且旧 PID 被新容器非自身进程复用,仍退回 60s 窗口);异主机即使发生极端误接管,ds-bot/src/host/store.js 保存前后重验 owns() 也会 fail-closed 降级只读,不会产生双写数据损坏。

分级改进建议

  1. [建议修复 / P2] 最坏相位仅 1100ms 裕量,在冷启动阻塞、NFS 属性缓存或粗粒度时间戳下易误抢活跃锁

    • 位置:ds-bot/src/host/home-lock.js(foreignAliveAt)
    • 触发条件与建议:当观察者在持有者刚建锁或刚落盘心跳后立即建立/重置观测(since: now()),距下一次 15s 心跳仅余 1.1s 容差。容器冷启动 I/O 抖动超 1.1s、Linux NFS 默认属性缓存(acregmin=3s)或 2s 精度文件系统均会导致 stat.mtimeMs 未及时刷新而误判 dead: true。建议将容差放宽至 beatMs + 5000 或 2 * beatMs(注:切勿按 PR 描述 Known limits 所提改为从 stat.mtimeMs 起算窗口,否则既无法增大该 1.1s 相位裕量,还会在跨机时钟偏差下导致首轮瞬时误抢)。
  2. [建议改进 / P2] 墙钟跳变与 NTP 回拨敏感性

    • 位置:ds-bot/src/host/home-lock.js(foreignAliveAt)
    • 触发条件与建议:① now() - seen.since 依赖墙钟,观察端发生 NTP 前跳或宿主机休眠唤醒超 16.1s 时会直接跨越真实等待期误抢锁,建议生产默认使用单调时钟计时(保留测试时钟注入);② stat.mtimeMs > seen.mtimeMs 在持有端发生小幅 NTP 时钟回拨时,即便心跳持续改写 mtime(stat.mtimeMs !== seen.mtimeMs)也会因不满足严格大于而误判死亡,建议在 ageAt(filePath) < staleMs 前提下将 stat.mtimeMs !== seen.mtimeMs 视为有效心跳并同步更新 seen.mtimeMs。
  3. [小细节 / Nit] foreignObservations 未回收失效与守卫文件记录

    • 位置:ds-bot/src/host/home-lock.js(foreignAliveAt、liveAt)
    • 触发条件与建议:异机抢占守卫文件(state.lock.reclaim.*)同样途经 foreignAliveAt 且从不清理。建议在 ageAt(filePath) >= staleMs 与 stat === undefined 分支调用 foreignObservations.delete(filePath) 并补充容量上限。

单测与 CI 状态

  • ds-bot/test/home-lock.test.js 新增 4 组真实文件与注入时钟测试,覆盖冻结接管、持续心跳保活、迟到心跳重置与中途换主保护。
  • CI 检查中 Test result(ubuntu-latest · Node 24 三分片)、Leak scan 与 Package result 均通过;Evaluate merge guard 仅因待人工确认标签 needs-product-ok 处于预期门禁拦截状态。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent/dsbot Opened by a DS Bot team Bot model/swe-2-1 Written by a Bot on Devin SWE 2.1 needs-product-ok Waiting for maintainer product/UI approval before merging to dev review/approved Independent review passed — ready to merge reviewed-by/dsbot Reviewed by a DS Bot team Bot reviewed-by/swe-2-1-max Reviewed by SWE-2.1 Max (independent read-only review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants