Repository navigation
fix(lockservice): fence stale binds by allocator epoch - #24903
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
There was a problem hiding this comment.
Review Result
Approved. I did not find any blocking issues in this PR.
What I Checked
GetBindandKeepLockTableBindnow return the allocator epoch to CN.- CN stale-bind purge uses the existing
LockTable.Versionsemantics consistently: binds withVersion < observed allocator epochare old allocator state and can be removed. - The added tests cover get-bind refresh, keepalive failure/epoch refresh, concurrent observation, remote/proxy bind purge, and waiter cleanup.
Local Verification
git diff --check HEAD^ HEAD
go test ./pkg/lockservice -run 'Test(CommitDetectsStaleLocalBindAfterAllocatorRestart|AllocatorVersionZeroKeepsLocalBinds|AllocatorObserverDoesNotPurgeSameEpochBindVersions|GetBindAllowsRegressedAllocatorVersionWithoutPurging|KeepaliveEpochPurgeKeepsGroupMovePop|AllocatorObserverPurgesRemoteAndProxyLockTables|AllocatorObserverConcurrentKeepaliveAndGetBind|AllocatorObserverCloseWaitersOnStaleLocalBind)$'Note: I started go test ./pkg/lockservice, but stopped it after it ran for more than 5 minutes without output and then verified the PR-specific test set above.
XuPeng-SH
left a comment
There was a problem hiding this comment.
I understand the bug this PR is trying to fix, but I found one substantive correctness issue in the epoch-fencing design itself.
The allocator epoch is initialized from time.Now().UnixNano() in pkg/lockservice/lock_table_allocator.go, while the observer side in service.go explicitly ignores any non-increasing allocator version (observedVersion < oldVersion or == oldVersion). That means a real allocator restart can fail to purge stale cached binds if the new process comes up with the same or a lower wall-clock timestamp (for example after a clock step backward / NTP correction / VM time skew). In that case getLockTableWithCreate() keeps returning the stale entry from tableGroups without ever re-contacting the allocator, which is exactly the class of stale-bind problem this PR is trying to fence off.
What makes this higher confidence is that the new test TestGetBindAllowsRegressedAllocatorVersionWithoutPurging explicitly locks in that behavior. I think the fix needs an epoch source that is guaranteed monotonic/unique across allocator restarts (persisted term/counter, restart generation, etc.), or the observer must still invalidate cache on allocator replacement even when the observed epoch is non-increasing.
fixed |
XuPeng-SH
left a comment
There was a problem hiding this comment.
I re-checked the current head from correctness and unhappy-path angles. The earlier allocator identity/fencing issues look materially improved, but I found one remaining blocker.
Blocker: handleForwardLock can deadlock while waiting for an in-flight bind allocation.
pkg/lockservice/service_remote.go:292 now acquires s.bindChangeMu.RLock() before calling s.getLockTable(). But getLockTable() can block in waitLockTableBind() when another goroutine is currently allocating the same table bind (pkg/lockservice/service.go:612-616). That allocating goroutine only closes the wait channel after publishLockTableBindFromAllocator() returns, and the publish/allocator-observe path needs s.bindChangeMu.Lock() (pkg/lockservice/service.go:656 and pkg/lockservice/service.go:816).
So the unhappy path is:
- goroutine A starts first access for table T and registers
s.mu.allocating[T]; - goroutine B enters
handleForwardLockfor T, takesbindChangeMu.RLock, then waits for A's allocation channel ingetLockTable(); - goroutine A receives the allocator response and tries to publish the bind, but blocks on
bindChangeMu.Lock; - A cannot close the allocation channel, while B keeps holding the read lock and waits forever.
This can hang forwarded lock RPCs during ordinary concurrent first-access/rebind timing; it does not require allocator restart.
Suggested fix: do not hold bindChangeMu while calling/waiting in getLockTable(). Mirror handleRemoteLock: fetch/wait for the lock table first, then take bindChangeMu.RLock() and re-validate that the current bind still matches before touching the txn or reporting success. Please also add a regression test that pauses one goroutine after the allocating channel is registered but before publish, then runs a concurrent forwarded-lock/getLockTable waiter and verifies publish can still complete.
Local checks passed:
git diff --check origin/3.0-dev...HEADgit merge-tree --write-tree HEAD origin/3.0-dev- targeted
go test ./pkg/lockservice -run 'Test(GetBindPurgesStaleBindWhenAllocatorIDChangesWithRegressedVersion|KeepaliveEpochPurgeKeepsGroupMovePop|KeepaliveOKFalseWithNewAllocatorVersionPurgesStaleBinds|KeepaliveOKFalseFencesActiveTxn|AllocatorObserverRejectsSupersededGetBindResponse|AllocatorPublishRejectsStaleBindAfterNewAllocatorObserved|AllocatorPublishRejectsOverwriteAfterConcurrentBindChanged|AllocatorObserverBoundsSupersededAllocatorIDs|AllocatorIDDistinguishesBindIdentity|AllocatorObserverPurgesRemoteAndProxyLockTables|AllocatorObserverConcurrentKeepaliveAndGetBind|AllocatorObserverCloseWaitersOnStaleLocalBind|RemoteBindRefreshRejectsSupersededAllocatorBind|RemoteRetryBackoffCapped|GetLockRemoteWithRetry|LockRemoteWithContextTimeoutTracksLockForUnlock|LockWithBindTimeout|LockWithBindNotFound|Issue3538)$' -count=1
fixed |
XuPeng-SH
left a comment
There was a problem hiding this comment.
I still think this needs changes.
The remaining blocker is the new unconditional remote-lock bookkeeping on every Send error in pkg/lockservice/lock_table_remote.go.
After this patch, the error path at lock_table_remote.go:176-180 always does:
_ = txn.lockAdded(l.bind.Group, l.bind, rows, l.logger)That is only safe for "request may already have reached the remote owner" failures. But morpc also has definite pre-send failures where the request never leaves the client:
pkg/common/morpc/backend.go:366-373returnsf.send.Ctx.Err()if the request cannot even enter the write queue.pkg/common/morpc/backend.go:905-913returnsErrRPCTimeoutduring connect timeout before any request is written.
Once such a purely local failure is recorded as a held remote lock, txn.close() will later always try to remote-unlock it (pkg/lockservice/txn.go:174-223). But remoteLockTable.unlock() retries forever while the bind stays unchanged (pkg/lockservice/lock_table_remote.go:224-250,361-406). So a caller cancel / local deadline / connect-timeout that never sent the RPC can regress into an unbounded commit/rollback hang.
I think we need to keep the old "do not track definitely-not-sent errors" behavior, or add an explicit transport signal that distinguishes "may have been sent" from "definitely not sent" before deciding to retain remote-lock bookkeeping.
Thanks for the careful review. I agree that unconditional bookkeeping on every Send error was too broad. I updated the fix to distinguish definite not-sent failures from ambiguous post-send failures. client.Send now wraps only AsyncSend failures where no Future was returned, which means the request did not enter the normal send/wait path. remoteLockTable.lock skips txn.lockAdded only for that not-sent marker and for ErrRPCTimeout, while still tracking ordinary context deadline/cancel errors returned after a Future exists so txn.close can issue the remote unlock when the request may already have reached the owner. I also added regression coverage for the not-sent path to verify no stale remote lock is recorded and no remote unlock is attempted, plus a helper test that keeps post-send context deadline errors in the tracked category. The existing post-send timeout test still passes. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
I found one blocking regression: the current head fails the existing unstable-network lockservice test.
With the normal MatrixOne test environment, go test -count=1 -timeout 240s ./pkg/lockservice now times out in:
TestCannotHungWithUnstableNetwork
The timeout happens after repeated logs like:
txn failed to unlock table on remote ... the connection has been disconnectedfailed to get bind ... the connection has been disconnected
and the package eventually panics with test timed out after 4m0s while that test is still running.
That is a real correctness regression for the exact unhappy path this PR is trying to harden: under unstable/disconnecting network conditions, the lockservice must not hang. Even before getting into the finer stale-bind fencing details, the current implementation is not safe to merge while an existing regression test for network instability is timing out.
Given the changed logic in remoteLockTable.lock() around tracking remote locks on send errors (shouldTrackRemoteLockOnSendError) plus the new allocator-epoch fencing, I would first fix the unstable-network hang and make sure the package test passes again. The new coverage is broad overall, but it also still misses one high-value race test for a first lock whose bind changes mid-flight, so this area could use another unhappy-path regression once the hang is fixed.
fixed |
XuPeng-SH
left a comment
There was a problem hiding this comment.
I think this still needs changes.
The latest head fixes the visible unstable-network hang and CI is green, but the remote-lock bookkeeping rule is now too broad in the other direction.
shouldTrackRemoteLockOnSendError treats ErrBackendClosed and ErrBackendCannotConnect as definite not-sent failures and skips txn.lockAdded. That is safe only when the request never completed the write path. However, in morpc ErrBackendClosed can also be delivered to a Future after the request has already been written and the client is waiting for the response: the read loop can schedule a connection reset, and makeAllWaitingFutureFailed fails all futures whose messageSent(nil) has already completed. The test-only disconnectAfterRead path also turns that response-side disconnect into backendClosed.
In that post-send/unknown case, the remote owner may already have acquired the lock. If the client skips local bookkeeping, txn.close() will not send a remote unlock, so release is delayed until remote/orphan timeout instead of happening at transaction end. This avoids the previous hang, but it creates a correctness/availability regression: conflicting transactions can be blocked by a lock whose owner-side acquisition is possible but whose client-side holder was intentionally forgotten.
I think the fix should distinguish transport phase, not just error code:
- wrap/mark only definite pre-send failures as
lockRequestNotSentError; - skip remote-lock bookkeeping only for that marker and other provably not-written cases;
- keep tracking post-send or unknown failures, including response-side disconnects, while bounding remote unlock retry so commit/rollback cannot hang forever.
This should also have a regression test where the lock request is written, the owner may acquire it, and the client connection fails before the response is observed; that path should still record the holder and attempt remote unlock on txn close.
Fixed. Bare ErrBackendClosed / ErrBackendCannotConnect are no longer treated as definitely-not-sent failures. We now skip remote-lock bookkeeping only for explicit not-sent markers and the existing connect-timeout case; ambiguous response-side disconnects keep the holder so txn close can send remote unlock. I also added a regression test covering a lock request that may have reached the owner before the client observes BackendClosed. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Reviewed latest head c3e49a8.
The previous remote-lock bookkeeping blocker is addressed: bare BackendClosed/BackendCannotConnect are now treated as ambiguous post-send failures and keep txn bookkeeping, while explicit not-sent markers and connect-timeout skip bookkeeping. Remote unlock retry is bounded by removeLockTimeout, so phantom tracked locks no longer create an unbounded close/rollback hang.
I also rechecked allocator replacement fencing, bind-change lock ordering, forwarded-lock first-bind wait, active txn bind-intent fencing, remote/proxy bind identity, and compatibility with missing allocator metadata. I do not see a remaining correctness blocker.
Local targeted verification passed:
go test -count=1 -timeout 240s ./pkg/lockservice -run 'Test(HandleForwardLockDoesNotHoldBindChangeLockWhileWaitingForBind|LockRemoteWithNotSentErrorSkipsRemoteTracking|LockRemoteWithResponseDisconnectTracksForUnlock|UnlockRemoteStopsRetryAfterDisconnectTimeout|ShouldTrackRemoteLockOnSendError|CannotHungWithUnstableNetwork|GetBindPurgesStaleBindWhenAllocatorIDChangesWithRegressedVersion|KeepaliveOKFalseFencesActiveTxn|AllocatorObserverRejectsSupersededGetBindResponse|AllocatorPublishRejectsStaleBindAfterNewAllocatorObserved|AllocatorPublishRejectsOverwriteAfterConcurrentBindChanged|AllocatorIDDistinguishesBindIdentity|BindChangedBeforeLockSuccessReturnsBindChanged)$'
CI is green on the 3.0 jobs.
Merge Queue Status
This pull request spent 56 minutes 6 seconds in the queue, including 55 minutes 42 seconds running CI. Required conditions to merge
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #24896
What this PR does / why we need it:
fix(lockservice): fence stale binds by allocator epoch