Skip to content

fix(locks): close the steal-restore residual — third-session create between rename-away and link-back leaves two believers #919

Open

Description

@admarble

Documented residual from #908 (PR #913), where it is flagged in the RESIDUAL comment of stealStaleLock and in the PR's "Known residual" section. Filed separately because #909 — the only other open locks issue — was already in flight when this surfaced.

Limitation

The stale-lock steal is now an identity-verified compare-and-swap, but plain lock files admit no atomic CAS on content, so one sub-millisecond window survives in stealStaleLock (src/lib/locks/lock-manager.ts, restore path):

A: holds a FRESH lock at lockPath
B: (stale classification raced) rename(lockPath → tmpB)   # mistakenly moves A's fresh lock
C: open("wx") → succeeds, writes L_C                       # path was momentarily empty
B: link(tmpB, lockPath) → EEXIST                           # restore refused — correctly won't clobber C
B: leaves tmpB as a *.steal.* orphan, loses the steal
Result: C holds on disk; A still believes it holds. Two believers, one lock file.

The restore's EEXIST branch is the right call locally (never clobber a live claim), but the fresh holder whose lock was renamed away is left with a stale belief.

Severity

Low. Strictly narrower than the pre-#908 bug (which failed on a single race, every time a steal landed on a fresh lock): this needs a mistaken steal AND a third-session O_EXCL create inside a sub-ms window. It never destroys a live lock by the loser's own action; worst case is one *.steal.* orphan (swept after 10 min) plus A's stale belief.

Fix sketch

