Skip to content

fix(#908): stale-lock steal is compare-and-swap, not unlink-then-create - #913

Merged
admarble merged 3 commits into
mainfrom
feature/908-fix-locks-stale-lock-steal-is-unlink-then-create-n
Aug 8, 2026
Merged

admarble merged 3 commits into
mainfrom
feature/908-fix-locks-stale-lock-steal-is-unlink-then-create-n

Conversation

@admarble

@admarble admarble commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Stealing a stale lock was unlink-then-create in both LockManager and CheckoutLock — two syscalls with a window in which two sessions that both classified the same lock stale could each destroy the other's freshly created lock and both believe they hold it (the exact two-holder failure the lock exists to prevent, and silent). This routes the steal through one shared stealStaleLock helper (alongside the already-shared classifyStaleness) that:

  1. Takes possession atomically with rename(lockPath → tmp) — of two racing stealers, exactly one moves the current inode; the loser gets ENOENT.
  2. Verifies identity: discards only the stale inode it classified.
  3. If a fresh lock appeared in the window, links it back into place untouched rather than destroying it, and reports the steal lost.

Win or lose, acquire falls through to the terminal openSync(…, "wx"), whose O_CREAT|O_EXCL arbitrates the real holder.

⚠️ Deviation from the spec's fix sketch (please read)

The /spec plan (AC-1) prescribed a plain rename-away: rename → unlink tmp → ENOENT = lost, then fall through. That is behaviorally identical to the unlink it replaces — a bare rename(lockPath, …) moves whatever inode is at the path, fresh or not, exactly like unlink. I verified this with a deterministic hand-driven interleave of both strategies: in the issue's own documented ordering (A.steal → A.create → B.steal → B.create), plain rename-away yields two holders, same as today. It also makes AC-4's mutation test impossible (CAS ≡ unlink ⇒ nothing to mutate).

The identity check in step 2/3 is what actually makes AC-1's requirement ("loser cannot remove the winner's fresh lock") hold and makes AC-4 mutation-verifiable. Full analysis in issue comment.

⚠️ Known residual (flagged for follow-up)

Plain lock files admit no atomic compare-and-swap on content, so one sub-millisecond window remains: a third session's O_CREAT|O_EXCL create racing our link-back restore. It is far narrower than the original (which failed on a single race, every time a stealer's removal landed on a fresh lock) and never destroys a live lock (worst case: a harmless *.steal.* orphan, which list() ignores). Fully closing it is a larger protocol change (claim file / lease) — recommend a follow-up issue rather than expanding this PR.

Pre-PR AC Verification

AC Source Description Status Evidence
AC-1 Original Steal is a CAS, not unlink-then-create; no steal path unlinks the live lockPath directly; loser cannot remove the winner's fresh lock ✅ Implemented (design adjusted — see Deviation) lock-manager.ts stealStaleLock (rename+verify+link-restore); both acquire branches wired
AC-2 Original Both lock classes fixed via one shared helper ✅ Implemented CheckoutLock imports stealStaleLock from lock-manager.ts; interleave test passes against both
AC-3 Original Existing behavior preserved (single-acquirer stale recovery, fresh holder blocks, orchestrator no-op, unparseable clearable) ✅ Implemented 87 pre-existing + new unit tests green in both lock suites
AC-4 Original New test mutation-verified ✅ Implemented See Mutation result below

Mutation result (AC-4 / repo gate-test rule)

Mutating stealStaleLock's identity check to always-match (⇒ blind unlink-then-create):

  • Exactly 2 tests fail — checkout-lock.test.ts and lock-manager.test.ts → "a loser cannot remove the winner's fresh lock (documented ordering)".
  • 87 others pass, including the ENOENT/winning-stealer tests and every pre-existing lock test.

Restored; suite green again.

