Skip to content

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

Closed

Description

@admarble

Found during adversarial validation of #906 (Design v2, "Adjacent defects"), and deliberately kept out of that PR. Verified against main at e2e57a7c.

Bug

Stealing a stale lock is unlink-then-create, not compare-and-swap, in both lock classes:

  • src/lib/locks/checkout-lock.ts — acquire() calls unlinkSafe(lockPath) when staleness() reports stale, then falls through to writeAtomic.
  • src/lib/locks/lock-manager.ts — same shape.

The create half is genuinely atomic (openSync(lockPath, "wx"), i.e. O_CREAT|O_EXCL). The steal is not, because the unlink and the create are separate syscalls with a window between them.

Interleaving

A: reads lock L0, classifies stale
B: reads lock L0, classifies stale          # both agree — L0 really is stale
A: unlink(L0)
A: open("wx") -> succeeds, writes L_A        # A now holds a FRESH lock
B: unlink(L_A)                               # B removes A's fresh lock, not L0
B: open("wx") -> succeeds, writes L_B
Result: both A and B believe they hold the lock; only L_B exists on disk.

B's unlink targets a path, not the inode it classified, so it destroys whatever is there — including a lock created microseconds earlier by a winner that already moved on.

Severity

Low-moderate. Requires two sessions to classify the same lock stale within one syscall window, so it needs a genuinely abandoned lock plus near-simultaneous acquires. But the consequence is the exact failure the locks exist to prevent — two holders — and it is silent.

Fix sketch

Make the steal a compare-and-swap: rename() the stale lock to a unique temp name and treat "my rename won" as the right to create. Only the process whose rename succeeded proceeds to openSync("wx"); the loser re-reads and either accepts the new holder or retries. rename is atomic on POSIX and the loser's rename fails with ENOENT, which distinguishes it cleanly.

Alternatively, drop the unlink entirely and have the stale path use openSync(tmp, "wx") + rename(tmp, lockPath) — last-writer-wins, but never leaves the window where two processes both think they created the file.

Test plan

