file: check the record lock before a compare-and-write
Summary
CompareAndSwap and CompareAndDelete in the file backend read a record, compare it and write it under a per-record directory lock, but never check afterwards that they still hold that lock. #3185 made the stale-lock takeover safe against other contenders (#3176). This adds the follow-up that the maintainer asked for there: a re-check right before the write.
Changes
withDirLockpasses its callback a check built onIsHeldByMe.CompareAndSwapandCompareAndDeletecall it right before the write or removal they protect (withHeldRecordLock, a thin wrapper that leaves the other callers ofwithRecordLockunchanged).- A lost lock fails the call with an error wrapping
dirlock.ErrLockNotHeld. It is deliberately notpersis.ErrConflict: nothing was written, and callers (for example the dispatch store) treat a conflict as "the record changed" and drop the entry from their index, which would lose a task that is still pending. - The check followed by the write is not atomic, so this narrows the window in which a lost lock goes unnoticed; it does not close it. The takeover in
dirlockis what keeps contenders apart.
Tests
TestCollection_LostLock: the lock directory is replaced by one held by another owner just before the check;CompareAndSwapandCompareAndDeletefail withErrLockNotHeld, notErrConflict, and the record is unchanged. It fails when the check is disabled.TestCollection_HeldLock: with the lock held, the write goes through and the check runs once.
Checked with go test -race on ./internal/persis/... and ./internal/cmn/dirlock/, go vet and GOOS=windows go vet on internal/persis/file, gofmt, and go fix -embedlit=false -diff. Windows tests were not run, only vet.
Related Issues
Checklist
- Code follows the project style guidelines
- Self-review of the code has been performed
- Tests have been added or updated as needed
- Changes have been tested locally
Summary by cubic
Makes CompareAndSwap and CompareAndDelete in the file backend verify they still hold the per-record lock right before writing, so a lock taken over by stale-lock recovery no longer lets them overwrite or delete a record owned by another process.
- A lost lock fails the call with an error wrapping
dirlock.ErrLockNotHeldinstead of writing; the error is deliberately notpersis.ErrConflict, since nothing was written and callers treat conflicts as "the record changed". - Adds tests for lost and held locks. The check narrows but does not close the window, because the check and the write are not atomic.
Summary by CodeRabbit
- Bug Fixes
- Compare-and-swap and compare-and-delete now verify that the directory lock is still held before changing a record. If the lock has been lost, the operation reports a lock error and leaves the record unchanged or in place, rather than proceeding based on an outdated lock state.