Test plan

  • npm run build — passes
  • npm run lint — passes (0 warnings)
  • Lock unit suites (checkout-lock.test.ts, lock-manager.test.ts) — 89 passed
  • AC-4 mutation verified (exactly the 2 documented-ordering tests fail under mutation)
  • ⚠️ checkout-lock.integration.test.ts — 7 pre-existing failures (SyntaxError: Unexpected end of JSON input, ExperimentalWarning-polluted subprocess stdout). Confirmed identical at the base commit 5a689301 in the same worktree → not introduced by this PR (the steal branch doesn't run in those fresh-lock race tests). CI is the backstop.

Closes #908

🤖 Generated with Claude Code


QA gap fixes (5cf65c2f)

Fresh-session QA (review) verdicted AC_MET_BUT_NOT_A_PLUS with three non-blocking gaps; all three are now filled in this PR:

  1. Acquire-level wiring tests (both classes). The helper tests proved stealStaleLock; nothing proved acquire() uses it. New tests inject the isPidAlive probe to swap in a fresh lock inside the classification→steal window — a blind-unlink call site destroys it and wrongly wins; the CAS refuses.
  2. stealStaleLock never throws. Rename errors degrade to a lost steal (the terminal O_EXCL create surfaces real environment errors with the pre-fix(locks): stale-lock steal is unlink-then-create, not compare-and-swap — two stealers can both win #908 errno); a hard-link capability failure (EPERM/ENOTSUP) now falls back to rename-restore, because leaving the fresh lock renamed-away IS the two-holder bug. Test seam (ops.link) added — capability errors can't be provoked on a normal tmpdir.
  3. Orphan sweep. Aged *.steal.* files (>10 min; the in-flight window is microseconds) are reaped best-effort on steal entry, scoped to the lock's own prefix — recent and foreign-lock orphans untouched.

Mutation results for the gap-fix tests (repo gate-test rule)

Mutation Expected kill Result
M1: LockManager.acquire stale branch → unlinkSafe(lockPath) lock-manager wiring test ✅ exactly 1 failed, 92 passed
M2: CheckoutLock.acquire stale branch → unlinkSafe(lockPath) checkout-lock wiring test ✅ exactly 1 failed, 92 passed
M3: delete sweepStealOrphans call orphan-sweep test ✅ exactly 1 failed, 92 passed
M4: delete rename-restore fallback link-refused test ✅ exactly 1 failed, 92 passed
M5: identity check → always-match (original AC-4 mutation, re-run) documented-ordering tests + new tests ✅ 5 failed (was 2): both interleave tests, both wiring tests, link-fallback test — identity-check coverage strictly deeper

93/93 lock unit tests green post-restore; worktree clean; typecheck clean.

Both LockManager and CheckoutLock recovered a stale lock via unlink(lockPath)
then openSync(wx) — two syscalls with a window in which two sessions that
both classified the same lock stale could each destroy the other's fresh lock
and both win (two holders).

Route the steal through one shared stealStaleLock helper (alongside the
already-shared classifyStaleness). It takes possession atomically with
rename(lockPath -> tmp) and verifies identity: it discards only the stale
inode it classified, and links a fresh lock that appeared in the window back
into place rather than destroying it. Win or lose, acquire falls through to
the terminal O_CREAT|O_EXCL create, which arbitrates the real holder.

Deviation from the spec's fix sketch: a plain rename-away is behaviorally
identical to the unlink it replaces (rename moves whatever is at the path,
fresh or not) — verified by hand-driven interleave. The identity check is
what makes AC-1 hold and AC-4 mutation-verifiable. A narrow residual (a third
session's create racing the restore) is documented for follow-up; it never
destroys a live lock.

Tests: white-box interleave tests in both lock suites driving the documented
A.steal -> A.create -> B.steal -> B.create ordering.

Entire-Checkpoint: 38d0311676e9
…n sweep

QA on PR #913 surfaced three non-blocking gaps; this fills all three:

1. Wiring tests (both classes): the helper tests proved stealStaleLock,
   but reverting either acquire() stale branch to a blind unlinkSafe
   failed no test. New per-class tests inject the isPidAlive probe to
   claim the path inside the classification->steal window; only a real
   CAS at the call site refuses to destroy that claim.

2. stealStaleLock never throws: rename errors degrade to a lost steal
   (the terminal O_EXCL create surfaces real environment problems with
   the same errno the pre-#908 path did), and a link-capability failure
   (EPERM/ENOTSUP) falls back to rename-restore — leaving the fresh lock
   renamed-away IS the two-holder bug, so restoring outweighs link's
   no-overwrite guarantee on such filesystems. Test seam (ops.link) added
   since capability errors cannot be provoked on a normal tmpdir.

3. Aged *.steal.* orphans (>10 min; the in-flight window is microseconds)
   are swept best-effort on steal entry, scoped to the lock's own prefix.

Mutation results recorded in the PR body.
@admarble
admarble merged commit a9e64ea into main Aug 8, 2026
5 checks passed
@admarble
admarble deleted the feature/908-fix-locks-stale-lock-steal-is-unlink-then-create-n branch August 8, 2026 03:47
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.

fix(locks): stale-lock steal is unlink-then-create, not compare-and-swap — two stealers can both win

1 participant