Skip to content

save.lock is not a lock: rm+create cannot be made atomic — move to mkdir acquisition and rename-based stale takeover #182

Closed

Description

@fdaviddpt

Evidence

save-session.sh allows multiple concurrent holders whenever a stale (dead-PID) lock is taken over. Measured with N real processes racing one pre-seeded dead-PID lock, 40 trials each, counting extract invocations:

contenders multi-winner rounds max simultaneous winners
2 0/40 1
4 1/40 2
5 2/40 2
8 11/40 (27.5%) 2
10 7/30 4

Two concurrent saves means two Haiku calls and two position writes — the corruption #168 was opened to prevent.

>2 concurrent invocations is realistic: PostToolUse fires per tool call and batching several tool calls per turn is normal usage.

Why the current shape cannot be repaired

#181 tried rm -f → recreate under noclobber → re-read and verify our own PID. It reduced the window and did not close it, because:

  1. The verify is a snapshot, not a lock. After a process verifies and sets HAVE_LOCK=true it never re-checks. A later contender's rm -f + recreate clobbers that winner's lock mid-flight.
  2. cleanup() gates on the HAVE_LOCK flag alone, never on whether LOCK_FILE still holds its own PID — so a displaced winner deletes a later legitimate holder's lock on exit. This is fix(save): only unlink save.lock when this process actually owns it #168's "non-owner deletes the lock" bug, reachable again through the takeover path. It is the mechanism behind winner counts above 2.

Adding more verification after rm -f cannot fix this. rm followed by create is two operations; no amount of checking between or after them makes the pair atomic.

Proposed fix

Use primitives that are genuinely atomic:

Acquisition — mkdir. mkdir either creates the directory or fails; exactly one process wins, with no check-then-act. Store the PID inside ($LOCK_DIR/pid) for liveness checks.

Stale takeover — mv (rename). Do not rm the stale lock. Rename it to a unique name:

if mv "$LOCK_DIR" "$LOCK_DIR.steal.$$" 2>/dev/null; then
    rm -rf "$LOCK_DIR.steal.$$"
    # only this process got here; now contend for mkdir normally
fi

Two processes attempting to rename the same directory: one succeeds, the loser gets ENOENT. The takeover becomes single-winner by construction rather than by timing.

cleanup() should verify ownership by content, not by flag — belt and braces once acquisition is atomic, but cheap and it directly closes finding 2.

Tests

Must exercise N = 2, 4, 8, 10, not just 2. The N=2 case passes even on the broken implementation, which is why #181 looked correct. Revert-prove each.

Also carry forward

LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null) needs || true — plain top-level assignment, so under set -e its status is cat's, and the file can vanish before the read (holder finished, or another process took over). Without it the loser exits 1 with an ERR-trap log where it should skip cleanly with 0. Independent of the lock redesign.

Caution: reverting that guard is caught by race-timing tests only ~25% of runs. It needs a deterministic test, not a probabilistic one.

Found reviewing #181, which is closed in favour of this.

