Repository navigation
Description
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:
- The verify is a snapshot, not a lock. After a process verifies and sets
HAVE_LOCK=trueit never re-checks. A later contender'srm -f+ recreate clobbers that winner's lock mid-flight. cleanup()gates on theHAVE_LOCKflag alone, never on whetherLOCK_FILEstill 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
fiTwo 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
fdaviddpt commentedon Jul 26, 2026
Design brief — one primitive, two call sites
Scoping note before the design: this should not be fixed in isolation. #173 (
now.mdwriters need serialising) needs the same primitive for the same reason — noflockon macOS. Landing them separately gives this repo three lock implementations:save.lock's noclobber pidfile, a newnow.lockspinner, 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:Acquisition is
mkdir.mkdireither 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 -ffollowed 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>/pidfor liveness checks.Stale takeover is
mv, neverrm. Whenmkdirfails and<lock_dir>/pidnames a dead process: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 withrm -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_releaseverify<lock_dir>/pidmatches$$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 wholenoclobberblock plus the takeover branch.HAVE_LOCKand the content-verify logic both disappear: ownership stops being something to track and check, and becomes something the primitive guarantees.cleanup()callslock_release.scripts/lib-now-lock.sh(from #173) — replaceflock -w "$_timeout" 9withlock_acquire. Everything else in that PR is sound and should be kept: the bounds guard innow_truncate_first, the sibling-temp-file + atomicmv, 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-haikuper 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
python3 -cwithfcntl.flockdoes not work as aflocksubstitute. 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.LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null)needs|| true. Plain top-level assignment, so underset -eits status iscat'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.[ "${REMEMBER_DEBUG:-1}" = "1" ] && log ...beforeexit 0is NOT aset -ehazard. Bash exempts a short-circuited final member of an&&list. Verified empirically for all three occurrences withREMEMBER_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'smacos-latesthas nobrew install util-linuxstep either.mkdir: atomic — secondmkdirof 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.
Merge main into lock primitive branch
fix(lock): save.lock was not a lock — one mkdir primitive for all thr…
fix(tests): assert the adopt race on _lock_try_adopt, not on lock_acq…
refactor(#898): retire two pre-v0.13 upgrade steps on the session-sta…
test(#898): hold save.lock in its directory form in the tmpdir-cleanu…