A protocol change, not a patch: a claim-file or lease scheme, so possession is proven by an artifact only one process can hold (e.g. an exclusively-created claim file consulted before any steal, or lease timestamps the holder refreshes), instead of by absence-then-create on a single path. Must cover both LockManager and CheckoutLock through the shared stealStaleLock helper so the classes cannot drift (same shape as #908's AC-2).

Test plan

Hand-driven interleave, same technique as #908's suites (multi-process tests serialize before the window): drive stealStaleLock and the terminal writeAtomic for three actors in the documented ordering above, and assert the protocol leaves exactly one believer. Mutation-verify per the repo gate-test rule.

Activity

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

    @admarble
    ContributorAuthor

    Complexity: Standard (6 synthesized ACs, 1 directory)

    Note: #919's body has no formal AC checklist (0 checkboxes). The ACs below are synthesized from its Fix sketch and Test plan and should be confirmed before /exec. This is a documented residual of #908/#913 — theory-driven, with no observed failure — which bears on the proportionality question in Open Questions.

    AC Quality Check

    Synthesized inline (no checkboxes to lint). One vagueness risk: "close the residual" is unmeasurable as stated — pinned below to the concrete A/B/C interleave asserting exactly one believer.


    Scope Assessment

    Non-Goals: ⚠️ No Non-Goals section in the issue. Implied (confirm): do not change cross-host/age staleness semantics, do not widen the numeric lock key, do not touch classifyStaleness.

    Metric Value Status
    Feature count 1 (steal-protocol hardening) ✅
    AC items 6 (synthesized) ✅
    Directory spread 1 (src/lib/locks/) ✅

    Verdict: ✅ SCOPE_OK (metrics green; concurrency-correctness risk is high — full Design Review + quality loop recommended).


    Acceptance Criteria

    AC-1: The two-believers window is closed

    Verification: Unit Test (hand-driven interleave via seams)
    Scenario: Given the issue's exact ordering — A holds fresh; B's stale classification raced and renames A's fresh lock away; C O_EXCL-creates in the momentary gap — When the protocol runs → Then exactly one session believes it holds, and that belief matches the on-disk lock.

    AC-2: Fix lives in shared code; classes cannot drift

    Verification: Unit Test
    Scenario: Given both LockManager.acquire and CheckoutLock.acquire → When either steals/acquires → Then both route through the shared helper in lock-manager.ts (same shape as #908's AC-2). No per-class copy of the protocol.

    AC-3: A live lock is never destroyed or clobbered (preserve #908)

    Verification: Unit Test
    Scenario: Given a fresh lock at lockPath → When a loser's steal or a racing create runs → Then the fresh holder's lock is never left renamed-away and a third session's fresh claim is never overwritten. All existing #908 steal tests still pass.

    AC-4: Acquire path still NEVER THROWS and degrades safely

    Verification: Unit Test
    Scenario: Given fs errors on the guard/steal primitives (ENOENT/EEXIST/EPERM/ENOTSUP) → When acquire runs → Then it degrades to "lost"/blocked (no throw); the terminal O_EXCL create still surfaces real env errors (EACCES) with the pre-#908 errno.

    AC-5: The new coordination artifact self-heals (no permanent block, no worse window)

    Verification: Unit Test
    Scenario: Given a process SIGKILLed mid-critical-section leaves the new guard/claim artifact → When later acquirers run → Then it is bounded by a short TTL + best-effort sweep (mirroring sweepStealOrphans), never blocking an issue indefinitely, and its own orphans are list()-invisible.

    AC-6: Hand-driven interleave test, mutation-verified

    Verification: Unit Test
    Scenario: Given the AC-1 test drives the window via test seams (extend ops, or inject a between-rename-and-link hook) — not spawned processes (they serialize before the window; see #908 tests + repo memory) → When the guard logic is deleted → Then exactly the AC-1 test fails (mutation result recorded in the commit/PR per CLAUDE.md gate rule).


    Rule Touchpoints

    AC-2/AC-3 are behavior rules ("shared … so classes cannot drift", "never destroy a live lock"). Touchpoints that must stay in lockstep:

    AC Touchpoint Snippet
    AC-2/3 src/lib/locks/lock-manager.ts:368 export function stealStaleLock(...) — shared helper
    AC-2/3 src/lib/locks/lock-manager.ts:513 LockManager.acquire → stealStaleLock(...)
    AC-2/3 src/lib/locks/checkout-lock.ts:296 CheckoutLock.acquire → stealStaleLock(...)

    The guard must wrap the classify→steal→terminal-create span in both acquire sites — so put it in shared code, not duplicated per class.


    Implementation Plan

    Root cause (confirmed by reading the code): stealStaleLock (lock-manager.ts:368) takes possession then checks identity (rename→read→link-back). Between the rename-away and the link-back, lockPath is empty, so a third session's writeAtomic O_EXCL (lock-manager.ts:775 / checkout-lock.ts:449) slips in. Because classify→steal→create is not serialized against a concurrent fresh create, the two-believers state can form. Plain files admit no content-CAS, so this needs a coordination artifact.

    Phase 1: Design the coordination artifact (decision gate)

    1. Recommended — short-lived exclusive guard file (Option A). A per-lockPath <lockPath>.guard created with O_CREAT|O_EXCL. A shared higher-order helper withAcquireGuard(lockPath, fn) in lock-manager.ts wraps re-read → re-classify → steal → terminal create. Both acquire methods call it. Since the fresh-create path now runs inside the guard, no third session can create on the momentarily-empty path → AC-1. Residual shrinks by orders of magnitude; the guard's own failure mode (SIGKILL mid-section) is availability-only, bounded by a short TTL + sweepStealOrphans-style reaper (AC-5).
    2. Rejected — lease/refresh (Option B): skill shells die immediately post-acquire (skipPidCheck) and cannot refresh a lease; incompatible with the dead-PID model classifyStaleness is built on.
    3. Rejected/deferred — accept-as-is (Option C): valid given Low severity (see Open Questions).

    Phase 2: Implement (shared code first)

    1. Add withAcquireGuard + guard reaper to lock-manager.ts; extend the ops seam so tests can drive the critical-section window deterministically.
    2. Route LockManager.acquire (line ~497-533) and CheckoutLock.acquire (line ~273-316) through it — re-classify inside the guard; a fresh re-read returns "blocked" without stealing.

    Phase 3: Tests + docs

    1. Add the AC-1 hand-driven interleave test to both suites; mutation-verify (AC-6). Update the RESIDUAL: block in stealStaleLock's docstring (lines 348-351) to describe the guard and its remaining bound, not the old open window.

    Design Review

    1. Where does this belong? In the shared lock-manager.ts steal/acquire code — the one place fix(locks): stale-lock steal is unlink-then-create, not compare-and-swap — two stealers can both win #908 already chose so the two lock classes can't diverge. Not in either acquire body.
    2. Simplest correct approach? Serialize only the mutating span (classify→steal→create) with one O_EXCL guard artifact. Cheaper than a full lease protocol or a schema change; reuses the existing orphan-sweep pattern.
    3. Existing pattern followed? fix(locks): stale-lock steal is unlink-then-create, not compare-and-swap — two stealers can both win #908's stealStaleLock (shared helper + ops seam) and sweepStealOrphans (best-effort TTL reaper). The guard is the same shapes applied one level up.
    4. What would a senior reviewer challenge? (a) "Does the guard just move the race?" — no: it converts a correctness window (two believers by live actors) into an availability window (a SIGKILLed guard, TTL-bounded), which is strictly better. (b) "Is a protocol change worth a Low-severity, never-observed residual?" — see Open Questions; the user decides. (c) Guard TTL vs. long /fullsolve critical sections — the guard covers microseconds of fs ops, not the whole run, so a seconds-scale TTL is safe.

    Feature Quality Planning

    Notable items:

    • Concurrency test integrity (memory feedback_multiprocess_race_tests_serialize): N spawned CLI procs do NOT test this — startup serializes them before the window. The seam-driven interleave is mandatory, not optional.
    • Mutation cleanup hazard (memory feedback_mutation_testing_destructive_cleanup): the test tmpdir is passed to rmSync in afterEach; never let a mutated var flow into that path.
    • No real evidence: residual is documented, not observed → weigh proportionality before building (Open Q1).

    Derived ACs

    Source Derived AC Priority
    Reliability AC-5 (guard self-heals, no permanent block) High
    Test integrity AC-6 (seam-driven + mutation-verified) High

    Open Questions

    1. Is a protocol change proportionate? — Recommendation: implement Option A (contained, ~1 file). Impact if wrong: added coordination surface + a new availability failure mode for a Low-severity, never-observed residual. If the user prefers, Option C (document the bound, close as wontfix) is defensible.
    2. Guard granularity — per-lockPath guard (recommended, no cross-issue contention) vs. one per-locksDir guard (simpler, serializes unrelated issues). Impact: the latter adds contention across concurrent issues.
    3. Confirm synthesized ACs — no checkboxes exist in the issue; confirm AC-1..AC-6 before /exec.

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled
    Reasoning: Concurrency-correctness protocol change in shared code. Skip testgen (the interleave test is bespoke — seam-driven, not a generic stub). No UI → no test phase. Enable the quality loop: an adversarial re-read of the interleave and the guard's own residual is where this fix lives or dies.


    Label Review

    Current: bug
    Recommended: bug (optionally add complex — it's a protocol change, though contained to one dir)
    Reason: Contained blast radius (1 directory) but high correctness risk.
    Quality Loop: Enabled by recommendation above (concurrency change), independent of scope verdict.

  3. added
    planned
    on Aug 8, 2026
  4. admarble commented on Aug 8, 2026

    @admarble
    ContributorAuthor

    #919 — fix(locks): close the steal-restore residual — third-session create between rename-away and link-back leaves two believers
    Open · bug
    ────────────────────────────────────────────────────────────────

    → PROCEED — Clear defect, fix sketch, and test plan; independent of the #914 stack

    Commands:
    sequant run 919 -Q --phases exec,qa # after in-flight spec

    spec → exec → qa

    Flags:
    -Q lock-protocol change spanning LockManager and CheckoutLock via the shared stealStaleLock helper
    --phases exec,qa spec already running for this issue; bug label skips testgen
    ────────────────────────────────────────────────────────────────
    ⚠ Locked by an in-flight spec-only run at assessment time — wait for it before exec
    ⚠ No checkbox ACs — spec must derive them; keep each derived AC on a single line (the AC parser is line-anchored)
    ────────────────────────────────────────────────────────────────

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

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions