Skip to content

fix(save): only unlink save.lock when this process actually owns it - #168

Merged
fdaviddpt merged 1 commit into
Digital-Process-Tools:mainfrom
Jutiphan:fix/lock-file-ownership
Jul 26, 2026
Merged

fdaviddpt merged 1 commit into
Digital-Process-Tools:mainfrom
Jutiphan:fix/lock-file-ownership

Conversation

@Jutiphan

Copy link
Copy Markdown
Contributor

The bug

scripts/save-session.sh installs trap cleanup EXIT before it attempts
to acquire save.lock, and cleanup() unlinks $LOCK_FILE unconditionally:

cleanup() { rm -f "$LOCK_FILE" "${CLEANUP_FILES[@]}"; }
trap cleanup EXIT

# --- Lock (atomic via noclobber) ---
if ! ( set -o noclobber; echo $$ > "$LOCK_FILE" ) 2>/dev/null; then
    LOCK_PID=$(cat "$LOCK_FILE" 2>/dev/null)
    if kill -0 "$LOCK_PID" 2>/dev/null; then
        [ "${REMEMBER_DEBUG:-1}" = "1" ] && log "lock" "locked by PID $LOCK_PID, skipping"
        exit 0
    fi
    ...

The trap is already armed when a process discovers another live PID holds
the lock and exits 0 to skip — so that exit also runs cleanup(), which
deletes $LOCK_FILE even though this process never held it. The file it
just deleted belongs to the still-running holder.

A third process racing in immediately afterward finds no lock file at all
(the noclobber write succeeds cleanly), acquires it, and now runs
concurrently with the original holder: two live save-session.sh
processes, two Haiku calls against overlapping transcript spans, two
save-position writes racing each other.

Why it matters

Many concurrent sessions/lanes sharing one REMEMBER_DIR is routine
(several worktree lanes, or two accounts, writing to the same project).
save.lock is the single serialization point the rest of the pipeline
(extraction, prompt-building, the Haiku call, position writes) all assume
is exclusive; this bug defeats it under three or more concurrent
invocations.

Reproduction

Three real processes, same REMEMBER_DIR:

  1. P1 starts, acquires save.lock, and is mid-extraction (slow).
  2. P2 starts while P1 holds the lock, sees it, logs "locked by PID …,
    skipping", and exits 0.
  3. Before this fix: P2's exit runs cleanup(), which deletes save.lock
    — even though P1 (PID recorded in the file) is still running.
  4. P3 starts right after P2 exits: finds no lock file, acquires cleanly,
    and now runs concurrently with P1.

The fix

A HAVE_LOCK flag, false by default, set to true on both paths
that actually take ownership of the lock — the fresh noclobber write,
and the stale-lock takeover (dead PID) — and never set on the skip path.
cleanup() only unlinks $LOCK_FILE when HAVE_LOCK is true. Temp-file
cleanup (${CLEANUP_FILES[@]}) stays unconditional — only the lock file's
removal is now ownership-gated.

Test evidence

New file: tests/test_save_session_lock_ownership.py, three real
subprocesses.

Before (unpatched main, HEAD d9480ec):

FAILED tests/test_save_session_lock_ownership.py::TestLockOwnership::test_skip_path_does_not_delete_holders_lock_file
AssertionError: P2's skip-path cleanup deleted the lock file entirely — P1 is still running and now unprotected
1 failed in 0.72s

After (patched):

1 passed in 4.00s

Regression suite

This machine has no jq, so main's baseline already has ~38
jq-dependent failures unrelated to this change (see PR "jq-free config
fallback" for detail). Judging by delta, not absolute count:

  • Baseline (main, HEAD d9480ec): 38 failed, 625 passed, 58 skipped
  • Patched: 38 failed, 626 passed, 58 skipped (identical pre-existing
    failures, +1 pass for this patch's new test)

Backward compatibility

None needed — single-process behavior (the overwhelming common case) is
unchanged; only the three-or-more-concurrent-process interleaving
changes, and only by no longer corrupting it.


This PR is independent of the other four bug-fix PRs I'm submitting
alongside it and can be reviewed/merged in any order.

save-session.sh installs `trap cleanup EXIT` before it attempts to
acquire save.lock, and cleanup() unlinked $LOCK_FILE unconditionally.
A process that discovers another live PID holds the lock exits 0 to
skip — but that exit runs the same trap, deleting the still-running
holder's lock file. A third process racing in right after finds no
lock at all, acquires cleanly, and now runs concurrently with the
original holder: two live save-session.sh processes, two Haiku calls
against overlapping transcript spans, two save-position writes racing
each other.

Fix: a HAVE_LOCK flag, set true on both paths that actually take
ownership (fresh noclobber write, stale-lock takeover), never set on
the skip path. cleanup() only unlinks the lock file when HAVE_LOCK is
true; temp-file cleanup stays unconditional.

New test: tests/test_save_session_lock_ownership.py drives three real
subprocesses (holder, skipper, racer) and asserts the lock file
survives the skipper's exit and still names the holder.
@fdaviddpt
fdaviddpt merged commit b61acfc into Digital-Process-Tools:main Jul 26, 2026
fdaviddpt added a commit that referenced this pull request Aug 5, 2026
test_skip_path_does_not_delete_holders_lock_file asserted that P1's
save.lock survived P2's skip, on the stated grounds that P1 was still
running — and nothing established that. P1 held the lock for a fixed
STUB_EXTRACT_SLEEP=3.0; when that window closed before P2 finished, P1
released the lock correctly and the assertion fired accusing P2 of a
teardown it never performed. One leg of twelve, macos-3.11.

The test had two outcomes where it needed three. An absent lock has an
innocent reading and a guilty one that produce the identical filesystem
state; only P1's liveness separates them. "P1 had already exited" is
neither a pass nor a failure, and now reports itself as inconclusive via
pytest.skip(... COVERAGE LOST ...) — the #293 idiom from
tests/test_lock_primitive.py.

The timing dependency is removed rather than widened. P1 now blocks in
its stub extract on a release file the test creates, so its hold covers
P2 and P3 by construction; the stub keeps a 60s cap. All environments
are built before P1 starts — each _make_env rewrote the same ten scripts
and the session jsonl into the tree P1 was executing from, which was
both a hazard and most of the work that had to fit in the window.

The gate is consulted only on the ambiguous branch: a lock still present
is unambiguous. A bare poll() would not have sufficed there either — it
reads None throughout save-session.sh's EXIT trap — so liveness is
believed only after a 2s grace, paid solely when about to fail or skip.

The P3 half rested on the identical unstated premise and got the same
treatment. Both inconclusive cases are now constructed deliberately by
new tests rather than waited for.

Verified: reverting #168 in cleanup() (unconditional rm -rf "$LOCK_DIR")
still fails with the accusation intact, so the invariant is not
weakened; disabling either liveness gate turns both new tests red with
exactly the #312 misattribution. No product change.
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.

2 participants