dirlock: let only one contender take over a stale lock
Fixes #3176
Note: #3182 by @SCcagg5 also addresses this issue, with a separate takeover-claim directory. I had already finished this one when I saw it, so I'm offering it as an alternative with a different design. The cases it tests explicitly are listed under "Compared with #3182" below; I haven't checked whether #3182 handles them too. Please pick whichever fits better. I'm happy to close this one, or to help review #3182 with the test harness described below.
Problem
TryLock recovered a stale lock by stat-ing it, renaming whatever was at .dagu_lock away, and creating a new one. Nothing tied the removal to the lock it had judged stale. If another contender removed the stale lock and created a fresh one in between, the slower contender renamed away the fresh lock and took the lock as well, so both entered the critical section. withDirLock doesn't check the fence token, so two CompareAndSwap calls on one record could both succeed.
Approach
The removal is now tied to one specific lock instance through a rename only one contender can win.
- Unique owner file. Each lock holds
owner.<id>(the fence token) instead ofowner. New locks are created with an exclusivemkdirof.dagu_lock, the same primitive older releases use, on every platform and filesystem. The directory is empty untilowner.<id>is written, so stale-lock recovery may remove it in that window and the owner file may land in another contender's directory. The creator therefore lists the directory after writing and holds the lock only if it finds its own owner file and no other owner or claim marker; otherwise it removes its file and returnsErrLockConflict. - Claim before removal. To take over a stale lock, a contender lists it, re-checks that it's stale, then renames that lock's own
owner.<id>toclaimed.<myid>. Only one contender can win that rename. If the lock was already removed or replaced, the rename fails with "not found" and the contender getsErrLockConflict. - Release by name, no directory move. The claimer removes the claimed lock's entries by the names it listed (they're unique per instance, so a newer lock at the same path is never touched), removes its claim file, and finally removes
.dagu_lockonly if it's empty ("not empty" or "not found" count as success). There is no move-and-put-back step, so a claimer that stalls past the stale threshold can't knock out a newer holder. - Unlock claims its own owner file the same way. If it's missing, the lock was taken over: it returns
ErrLockNotHeldand touches nothing. - Other layouts: an empty stale directory is removed with
rmdir, which fails on a held lock because a held lock always contains its owner file. A legacyownerfile and leftoverclaimed.*files are claimed by renaming them too. A directory with only unknown files is claimed by an exclusive create plus a re-list, backing off if another marker appears. - macOS: the claim rename can return
EINVALwhen another process is moving the directory at that moment. That is mapped toErrLockConflict(andErrLockNotHeldinUnlock), soLock()retries instead of failing. - Cleanup: after a successful takeover,
.dagu_lock.releasing.*siblings older than the stale threshold are removed.
The public API (DirLock, New, LockOptions) is unchanged. I didn't add a fence re-check in withDirLock: a check before the write would still be check-then-act, and with an atomic takeover it adds no real safety.
Maintainer changes
Pushed on top of the contributor's commits:
afef74cCreate locks with an exclusivemkdir. Older releases create.dagu_lockempty and writeownerafterwards. The rename-based install (d37cba1,ca14df0) replaced such an empty directory wherever no-replace renames are unavailable (NFS, platforms other than Linux and macOS), so an old and a new binary could both hold the lock with no stale lock involved. That state is normal betweendagu upgradeand the next restart, because the running scheduler launches runs with the upgraded binary. Exclusivemkdiris atomic everywhere, including NFS, and needs no platform code. A multi-process test (12 processes, shared counter, no stale locks) lost 1626 updates with mixed old and new binaries on781300aand 0 now.30f1c87Delete read-only entries in place; never rename a claimed lock directory. Releasing deletes the claimed directory's entries in place. When permissions block that, it now gives the owner write access to the stuck directories and files (scoped to the lock directory withos.Root) and retries, so a read-only entry no longer blocks the lock. An entry that still cannot be deleted (for example an immutable file) is reported byTryLockwith its path and keeps the lock occupied until someone removes it.0723ff8instead moved the directory aside, but that move goes by path: a claimer pausing past the stale threshold between its claim check and the move could rename away a newer holder's lock.0e8d130,802bd27Restore owner access before unlocking. Unlock renames its owner file inside the lock directory, lists it and removes it, so a held lock whose directory lost owner access (modes 0000, 0300, 0500, or the read-only attribute on Windows) stayed locked until stale. Unlock now restores owner access once before releasing (onelstat, and achmodonly when needed). Unlock remains about 19% faster thanmain.6d306fbRestore owner access before a takeover. Taking over lists and renames entries inside the lock directory, whichmain's rename within the parent did not need. A lock directory that lost owner access (for example modes 0300 or 0500 after a restore) blocked recovery, including scheduler startup and failover. A takeover now gives the owner full access back first, throughos.Rooton the target directory.73ca337Sweep before creating the taken-over lock. The sweep ran after the new lock was created, so a slow sweep ate into its lease; past the stale threshold another contender could take the lock over whileTryLockstill reported success.d3a05eeRemove the lock directory when its owner write fails. A failure before the owner file existed (for example a permission error) left an empty lock directory that blocked everyone until it went stale.07d1680Sweep temporary directories only after a stale takeover. Reverts the per-acquire sweep from781300a. It listed the target directory on every acquire.
Lock plus unlock, median of 8 interleaved runs against main: macOS (APFS) 300 µs vs 325 µs (−8%), Linux (ext4) 64 µs vs 68 µs (−5%). Acquire alone is about +15% (~17 µs) on macOS because of the listing that makes mkdir creation safe, and unchanged on Linux; release is 15–20% faster on both. Allocations are about +1 KB (+4) per cycle. Windows and network filesystems were not benchmarked. The rename-based install was +18% overall on macOS.
Not changed here: an EINVAL guard in Unlock (not reproduced in about 7,200 contended cycles), recovery of stale locks owned by another Unix user, and a fence check before compare-and-swap writes (follow-up).
Tests
The stale-takeover tests are table-driven over the stale-lock layouts (abandoned holder, empty directory, legacy owner file, and junk-only where it applies). Three unexported test hooks (beforeStaleClaim, afterClaim, beforeOwnerWrite) make the interleavings deterministic.
| Test | What it checks | On the old code |
|---|---|---|
TestStaleTakeover_InterleavedContenders | Contender 2's hook runs contender 1's full TryLock between 2's stale check and its claim; 1 must keep the lock, 2 must get ErrLockConflict | fails: 2 takes over 1's fresh lock |
TestStaleTakeover_ManyContenders | 16 goroutines × 20 rounds per layout, random 0–2 ms gaps; exactly one winner (at most one for an empty directory, after which the lock is free), every loser gets ErrLockConflict | fails: 6–11 winners |
TestStaleTakeover_StalledClaimer | A claimer stalls after claiming, the lock is taken over and re-created; the stalled one must not touch the new lock (TryLock and Unlock paths) | fails |
TestStaleTakeover_SingleContender | Every stale layout can be taken over; no temp dirs left | — |
TestUnlock_AfterStaleTakeover | After a takeover, the old holder's Unlock / Heartbeat / IsHeldByMe don't disturb the new holder | regression guard |
TestIsLostClaimError | ENOENT and EINVAL count as a lost claim; EACCES and others don't | fails on EINVAL |
TestStaleTakeover_CleansAbandonedTempDirs | Old releasing dirs are removed; fresh ones and unrelated dirs are kept | fails |
TestTryLock_LegacyContenders | Current instances and an emulation of the previous release (Mkdir, then write owner) contend for a fresh lock; no update to a shared counter may be lost | fails on 781300a (9/10 runs), and with the os.Rename fallback of d37cba1 |
TestUnlock_RestrictedLockDir | A held lock's directory is set to 0000, 0300 or 0500; Unlock still releases it and the next contender acquires at once | fails on 6d306fb; 0300 and 0500 pass on main |
TestStaleTakeover_RestrictedLockDir | A stale lock directory with mode 0000, 0300 or 0500 is taken over | fails on d3a05ee, passes on main |
TestStaleTakeover_SlowSweep | A takeover's sweep takes longer than the stale threshold; right after TryLock returns, a second contender still gets ErrLockConflict | fails on 30f1c87 |
TestCreateLock_OwnerWriteFails | Writing the owner file is denied; once that is fixed, the next attempt acquires the lock at once | fails on 30f1c87 |
TestRelease_ReadOnlyEntry | A read-only entry sits in the lock directory; after Unlock or a stale takeover, the next contender still acquires the lock | fails on afef74c |
TestCreateLock_Contested | Before the owner file is written, the new directory is removed, replaced by another contender's lock, or claimed; TryLock reports a conflict and leaves the other contender's files alone | new behavior |
Changed existing test: TestNotificationMonitor_LockTheftSelfFencesActiveOwner (chatbridge) faked a theft by overwriting .dagu_lock/owner. The new layout reads owner.<id>, so that overwrite no longer counted as a theft. The test now replaces the whole lock directory, the way TestScheduler_SelfFencesOnOwnershipLoss already does. What it asserts is unchanged: the monitor notices the theft, self-fences, and stops its session.
Multi-process check (not part of the PR): a small harness started 16 real OS processes per round, all calling TryLock on one stale .dagu_lock (aged 60 s) at the same moment, on macOS. In "try" mode exactly one must hold the lock and the other 15 must get ErrLockConflict. In "cas" mode each does Lock → read counter → write counter+1 → Unlock, and the final counter must equal 16.
- Old code: about half the rounds had two winners, and "cas" lost updates.
- This branch: 200 rounds per layout per mode (19,200 process runs), 0 bad rounds, 0 errors other than
ErrLockConflict, and no leftover temp directories. Also clean with CPU-burner load running alongside.
Validation
go build ./... # ok
go vet ./internal/cmn/dirlock/ ./internal/service/chatbridge/ # ok
GOOS=windows go vet ./internal/cmn/dirlock/ # ok
./.local/bin/golangci-lint run ./internal/cmn/dirlock/... ./internal/service/chatbridge/... # 0 issues
go test -race -count=50 ./internal/cmn/dirlock/ # ok
go test -race -count=2 ./internal/cmn/dirlock/... ./internal/persis/file/... # ok
go test -race -count=5 ./internal/service/chatbridge/ # ok
Every other package that imports dirlock passes too (scheduler, coordinator, notification, replaycache, workspacebundle, frontend/api/v1, internal/cmd, and others). I couldn't run the tests on a real Windows machine.
Compared with #3182
Both designs give a single winner among contenders taking over the same stale lock. Cases this branch tests explicitly, in case they're useful for either PR:
- Stalled claimer. A contender that claims a stale lock and then stalls past the threshold, while the lock is taken over and re-created, can't remove or move the newer lock, because release goes by name and never moves the directory (
TestStaleTakeover_StalledClaimer). - Unlock races. Unlock uses the same claim, so an old holder whose lock was taken over can't delete the new holder's lock (
TestUnlock_AfterStaleTakeover). - macOS EINVAL. Under real multi-process contention on APFS, a rename inside a directory being moved by another process sometimes returns
EINVAL. Without mapping it, about 4% of contended rounds made a loser'sLock()fail outright instead of retrying.
Known limits (not changed here)
- Heartbeat isn't tied to the claim (existed before this change): a contender that judged a lock stale and then stalls can still claim it after the holder heartbeats, because Heartbeat only updates the time. Renaming the owner file to a new generation on each heartbeat would close this; it seemed better as a follow-up.
- Mixed versions (between an in-place upgrade and the next restart): acquiring a free lock is exclusive between old and new binaries, because both create the lock directory with an exclusive
mkdir. An old binary's own stale takeover keeps its old race, since it renames the lock directory away without a claim. New code can still take over old-format stale locks. - Stale locks left by another Unix user: taking one over needs access inside the lock directory, not only write access to the parent. Directories this user owns get their owner access restored first; another user's cannot be recovered without moving the directory by path, which this design avoids.
- An entry that cannot be deleted (immutable, or owned by another user): the release fails with an error naming it, and the lock stays occupied until someone removes it. Older releases silently moved the directory aside, which this design avoids because a move by path can displace a newer holder.
- A directory with only unknown files, or an empty one: contenders arriving at the same moment can all back off, which is safe but means that round has no winner. For an empty directory, each contender that removes it may remove another's new lock directory before its owner file lands; the next attempt finds the lock free.
Checklist
- The smallest relevant test or validation command passes
-
make lintpasses for Go changes when practical (rangolangci-linton the touched packages) - New code includes tests when behavior changes
- Documentation updated if applicable (no user-facing docs affected)
- Commit messages follow the Go Commit Message Guidelines
Summary by cubic
Fixes a race in dirlock's stale-lock takeover that could let two contenders both take a stale lock and enter the critical section; the public API is unchanged.
Each lock now has a unique owner file (owner.<id>), and a takeover must rename that file — a rename only one contender can win, so losers get ErrLockConflict instead of the fresh lock.
Details
- Locks are created with an exclusive
mkdirof.dagu_lock, so a fresh acquire never replaces another contender's lock, even against older binaries. - A stale lock is released by deleting its listed entries by name and removing the directory only if empty, so a claimer that stalls can't knock out a newer holder.
Unlockclaims its own owner file and returnsErrLockNotHeldwithout touching anything when the lock was taken over.- macOS
EINVALfrom a claim rename is mapped toErrLockConflict(andErrLockNotHeldinUnlock) soLock()retries. - A takeover sweeps abandoned
releasing.*temp dirs older than the stale threshold before creating the new lock, so the sweep doesn't eat into its lease. - A failed owner write removes the empty lock directory instead of leaving it blocking contenders until it goes stale.
- Takeovers restore the owner's access to a lock directory that lost permissions, and deleting a read-only entry is retried after granting write access, so a single stuck entry no longer blocks the lock.
Unlockrestores the lock directory's owner access before releasing, so even a lock with no owner access at all can be released.- The chatbridge lock-theft test now replaces the whole lock directory, since overwriting
ownerno longer counts as theft. - New tests cover interleaved contenders, 16-contender races, stalled claimers, restricted lock dirs, read-only entries, and abandoned-temp-dir cleanup.
Rolling upgrade: old binaries still write the legacy owner file and take over stale locks by path, so stop old processes before upgrading to avoid the old race between mixed versions.
Summary by CodeRabbit
- Bug Fixes
- Improved lock recovery when a lock is stale or abandoned, including cases where multiple processes attempt to claim it at the same time.
- Prevented an old lock holder from releasing a replacement lock and ensured active owners detect when their lock has been taken over.
- Cleaned up old temporary lock directories during stale-lock recovery while preserving recent and unrelated entries.