Skip to content

Fixed - Lock watchdog stops renewing a hold retaken right after unlock #7455 - #7460

Open
eatmoreduck wants to merge 3 commits into
redisson:masterfrom
eatmoreduck:fix-lock-renewal-stale-cancel
Open

eatmoreduck wants to merge 3 commits into
redisson:masterfrom
eatmoreduck:fix-lock-renewal-stale-cancel

Conversation

@eatmoreduck

@eatmoreduck eatmoreduck commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

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.buildChunk remembers 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, and cancelExpirationRenewal removes 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. 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. Every cancel names the registration it removes, and removing by id is idempotent, which covers the cases below and the one of the issue:

  • A renewal chunk records the ids of the thread, and a "gone" result removes exactly those. A hold the thread takes after the renewal was computed has another id and stays.
  • 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 after NoSyncedSlavesException cancels the same registration again and removes nothing the second time. Overlapping unlocks claim distinct holds — without the claim, two unlockAsync calls 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. An unlockAsync followed by a lockAsync without waiting leaves the hold of the new acquire alone.
  • The cancels that do not come from an unlock route through the same final method: setLeaseTimeIfNotSet claims an available registration before it cancels, so a lease change cannot eat the hold a pending unlock has claimed, and forceUnlock removes 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 in LockTask.
  • The ids come from one counter of 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.
  • RedissonFasterMultiLock inherits the unlock of the base class now and names its id too. Its own copy was the same code.

FairLockWaiterTask shares the entry class but never cancels from a result, it only registers.

This does not change #7454.

Tests

RenewalTaskTest is new and needs no Redis. It drives LockTask, ReadLockTask and FastMultilockTask with 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 through LockRenewalScheduler.
  • 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 of UnlockAsyncRegistrationTest and 2 of the 3 tests of ReadLockEntryTest fail. With the null fallback restored, cancelWithoutARegistrationCancelsNothing fails, and the read unlock with a lease fails against Redis.

Verification

The RenewalLost program from the issue, on master at b019f0e and on this branch (macOS arm64, OpenJDK 25, Redis 8.10.2):

Run master this branch
RenewalLost 1500 45 8,822 cycles, 18 holds lost, 18 taken by client two 3 runs of 20,092 to 22,999 cycles, 0 lost
RenewalLost 30000 150 not run locally (the issue reports 4 lost in 24,516 cycles) 74,415 cycles, 0 lost
8 threads, one lock each, watchdog 300 ms, 45 s 78,046 cycles, 420 holds lost, 420 expired in Redis 233,435 cycles, 0 lost
8 threads on one read lock, watchdog 300 ms, 45 s 200,988 cycles, 2 holds lost, 2 expired in Redis 203,805 cycles, 0 lost

The 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=false passes with 0 checkstyle violations.

RenewalTaskTest, UnlockAsyncRegistrationTest and ReadLockEntryTest pass: 24 tests.

The existing lock suites RedissonLockExpirationRenewalTest, RedissonLockTest, RedissonReadWriteLockTest, RedissonSpinLockTest, RedissonFasterMultiLockTest and RedissonFairLockTest ran against Redis in Docker on da5d7b1: 152 tests, 145 passed.

  • The five testInCluster tests error in my environment with Container startup failed for image alpine/socat:1.7.4.3-r0. RedissonLockTest#testInCluster fails the same way on master.
  • RedissonFairLockTest#testAcquireFailedTimeoutDrift_Descrete and RedissonFairLockTest#testMultipleLocks failed while the six suites ran on a loaded machine. Both passed when run alone.

@mrniko mrniko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please resolve the conflicts

…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]>
@eatmoreduck
eatmoreduck force-pushed the fix-lock-renewal-stale-cancel branch from e84fb83 to d0baec1 Compare December 1, 2026 16:02
@eatmoreduck

Copy link
Copy Markdown
Contributor Author

Rebased onto master (1d8129a). The conflict was in RenewalTask only. #7454 removed tryRun() and stop() and moved arming the timeout out of compute(); this change only adds the registration counter next to that and the id check in cancelExpirationRenewal, so both are intact.

On the new base RenewalTaskTest and ReadLockEntryTest pass, and mvn -T 1C -B clean verify -DskipTests -Dmaven.test.skip=false -pl redisson passes with 0 checkstyle violations.

@eatmoreduck

Copy link
Copy Markdown
Contributor Author

While I ran the lock suites on the rebased branch, RedissonLockTest#testLockIsNotRenewedAfterInterruptedTryLock failed. It fails on master too when it is run alone (5 of 5 runs), with the same trace, so it is not related to this change. I filed it as #7463, with a fix in #7464.

The other failures I saw on the rebased branch are the testInCluster tests, which cannot start the alpine/socat container on my machine, RedissonFairLockTest.testMultipleLocks, which fails on master alone as well, and a few timing-sensitive tests that pass when they are run alone.

@mrniko mrniko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 both threadId2counter and threadId2registration; 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 to cancelExpirationRenewal, which removes exactly that id. forceUnlock still removes everything.
  • Take the ids from one counter in LockRenewalScheduler. RedissonReadLock.cancelExpirationRenewal cancels in both LockTask and ReadLockTask, 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:

  1. unlockAsync(threadId) followed by lockAsync(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.
  2. An unlock retried after NoSyncedSlavesException. ServiceManager.execute reruns unlockAsync0. The script is idempotent by requestId, but cancelExpirationRenewal runs 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.

@mrniko mrniko added this to the 4.9.0 milestone Dec 2, 2026
@mrniko mrniko added the bug label Dec 2, 2026
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]>
@eatmoreduck

Copy link
Copy Markdown
Contributor Author

Done in 0dc1275, following the proposed change.

  • LockEntry keeps a list of ids per thread. It replaces threadId2counter and threadId2registration; 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.
  • unlockAsync(threadId) reads the newest id of the thread before it sends the script. The id is read once per operation and captured by the closure, so a retry after NoSyncedSlavesException cancels the same registration again and removes nothing the second time. forceUnlock still removes everything.
  • The ids come from one counter in LockRenewalScheduler. RedissonReadLock.cancelExpirationRenewal cancels in both LockTask and ReadLockTask, and now an id cannot name a hold of the other task.
  • RedissonFasterMultiLock had a byte-identical copy of the unlock of the base class. The copy is gone and it names its id now too.
  • The cancels that do not name a registration, setLeaseTimeIfNotSet and the forceUnlock paths, remove the hold the thread took last, or the whole entry when no thread is named.

RenewalTaskTest has the two requested tests: unlockCallbackDoesNotCancelHoldRetakenAfterTheRelease (the renewal result removes the released hold, the thread retakes the lock, then the unlock callback removes nothing) and retriedUnlockDoesNotCancelTheOuterHold (a retried unlock cancels the same id twice, the outer hold of a reentrant lock keeps its renewal). With the removal by id reverted to a removal by thread, seven of the nine tests fail, both new ones among them.

The lock suites ran against Redis in Docker again: 144 of 150 pass, the five testInCluster tests error on the socat image in my environment, and testRemainTimeToLive failed once on a loaded machine (10 ms tolerance, 24 ms drift) and passed alone.

@mrniko mrniko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, through LockRenewalScheduler.
  • RenewalTaskTest: a fast multilock result still cancels a hold that is registered.
  • A test that unlockAsync reads the id before the script: hold a lock, call unlockAsync, 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]>
@eatmoreduck

Copy link
Copy Markdown
Contributor Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Development

Successfully merging this pull request may close these issues.

Lock watchdog: a held RLock stops being renewed and expires while held when the same thread re-takes it right after unlock()

2 participants