The existing multi-process race test cannot pin this — CLI startup serializes the processes long before the syscall window (documented in checkout-lock.test.ts's atomic-create block, which reaches for writeAtomic directly for the same reason). Drive the window directly: two CheckoutLock instances, both past the staleness read, interleaved by hand.

Activity

  1. added
    bug
    on Aug 7, 2026
  2. admarble commented on Aug 7, 2026

    @admarble
    ContributorAuthor

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

    → PROCEED — Non-atomic steal confirmed on main at 5a68930 — checkout-lock.ts:272 unlinks, :284 falls through to writeAtomic

    Commands:
    sequant run 908 -Q

    spec → exec → qa

    Flags:
    -Q compare-and-swap rewrite across two lock classes plus a hand-interleaved concurrency test

    Considered:
    --testgen bug-only label; testgen skips bug/fix issues even though the body carries a Test plan
    --security-review no security/auth label — concurrency correctness, not authz
    ────────────────────────────────────────────────────────────────
    ⚠ Body has zero - [ ] checkboxes — spec must derive ACs from the Fix sketch / Test plan; --strict-preflight would hard-stop this issue
    ⚠ The existing multi-process race test cannot pin this — CLI startup serializes the procs. The new test must drive the syscall window by hand (two CheckoutLock instances past the staleness read) and be mutation-verified
    ⚠ Order: land 908 before 909 — both edit src/lib/locks/lock-manager.ts; 908 rewrites the acquire steal path, 909's smaller resolveLocksDir change rebases onto it cheaply
    ────────────────────────────────────────────────────────────────

  3. admarble commented on Aug 7, 2026

    @admarble
    ContributorAuthor

    /spec Plan — CAS steal for stale locks

    Complexity: Standard (4 derived ACs, 1 directory · src/lib/locks/)

    The issue is a bug report; ACs below are derived from its Fix sketch and Test plan.

    Acceptance Criteria

    • AC-1 — Steal is a compare-and-swap, not unlink-then-create. The destructive unlinkSafe(lockPath) in the stale-recovery branch (checkout-lock.ts:270-272, lock-manager.ts:273-274) is replaced by an atomic rename-away: rename the stale lockPath to a unique sibling temp; only the process whose rename wins (loser gets ENOENT) proceeds. No steal path ever unlinks the live lockPath directly. Verify: Unit test driving the syscall window by hand → exactly one holder; loser cannot remove the winner's fresh lock.
    • AC-2 — Both lock classes fixed via one shared helper. CheckoutLock and LockManager route the steal through a shared exported helper (mirroring how classifyStaleness is already shared), so the two cannot drift. Verify: interleave test passes against both classes.
    • AC-3 — Existing behavior preserved. Single acquirer still recovers a stale lock; fresh holder still blocks (stale: false); orchestrator no-op; unparseable lock still clearable. Verify: existing lock suites green, no assertion changes.
    • AC-4 — New test is mutation-verified. Reverting the fix (CAS → unlink-then-create) makes exactly the new interleave test fail. Verify: record the mutation result in the PR body (repo gate-test rule).

    Design (recommended)

    • Rename-away CAS (issue Fix sketch feat: Complete remaining v1.0 features (AC-10, AC-13, AC-14) #1). Reject sketch docs: Add pre-release checklist #2 (tmp + rename-replace, "last-writer-wins"): a plain replace lets both stealers' renames succeed, so both believe they hold the lock — that is the two-holder bug again. Only a CAS on the stale inode yields a single winner; the terminal openSync(lockPath, "wx") in writeAtomic then arbitrates the actual holder, so exactly one process ends up holding regardless of who won the rename. The loser falls through to writeAtomic, whose existing EEXIST → read holder branch already handles "accept the new holder" — no new retry loop.
    • Add stealStaleLock(lockPath, { pid, now }) next to classifyStaleness in lock-manager.ts; import it into checkout-lock.ts. Add renameSync to the fs imports in both files.

    Implementation

    1. Add + export the shared CAS steal helper (renameSync(lockPath, tmp); on success unlink the temp; on ENOENT report "lost"; re-throw other errno).
    2. Wire both acquire steal branches to it, then fall through to writeAtomic.
    3. Add white-box interleave tests to checkout-lock.test.ts (extend the atomic-create block) and lock-manager.test.ts, driving A:steal → B:steal(lost) → A:create → B:create. Mutation-verify (AC-4).

    Notes / open questions

    • Cross-platform: keep the temp a sibling in the same locksDir (same filesystem ⇒ atomic rename). Fresh unique temp name ⇒ no Windows replace-semantics divergence.
    • Orphan temp files: the winner unlinks its own temp; a crash mid-steal leaves one harmless *.steal.* orphan (not *.lock, skipped by list()). Sweeping it in clear is likely out of scope — flag for the reviewer.
    • Q: share vs mirror the helper — recommend share (avoids the standing two-lock-class drift risk).

    Recommended workflow: exec → qa (quality loop disabled). No UI, no new public API surface.

    The multi-process race test cannot pin this (CLI startup serializes the processes; documented in checkout-lock.integration.test.ts:525 and the atomic-create block at checkout-lock.test.ts:183) — the new test drives the window in-process with two instances.

  4. added
    planned
    on Aug 7, 2026
  5. admarble commented on Aug 7, 2026

    @admarble
    ContributorAuthor

    /exec halted — the agreed design (plain rename-away CAS) does not fix the bug

    Verified empirically with a deterministic, hand-driven simulation of both lock classes' steal path (two "processes" interleaved by hand, same as the white-box atomic-create tests). Wiring simulated exactly as the /spec plan prescribes: if (staleReason) { stealStaleLock(lockPath, {pid, now}); } return writeAtomic(...), with stealStaleLock = renameSync(lockPath, tmp) → unlink tmp → ENOENT = "lost".

    Interleaving current unlink plain rename-away (spec AC-1 design)
    A.steal → A.create → B.steal → B.create (the issue's own documented ordering) 2 holders 2 holders — B's rename succeeds on A's fresh lock and destroys it (Bsteal=won)
    A.steal → B.steal → A.create → B.create 1 holder 1 holder

    Root cause: rename(lockPath, tmp) removes whatever inode is at that path — including a fresh lock a winner just created — exactly like unlink(lockPath). The "loser gets ENOENT" distinction only fires in the ordering where the old code was already safe (the terminal openSync(…, "wx") arbitrates). It gives the fresh lock zero protection, which is the whole bug.

    Consequences:

    • AC-1's requirement ("loser cannot remove the winner's fresh lock") is not met by AC-1's own prescribed design.
    • AC-4 (mutation-verify) is unsatisfiable: since plain rename-away ≡ unlink behaviorally, no hand-driven test can fail under the CAS→unlink mutation. Writing one would be a tautological gate test (forbidden by this repo's gate-test rule).

    What actually works (and its residual)

    An identity-verified CAS does fix both orderings (1 holder each) and is mutation-testable: rename away → read the moved file → proceed only if it's the stale holder you classified; otherwise rename(tmp → lockPath) to restore it and bail. But the restore step opens its own narrower race — rename(tmp → lockPath) can clobber a newer create in the momentary-empty window. So a fully-correct steal is a genuine design decision, not a mechanical wiring change.

    Options for re-spec

    1. Identity-verified CAS with a defined restore/orphan story (and an accepted, documented residual restore-window), or
    2. create-temp + link()-into-place (link fails EEXIST if a holder exists — no blind removal of a live lock), or
    3. explicitly accept a documented residual and scope the fix to the tight window only.

    No code was written; main unchanged. Recommend re-running /spec with a corrected primitive before /exec.

  6. admarble commented on Aug 7, 2026

    @admarble
    ContributorAuthor

    /exec complete — PR #913

    Implemented the stale-lock steal as an identity-verified compare-and-swap through one shared stealStaleLock helper (both LockManager and CheckoutLock). This deviates from AC-1's prescribed plain rename-away, which I verified is behaviorally identical to the unlink it replaces (see prior comment). The identity check is what makes AC-1's requirement hold and AC-4 mutation-verifiable.

    AC coverage

    • AC-1 ✅ CAS steal, no direct unlink of live lockPath, loser cannot remove a fresh lock (design adjusted — identity-verified, not plain rename)
    • AC-2 ✅ one shared helper across both lock classes
    • AC-3 ✅ existing behavior preserved (89 lock unit tests green)
    • AC-4 ✅ mutation-verified — mutating the identity check to always-match fails exactly the 2 documented-ordering tests; 87 others (incl. all pre-existing) stay green

    Files

    • src/lib/locks/lock-manager.ts — stealStaleLock helper + StaleLockIdentity; acquire steal branch wired
    • src/lib/locks/checkout-lock.ts — imports the shared helper; acquire steal branch wired
    • src/lib/locks/{lock-manager,checkout-lock}.test.ts — white-box interleave tests
    • CHANGELOG.md

    Checks

    • build ✅ · lint ✅ (0 warnings) · lock unit suites 89 passed
    • ⚠️ checkout-lock.integration.test.ts: 7 pre-existing failures (subprocess ExperimentalWarning pollutes JSON stdout) — reproduced identically at base 5a689301 in the same worktree, not introduced here. CI is the backstop.

    Known residual (follow-up)

    A third session's O_EXCL create racing the link-back restore is a sub-ms window plain lock files can't close atomically. Never destroys a live lock; far smaller than the original. Recommend a follow-up issue for a claim-file/lease protocol if full closure is wanted.

  7. admarble commented on Aug 7, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #908

    Self-review disclosure: this QA was performed by the same agent that wrote the implementation. The core design deviation is flagged prominently below for a human reviewer.

    AC Coverage

    AC Description Status Notes
    AC-1 Steal is a CAS, not unlink-then-create; no steal path unlinks the live lockPath; loser cannot remove the winner's fresh lock MET (design adjusted) Implemented as identity-verified rename CAS (rename→verify→link-restore), not the spec's plain rename-away. Plain rename-away is behaviorally identical to unlink (proven by hand-driven interleave); the identity check is what makes "loser cannot remove the winner's fresh lock" actually hold. lock-manager.ts:278
    AC-2 Both lock classes fixed via one shared helper MET CheckoutLock imports stealStaleLock from lock-manager.ts; interleave test present in both suites
    AC-3 Existing behavior preserved MET 89 lock unit tests green incl. all pre-existing; corrupt/unparseable-lock path unchanged (steal branch only runs on a parseable existing)
    AC-4 New test mutation-verified MET Mutating the helper's identity check to always-match fails exactly the 2 documented-ordering tests; 87 others stay green

    Coverage: 4/4 AC met (AC-1 with a documented design adjustment).

    CI Status

    Check State Impact
    typecheck pass ✅ MET
    validate-skills pass ✅ MET
    node-floor-guard pass ✅ MET
    validate-plugin pass ✅ MET
    build (22.x) pending ⏳ PENDING (gating; runs the test suite)

    Non-markdown diff → no relaxation. One gating check pending ⇒ verdict floors at NEEDS_VERIFICATION.

    Quality Metrics

    Metric Value
    Type issues (any) 0
    Deleted tests 0
    Files changed 5 (+321 / -2)

    Test note (local integration suite)

    checkout-lock.integration.test.ts shows 7 failures locally (SyntaxError: Unexpected end of JSON input, subprocess ExperimentalWarning polluting JSON stdout). Reproduced identically at base 5a689301 in the same worktree ⇒ pre-existing/environmental, not introduced here (the steal branch doesn't run in those fresh-lock race tests). Those tests are on main, so CI's build (22.x) decides authoritatively.

    Sibling-site scan

    • Only steal-recreate sites were the two acquire stale branches — both now routed through stealStaleLock.
    • forceAcquire (lock-manager.ts:455) unlinks-then-creates too but throws on losing the O_EXCL race, so it cannot silently double-hold — different pattern, out of scope, not a sibling of this bug.
    • release/releaseExternal/clear unlink only an owned/confirmed/stale-corrupt lock — legitimate removals, not steal-recreate.

    Adversarial Re-Read

    Findings (non-blocking, Gaps Found):

    1. Wiring not mutation-covered. The new tests exercise the exported stealStaleLock helper directly; the wiring (acquire calling the helper vs a blind unlinkSafe) is not gated — reverting only acquire's branch to unlinkSafe would fail no test (single-actor stale recovery passes under both). The fix locus (helper) is mutation-verified, so AC-4 is literally met, but a regression in the one-line wiring would slip through. Suggest a follow-up acquire-level guard test.
    2. linkSync portability. The restore path adds a hard-link dependency and rethrows any errno other than EEXIST/ENOENT (e.g. EPERM/ENOTSUP on an exotic FS), which would propagate out of acquire. .sequant/locks is a normal dir so this is low-risk, but it's a new failure surface the old code didn't have.
    3. Documented residual restore-race (a third session's O_EXCL create racing the link-back) — acknowledged in code + PR; never destroys a live lock; strictly narrower than the original single-syscall window.

    Status: Gaps Found (all non-blocking; none downgrade below the CI-pending gate)

    Trust-Boundary Check

    Finding: Clean — diff implements only the product requirement (fix the steal race); no agent-directed instruction from the issue body was acted on.

    Status: Clean

    Risk Assessment

    • Likely failure mode: the documented residual — a third acquirer creating in the sub-ms window between a mistaken rename-away and the link-restore. Never yields two on-disk holders that destroy a live lock; worst case a harmless *.steal.* orphan.
    • Not tested: the residual multi-race itself (inherent to plain lockfiles); the acquire→helper wiring (see Gap 1); linkSync failure on non-standard filesystems.
    • Sibling sites considered: forceAcquire (throw-on-loss, not a silent two-holder sibling); release/clear (legitimate removals). No cross-file siblings beyond the two named lock classes, both fixed.
    • Sibling-line audit: both acquire stale branches (the two intra-project sites) audited and fixed identically via the shared helper.

    CHANGELOG Verification

    Result: CHANGELOG requirements met — [Unreleased] › Fixed entry present with (#908).

    Verdict: NEEDS_VERIFICATION

    All four ACs are met on the merits and the fix is correct (AC-1 satisfied via an identity-verified CAS, a documented and justified deviation from the spec's no-op plain rename-away). The blocker is external: the gating build (22.x) CI check is still running and must report green before merge. Re-run /qa 908 once CI completes.

    Two non-blocking improvements to address in this PR or a follow-up: (1) add an acquire-level mutation test so the wiring — not just the helper — is gated; (2) note/relax the linkSync portability surface.

    Documentation: internal concurrency fix; no user-facing docs needed beyond the CHANGELOG entry.

  8. added
    needs-verification
    on Aug 7, 2026
  9. admarble commented on Aug 8, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #908 (fresh-session re-run)

    Context: Prior QA at this same commit (9a953e84) was a disclosed self-review by the implementing agent and verdicted NEEDS_VERIFICATION solely on the pending build (22.x) check. This run is an independent fresh-session review: full inline re-read of the diff, local test execution, and an independent reproduction of the AC-4 mutation — plus resolution of the CI gate, which is now green.

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Steal is CAS, not unlink-then-create; loser cannot remove winner's fresh lock MET Identity-verified rename CAS (stealStaleLock, lock-manager.ts:271). Independently re-read: rename → verify identity → discard or link-restore. The documented deviation from the spec's plain rename-away is correct — a bare rename moves whatever inode is at the path, so it would be behaviorally identical to the unlink it replaces.
    AC-2 Original Both lock classes fixed via one shared helper MET Both acquire stale branches route through the shared helper (checkout-lock.ts:279, lock-manager.ts:405); no unlinkSafe(lockPath) survives in either stale branch. Interleave tests present in both suites.
    AC-3 Original Existing behavior preserved MET 89/89 lock unit tests green locally in the worktree; full suite green in CI (build (22.x) SUCCESS). Corrupt-lock path unchanged (steal branch requires a parseable existing).
    AC-4 Original New test mutation-verified MET Independently reproduced this run: mutated the identity check to always-match → exactly the 2 "loser cannot remove the winner's fresh lock (documented ordering)" tests fail (34→1 failed, 55→1 failed; 87 others pass); restored clean. Matches the result recorded in the PR body per the repo gate-test rule.

    Coverage: 4/4 AC met. Original ACs: 4/4. Derived ACs: none (no quality plan).

    Quality Plan Verification

    N/A — no quality plan found in issue comments.

    Precheck Findings

    Precheck Findings: unavailable — inline fallback used.

    CI Status

    Check State Bucket Impact
    build (22.x) SUCCESS pass ✅ MET
    typecheck SUCCESS pass ✅ MET
    node-floor-guard SUCCESS pass ✅ MET
    validate-skills SUCCESS pass ✅ MET
    validate-plugin SUCCESS pass ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed. The gating check that forced the prior NEEDS_VERIFICATION is now green — that verdict is resolved.

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 5 OK
    Lines added +321 -
    Lines deleted -2 -

    Cache Status

    N/A — inline fresh review (no cached results consumed; diff hash unchanged from prior full run).

    Build Verification

    N/A — build passed (CI build (22.x) SUCCESS).

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/locks/lock-manager.ts Standard ✅ Yes lock-manager.test.ts (+79)
    src/lib/locks/checkout-lock.ts Standard ✅ Yes checkout-lock.test.ts (+85)

    Coverage: 2/2 changed source files have corresponding tests. Critical paths without tests: None.

    Code Review

    Strengths:

    • The interleave tests drive the issue body's exact documented ordering (A.steal → A.create → B.steal → B.create) by hand — the motivating example is a mandatory fixture and it is one, verbatim.
    • The deviation from the spec's plain rename-away is not just documented but proven: plain rename-away is behaviorally identical to the unlink it replaces, and the PR records the hand-driven interleave demonstrating it. This is prescription-vs-requirement handled correctly — the AC's requirement is built, the AC's suggested design is flagged as insufficient.
    • linkSync for restore (never overwrites) is the right primitive — a rename(tmp, lockPath) restore would clobber a third session's new claim.
    • Shared helper mirrors the existing classifyStaleness sharing pattern, so the two lock classes cannot drift (the same reasoning that motivated AC-2).

    Issues: none blocking. See recommendations.

    Suggestions (prose recommendations, distinct from AC gaps — all ACs are met):

    1. Wiring not mutation-covered: the new tests exercise stealStaleLock + writeAtomic directly; reverting either acquire stale branch back to unlinkSafe(lockPath) would fail no test (single-actor stale recovery passes under both). The fix locus is mutation-verified, the one-line wiring is not. Follow-up: an acquire-level guard test.
    2. New throw surface: stealStaleLock rethrows non-ENOENT rename errors and non-EEXIST/ENOENT link errors out of acquire, where the old unlinkSafe swallowed them. Low risk in .sequant/locks (normal dir), but exotic-FS EPERM/ENOTSUP on linkSync is a new failure path.
    3. *.steal.* orphans are never cleaned (only created in the rare lost-restore race; list() ignores them). Cosmetic.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Asserts on-disk lock state and acquire outcomes; the private writeAtomic access is justified and documented (CLI startup serializes real processes past the syscall window)
    Coverage Depth ✅ OK Win, documented-ordering loss, and ENOENT-loss paths all covered in both suites
    Mock Hygiene ✅ OK No mocks; real filesystem in tmp dirs
    Test Reliability ✅ OK Deterministic hand-driven interleave — exactly the right answer to the race-tests-serialize problem

    Anti-Pattern Detection

    Dependency Audit: N/A — no dependency changes.

    Code Patterns: No findings. No any, no empty catches (each catch filters errno and rethrows), no secrets, no unbounded loops or timers.

    Call-Site Review

    New exported functions detected: 1 (stealStaleLock; plus StaleLockIdentity type)

    Function Call Sites Loop? Conditions AC Match
    stealStaleLock lock-manager.ts:405 (acquire), checkout-lock.ts:279 (acquire) No Both gated by if (staleReason) on a parsed existing; win or lose falls through to the terminal O_EXCL create ✅ Matches AC-1/AC-2 exactly

    Findings: none — return value deliberately unused at both sites (the O_EXCL create arbitrates), which is correct and documented.

    Execution Evidence

    N/A — no scripts/ or CLI changes (library + tests + CHANGELOG only).

    Skill Command Verification

    N/A — no skill files changed.

    Detection Pattern Verification

    N/A — no pattern changes in skill markdown.

    CLI Registration Verification

    N/A — no option interface changes.

    Smoke Test

    Not Required — no workflow-affecting changes (skills/scripts/CLI untouched).

    Manual Test ACs

    N/A — no manual-test or evidence-naming ACs beyond AC-4's mutation requirement, whose artifact exists (recorded in PR body) and was independently reproduced this run.

    Risk Assessment

    • Likely failure mode: the documented residual — a third session's O_EXCL create landing in the sub-ms window between a mistaken rename-away and the link-restore leaves that stealer's copy as an orphan while the third session holds. Never destroys a live lock via the loser's own action; strictly narrower than the original window, which failed on a single race.
    • Not tested: the acquire→helper wiring (suggestion 1); linkSync failure on non-standard filesystems; the residual three-way race itself (inherent to plain lockfiles).
    • Sibling sites considered: forceAcquire (lock-manager.ts) also unlinks-then-creates but throws on losing the O_EXCL race, so it cannot silently double-hold — different pattern, correctly out of scope. release/releaseExternal/clear unlink only owned/confirmed locks. No other cross-file steal-recreate sites.
    • Sibling-line audit: both acquire stale branches — the only two steal sites — are fixed identically via the shared helper; verified no unlinkSafe(lockPath) survives in either stale branch.

    Trust-Boundary Check

    Finding: Clean — diff implements only product requirements (the steal-race fix); the issue body contains analysis, a fix sketch, and a test plan, none of it agent-directed (no commands to run, URLs to fetch, or files to exfiltrate), and nothing in the diff traces to any such instruction.

    Status: Clean

    Behavior-Rule Survival Check

    AC Triggered? Survivors Status
    AC-1–AC-4 No (no default/always/never/skip behavior-rule phrasing) — N/A

    Status: N/A — verified directly regardless: the OLD-rule pattern (unlinkSafe(lockPath) in a stale branch) survives in neither lock class.

    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (fix(#908): commit)
    [Unreleased] entry ✅ Present (Fixed section)
    Entry format ✅ Valid (includes (#908))

    Result: CHANGELOG requirements met.

    Adversarial Re-Read

    Findings: (1) Motivating fixture consulted and run — the issue's documented interleaving is driven verbatim by the two new "documented ordering" tests, and I re-ran them under mutation myself. (2) Evidence claims audited — the PR's mutation claim is a post-fix validation, not a bug repro, and it reproduced exactly (2 fail / 87 pass). (3) Process state inspected — worktree clean, 0 behind origin/main, branch in sync with remote, HEAD matches prior QA SHA. (4) Sibling sites cited concretely (see Risk Assessment). (5) Non-Goals respected — the residual three-way race is documented and deferred rather than silently scope-expanded into a lease protocol. Remaining gaps are the three non-blocking suggestions above (untested wiring, new throw surface, orphan accumulation).

    Status: Gaps Found (all non-blocking)

    Verdict: AC_MET_BUT_NOT_A_PLUS

    All 4 ACs are met and independently verified this run — including a fresh reproduction of the AC-4 mutation result — and the CI gate that forced the prior NEEDS_VERIFICATION is now fully green (5/5 checks). The verdict lands at AC_MET_BUT_NOT_A_PLUS rather than READY_FOR_MERGE per the §7 algorithm (adversarial re-read: Gaps Found), on the strength of one substantive gap: the acquire→helper wiring is not mutation-covered, so a regression re-introducing the blind unlink at either call site would ship green. That is follow-up material, not a merge blocker — do not route this to /loop.

    Recommended before or shortly after merge (PR #913 or follow-up):

    1. Acquire-level guard test gating the wiring (mutation-verify by reverting one stale branch to unlinkSafe).
    2. Follow-up issue for the documented residual (claim-file/lease protocol) — per the PR's own recommendation.

    Documentation

    • CHANGELOG entry added (user-facing fix)
    • N/A otherwise — internal concurrency fix; behavior documented extensively in code comments and CHANGELOG

    Documentation: Before merging, run /docs 908 if desired; the CHANGELOG entry likely suffices for an internal fix.

    Next Steps

    1. Merge PR fix(#908): stale-lock steal is compare-and-swap, not unlink-then-create #913 (all ACs met, CI green), or first add the acquire-level wiring test in-PR.
    2. File the follow-up issue for the residual restore-race protocol change.
  10. added
    needs-improvement
    and removed
    needs-verification
    on Aug 8, 2026
  11. added a commit that references this issue on Aug 8, 2026
  12. admarble commented on Aug 8, 2026

    @admarble
    ContributorAuthor

    QA gaps filled (5cf65c2f on PR #913)

    All three gaps from the QA review are closed in-PR:

    1. Wiring now mutation-covered — new acquire-level tests in both suites drive the racing window through acquire() itself (via the injected isPidAlive probe). Reverting either stale branch to blind unlinkSafe now fails exactly one test each (M1/M2 below).
    2. Throw surface removed — stealStaleLock never throws: rename errors degrade to a lost steal; hard-link refusal (EPERM/ENOTSUP) falls back to rename-restore so a fresh lock is never left renamed-away.
    3. Orphans reaped — aged *.steal.* files (>10 min) swept best-effort on steal entry, prefix-scoped.

    Mutation evidence (full table in the PR body): M1–M4 each kill exactly their own gate test (1 failed / 92 passed); re-running the original AC-4 identity mutation now kills 5 tests (was 2). 93/93 lock unit tests green; typecheck clean.

    CI is running on 5cf65c2f. Once green, re-run /qa 908 — with the adversarial-re-read gaps closed, the remaining path to READY_FOR_MERGE is just the CI gate.

  13. admarble commented on Aug 8, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #908 (re-run at 5cf65c2f)

    Self-review disclosure: the gap-fix commit (5cf65c2f) was authored by the same session performing this QA. Mitigations: the base commit (9a953e84) was reviewed by this session while independent of it; the new commit is tests + hardening only; every new gate test is mutation-verified with results recorded in the PR body; the three quality-check sub-agents ran independently; and CI (which runs the full suite) is green at this exact SHA. Flagged for the human merger regardless.

    AC Coverage

    AC Source Description Status Notes
    AC-1 Original Steal is CAS; loser cannot remove winner's fresh lock MET Identity-verified rename CAS (stealStaleLock). Now also enforced at the wiring level: per-class acquire-level tests inject the racing winner into the classification→steal window (M1/M2 mutation-verified).
    AC-2 Original Both lock classes fixed via one shared helper MET Both acquire stale branches route through stealStaleLock; per-class wiring tests prove each call site, not just the helper.
    AC-3 Original Existing behavior preserved MET 93/93 lock unit tests green locally at HEAD; full suite green in CI (build (22.x) SUCCESS at 5cf65c2f). Steal now never throws — rename errors degrade to a lost steal and the terminal O_EXCL create surfaces environment errors with the same errno as pre-#908.
    AC-4 Original New test mutation-verified MET Five mutations recorded in PR body (M1–M5), each killed by exactly its own gate test; the original identity-check mutation is now killed by 5 tests (was 2).

    Coverage: 4/4 AC met. Original ACs: 4/4. Derived ACs: none (no quality plan).

    Quality Plan Verification

    N/A — no quality plan found in issue comments.

    Precheck Findings

    Precheck Findings: unavailable — inline fallback used.

    CI Status

    Check State Bucket Impact
    build (22.x) SUCCESS pass ✅ MET
    typecheck SUCCESS pass ✅ MET
    node-floor-guard SUCCESS pass ✅ MET
    validate-skills SUCCESS pass ✅ MET
    validate-plugin SUCCESS pass ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed — at HEAD 5cf65c2f. PR is MERGEABLE.

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 5 OK
    Lines added +538 -
    Lines deleted -3 -

    Sub-agent checks: type-safety pass, scope/size pass (single concern, ~1.4:1 test-to-code ratio), security pass (0 critical/0 warning; 2 informational notes on the deliberate best-effort catches, both assessed fail-closed — they preserve an existing holder's lock, never grant a false acquisition).

    Cache Status

    N/A — fresh inline + sub-agent run (diff hash changed since prior QA).

    Build Verification

    N/A — build passed (CI green).

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    src/lib/locks/lock-manager.ts Standard ✅ Yes lock-manager.test.ts (+174)
    src/lib/locks/checkout-lock.ts Standard ✅ Yes checkout-lock.test.ts (+137)

    Coverage: 2/2. Critical paths without tests: None — the wiring, the CAS, the link-refused fallback, and the orphan sweep are each gated by a mutation-verified test.

    Code Review

    Strengths:

    • The wiring tests close the strongest finding from the prior QA: reverting either acquire stale branch to a blind unlink now fails exactly one named test per class.
    • The never-throw contract is behavior-preserving by construction: any errno the steal swallows re-surfaces from the terminal O_CREAT|O_EXCL create, matching the pre-fix(locks): stale-lock steal is unlink-then-create, not compare-and-swap — two stealers can both win #908 failure surface.
    • The link-refused fallback makes the right trade: rename-restore's microscopic clobber window (third-session create racing the restore ON a no-hardlink FS) versus destroying the fresh lock every time on such filesystems.
    • Orphan sweep is prefix-scoped (verified against longer issue numbers — 42.lock.steal. does not match 425.lock.steal.) and TTL-gated at 10 min against a microseconds-long legitimate window.

    Issues: none.

    Suggestions: none remaining in this PR. (Follow-up issue for the documented residual — claim-file/lease protocol — remains recommended as tracking housekeeping; the residual is a documented, issue-acknowledged limit of plain lockfiles, not an unaddressed gap in this diff.)

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Wiring tests drive the public acquire(); the isPidAlive injection is a constructor-supported seam, not internals poking
    Coverage Depth ✅ OK Win / documented-ordering loss / ENOENT loss / link-refused fallback / sweep aging+scoping all covered
    Mock Hygiene ✅ OK No module mocks; one injected syscall (ops.link) documented as the only way to provoke capability errors
    Test Reliability ✅ OK Deterministic; fixed injected clocks; sweep test verified safe against wall-clock/injected-clock mismatch (negative age can never trigger a sweep)

    Issues Found: none.

    Anti-Pattern Detection

    Dependency Audit: N/A — no dependency changes.

    Code Patterns: No critical findings. The best-effort catch blocks are deliberate, individually commented, and scoped to cleanup of the steal's private scratch files (security sub-agent concurs: fail-closed).

    Call-Site Review

    New exported functions: stealStaleLock (both acquire stale branches, gated by if (staleReason), no loops — matches AC-1/AC-2; return value deliberately unused, the O_EXCL create arbitrates). No new exports in the gap-fix commit (helpers are module-private).

    Execution Evidence

    N/A — no scripts/ or CLI changes (library + tests + CHANGELOG only).

    Skill Command Verification

    N/A — no skill files changed.

    CLI Registration Verification

    N/A — no option interface changes.

    Smoke Test

    Not Required — no workflow-affecting changes (skills/scripts/CLI untouched).

    Manual Test ACs

    AC Verification Method Runtime Test Status Evidence
    AC-4 Evidence-naming (mutation artifact) ✅ Executed M1–M5 run this session, results recorded verbatim in PR body

    Manual Test Enforcement: 1/1 verified at runtime.

    Risk Assessment

    • Likely failure mode: the documented residual — a third session's O_EXCL create landing in the sub-ms restore window. Never destroys a live lock via the loser's own action; strictly narrower than the pre-fix window; flagged for a follow-up protocol change.
    • Not tested: the residual three-way race itself (inherent to plain lockfiles; no content-CAS primitive exists to test against).
    • Sibling sites considered: forceAcquire (throws on losing the O_EXCL race — cannot silently double-hold); release/releaseExternal/clear (owned/confirmed removals only). No other cross-file steal-recreate sites.
    • Sibling-line audit: both acquire stale branches fixed via the shared helper and now individually wiring-tested; no unlinkSafe(lockPath) survives in either stale branch.

    Trust-Boundary Check

    Finding: Clean — diff implements only product requirements (the steal-race fix and its QA-gap hardening); no agent-directed instruction from the issue body or comments was acted on.

    Status: Clean

    Behavior-Rule Survival Check

    AC Triggered? Survivors Status
    AC-1–AC-4 No (no behavior-rule keyword pairs) — N/A

    Status: N/A — verified directly regardless: the OLD-rule pattern (blind unlinkSafe(lockPath) in a stale branch) survives in neither class, and is now mutation-gated against reintroduction.

    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅ Found
    User-facing changes ✅ Yes (fix(#908): commits)
    [Unreleased] entry ✅ Present (Fixed, includes (#908))
    Entry format ✅ Valid

    Result: CHANGELOG requirements met.

    Adversarial Re-Read

    Findings: No gaps found because: (1) the motivating fixture — the issue's documented interleaving — is driven verbatim by the interleave tests AND now through the public acquire() path by the wiring tests; (2) evidence claims audited: all five mutation results were executed this session, each restore verified clean, and the PR-body record matches the observed kills exactly; (3) process state inspected: worktree clean, branch synced, 0 behind main, CI green at this exact SHA; (4) sibling sites cited concretely in Risk Assessment (intra-file: both stale branches; cross-file: forceAcquire/release/clear audited as non-siblings); (5) Non-Goals respected: the residual three-way race remains a documented deferral, not silent scope expansion, and the gap-fix commit stayed within the QA findings it set out to close. Specific hardening re-checks performed: sweep arithmetic under the tests' fixed injected clock (negative age cannot sweep), sweep prefix scoping against longer issue numbers, tmp-file disposition on every restore branch (link-success, EEXIST-orphan, ENOENT, rename-fallback), and the errno-equivalence argument for the never-throw contract.

    Status: Clean

    Verdict: READY_FOR_MERGE

    All 4 ACs met, CI fully green at HEAD (5cf65c2f), and every gap from the prior QA is closed with mutation-verified coverage: the acquire→helper wiring (M1/M2), the never-throw steal with link-refused fallback (M4), and the orphan sweep (M3). The identity check at the heart of AC-1 is now gated by 5 independent tests. Sub-agent checks pass across type safety, scope, and security. No remaining in-PR suggestions.

    Caveat for the human merger: the final commit is a same-session self-review (disclosed above) — the mutation evidence and green CI are the independent signals.

    Documentation

    • CHANGELOG entry added (user-facing fix, (#908))
    • N/A otherwise — internal concurrency fix; behavior documented in code comments and CHANGELOG

    Next Steps

    1. Merge PR fix(#908): stale-lock steal is compare-and-swap, not unlink-then-create #913.
    2. File the follow-up issue for the documented residual (claim-file/lease protocol to close the sub-ms restore race).
  14. added
    ready-for-review
    and removed
    needs-improvement
    on Aug 8, 2026
  15. added 2 commits that reference this issue on Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions