Repository navigation
Fixed - Lock watchdog stops renewing a hold retaken right after unlock #7455 - #7460
eatmoreduck wants to merge 3 commits into
Conversation
…redisson#7455 A renewal sent before an unlock can report the lock as gone after the same thread has taken it again. The result callback then cancels by lock name and thread id, which removes the new hold, so it is never renewed. Each acquire now registers its hold under a new id. A renewal result carries the ids it was computed for, and its callback cancels a registration only if that id is still the latest one of the thread. LockTask, ReadLockTask and FastMultilockTask cancel from a result in the same way and are all covered. Signed-off-by: yu.xia <[email protected]>
e84fb83 to
d0baec1
Compare
|
Rebased onto master (1d8129a). The conflict was in On the new base |
|
While I ran the lock suites on the rebased branch, The other failures I saw on the rebased branch are the |
mrniko
left a comment
There was a problem hiding this comment.
Thanks, for the suggested changes.
Could you use the id for the unlock as well? In that case every cancel names the registration it removes, not the thread.
Proposed change
- Give every acquire its own id and keep the ids per thread in
LockEntry(a list). It replaces boththreadId2counterandthreadId2registration; the hold count is the size of the list. - A renewal chunk records the ids of the thread, and a "gone" result removes exactly those ids.
unlockAsync(threadId)reads the newest id of the thread before it sends the script and passes it tocancelExpirationRenewal, which removes exactly that id.forceUnlockstill removes everything.- Take the ids from one counter in
LockRenewalScheduler.RedissonReadLock.cancelExpirationRenewalcancels in bothLockTaskandReadLockTask, so an id must not match in the other task.
Why
Removing by id is idempotent, which also fixes two cases the current version leaves open:
unlockAsync(threadId)followed bylockAsync(threadId)without waiting. A renewal result that arrives after the release, but before the unlock callback, removes the hold. The new lock registers, and then the unlock callback cancels by thread id and removes the new hold.- An unlock retried after
NoSyncedSlavesException.ServiceManager.executererunsunlockAsync0. The script is idempotent byrequestId, butcancelExpirationRenewalruns once per attempt, so a reentrant lock loses the renewal of its outer hold.
It has to be one id per acquire. If the unlock only passes the current "latest id" next to the counter, a late unlock is skipped and its hold stays counted, and case 2 still matches on the second cancel.
Tests for both cases in RenewalTaskTest would be welcome.
One registration id per acquire: LockEntry keeps the ids of a thread instead of a hold counter, so the holds of a thread are its ids and the reentrancy depth is their count. A renewal chunk records the ids, and a "gone" result removes exactly those. unlockAsync reads the newest id of the thread before it sends the script and cancels exactly that one, so a hold the thread takes after the release, and a retry of the unlock, cannot be canceled by a late or repeated cancel. Removing by id is idempotent, which also covers an unlockAsync followed by a lockAsync without waiting, and an unlock retried after NoSyncedSlavesException. The ids come from one counter of LockRenewalScheduler, because a read lock cancels in the lock and in the read lock renewal task, so an id must not name a hold of the other task. forceUnlock still removes everything. RedissonFasterMultiLock inherits the unlock of the base class now and names its id too, its own copy was the same. Tests for both cases in RenewalTaskTest. With the removal by id reverted to a removal by thread, seven of the nine tests fail, both new ones among them. Signed-off-by: yu.xia <[email protected]>
|
Done in 0dc1275, following the proposed change.
The lock suites ran against Redis in Docker again: 144 of 150 pass, the five |
mrniko
left a comment
There was a problem hiding this comment.
Thanks for the rework.
A few things before merging.
1. An unlock that finds no registration should cancel nothing
unlockAsync reads the id before the script (RedissonBaseLock.java:180). When it is null, cancelExpirationRenewal falls back to the cancel by thread (:88-89), which removes the newest registration of the thread at the time the reply arrives.
The case that hits every time is a read lock with a lease inside a write-locked section:
rw.writeLock().lock();
rw.readLock().lock(2, TimeUnit.SECONDS);
rw.readLock().unlock();A lock with a lease is not registered, so the read unlock reads null and passes it to super (RedissonReadLock.java:163). The cancel by thread then removes the registration of the write lock in LockTask, and the write lock expires while it is held.
The other case is async: a renewal result already dropped the hold (the key expired), unlockAsync reads null, the caller locks again before the reply, and the reply removes the new hold.
2. Tests for the lock classes
All new tests call the task directly, so each of these changes would still pass them:
- reading the id in the reply handler instead of before the script
- a counter per task instead of the shared one
- recording no ids in
FastMultilockTask.buildChunk
Could you add:
RedissonReadWriteLockTest: write lock, read lock, read unlock, and the write lock is still renewed. Once with a plain read lock and once with a lease.RenewalTaskTest: an id of the read lock task cancels nothing in the lock task, throughLockRenewalScheduler.RenewalTaskTest: a fast multilock result still cancels a hold that is registered.- A test that
unlockAsyncreads the id before the script: hold a lock, callunlockAsync, register a second hold while the reply is pending, complete the reply, and the lock is still renewed.
Sketches for the first three (not compiled)
// RedissonReadWriteLockTest; the same again with rw.readLock().lock()
@Test
public void testReadUnlockWithLeaseKeepsWriteLockRenewal() {
RReadWriteLock rw = redisson.getReadWriteLock("lock");
rw.writeLock().lock();
// a lock with a lease is not registered, so its unlock has nothing to cancel
rw.readLock().lock(10, TimeUnit.SECONDS);
rw.readLock().unlock();
RedissonLock writeLock = (RedissonLock) rw.writeLock();
assertThat(writeLock.isExpirationRenewalScheduled(Thread.currentThread().getId())).isTrue();
rw.writeLock().unlock();
} // RenewalTaskTest
@Test
public void readLockIdNamesNoHoldOfTheLockTask() {
LockRenewalScheduler scheduler = new LockRenewalScheduler(executor);
scheduler.renewLock(NAME, THREAD_ID, "lock:1:write");
scheduler.renewReadLock(NAME, THREAD_ID, LOCK_NAME, NAME + ":{");
// what the unlock of a read lock does: its id is cancelled in both tasks
Long readId = scheduler.getReadLockRegistrationId(NAME, THREAD_ID);
scheduler.cancelLockRenewal(NAME, THREAD_ID, readId);
scheduler.cancelReadLockRenewal(NAME, THREAD_ID, readId);
assertThat(scheduler.isLockRenewed(NAME, THREAD_ID)).isTrue();
}
@Test
public void fastMultilockResultCancelsHoldThatIsStillRegistered() {
FastMultilockTask task = new FastMultilockTask(LEASE_TIME, executor, ids::incrementAndGet);
task.add(NAME, LOCK_NAME, THREAD_ID, Arrays.asList("lock:1:field"));
task.execute();
renewalReply.complete(false);
assertThat(task.name2entry).doesNotContainKey(NAME);
}3. cancelExpirationRenewal(Long, Boolean)
The unlock calls the three-argument method now, so an override of the two-argument one in a subclass is skipped on unlock without any error. Please make the two-argument method final.
4. Small things
LockEntry.removeThreadId has no caller left, and it now removes every hold of the thread instead of one. Please delete it.
An unlock that reads no registration must cancel nothing. Preserve the forceUnlock cleanup, make the two-argument cancel final, and remove the unused removal method and scheduler overload. Claim a separate registration for each overlapping unlock while keeping the hold renewed until its reply arrives. Retries reuse the claimed id. Lease changes also claim an available registration, so a lease change and a pending unlock cannot cancel the same hold and leave renewal behind. Cover read unlocks with and without a lease, ids shared across tasks, fast multilock result cleanup, delayed unlock replies in both orders, unlock retries, and setting a lease while an unlock is pending. Validation: 24 unit tests and 147 Redis lock tests pass. Five cluster cases are excluded due to the previously reproduced socat image issue. Both real-Redis overlap reproducers pass. Clean verify, checkstyle and license checks pass. Signed-off-by: yu.xia <[email protected]>
|
Addressed in da5d7b1. The null-registration fallback was a regression in my rework; it now cancels nothing. The two-argument cancel is final, the unused method is removed, and the requested tests are added. Also fixed overlapping unlock/lease-change cancellations by claiming separate registration IDs. Local checks pass: 24 unit tests, 147 Redis lock tests, build, checkstyle and license checks. Five known socat-dependent cluster cases were excluded. |
Fixes #7455
Problem
When a thread releases a watchdog lock and takes the same lock again, the hold it has just taken is sometimes no longer registered for renewal. Nothing is logged. If that hold lasts longer than
lockWatchdogTimeout, the key expires and another client can take the lock while the first thread still holds it.The cancel comes from the result of a renewal that was sent before the unlock.
LockTask.buildChunkremembers the first thread of each key, and the callback cancels that thread when the script reports the key as gone. The result only says that the lock was not held when the script ran. By the time the callback runs, the same thread can hold the lock again, andcancelExpirationRenewalremoves by lock name and thread id only, so it cannot tell the earlier hold from the new one. #7070 made the add and the cancel atomic with each other. It does not cover a cancel that arrives with a stale result.Fix
Every acquire registers its hold under an id of its own.
LockEntrykeeps the ids of a thread instead of a hold counter, so the holds of a thread are its ids and the reentrancy depth is their count. Every cancel names the registration it removes, and removing by id is idempotent, which covers the cases below and the one of the issue:unlockAsync(threadId)claims the newest id of the thread that no other operation claimed (LockEntry.claimNewestRegistrationId), before it sends the script, and cancels exactly that one when the reply arrives. The claimed hold stays registered until then, so a pending unlock does not stop its renewal. The id is claimed once per operation and captured by the closure, so a retry afterNoSyncedSlavesExceptioncancels the same registration again and removes nothing the second time. Overlapping unlocks claim distinct holds — without the claim, twounlockAsynccalls on a reentrant hold would both name the newest id and leave the other level's registration behind, and the watchdog would renew a fully released lock. AnunlockAsyncfollowed by alockAsyncwithout waiting leaves the hold of the new acquire alone.setLeaseTimeIfNotSetclaims an available registration before it cancels, so a lease change cannot eat the hold a pending unlock has claimed, andforceUnlockremoves the whole entry. A named thread whose claim finds no registration cancels nothing: an unregistered hold, like a read lock taken with a lease inside a write-locked section, must not cancel the registration of the write hold inLockTask.LockRenewalScheduler. A read lock cancels in the lock and in the read lock renewal task, so an id must not name a hold of the other task.RedissonFasterMultiLockinherits the unlock of the base class now and names its id too. Its own copy was the same code.FairLockWaiterTaskshares the entry class but never cancels from a result, it only registers.This does not change #7454.
Tests
RenewalTaskTestis new and needs no Redis. It drivesLockTask,ReadLockTaskandFastMultilockTaskwith a renewal whose reply is held back until the thread has released and retaken the lock.On master the round-trip tests fail with a
ClassCastException-free but wrong cancel: 5 of the original 7 fail there (the retaken hold is removed on master for lock, read lock and fast multilock; a reentrant acquire while a renewal is pending is decremented; in a shared entry the retaken hold is removed). The 2 tests that check a result for a still registered hold pass on master and with the fix.The tests of the two review rounds:
unlockCallbackDoesNotCancelHoldRetakenAfterTheRelease: the renewal result removes the released hold, the thread retakes the lock, then the unlock callback cancels the released id again and must remove nothing.retriedUnlockDoesNotCancelTheOuterHold: a retried unlock cancels the same id twice, the outer hold of a reentrant lock keeps its renewal.readLockIdNamesNoHoldOfTheLockTask: the id of the read lock task names no hold of the lock task, cancelled throughLockRenewalScheduler.fastMultilockResultCancelsHoldThatIsStillRegistered: a fast multilock result still cancels a hold that is registered.cancelWithoutARegistrationCancelsNothing: a cancel that found no registration removes nothing, in both tasks.RedissonReadWriteLockTest: the write lock keeps its renewal after a read unlock, once with a plain read lock and once with a lease.UnlockAsyncRegistrationTest(no Redis): the delayed reply of an unlock does not cancel a hold taken while it was pending; overlapping unlocks cancel different holds, with replies in both orders, for the lock, the read lock and the fast multilock; a retried unlock does not claim another hold; a lease change does not cancel the registration of a pending unlock.With the removal by id reverted to a removal by thread, 8 of the 12 tests of
RenewalTaskTest, 8 of the 9 tests ofUnlockAsyncRegistrationTestand 2 of the 3 tests ofReadLockEntryTestfail. With the null fallback restored,cancelWithoutARegistrationCancelsNothingfails, and the read unlock with a lease fails against Redis.Verification
The
RenewalLostprogram from the issue, onmasterat b019f0e and on this branch (macOS arm64, OpenJDK 25, Redis 8.10.2):RenewalLost 1500 45RenewalLost 30000 150The last two runs use a variant of the same program: every thread checks the registration right after
lock()and keeps a lost hold past the watchdog, then checks whether its hold is still in Redis.mvn -pl redisson clean verify -DskipTests -Dmaven.test.skip=falsepasses with 0 checkstyle violations.RenewalTaskTest,UnlockAsyncRegistrationTestandReadLockEntryTestpass: 24 tests.The existing lock suites
RedissonLockExpirationRenewalTest,RedissonLockTest,RedissonReadWriteLockTest,RedissonSpinLockTest,RedissonFasterMultiLockTestandRedissonFairLockTestran against Redis in Docker on da5d7b1: 152 tests, 145 passed.testInClustertests error in my environment withContainer startup failed for image alpine/socat:1.7.4.3-r0.RedissonLockTest#testInClusterfails the same way on master.RedissonFairLockTest#testAcquireFailedTimeoutDrift_DescreteandRedissonFairLockTest#testMultipleLocksfailed while the six suites ran on a loaded machine. Both passed when run alone.