Activity

  1. fdaviddpt commented on Jul 26, 2026

    @fdaviddpt
    ContributorAuthor

    Design brief — one primitive, two call sites

    Scoping note before the design: this should not be fixed in isolation. #173 (now.md writers need serialising) needs the same primitive for the same reason — no flock on macOS. Landing them separately gives this repo three lock implementations: save.lock's noclobber pidfile, a new now.lock spinner, and whatever lands here. That is the drift #177 is open about. One change, one helper, both call sites.

    Closes: this issue, #173, and one entry of #177.


    1. The primitive

    New file, scripts/lib-lock.sh, sourced where needed:

    lock_acquire <lock_dir> <timeout_seconds>   -> 0 acquired, 1 timed out
    lock_release <lock_dir>                     -> idempotent, safe if not held
    

    Acquisition is mkdir. mkdir either creates the directory or fails — one syscall, no check-then-act, no window. This is the property the current code lacks and the reason #181 could not be repaired: rm -f followed by create is two operations, and no amount of verification between or after them makes the pair atomic.

    On success, write the owning PID to <lock_dir>/pid for liveness checks.

    Stale takeover is mv, never rm. When mkdir fails and <lock_dir>/pid names a dead process:

    if mv "$lock_dir" "$lock_dir.steal.$$" 2>/dev/null; then
        rm -rf "$lock_dir.steal.$$"
        # only this process reached here; now contend for mkdir normally
    fi

    Two processes renaming the same directory: exactly one succeeds, the loser gets ENOENT. The takeover becomes single-winner by construction rather than by timing — which is the whole bug. Do not replace this with rm -rf + retry; that reintroduces the multi-winner cascade measured in the table above.

    Release removes the directory. Ownership is structural — only the creator can have made it — so no PID comparison is needed on the happy path. Still worth having lock_release verify <lock_dir>/pid matches $$ before removing, as defence against a future caller releasing a lock it never took.

    Timeout: spin with a short sleep until the deadline. Verify fractional sleep (sleep 0.05) on both macOS and the CI image before relying on it — if it is not portable, fall back to integer seconds and accept coarser contention behaviour.

    2. Call sites

    scripts/save-session.sh — replace the whole noclobber block plus the takeover branch. HAVE_LOCK and the content-verify logic both disappear: ownership stops being something to track and check, and becomes something the primitive guarantees. cleanup() calls lock_release.

    scripts/lib-now-lock.sh (from #173) — replace flock -w "$_timeout" 9 with lock_acquire. Everything else in that PR is sound and should be kept: the bounds guard in now_truncate_first, the sibling-temp-file + atomic mv, and keeping the 180s Haiku call outside the lock with the byte-offset truncate preserving concurrent appends. Preserve the author's commit.

    3. Test matrix

    N = 2, 4, 8, 10 concurrent processes, ≥40 iterations each, asserting at most one runs extract/call-haiku per round, plus exactly one winner (no silently-missed cycle).

    Revert-prove every test against the pre-fix implementation.

    4. Traps — all four cost time already, do not rediscover them

    1. N=2 tests pass on broken code. The entire reason fix(save): make the stale-lock takeover atomic #181 shipped looking correct: 0/40 multi-winner at N=2, 11/40 at N=8. Any test suite that stops at two processes proves nothing.
    2. python3 -c with fcntl.flock does not work as a flock substitute. An advisory lock belongs to the open file description and is released when the Python child exits — the shell then proceeds holding nothing, silently. This looks like an obvious fix (python3 is already a hard dependency) and it is wrong.
    3. LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null) needs || true. Plain top-level assignment, so under set -e its status is cat's, and the file can vanish before the read. Without it the loser exits 1 with an ERR-trap log where it should skip with 0. Reverting the guard is caught by race-timing tests only ~25% of runs — it needs a deterministic test, not a probabilistic one. Carry this forward even if the surrounding code is rewritten.
    4. [ "${REMEMBER_DEBUG:-1}" = "1" ] && log ... before exit 0 is NOT a set -e hazard. Bash exempts a short-circuited final member of an && list. Verified empirically for all three occurrences with REMEMBER_DEBUG=0. Do not re-litigate it.

    5. Environment facts, verified on the target machine

    • flock: absent — not on PATH, no /usr/bin/flock. CI's macos-latest has no brew install util-linux step either.
    • mkdir: atomic — second mkdir of an existing path fails, as required.
    • python3 + fcntl.flock: importable, but see trap 2.

    6. Why this is worth doing properly

    Every failure mode here is a silent one. Two holders means two Haiku calls and two position writes; a missed cycle means a save that never happens. Neither surfaces as an error — the symptom is memory that quietly stops being right, which is the failure class this entire repo exists to eliminate. #181 was green, tested, and wrong. Budget accordingly.

  2. added 2 commits that reference this issue on Oct 5, 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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions