dirlock: make the stale-lock takeover safe against other contenders
Summary
Make the replacement of a stale directory lock safe against other
contenders, so that two processes that observe the same stale lock can
no longer both end up inside the critical section. This is what let two
CompareAndSwap calls on one record both succeed (#3176).
Before: both contenders Stat the stale lock. The first removes it and
creates its own lock; the second then renames away that fresh lock (the
rename acts on the path, not on the directory that was observed) and
creates yet another one.
After: a contender that sees a stale lock must first create a claim
directory named after the identity of that stale lock
(.dagu_lock.takeover.<hash>). Only the creator proceeds; the others
get ErrLockConflict and see the winner's lock on their next attempt.
The winner re-checks, while holding the claim, that the lock at the path
is still the stale one it observed, and only then removes it, creates
its own lock and drops the claim. This gives one winner among the
contenders that take over a stale lock. Races involving the previous
owner (release, heartbeat) remain detection-based through the fence
token; they are narrowed, not closed (see "Not covered").
The public API (DirLock, New, LockOptions) is unchanged.
Changes
One commit per step; each builds and passes the tests of the touched
packages on its own.
dirlock: split the stale-lock takeover into its own function: pure
refactor (takeOverStaleLock,createLock) plus an unexported hook
that runs after a stale lock was observed, for tests. No behaviour
change.dirlock: claim a stale lock before taking it over: the claim
directory, re-verification under the claim, and a check after the
rename that the moved directory is the observed one (put back
otherwise). The claim name is reserved:IsLockDirectoryNamecovers
it, so the directory scanners that skip lock metadata skip it too.dirlock: expire a takeover claim left by a crashed process: a claim
older than the stale threshold is treated as abandoned and removed, so
a crash during a takeover does not block that lock forever. A
successful takeover also sweeps the other abandoned claims next to the
lock.dirlock: remove only our own lock on unlock:Unlockused to check
the token and then rename the lock away; a takeover in between made it
remove the new holder's lock. It now renames the directory aside,
verifies that it still carries its own token and puts it back
otherwise, returningErrLockNotHeld.file: check the record lock before a compare-and-write:
CompareAndSwapandCompareAndDeleteverifyIsHeldByMeright
before the write they protect. A lost lock now surfaces as an error
for that call (wrappingdirlock.ErrLockNotHeld) instead of a silent
late write. It is deliberately notpersis.ErrConflict: callers treat
a conflict as "the record changed" (for example the dispatch store
drops the pending entry), but nothing was written, so the call simply
fails and can be retried. The check and the write are not atomic, so
this only narrows the window.Put,Create,Deleteand
RemoveCorruptare not changed.
Tests (in dirlock_test.go, and collection_lock_test.go for the
record-lock tests, which need package-internal access): a deterministic
reproduction of the slow second contender, a concurrency stress (several
lock instances on one stale directory, at most one holder at a time), a
fresh claim blocks takeover, an abandoned claim does not, the claim is
released on the conflict path, a lock replaced after it was observed is
not renamed, put-back of an unexpected directory, Unlock after a
takeover leaves the new lock alone, reserved names, and the lost-lock
(ErrLockNotHeld, not ErrConflict) cases for CompareAndSwap/CompareAndDelete.
Related Issues
Fixes #3176
Checklist
- Code follows the project style guidelines
- Self-review of the code has been performed
- Tests have been added or updated as needed
- Documentation has been updated as needed (no user-facing docs
describe this behaviour; comments explain the new protocol) - Changes have been tested locally
Testing
gofmt -l,go fix -embedlit=false -diff ./...: no outputgo vetandGOOS=windows go veton./internal/cmn/dirlock/,
./internal/persis/...: cleango test -raceon./internal/cmn/dirlock/...,./internal/persis/...,
./internal/cmn/fileutil/...: pass. The only failure is
TestTryLoadForDay_StaleIndex_NewAttemptindagrunindex, which is
unrelated to this change and fails intermittently on its own.- New tests with
-race -count=20 -cpu 1,4: stable (the stress test
takes about 0.6 s per run) go test -p 4on./internal/cmd/...,./internal/service/scheduler/...,
./internal/runtime/workspacebundle/...,./internal/service/chatbridge/...,
./internal/service/coordinator/...,./internal/cmn/replaycache/...: pass- The reproduction test and the stress test fail on the code before the
fix (the second contender acquires while the first still reports
holding the lock) and pass after it. TheUnlock, claim-verification
and lost-lock tests each fail when the corresponding change is
reverted.
Not covered
- Staleness is still based on the lock directory's modification time;
this PR does not change that. Behaviour under clock skew or on network
file systems was not tested. - Only contenders that take over a stale lock are serialized. Races that
involve the previous owner stay detection-based and are narrowed, not
closed: the owner may release, or heartbeat, between a takeover's
checks and its rename, andUnlockand the takeover both rename a
directory aside before they can look at it. A directory that turns out
not to be the expected one is renamed back on a best-effort basis.
renamereplaces an empty directory at the target and fails on a
non-empty one, so in that window a lock can be lost or held by two
processes, and a fresh lock can be left without an owner file (it
clears once it is older than the stale threshold). The fence token
lets a displaced holder notice the loss, andCompareAndSwap/
CompareAndDeletenow check it before writing. - Removing an abandoned claim has the same caveat when several
contenders race on the same abandoned claim. - A claim left by a crashed process delays the takeover of that lock by
up to the stale threshold. A crash between creating the new lock and
removing the claim leaves an empty claim directory behind; scanners
skip it, and the next successful takeover next to it removes it once
it is older than the stale threshold. - The check in
CompareAndSwap/CompareAndDeleteis a check followed
by a write, not an atomic operation. - Windows: only
go vetforGOOS=windowswas run, not the tests.