Skip to content

fix(save): make the stale-lock takeover atomic - #181

Closed
fdaviddpt wants to merge 1 commit into
mainfrom
fix/stale-lock-takeover-race
Closed

fdaviddpt wants to merge 1 commit into
mainfrom
fix/stale-lock-takeover-race

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Follow-up to #168, which closed one half of the lock-ownership problem and left the other open.

The bug

The stale-lock takeover branch was a plain overwrite with no compare-and-swap:

log "lock" "stale lock (PID $LOCK_PID dead), taking over"
echo $$ > "$LOCK_FILE"
HAVE_LOCK=true

Two processes that both observe the same dead PID both take over, both set HAVE_LOCK, and both proceed — two concurrent saves, two Haiku calls, two position writes. That is the corruption #168's own description names, reached by the stale path rather than the contention path.

Reproduced with two real processes against a pre-seeded dead-PID lock in 4 of 5 runs.

The fix

Unlink, re-create under noclobber so only one contender can create the file (the loser skips this cycle), then re-read and stand down unless it holds our own PID. Whoever writes last wins, everyone else exits. Never two holders.

Not a true CAS, and the code says so. Between the verify and the first real work another takeover could still clobber the file — microseconds wide, confined to this branch. mkdir has real atomic-create semantics and is the honest long-term fix, but it changes the lock representation, so it is not this PR. Worth its own issue.

Second defect, found while testing

LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null) is a plain top-level assignment, so under set -e its exit status is cat's — and the lock file can be gone by the time it is read. Pre-existing, but this PR's own rm -f makes the window easy to hit: the loser exited 1 with an ERR-trap log in ~2 of 12 runs where it should have skipped cleanly with 0.

It never let a second process through (HAVE_LOCK is not yet set, so cleanup() is a no-op on the lock), but it turned a normal outcome into a logged failure. Guarded with || true.

Verification

  • Test spawns two real save-session.sh processes against a dead-PID lock, 8 iterations per run, asserting at most one runs extract/call-haiku.
  • Revert-proved: restore the three pre-fix lines and it fails at iteration 0 — both processes proceeded past the stale lock takeover (extract ran 2 times), with both call logs showing the full pipeline.
  • 5 consecutive runs green (40 race iterations) with strict exit-code assertions restored after the || true guard.
  • ~100+ race iterations during investigation, never a double winner.

Checked and cleared

[ "${REMEMBER_DEBUG:-1}" = "1" ] && log ... immediately before exit 0 looked like a set -e hazard. It is not — bash exempts a short-circuited final member of an && list. Verified empirically for all three occurrences with REMEMBER_DEBUG=0.

Co-Authored-By: Max

#168 stopped a non-owner deleting the lock, but left the other half open. The
takeover branch was a plain overwrite:

    log "lock" "stale lock (PID $LOCK_PID dead), taking over"
    echo $$ > "$LOCK_FILE"
    HAVE_LOCK=true

Two processes that both observe the same dead PID both take over, both set
HAVE_LOCK, and both proceed — two concurrent saves, two Haiku calls, two
position writes. That is the corruption #168's description names, reached by
the stale path instead of the contention path. Reproduced with two real
processes against a pre-seeded dead-PID lock in 4 of 5 runs.

Now: unlink, re-create under noclobber so only one contender can make the file,
then re-read and stand down unless it holds our own PID. Whoever writes last
wins and everyone else exits. Never two holders.

Not a true compare-and-swap — between the verify and the first real work
another takeover could still clobber the file. That window is microseconds and
confined to this branch. mkdir would give real atomic-create semantics and is
the honest long-term fix; it changes the lock representation, so it is not
this commit.

Also guards `LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null)` with `|| true`. It is a
plain top-level assignment, so under set -e its status is cat's, and the lock
file can be gone by the time it is read. Pre-existing, but the new `rm -f`
makes the window easy to hit: the loser exited 1 with an ERR-trap log in ~2 of
12 runs where it should have skipped cleanly with 0. Never let a second process
through — HAVE_LOCK is not yet set, so cleanup() is a no-op — but it turned a
normal outcome into a logged failure.

Test spawns two real processes against a dead-PID lock, 8 iterations, and
asserts at most one runs extract/call-haiku. Reverted, it fails at iteration 0
with both processes extracting. 5 consecutive runs green (40 iterations) with
strict exit-code assertions.

Co-Authored-By: Max <noreply>
@fdaviddpt

Copy link
Copy Markdown
Contributor Author

Correcting this PR: the central claim in the description is false. Adversarial review disproved it empirically.

I wrote "whoever writes last wins and everyone else exits — never two holders." That holds for exactly two contenders, which is all my test exercises. Beyond that it breaks:

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

The verify step ([ "$(cat "$LOCK_FILE")" != "$$" ] && exit 0) is a one-time snapshot, not a held lock. Once a process passes it and sets HAVE_LOCK=true, it never re-checks — so a later contender's rm -f + recreate clobbers an already-verified winner's lock while it is still mid-flight.

Worse, and I missed it entirely: cleanup() gates on the HAVE_LOCK boolean alone, never on whether LOCK_FILE still contains its own PID. A displaced winner therefore deletes whatever is currently there on exit — including the lock of a process that legitimately acquired it afterwards. That is exactly the "non-owner deletes the lock" bug #168 fixed, reintroduced through the path I added.

And >2 concurrent invocations is not a contrived load here: PostToolUse fires per tool call, and batching several tool calls per turn is normal in this product.

Closing this rather than patching it. The approach is wrong at the root: rm -f followed by create is not atomic and cannot be made atomic by adding verification after it. Any fix built on that sequence is a narrower window, not a lock.

The real fix uses primitives that actually are atomic:

  • mkdir for acquisition — succeeds for exactly one process, fails for all others
  • mv (rename) to break a stale lock — two processes both attempting to rename the same directory means exactly one succeeds and the loser gets ENOENT, so the takeover itself becomes single-winner

That changes the lock representation, so it belongs in its own change with its own tests at N=2, 4, 8 and 10 — the concurrency levels that exposed this.

The || true guard on LOCK_PID=$(cat ...) is a genuine independent fix and I will carry it forward. Note for whoever picks that up: reverting it is caught by the existing test only ~25% of the runs, so it needs its own deterministic test rather than relying on race timing.

Thanks to the review for pushing past the two-process case. I would have shipped this.

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.

1 participant