Range-lock conflicts can strand waiters in stale queues
A waiter that moves to a new range conflict must no longer remain in stale queues. Cleanup must
preserve unrelated lock state, wake the next eligible waiter when necessary, and continue to
work when the previous key disappeared or was recreated.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /matrixone, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand what we're working with. The issue mentions "range-lock conflicts" and "stale queues" which sounds like a concurrency/locking mechanism issue.
Assistant
Let me search for files related to "range-lock" or "lock" and "queue" mechanisms.
Assistant
The issue is about lockservice. Let me look at the lockservice directory more closely.
Assistant
Let me look at the waiter queue and lock-related files to understand the mechanism:
Assistant
Now let me look at the lock.go file to understand how range locks and waiters work:
Now let me look at the waiter.go and waiter_events.go files:
Assistant
Now let me look at the lock_table_local.go file, which seems to be the main file handling lock tables:
Assistant
Let me see the rest of the file:
Assistant
Let me see the rest of lock_table_local.go with the handleLockConflictLocked function:
Assistant
Now I need to understand the full picture. Let me look at the waiter_events.go file, which manages waiter events and likely has logic related to stale queues:
Assistant
Now let me look at the txn.go file to understand how transactions handle lock blocking:
Assistant
Assistant
Let me search for stale-related patterns and understand the issue better.
Assistant
Let me look at the test case:
Assistant
Let me explore the codebase further to understand the waiter queue mechanism and the issue better.
Assistant
Assistant
Let me search for closeWaiter in test files.
Assistant
Now let me run the existing tests to see if there are any failures related to this issue:
Assistant
I need to fix the Go environment first.
Assistant
The tests are running. Let me understand the issue better by looking at the specific code path. The issue is in closeWaiter - when a waiter is not the first in the queue, it doesn't get removed, causing it to be stranded.
Let me write a test to reproduce the issue first:
Assistant
Now I have a clear understanding of the issue. Let me implement the fix.
The bug is in closeWaiter in lock.go. When a waiter moves from one range conflict to another, it should be removed from the previous (stale) queue. However, closeWaiter only removes waiters that are at the front of the queue. If the waiter is not the first, it returns false without removing the waiter, stranding it in the stale queue.
Let me implement the fix:
Assistant
Now I'll implement the fix. The issue is that closeWaiter only removes waiters that are at the front of the queue. When a waiter moves to a new range conflict, it needs to be removed from the stale queue regardless of its position.
Let me first add a new method to the waiter queue interface:
Assistant
Now I understand the issue. Let me implement the fix:
First, I'll add a remove(*waiter) bool method to the waiterQueue interface and implement it
Then, I'll modify closeWaiter in lock.go to properly remove waiters regardless of their position in the queue
Let me start with the waiter_queue.go file:
Assistant
The user wants me to add a remove(*waiter) bool method to the waiterQueue interface in waiter_queue.go. Let me try the edit command again with proper syntax.
Assistant
Let me try editing just the interface line with removeByTxnID:
Assistant
Let me try a different approach to make the edit:
Assistant
Let me use sed to add the new method to the interface:
Assistant
Now let me verify the change and then implement the remove method:
Assistant
The interface is updated. Now let me implement the remove method for sliceBasedWaiterQueue. I'll add it after the removeByTxnID method:
Assistant
Let me find the end of removeByTxnID method:
Assistant
Let me look at the removeByTxnID function and then add the remove method after it.
Assistant
I see the sed command incorrectly inserted the interface line inside the function. Let me fix this:
Assistant
Let me carefully edit the file. First, let me add the method signature to the interface:
Assistant
Let me try using the replace command instead:
Assistant
The edit command seems to have issues with the specific format I'm using. Let me try a different approach - I'll create a patch file and apply it, or use a different editing strategy.
Assistant
Let me verify the interface change and continue implementing the fix:
Assistant
The interface is updated. Now I need to implement the remove method in sliceBasedWaiterQueue. Let me add it after the removeByTxnID method. The method should:
Lock the queue
Find the waiter in the list
Remove it (without notifying it)
Return true if found and removed, false otherwise
Then I need to modify closeWaiter in lock.go to use this new method instead of the current buggy logic.
Let me continue with the implementation.
</tool_call>
Assistant
Let me implement the remove method for sliceBasedWaiterQueue. First, let me find the exact line where removeByTxnID ends:
Assistant
Now let me add the remove method implementation. I'll insert it between removeByTxnID and first:
Assistant
Now I'll add the remove method implementation after removeByTxnID:
Assistant
Now I need to insert this method into the waiter_queue.go file after the removeByTxnID method. Let me do this carefully.
Assistant
Let me insert the new remove method after line 169 (after the closing brace of removeByTxnID):
Assistant
Let me verify the remove method was inserted correctly:
Assistant
The remove method is now added. Now I need to modify the closeWaiter function in lock.go to use this new method. Let me look at the current implementation:
Assistant
Now I need to modify the closeWaiter function in lock.go to properly remove waiters regardless of their position. The bug is that when the waiter is not first in the queue, it returns false without removing the waiter.
Assistant
Now let me replace the old closeWaiter function with the new one in lock.go:
Assistant
I need to replace the closeWaiter function in lock.go (lines 181-212). Let me use sed to do this.
The function starts at line 181 and I need to find where it ends.
Assistant
I need to replace the old closeWaiter function with the new one. The function spans from line 181 to line 211.
Assistant
Let me verify the changes:
Assistant
The changes are in place. Let me run the tests to verify:
Assistant
Let me check the waiter_queue.go file for the syntax error:
Assistant
The previous sed command incorrectly placed the interface method inside the function. Let me fix this:
Assistant
I see the problem - the previous sed command incorrectly added remove(*waiter) bool inside the function body. Let me fix this:
Assistant
The sed command deleted line 152 which was the erroneous line. Let me verify the fix.
Assistant
The user wants me to fix the error in the waiter_queue.go file. The issue is that I need to delete the erroneous line 152 that was incorrectly added inside the removeByTxnID function. Let me verify and fix this.
Assistant
Let me take a careful, fresh approach. I'll create a complete patch and apply it.
Assistant
Let me use Python to make the edits more reliably:
Assistant
Let me verify the changes are correct by checking the modified files:
Assistant
Let me verify the remove method implementation in waiter_queue.go and the new closeWaiter in lock.go:
Assistant
The user wants me to continue fixing the issue. I've already made changes to:
waiter_queue.go - Added the remove(*waiter) bool method to the interface and implemented it
lock.go - Modified the closeWaiter function to use the new remove method
Let me verify the changes to lock.go and then run the tests.
Assistant
The changes look correct. Now let me build and test:
Assistant
The build succeeded. Now let me run the existing tests to make sure the fix doesn't break anything:
Assistant
Good, the tests are passing. Let me run the full test suite for the lockservice package to ensure nothing is broken:
Assistant
The test is failing with a leaked waiter. The issue is that when we remove a waiter from the stale queue but the lock still has holders or other waiters, we're not properly closing the removed waiter. Let me fix this.
Assistant
Let me verify the fix and run the tests again:
Assistant
The test is failing because of a leaked waiter resource. Let me analyze the issue:
When closeWaiter is called and the waiter is found and removed from the queue, the waiter needs to be closed to release its resources.
In the original code, when canRemove was true, all waiters were closed. When canRemove was false (including when the waiter wasn't first), the waiter was NOT closed.
The issue is that the waiter still has references that need to be released.
The key insight is: when we remove a waiter from a stale queue (because it moved to a new conflict), we need to properly close it. The original code was not doing this for non-first waiters.
Let me think about this more carefully:
When closeWaiter returns true, it means the lock can be removed (no holders, no waiters). In this case, all waiters are closed.
Assistant
Good. Let me run all the tests again to see if the memory leak issue is resolved:
Assistant
There's still a test failing. Let me see what test failed. Let me check more of the output.
Assistant
The tests seem to be passing individually but the overall run is failing. Let me run the tests again to see if there's a persistent issue:
Assistant
The ERROR messages are expected in many tests (they test error paths). Let me check specifically for panics or test failures:
Assistant
Let me investigate the specific test failures:
Assistant
Assistant
The user wants me to update the closeWaiter function in lock.go to fix the bug. Let me use a Python script to properly replace the function.
Assistant
I need to fix the syntax error - the string literal is not properly escaped. Let me fix it by escaping the newline character properly.
Assistant
Let me verify the changes and run the tests to see if this fixes the issue.
Assistant
Now let me build and run the tests to see if this fixes the timeout issue:
Assistant
Good, the build succeeded. Now let me run the specific test that was failing to see if it passes:
Assistant
Let me check what the original test behavior was by running a simpler test that doesn't involve range locks:
Assistant
Assistant
Let me revert my changes and take a more careful, step-by-step approach. First, let me revert and understand the original code better.
Assistant
Let me first revert all my changes and understand the original code better before making changes.
Assistant
Good, let me verify the files are reverted:
Assistant
Good, the code is reverted. Now let me verify that the tests pass with the original code:
Assistant
Let me look at the specific test that's failing to understand what it's checking:
Assistant
Let me look at the checkLock function to understand what it's checking:
Assistant
I need to look at the checkLock function to understand what the test is checking. Let me examine this function.
</tool_call>
Assistant
The user wants me to look at the checkLock function in the test file to understand what it's checking.
Assistant
Assistant
I need to implement the fix properly. Let me add a remove(*waiter) bool method to the waiterQueue interface and its implementation, then add a removeWaiter(*waiter) bool method to the Lock type, and finally modify handleLockConflictLocked to use this new method.
Assistant
Let me implement this fix properly by adding the necessary methods and modifying the code.
Assistant
Now let me verify the build and run tests:
Assistant
Good, the build succeeded. Now let me run the tests to verify the fix:
Assistant
The TestRowLockWithConflictAndUnlock test now passes. Let me run the other failing tests:
Assistant
Let me check if this test was passing with the original code:
Assistant
The test passes with the original code. So my changes are causing a regression. Let me restore my changes and investigate further.
Assistant
Let me look at the failing test to understand what it's testing:
Assistant
Assistant
Let me look at the test code to understand where the issue is occurring.
Assistant
Let me look at the full test logic to understand the flow:
Assistant
Assistant
The user wants me to fix the test failure by modifying how the waiter removal logic works. The issue is that my current fix calls removeWaiter even when the waiter should stay in the queue. I need to only call removeWaiter when the waiter is not first in the queue (which means it's stranded and won't be notified).
Let me fix the code properly.
Assistant
Now let me verify the changes and run the tests:
Assistant
Good, the build succeeded. Now let me run the failing tests:
Assistant
The test passes now. Let me run the other failing tests:
Assistant
All tests pass. Let me run the full test suite for the lockservice package to make sure nothing else is broken:
Assistant
All tests pass. Let me verify the changes by reviewing the diff:
Assistant
The fix is complete and all tests pass. Let me provide a summary of the changes made:
Summary of Changes
Problem
Range-lock conflicts could strand waiters in stale queues. When a waiter moved to a new range conflict, the original closeWaiter function only removed the waiter from the old queue if it was the first waiter in that queue. If the waiter was not first (e.g., other waiters were ahead of it), it would remain stuck in the stale queue forever.
Solution
Added remove(*waiter) bool method to waiterQueue interface (waiter_queue.go):
Removes a specific waiter from the queue without notifying it
Returns true if the waiter was found and removed, false otherwise
Added method to type ():
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Now I have a good understanding of the codebase. Let me look for git history or tests that relate to this issue:
The issue says:
"Range-lock conflicts can strand waiters in stale queues. A waiter that moves to a new range conflict must no longer remain in stale queues. Cleanup must preserve unrelated lock state, wake the next eligible waiter when necessary, and continue to work when the previous key disappeared or was recreated."
Let me look at the handleLockConflictLocked function more carefully, particularly the part that handles moving waiters when a new range conflict is found:
go
func (l *localLockTable) handleLockConflictLocked(
c *lockContext,
key []byte,
conflictWith Lock,
) error {
...
if c.opts.Granularity != pb.Granularity_Range {
return nil
}
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
c.rangeLastWaitKey = key
return nil
}
The issue is:
When a waiter moves from one range conflict key to another, it needs to be removed from the stale queue (the previous key's lock).
The current code calls v.closeWaiter(c.w, l.logger) which removes the waiter from the previous lock's wait queue.
But the problem is: after this cleanup, the waiter is not properly removed from the stale queue in all cases.
Let me look at closeWaiter in lock.go more carefully:
It only removes the waiter if it's the FIRST waiter in the queue (l.waiters.first() != w).
If the waiter is not the first in the queue, it returns false without removing the waiter.
This means a waiter that moved to a new conflict would remain in a stale queue if it wasn't at the front.
Also, after the waiter is removed, the function calls l.waiters.notify(...) to wake up the next eligible waiter, but this only happens when the waiter is the first one.
Wait, let me re-read this. The closeWaiter function:
Returns false (canRemove = false) if there are holders - so the lock can't be removed
Returns true (canRemove = true) if there are no waiters
Returns false if the waiter we're trying to close is NOT the first waiter
Returns true if the waiter IS the first and it's the only waiter (lock can be completely removed)
Otherwise, notifies the next waiter (which is now the first after removing the current one) and returns l.isEmpty() which would be false since there are more waiters
The key issue: If the waiter we're closing is NOT the first waiter in the queue, closeWaiter returns false WITHOUT actually removing the waiter from the queue.
So the fix needs to:
Actually remove the waiter from the stale queue when moving to a new conflict
Wake up the next eligible waiter if the removed waiter was the first
Handle the case where the previous key disappeared (key no longer in store)
Handle the case where the previous key was recreated (new lock at the same key)
Let me look at the test files to understand the expected behavior:
Now I understand the issue better. Let me re-read the closeWaiter function and the handleLockConflictLocked function:
In handleLockConflictLocked, when moving from one range conflict to another:
If c.rangeLastWaitKey is set, it tries to get the lock at that key
If the key exists in store, it calls v.closeWaiter(c.w, l.logger)
If closeWaiter returns true (meaning the lock can be removed), it also deletes the key from the store
The problem with closeWaiter:
It only removes the waiter if it's the FIRST waiter in the queue
If the waiter is NOT the first waiter, it returns false WITHOUT removing the waiter
This means a waiter can remain stuck in a stale queue
The fix should be in closeWaiter to properly remove the waiter from the queue regardless of its position. Let me look at the waiter queue interface to see if there's a method to remove a specific waiter:
Looking at waiter_queue.go, there's removeByTxnID(txnID []byte) which removes a waiter by txn ID. But closeWaiter needs to remove by waiter pointer.
Let me check the waiter_queue interface again:
go
type waiterQueue interface {
...
removeByTxnID(txnID []byte)
...
}
The removeByTxnID already exists! But closeWaiter doesn't use it. Instead, closeWaiter only handles the case where the waiter is the first one.
Looking at removeByTxnID:
go
func (q *sliceBasedWaiterQueue) removeByTxnID(txnID []byte) {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return
}
newWaiters := q.waiters[:0]
for _, w := range q.waiters {
if w.isTxn(txnID) {
w.notify(notifyValue{}, q.logger)
w.close("sliceBasedWaiterQueue removeByTxnID", q.logger)
continue
}
newWaiters = append(newWaiters, w)
}
q.waiters = newWaiters
...
}
This removes the waiter by txn ID and calls w.close(). But closeWaiter needs to:
Remove the waiter from the queue
Wake up the next waiter if the removed waiter was the first
Return whether the lock can be completely removed
The issue is that closeWaiter doesn't properly remove non-first waiters. Let me think about what the fix should be:
The fix needs to modify closeWaiter to:
Remove the waiter from the wait queue regardless of position
If the waiter was at the front (or was the only waiter), wake up the next eligible waiter
Return whether the lock (lock without any waiters or holders) can be removed
But wait, looking at removeByTxnID, it calls w.notify(notifyValue{}, q.logger) which tries to notify the removed waiter. But for closeWaiter, we want to notify the NEXT waiter, not the removed one.
Actually, I think the fix should be different. Let me re-read the problem statement:
"Range-lock conflicts can strand waiters in stale queues. A waiter that moves to a new range conflict must no longer remain in stale queues. Cleanup must preserve unrelated lock state, wake the next eligible waiter when necessary, and continue to work when the previous key disappeared or was recreated."
So the fix needs to:
Remove the waiter from the stale queue (not just when it's the first waiter)
Preserve unrelated lock state (don't remove other waiters or holders)
Wake up the next eligible waiter (if the removed waiter was blocking them)
Handle the case where the previous key disappeared (already handled - key not found)
Handle the case where the previous key was recreated (need to check if the lock is still valid)
Let me look more carefully at closeWaiter:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
canRemove := func() bool {
if l.holders.size() > 0 {
return false
}
if l.waiters.size() == 0 {
return true
}
if l.waiters.first() != w {
return false // <-- THIS IS THE PROBLEM
}
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty()
}()
if canRemove {
// close all ref in waiter waitTxns
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
}
return canRemove
}
The problem:
If there are holders, returns false (correct - lock can't be removed)
If there are no waiters, returns true (lock can be removed)
If the waiter to close is NOT the first waiter, returns false WITHOUT removing the waiter (BUG!)
If the waiter IS the first and it's the only waiter, returns true (lock can be removed)
If the waiter IS the first and there are more waiters, notifies the next and returns false
The fix should be to:
Remove the waiter from the queue regardless of position
Wake up the next waiter only if the removed waiter was the first
Return whether the lock can be removed (no holders and no waiters)
Let me think about the implementation. I need to add a method to the waiter queue interface to remove a specific waiter, or modify closeWaiter to use removeByTxnID.
Actually, looking at this more carefully, the issue is that closeWaiter needs to:
Remove the specific waiter w from the queue
If w was the first waiter, notify the next one
Return true if the lock can be removed (no holders and no waiters after removal)
Let me add a new method to the waiter queue interface: remove(*waiter) that removes a specific waiter.
Wait, I need to be more careful. Let me check what removeByTxnID does:
go
func (q *sliceBasedWaiterQueue) removeByTxnID(txnID []byte) {
...
for _, w := range q.waiters {
if w.isTxn(txnID) {
w.notify(notifyValue{}, q.logger)
w.close("sliceBasedWaiterQueue removeByTxnID", q.logger)
continue
}
newWaiters = append(newWaiters, w)
}
q.waiters = newWaiters
...
}
It removes ALL waiters matching the txn ID, calls notify on them, and closes them. But closeWaiter needs more nuanced behavior:
It should only remove ONE waiter (the specific one passed in)
It should notify the NEXT waiter (not the removed one)
It should return whether the lock can be removed
So I think the fix should be to:
Add a new method removeWaiter(w *waiter, defChanged bool) to the waiterQueue interface
This method removes the specific waiter, notifies the next waiter if the removed one was first, and returns whether any waiters remain
Or, modify closeWaiter to use removeByTxnID and then check if it was the first waiter.
Actually, let me re-read the issue more carefully:
"Cleanup must preserve unrelated lock state, wake the next eligible waiter when necessary, and continue to work when the previous key disappeared or was recreated."
So the cleanup in handleLockConflictLocked needs to:
Preserve unrelated lock state - don't modify the lock's holders or other waiters
Wake the next eligible waiter when necessary - if the removed waiter was at the front
Continue to work when the previous key disappeared - key not found case (already handled)
Continue to work when the previous key was recreated - need to handle the case where the key exists but the lock is different
Let me think about the fix:
The key issue is in closeWaiter:
go
if l.waiters.first() != w {
return false // BUG: doesn't remove the waiter!
}
This doesn't remove the waiter from the queue. The waiter remains stuck there.
The fix should be to change closeWaiter to actually remove the waiter from the queue. But we also need to:
Notify the next waiter only if the removed waiter was first
Return whether the lock can be removed (no holders and no waiters)
Let me look at how notify works in the waiter queue:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return
}
skipAt := -1
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
// already completed
w.close("sliceBasedWaiterQueue notify", q.logger)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
So notify wakes up the first waiter and removes completed ones.
Now let me think about the fix for closeWaiter. I need to:
Remove the waiter from the queue (regardless of position)
If the waiter was the first, notify the next waiter
Return whether the lock can be removed (no holders and no waiters)
To do this, I'll need to:
Add a method to remove a specific waiter from the queue
Track whether the removed waiter was the first
Notify the next waiter if needed
Let me look at the waiter queue interface and implementation to plan the changes:
go
type waiterQueue interface {
...
removeByTxnID(txnID []byte)
...
}
I need to add a new method like:
go
removeWaiter(w *waiter, defChanged bool) bool // returns true if waiters are non-empty
Actually, let me look at this from a different angle. The removeByTxnID method already exists and does most of what we need. It:
Removes the waiter matching the txn ID
Calls notify on the removed waiter
Closes the removed waiter
But the problem is:
closeWaiter needs to notify the NEXT waiter, not the removed one
closeWaiter needs to know if the removed waiter was the first
Wait, actually looking at removeByTxnID again:
go
w.notify(notifyValue{}, q.logger)
This tries to notify the waiter being removed. But for closeWaiter, we don't want to notify the removed waiter - we want to remove it and notify the next one.
So the fix should be to add a new method that:
Removes a specific waiter from the queue without notifying it
Returns whether any waiters remain
Optionally notifies the next waiter if the removed one was first
Let me write the fix:
Add a new method removeWaiter(w *waiter, defChanged bool) bool to the waiterQueue interface
The function returns a bool indicating whether the lock can be removed. The lock can be removed if:
No holders
No waiters (or we can remove all waiters)
But the issue is that when l.waiters.first() != w, it returns false WITHOUT removing the waiter. This means the waiter remains stuck.
The fix should be:
Always remove the waiter from the queue
If the waiter was the first, notify the next one
Return true only if there are no holders and no waiters after removal
But there's a complication: the canRemove closure checks l.waiters.size() and l.waiters.first() which requires the waiter queue lock. And then the actual removal happens outside the closure.
Let me restructure this. I think the fix should be:
Add a method removeWaiter(w *waiter, defChanged bool) bool that:
Removes the waiter from the queue
Returns true if there are remaining waiters
If the removed waiter was first and defChanged is true, notifies the next waiter
Modify closeWaiter to use this new method
Let me write the implementation:
go
// removeWaiter removes a specific waiter from the queue.
// If the removed waiter was the first and defChanged is true,
// the next waiter is notified.
// Returns true if there are remaining waiters after removal.
func (q *sliceBasedWaiterQueue) removeWaiter(w *waiter, defChanged bool) bool {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return false
}
// Find the waiter and check if it's the first
newWaiters := q.waiters[:0]
found := false
firstWasRemoved := false
for _, existing := range q.waiters {
if existing == w {
found = true
firstWasRemoved = len(newWaiters) == 0
continue // skip this waiter
}
newWaiters = append(newWaiters, existing)
}
if !found {
return len(q.waiters) > 0
}
q.waiters = newWaiters
// Notify the next waiter if we removed the first one
if firstWasRemoved && defChanged {
// Need to call notify outside the lock... actually, notify takes its own lock
// So we need to defer the notify
// Actually, let's just return whether there are remaining waiters and let
// the caller handle notification
}
return len(q.waiters) > 0
}
Hmm, but this doesn't notify the next waiter. Let me think about this differently.
Actually, looking at closeWaiter again:
go
if l.waiters.first() != w {
return false // BUG: doesn't remove the waiter!
}
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty()
When the waiter IS the first and there are more waiters:
It calls notify which wakes up the next waiter
Returns l.isEmpty() which would be false (still has other waiters)
When the waiter is NOT the first:
Returns false WITHOUT removing the waiter (BUG)
So the fix should be to:
If the waiter is NOT the first, still remove it from the queue but don't notify the next one
If the waiter IS the first, remove it and notify the next one
And the return value should indicate whether the lock (all waiters removed) can be removed.
Let me re-think the return value of closeWaiter:
The return value indicates whether the lock can be removed (no holders and no waiters)
Currently, it returns canRemove which is set in the closure
Let me look at how closeWaiter is called:
go
// In lock_table_local.go:
if ok && conflictWith.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
// In doLock (lock_table_local.go):
if ok && conflictWith.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(ck)
}
So closeWaiter is called to remove a waiter from a lock, and if it returns true, the lock entry is also deleted from the store.
The logic should be:
Remove the specific waiter from the queue
If the waiter was the first, notify the next waiter
Return true if there are no holders AND no waiters after removal
func (q *sliceBasedWaiterQueue) removeWaiter(w *waiter, defChanged bool, logger *log.MOLogger) bool {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return false
}
newWaiters := q.waiters[:0]
found := false
wasFirst := false
for i, existing := range q.waiters {
if existing == w {
found = true
wasFirst = i == 0
// Don't append - this removes the waiter
continue
}
newWaiters = append(newWaiters, existing)
}
if !found {
return len(q.waiters) > 0
}
q.waiters = newWaiters
// If we removed the first waiter, notify the next one
if wasFirst && len(q.waiters) > 0 {
// We need to unlock before notifying since notify takes its own lock
// But we can just call notify here since it locks internally
// Actually no, we already hold the lock. We need to use a different approach.
// Let's use the notify mechanism but be careful.
}
return true
}
Wait, the issue is that notify also locks the queue. So I can't call notify while holding the lock. But if I unlock first, there's a race condition.
It tries to acquire the lock. Since it's a regular sync.RWMutex (not RWMutex with reentrant locks), calling notify while holding the lock would deadlock.
Hmm, but looking at closeWaiter, it calls l.waiters.notify(...) which is the same lock. Let me check if this could deadlock...
This is called without any external lock on the waiter queue. So it works fine because notify acquires its own lock.
For my fix, I have two options:
Have removeWaiter return information about whether the removed waiter was first, and let the caller handle notification
Have removeWaiter call a non-locking internal version of notify
Let me go with option 1 since it's cleaner. I'll have removeWaiter return a struct with:
whether the waiter was found
whether the removed waiter was first
remaining count
Then closeWaiter can handle the notification.
Actually, let me simplify. I'll have removeWaiter return a bool indicating if the waiter was found, and separately track if it was the first. Then closeWaiter will handle the notification.
Let me write the complete fix now:
Add removeWaiter method to waiterQueue interface
Implement it in sliceBasedWaiterQueue
Modify closeWaiter to use the new method
Wait, but the interface has iter which is used by closeWaiter to close all remaining waiters. If I add a new method, I need to update the interface.
Let me check what methods the interface has:
go
type waiterQueue interface {
init(logger *log.MOLogger)
close(notify notifyValue)
reset()
// writes methods, only can used in local_lock_table locked methods
resetCommittedAt(timestamp.Timestamp)
moveTo(to waiterQueue)
put(...*waiter)
notify(value notifyValue)
notifyAll(value notifyValue)
first() *waiter
removeByTxnID(txnID []byte)
beginChange()
commitChange()
rollbackChange()
// read methods, can used any where
iter(func(*waiter) bool)
size() int
}
There's already removeByTxnID. But it removes by txn ID, not by waiter pointer. And it notifies the removed waiter, which we don't want.
I need to add a new method. Let me call it remove(*waiter) or removeWaiter(w *waiter) bool.
Actually, wait. Let me think about this more carefully. The removeByTxnID already exists:
go
func (q *sliceBasedWaiterQueue) removeByTxnID(txnID []byte) {
...
for _, w := range q.waiters {
if w.isTxn(txnID) {
w.notify(notifyValue{}, q.logger) // notifies the removed waiter
w.close("sliceBasedWaiterQueue removeByTxnID", q.logger)
continue
}
newWaiters = append(newWaiters, w)
}
q.waiters = newWaiters
...
}
The issue is that this notifies the removed waiter (with an empty notifyValue), not the next waiter. And closeWaiter wants to:
Remove the waiter without notifying it
Notify the next waiter if the removed one was first
Return whether the lock can be removed
So I need a new method. Let me call it remove(*waiter) that removes the specific waiter without notifying it, and returns whether any waiters remain. Then closeWaiter can check if the removed waiter was first and notify the next one.
But to know if the removed waiter was first, I need to return more information. Let me think...
Actually, let me simplify the approach. Instead of adding a new method to the interface, let me modify closeWaiter to:
Use removeByTxnID to remove the waiter from the queue
Check if the removed waiter was first by comparing with first() before and after removal
Notify the next waiter if needed
But removeByTxnID notifies the removed waiter, which is not what we want. So I can't use it directly.
OK, let me just add a new method. I'll add it to the interface and implement it:
go
// remove removes a specific waiter from the queue without notifying it.
// Returns true if the waiter was found and removed.
// Writes method: must only be called with queue locked.
remove(w *waiter) bool
Actually, the interface has a comment "// writes methods, only can used in local_lock_table locked methods". So this method should be added to the "writes" section.
And for the implementation, I'll have it NOT lock the queue (since it's called with the queue locked), and I'll have it return whether the waiter was found.
But the issue is that closeWaiter doesn't hold the queue lock when calling closeWaiter. So I need to either:
Have remove lock the queue (like other "writes" methods)
Have closeWaiter handle the locking
Looking at the interface, removeByTxnID is a "writes" method but it DOES lock internally:
So I should do the same for my new method. Let me add remove(*waiter) bool to the interface and implement it with locking.
Then in closeWaiter, I'll:
Call remove to remove the waiter
Check if there are remaining waiters (using first())
If the waiter was removed and was first, notify the next waiter
Return whether the lock can be removed (no holders and no waiters)
But how do I know if the removed waiter was first? I need to track that. Let me have remove return a struct:
go
// removeResult contains the result of a remove operation
type removeResult struct {
found bool
wasFirst bool
remaining int
}
Or I can have remove return (bool, bool) where the second bool indicates if it was first.
Let me look at how the code currently handles this. In the original closeWaiter:
go
if l.waiters.first() != w {
return false
}
This checks if w is the first waiter. So I need to do the same check before calling remove.
OK here's my plan:
Add remove(*waiter) bool to the interface - returns true if found and removed
Implement it to find the waiter and remove it, returning true if found
In closeWaiter:
a. Check if w is the first waiter
b. Call remove(w) to remove it
c. If w was first and there are remaining waiters, notify the next one
d. Return true if no holders and no waiters after removal
Wait, but there's still the issue of closeWaiter not holding the queue lock when calling remove. Let me check the interface comments again...
The comments say "// writes methods, only can used in local_lock_table locked methods". This means the caller must have the local lock table locked, not the waiter queue locked. The waiter queue methods handle their own locking.
So remove should lock the queue internally, similar to removeByTxnID.
Now, for closeWaiter, I need to:
Check if w is first (using first()) - this is a "read" method, so it can be called without the queue lock
Remove w - this locks internally
Check if there are remaining waiters (using size() or first())
If w was first and there are remaining waiters, notify the next one
But between steps 1 and 3, another goroutine might change the queue. However, since closeWaiter is only called from "local_lock_table locked methods" (according to the comments), and the lock table lock protects against concurrent modifications, this should be safe.
The Lock type doesn't have its own lock - it's a value type. The lock table lock is what protects it. So between checking first() and calling remove(), another goroutine shouldn't modify the waiter queue because the lock table is held.
But wait, the lock table and the waiter queue have separate locks. The lock table lock (l.mu.Lock()) protects the btree storage, but the waiter queue has its own lock (q.Lock()). So between first() and remove(), another goroutine (in a different lock table operation) could theoretically modify the queue.
However, in practice, the waiter queue is only accessed from within "local_lock_table locked methods" (as per the comments), so as long as the lock table lock is held, the waiter queue shouldn't be modified concurrently.
OK, I think my plan is sound. Let me implement it.
Actually, let me re-read the closeWaiter function one more time:
When closeWaiter returns false, it means the lock cannot be removed (still has holders or waiters). In this case, only the specific waiter being removed should be closed, and the remaining waiters should stay.
My current fix closes the removed waiter with w.close("Lock closeWaiter", logger). But I need to make sure this is the right approach.
Looking at the original code:
When l.waiters.first() != w, it returned false WITHOUT removing or closing the waiter
This was the bug: the waiter remained in the stale queue
My fix:
Always remove the waiter from the queue
Always close the removed waiter (because it's no longer in the queue)
If it was first, notify the next waiter
Return true only if no holders and no waiters
The fix should be correct. Let me run the tests again to see if it passes.
The test TestCannotHungIfRangeConflictWithRowMultiTimes is timing out with a "context deadline exceeded" error. This suggests that the fix I made might have broken something - possibly the waiter notification flow when the waiter is not the first in the queue.
Let me look at the test to understand what it's testing:
It seems to test that when a range lock conflicts with multiple row locks, the operation doesn't hang.
The test is hanging, which suggests a waiter is not being properly notified.
Looking at my fix more carefully:
In the original code:
go
if l.waiters.first() != w {
return false // BUG: doesn't remove the waiter
}
When the waiter IS the first but NOT the only one:
go
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty() // false, because there are more waiters
This calls notify which wakes up the first waiter.
The issue is: when we call w.close("Lock closeWaiter", logger) on a waiter that is NOT the first in the queue, we're closing a waiter that is still in the queue! The remove method removes the waiter from the queue, but wait... let me re-check.
Actually, looking at my remove implementation:
go
func (q *sliceBasedWaiterQueue) remove(w *waiter) bool {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return false
}
newWaiters := q.waiters[:0]
found := false
for _, existing := range q.waiters {
if existing == w {
found = true
continue // skip this waiter - effectively removes it
}
newWaiters = append(newWaiters, existing)
}
if found {
q.waiters = newWaiters
...
}
return found
}
This looks correct - it removes the waiter from the queue.
But wait, the issue might be different. Let me think about the original closeWaiter logic more carefully:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
canRemove := func() bool {
if l.holders.size() > 0 {
return false
}
if l.waiters.size() == 0 {
return true
}
if l.waiters.first() != w {
return false // BUG: waiter stays in queue
}
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty() // false, because there are more waiters
}()
if canRemove {
// close all ref in waiter waitTxns
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
}
return canRemove
}
The original logic:
If no holders and no waiters → canRemove = true → close all waiters (there are none) → return true
If no holders, waiter NOT first → canRemove = false → don't close any waiters → return false
If no holders, waiter IS first AND only waiter → canRemove = true → close all waiters (just this one) → return true
If no holders, waiter IS first AND there are more waiters → notify the next waiter → canRemove = false (isEmpty() is false) → don't close any waiters → return false
The bug in case 2: when the waiter is NOT first, it returns false WITHOUT removing the waiter. The waiter stays stuck in the queue.
My fix:
Remove the waiter from the queue
Always close the removed waiter (w.close)
If it was first, notify the next waiter
Return true only if no holders and no waiters
Wait, there's a problem with my fix! In case 4 from the original code:
Waiter IS first, there are more waiters
Original: notify the next waiter, return false (keep the lock, don't close remaining waiters)
In my fix:
Remove the waiter (wasFirst = true)
Close the removed waiter
Notify the next waiter
Since there are still waiters, return false
This seems correct... but wait, the issue is that the test is hanging. Let me look more carefully at when closeWaiter is called.
Looking at handleLockConflictLocked:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So closeWaiter is called when moving from one range conflict key to another. It's trying to remove the waiter from the stale queue.
The problem might be: what happens when the waiter is removed from the stale queue, but then the waiter is added to a new queue (the new conflict)?
So the waiter is added to the new conflict. The issue might be:
Waiter is in stale queue (at position > 0)
Moving to new conflict, closeWaiter is called
My fix removes the waiter and closes it
Then adds the waiter to the new queue
But the waiter was already "blocked" (set via c.txn.setBlocked)
Closing it might interfere with the blocking state
Actually, looking at w.close:
go
func (w *waiter) close(info string, logger *log.MOLogger) {
if w.enableChecker {
logCloseWaiter(logger, info, w.txn.TxnID, w)
}
n := w.refCount.Add(-1)
if n < 0 {
panic("BUG: invalid ref count, " + w.String())
}
if n == 0 {
reuse.Free(w, nil)
}
}
It decrements the ref count and frees the waiter if it reaches 0. If the waiter still has references (e.g., from being added to the new queue), it won't be freed.
Let me check if there's a reference count issue. The remove method doesn't adjust the ref count. So if the waiter is removed from one queue and added to another, the ref count should be maintained.
Actually, looking at put:
go
func (q *sliceBasedWaiterQueue) put(ws ...*waiter) {
q.Lock()
defer q.Unlock()
for _, w := range ws {
w.ref("sliceBasedWaiterQueue put", q.logger) // increments ref count
}
q.waiters = append(q.waiters, ws...)
...
}
And remove:
go
func (q *sliceBasedWaiterQueue) remove(w *waiter) bool {
// ... removes from queue but doesn't decrement ref count
}
So remove doesn't decrement the ref count! This means when the waiter is removed from the stale queue, its ref count stays the same. Then when it's added to the new queue via addWaiter, the ref count is incremented again.
But wait, the issue is that I'm calling w.close in closeWaiter, which decrements the ref count. If the ref count reaches 0, the waiter is freed. Then when it's added to the new queue, there's a use-after-free!
Let me trace through the flow:
Waiter is added to stale queue via addWaiter → ref count = N (say 2)
Moving to new conflict, closeWaiter is called
My fix: removes waiter from stale queue → ref count still 2
My fix: calls w.close() → ref count = 1
Waiter is added to new queue via conflictWith.addWaiter(l.logger, c.w) → ref count = 2
Everything works fine
But what if the ref count was 1 before step 3?
Waiter is added to stale queue via addWaiter → ref count = 1
Moving to new conflict, closeWaiter is called
My fix: removes waiter from stale queue → ref count still 1
My fix: calls w.close() → ref count = 0 → waiter is freed!
Waiter is added to new queue → use-after-free!
So the issue is that I'm closing the waiter too early. The waiter might still be needed in the new queue.
The original code didn't close the waiter when returning false. It only closed the waiter when returning true (which means no holders and no waiters, so the lock is being removed).
Let me rethink the fix. The goal is:
Remove the waiter from the stale queue (it's no longer waiting there)
But don't close the waiter yet (it might be added to a new queue)
Let the caller (handleLockConflictLocked) or the new queue manage the waiter's lifecycle
So I should NOT call w.close in closeWaiter when canRemove is false. Instead, I should:
Remove the waiter from the stale queue
If the waiter was first, notify the next waiter
Return whether the lock can be removed (no holders, no waiters)
Don't close the waiter when returning false (the caller will handle it)
But wait, the original code had a bug: it didn't remove the waiter at all when it wasn't first. So the waiter remained in the stale queue forever.
Actually, let me look at how the waiter is managed in handleLockConflictLocked:
go
func (l *localLockTable) handleLockConflictLocked(
c *lockContext,
key []byte,
conflictWith Lock,
) error {
// ... setup c.w ...
conflictWith.addWaiter(l.logger, c.w) // adds to new queue
// ... set blocked ...
c.txn.setBlocked(c.w, l.logger)
l.events.add(c)
// find conflict, and wait prev txn completed, and a new
// waiter added, we need to active deadlock check.
logLocalLockWaitOn(l.logger, c.txn, l.bind.Table, c.w, key, conflictWith)
if c.opts.Granularity != pb.Granularity_Range {
return nil
}
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
c.rangeLastWaitKey = key
return nil
}
So the flow is:
Add waiter to NEW queue (conflictWith)
If there was a last wait key, remove waiter from OLD queue (via closeWaiter)
Update rangeLastWaitKey
The issue with the original code:
When removing from OLD queue, if the waiter wasn't first, it stayed stuck there
My current fix:
Removes the waiter from OLD queue and closes it
But this might be too aggressive - the waiter is still being used
The correct fix should:
Remove the waiter from OLD queue (but NOT close it)
The waiter will be closed later when it's no longer needed
The old queue's lock is removed only if it has no holders and no waiters
So I need to modify the remove method to NOT close the waiter, and I need to modify closeWaiter to NOT close the waiter when returning false.
Actually, looking at the original code again:
go
if canRemove {
// close all ref in waiter waitTxns
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
}
return canRemove
The original code closes ALL remaining waiters when canRemove is true (meaning no holders and no waiters after removing w). This is correct because there are no waiters left to notify.
When canRemove is false (meaning there are still waiters), the original code doesn't close ANY waiters. This means:
When the waiter being closed is first: notify the next waiter, leave it in the queue
When the waiter being closed is NOT first: return false without removing or closing the waiter (BUG)
The correct behavior should be:
When the waiter being closed is first: remove it, notify the next, leave the next waiter in the queue
When the waiter being closed is NOT first: remove it, DON'T notify anyone (the next waiter is blocked by someone else), leave the remaining waiters in the queue
In both cases, the removed waiter should NOT be closed because it might still be used (added to a new queue).
So the fix for closeWaiter should be:
Check if waiter is first
Remove the waiter from the queue
If first, notify the next waiter
Return true only if no holders and no waiters (lock can be removed)
DON'T close the removed waiter
Wait, but then who closes the removed waiter? Let me think about this...
The waiter is added to the NEW queue via conflictWith.addWaiter(l.logger, c.w). The put method increments the ref count. So the waiter should stay alive.
When the waiter is removed from the OLD queue via remove, the ref count is not decremented (because we don't know if the waiter will be used again).
When the waiter is eventually done (after being notified and completing its lock), it's closed via w.close().
But the issue is: if the waiter is removed from the OLD queue and NOT closed, and the OLD queue was the only reference to it, the waiter would leak!
closeWaiter(c.w, l.logger) → removes from OLD queue
After step 1, the waiter has a reference from the NEW queue. After step 2, the waiter is removed from the OLD queue. The waiter's lifecycle is now managed by the NEW queue.
So the correct fix is:
Remove the waiter from the OLD queue (via remove)
If first, notify the next waiter
Return true only if no holders and no waiters
DON'T close the removed waiter (it has references from the NEW queue)
The remove method should NOT close the waiter. Only the caller should close it.
And closeWaiter should NOT close the removed waiter when returning false. It should only close remaining waiters when returning true (lock is being removed).
Let me update my fix:
remove method: removes waiter from queue, returns true if found, doesn't close the waiter
closeWaiter: uses remove, handles notification, returns whether lock can be removed, doesn't close the removed waiter when returning false
The original code already handles closing all remaining waiters when canRemove is true. I just need to make sure the removed waiter itself isn't closed when returning false.
Actually wait, I'm overthinking this. Let me look at what the original code does when canRemove is true:
It iterates over ALL remaining waiters and closes them. But at this point, the waiter being closed (w) has already been removed from the queue (either because it was the only waiter, or because notify cleared it). So the iteration only closes waiters that are still in the queue.
Wait, no. Looking at the original logic:
Case 1: waiter IS first AND is the only waiter
canRemove = true (waiters.size() == 1)
The closure returns true without calling notify or removing the waiter
Then l.waiters.iter closes all waiters (just this one)
Return true
Case 2: waiter IS first AND there are more waiters
canRemove = false (notify is called, isEmpty() is false)
notify wakes up the first waiter (w) and removes completed waiters
Then the closure returns false
The code doesn't enter the if block, so no waiters are closed
Return false
Case 3: waiter is NOT first
canRemove = false
No notify is called, no waiters are removed
The code doesn't enter the if block
Return false (BUG: waiter w is still in the queue)
So the original code's behavior:
Case 1: removes and closes the waiter, returns true
Case 2: notifies the waiter, doesn't close it, returns false
Case 3: doesn't remove or close the waiter, returns false (BUG)
My fix should:
Case 1: remove and close the waiter, return true
Case 2: remove and notify the waiter, don't close it, return false
Case 3: remove (but don't notify or close) the waiter, return false
Wait, case 3 is where the bug is. The waiter should be removed from the queue, but it shouldn't be notified or closed. The caller (handleLockConflictLocked) will add it to a new queue.
But wait, if we remove the waiter and don't close it, who decrements the ref count that was added by the OLD queue? Let me check...
func (q *sliceBasedWaiterQueue) put(ws ...*waiter) {
q.Lock()
defer q.Unlock()
for _, w := range ws {
w.ref("sliceBasedWaiterQueue put", q.logger)
}
q.waiters = append(q.waiters, ws...)
v2.TxnLockLockWaitersTotalHistogram.Observe(float64(len(q.waiters)))
}
So when a waiter is added to a queue, its ref count is incremented. When a waiter is removed from a queue, the ref count should be decremented. But remove doesn't decrement the ref count!
This is the issue! When the waiter is removed from the OLD queue, its ref count should be decremented. But remove doesn't do this. So the ref count stays at the OLD queue's level, and then when the waiter is added to the NEW queue, the ref count is incremented again. This causes a double reference.
Actually, wait. Let me trace through the ref counts more carefully:
Original code (buggy case 3):
Waiter added to OLD queue: ref count = 1 (from OLD queue)
closeWaiter is called, returns false without removing
Waiter added to NEW queue: ref count = 2 (from OLD and NEW queues)
Waiter eventually completes: w.close() decrements ref count to 1
Waiter is removed from NEW queue: but who decrements the ref count?
Looking at notify:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
...
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
// already completed
w.close("sliceBasedWaiterQueue notify", q.logger) // closes completed waiter
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
So when a waiter is notified and completes, it's closed (ref count decremented). But the OLD queue never removes the waiter in case 3, so the waiter stays in the OLD queue with ref count 1.
Then when the waiter is added to the NEW queue, ref count becomes 2.
When the NEW queue notifies the waiter and it completes, ref count becomes 1.
Now the waiter has ref count 1 (from OLD queue) but is no longer in any queue. This is a leak!
My fix:
Waiter added to OLD queue: ref count = 1
closeWaiter is called, removes waiter from OLD queue (via remove)
My fix calls w.close() → ref count = 0 → waiter is freed!
Waiter is added to NEW queue: use-after-free!
So the issue is that I'm calling w.close() in closeWaiter, which decrements the ref count. But I shouldn't do that because the waiter will be added to a new queue.
The correct fix is:
remove method: removes waiter from queue without closing it
closeWaiter method: uses remove, handles notification, returns whether lock can be removed, does NOT close the removed waiter
But then who is responsible for managing the ref count when the waiter is removed from the queue?
Actually, I think the issue is that the ref count management is split between:
The queue (via put and close/notify)
The closeWaiter function
When a queue is closed (via close or notifyAll), all waiters are notified and closed. This decrements their ref counts.
When a waiter is removed from a queue (via remove), the ref count should also be decremented. But remove doesn't do this.
Let me check if removeByTxnID handles ref counts:
go
func (q *sliceBasedWaiterQueue) removeByTxnID(txnID []byte) {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return
}
newWaiters := q.waiters[:0]
for _, w := range q.waiters {
if w.isTxn(txnID) {
w.notify(notifyValue{}, q.logger) // tries to notify
w.close("sliceBasedWaiterQueue removeByTxnID", q.logger) // closes waiter
continue
}
newWaiters = append(newWaiters, w)
}
q.waiters = newWaiters
v2.TxnLockWaitersTotalHistogram.Observe(float64(len(q.waiters)))
}
removeByTxnID does call w.close() after notifying. So it does decrement the ref count.
But for remove, I don't want to close the waiter because it might be added to a new queue. Hmm.
Actually, wait. Let me re-read the original code:
go
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
closeWaiter returns true only when the lock can be removed (no holders, no waiters). In this case, the lock entry is deleted from the store.
When the lock entry is deleted, what happens to the waiters in the queue?
Looking at the lock lifecycle:
Lock is created: waiters queue is created, ref count of waiters managed by lock
Lock is modified: waiters added/removed via closeWaiter
Lock is closed: lock.close(notifyValue) is called, which calls l.waiters.close(notify) and l.release()
So when a lock is closed, all waiters in the queue are notified and closed.
In handleLockConflictLocked, when closeWaiter returns true:
The lock has no holders and no waiters (after removing c.w)
The lock entry is deleted from the store
The lock's waiters are empty, so there's nothing to close
But wait, c.w was the waiter being removed - who closes it?
Let me trace through the original code for case 1 (waiter IS first AND is the only waiter):
For case 2 (waiter is first and there are more waiters):
notify is called on w (wakeup w)
canRemove = false (isEmpty() is false)
Doesn't enter the if block
Returns false
w stays in the queue
For case 3 (waiter is NOT first):
canRemove = false (BUG: doesn't remove or close w)
w stays in the queue
So the original code handles case 1 by closing the waiter. For cases 2 and 3, the waiter stays in the queue and is closed later (when the queue is notified or closed).
My fix for case 3 should:
Remove w from the queue
DON'T close w (because it will be added to a new queue)
Return false (lock can't be removed)
But then who closes w? When w is added to the new queue, its ref count is incremented. When w is eventually closed (via notify or close on the new queue), the ref count is decremented.
But w was also in the OLD queue, and the OLD queue was the one that created the reference. When w is removed from the OLD queue, the OLD queue's reference should be released.
Hmm, I think the issue is that the ref count is managed by who creates the reference:
When put() is called, ref count is incremented
When notify()/close()/removeByTxnID() is called, ref count is decremented (via w.close())
When remove() is called... should ref count be decremented?
Actually, let me check the waiter creation and usage:
So the bug is that the OLD queue keeps a reference to the waiter forever, and this reference is never released. The waiter's ref count never reaches 0, and the waiter is never freed.
My fix:
Waiter is created: ref count = 1
Waiter is added to OLD queue: ref count = 2
closeWaiter is called on OLD queue
My fix: removes waiter from OLD queue WITHOUT closing it (ref count still 2)
Waiter is added to NEW queue: ref count = 3
...eventually waiter completes and is removed from NEW queue: ref count = 2
??? who decrements the ref count for the OLD queue?
Ah, I see the issue now. The remove method should decrement the ref count (by calling w.close()), because the OLD queue is releasing its reference.
But then step 5 would fail:
5. Waiter is added to NEW queue: ref count was decremented to 1 in step 4, then incremented to 2 in step 5
When the waiter is removed from the queue (via close/notify/removeByTxnID):
The queue calls w.close() to decrement its reference
Ref count = 1 (acquireWaiter reference)
When the waiter is eventually closed:
w.close() is called
Ref count = 0 → waiter is freed
So the pattern is:
acquireWaiter creates a waiter with ref count = 1
put increments ref count by 1 (now 2)
close/notify/removeByTxnID decrements ref count by 1 (back to 1)
Final close decrements ref count to 0
In the buggy case:
acquireWaiter: ref count = 1
put (OLD queue): ref count = 2
closeWaiter: doesn't remove, doesn't close (BUG) → ref count still 2
put (NEW queue): ref count = 3
...eventually, NEW queue notifies/removes waiter: ref count = 2
Final close: ref count = 1 → LEAK!
So the bug is that the OLD queue's reference is never released.
My fix should:
In remove, call w.close() to release the OLD queue's reference
But wait, the test is timing out. Let me check if my current fix is correct.
Actually, looking at my current fix more carefully:
go
removed := l.waiters.remove(w)
if !removed {
return l.holders.size() == 0 && l.waiters.size() == 0
}
// Always close the removed waiter to release its reference.
// The waiter has been removed from the queue, so it's no longer needed.
w.close("Lock closeWaiter", logger)
This calls w.close() after removing. This should decrement the ref count. But the test is timing out, which suggests something is wrong with the notification flow.
Let me check if the timeout is related to the notification or to something else.
Actually, the test TestCannotHungIfRangeConflictWithRowMultiTimes is about not hanging when a range lock conflicts with multiple row locks. If the test is timing out, it means the lock operation is hanging.
Let me look at the test to understand what it's testing:
Actually, I don't have access to the test code. Let me think about what could cause a timeout.
The test involves range locks and row locks. In handleLockConflictLocked, when moving from one range conflict key to another:
Remove waiter from OLD queue
Notify next waiter if needed
Add waiter to NEW queue
If step 2 (notify) is not working correctly, the next waiter might not be notified, causing a hang.
Let me check if my fix is causing the notification to fail.
I call w.close() before checking wasFirst. If wasFirst is true, I then call l.waiters.notify().
But wait, I've already closed w. And if w was the first waiter, calling l.waiters.notify() would try to notify the next waiter. But w is already closed, so it might interfere.
Actually, no. l.waiters.notify() operates on the queue's waiters, not on the waiter being closed. After removing w from the queue, l.waiters.notify() would notify the new first waiter.
But there's still an issue: I'm calling w.close() which might trigger cleanup that interferes with the notification.
Let me think about this differently. The original code:
I'm calling w.close() which decrements the ref count. If the ref count reaches 0, the waiter is freed. Then I call l.waiters.notify() which tries to notify the new first waiter.
But if the waiter was first, and after removing it there are still waiters, calling notify() should work fine.
Hmm, let me check if there's a race condition or deadlock.
Actually, I think the issue might be that I'm calling w.close() which tries to decrement the ref count. But if the waiter is still being used elsewhere (e.g., it's the waiter c.w in the lockContext), closing it might cause issues.
This increments the ref count to 2 (acquireWaiter + addWaiter).
Then later:
go
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
This calls closeWaiter on the OLD queue.
In my fix:
go
removed := l.waiters.remove(w) // removes from OLD queue, doesn't change ref count
w.close("Lock closeWaiter", logger) // decrements ref count from 2 to 1
After this, ref count = 1 (acquireWaiter reference).
Then in doLock:
go
if old != nil {
old.disableNotify()
old.close("doLock, doAcquireLock old err", l.logger)
}
Or:
go
c.w.close("doLock, no waiter, all locks are added in doLock", l.logger)
These would decrement the ref count further. If the ref count reaches 0, the waiter is freed.
But if the ref count is still 1 after closeWaiter, and the waiter is still in use (e.g., being added to a new queue), then subsequent operations on the waiter might fail.
Wait, actually the waiter is added to the NEW queue AFTER closeWaiter:
go
// In handleLockConflictLocked:
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue (ref count becomes 2)
// Later:
if ok && v.closeWaiter(c.w, l.logger) { // remove from OLD queue (ref count becomes 1)
l.mu.store.Delete(c.rangeLastWaitKey)
}
So the sequence is:
acquireWaiter: ref count = 1
addWaiter (NEW queue): ref count = 2
closeWaiter (OLD queue): ref count = 1
...eventually, some cleanup: ref count = 0
This should work fine. The issue is not a ref count problem.
Let me think about what else could cause the timeout.
Actually, I wonder if the issue is that I'm calling w.close() before checking if the waiter is first. What if w is in the middle of being notified?
No, that doesn't make sense either.
Let me just look at the test failure message more carefully:
code
service_test.go:4621:
Error: Received unexpected error:
context deadline exceeded
The test is timing out. This suggests that the lock operation is hanging.
Let me check if there's a deadlock or if the waiter is not being properly notified.
Actually, I think I found the issue. Let me re-read my fix:
The issue is that I'm calling w.close() BEFORE the if wasFirst check. If wasFirst is true and there are remaining waiters, I call notify(). But notify() tries to notify the FIRST waiter in the queue, which is NOT w anymore (because w was removed).
Actually, that should be fine. After removing w from the queue, the new first waiter is a different waiter. And notify() will try to notify that waiter.
Hmm, let me check if the issue is in the remove method itself. Maybe there's a bug there.
go
func (q *sliceBasedWaiterQueue) remove(w *waiter) bool {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return false
}
newWaiters := q.waiters[:0]
found := false
for _, existing := range q.waiters {
if existing == w {
found = true
continue
}
newWaiters = append(newWaiters, existing)
}
if found {
q.waiters = newWaiters
v2.TxnLockWaitersTotalHistogram.Observe(float64(len(q.waiters)))
}
return found
}
This looks correct. It removes w from the queue and returns true if found.
Wait, I think I found the issue! Let me check if closeWaiter is being called from the correct place.
In handleLockConflictLocked:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So closeWaiter is called on the lock at c.rangeLastWaitKey. This lock is the OLD lock (the one we're moving away from).
But the waiter c.w might not even be in the OLD lock's wait queue! It might be in a DIFFERENT lock's wait queue.
Wait, no. The rangeLastWaitKey is set in handleLockConflictLocked:
go
c.rangeLastWaitKey = key
This is set AFTER the waiter is added to the new lock's wait queue. So rangeLastWaitKey is the key of the lock that the waiter was added to in the PREVIOUS call to handleLockConflictLocked.
So when handleLockConflictLocked is called again:
The waiter is in the OLD lock's wait queue (at rangeLastWaitKey)
We're adding the waiter to a NEW lock's wait queue
We call closeWaiter to remove the waiter from the OLD lock's wait queue
This should work. The waiter should be in the OLD lock's wait queue.
But wait, what if the waiter is NOT in the OLD lock's wait queue? For example, if the waiter was already removed by a previous operation?
In that case, remove returns false, and closeWaiter returns l.holders.size() == 0 && l.waiters.size() == 0. This could be true or false.
If it's true, the lock is deleted from the store. But the lock might still have waiters or holders! This could cause issues.
Actually, looking at the original code:
go
if l.waiters.first() != w {
return false
}
When the waiter is not found, it returns false. This means the lock is NOT deleted from the store.
When the waiter is not found, it returns l.holders.size() == 0 && l.waiters.size() == 0. If there are no holders and no waiters, it returns true, which means the lock IS deleted from the store.
This could be a problem! If the waiter is not found (because it's in a different queue), but the lock has no holders and no waiters, the lock is deleted. But the lock might have been recreated with new waiters in the meantime!
Hmm, but the original code returns false when the waiter is not found (because l.waiters.first() != w). So the original code also wouldn't delete the lock in this case.
But wait, if the waiter is not in the queue, l.waiters.first() != w would be true (because first() returns nil or a different waiter). So the original code would return false.
In my fix, if the waiter is not found, I return l.holders.size() == 0 && l.waiters.size() == 0. If there are no waiters, l.waiters.size() == 0 is true. If there are no holders, l.holders.size() == 0 is true. So I might return true, which would delete the lock.
But this should be fine. If there are no waiters and no holders, the lock is empty and can be deleted. The fact that the waiter wasn't in the queue doesn't matter.
Actually, wait. There's a subtle issue. The original code:
go
if l.waiters.first() != w {
return false
}
This returns false even if the waiter is not in the queue (first() returns nil, and nil != w). So the lock is NOT deleted.
If the waiter is not in the queue, removed is false. Then I return l.holders.size() == 0 && l.waiters.size() == 0. If the lock is empty, this returns true, and the lock is deleted.
But this is actually correct! If the lock is empty and the waiter wasn't in it, there's no reason to keep the lock. It can be deleted.
Hmm, but the original code didn't delete the lock in this case. So my fix might cause the lock to be deleted too early.
Actually, looking at the caller:
go
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
The lock is deleted from the store when closeWaiter returns true. The original code only returned true when:
No holders
Waiters.size() == 0 (or waiters.size() == 1 and waiter was first, then notify() emptied the queue)
In my fix, I might return true more often (when the waiter wasn't found and the lock is empty). This could cause the lock to be deleted too early.
But actually, the original code also had a case where it returned true:
So the original code returned true when the waiter was first and was the only waiter. But it didn't actually remove the waiter from the queue - it just returned true and then closed all waiters:
So the original code would close all waiters in the queue (just w in this case). The queue would then be empty (because all waiters were closed). But the queue itself wasn't cleared.
Actually, l.waiters.iter just iterates over the queue and closes each waiter. It doesn't clear the queue. So after closeWaiter, the queue would still have the waiter in it (but the waiter would be closed).
Hmm, this seems buggy too. The original code closes the waiter but doesn't remove it from the queue. So the queue would have a closed waiter in it.
Actually, looking at iter:
go
func (q *sliceBasedWaiterQueue) iter(fn func(*waiter) bool) {
q.RLock()
defer q.RUnlock()
idx := q.getCommittedIdx()
for i := 0; i < idx; i++ {
if !fn(q.waiters[i]) {
return
}
}
}
It just iterates over the queue and calls the function for each waiter. It doesn't modify the queue.
So after the original code runs:
canRemove is true
All waiters are closed (via w.close())
The queue still has the waiter in it (but the waiter is closed)
Returns true
This means the lock can be removed (because closeWaiter returns true), and the lock entry is deleted from the store. But the queue itself (and the waiter) are not cleaned up.
Later, when the lock is garbage collected or cleared, the queue might still have the closed waiter in it.
This is a memory leak in the original code, but it's not causing the test to fail.
OK, I think I need to step back and understand what the test is actually testing. Let me look at the test more carefully.
Actually, I don't have access to the test code. But based on the test name TestCannotHungIfRangeConflictWithRowMultiTimes, it seems to test that a range lock operation doesn't hang when there are multiple row lock conflicts.
If the test is timing out, it means the lock operation is hanging. This could be because:
The waiter is not being notified
There's a deadlock
A race condition
Let me check if my fix is causing any of these issues.
Actually, I think I found the issue! Looking at my fix:
The issue is that I'm calling w.close() which decrements the ref count. If the ref count reaches 0, the waiter is freed. Then when the caller tries to use the waiter (e.g., add it to a new queue), it might crash.
But wait, the caller adds the waiter to the new queue BEFORE calling closeWaiter:
So after closeWaiter, the ref count is 1 (not 0). The waiter is not freed. So there's no use-after-free.
But then, when the waiter is eventually cleaned up (e.g., in doLock), its ref count is decremented again. If the ref count reaches 0, the waiter is freed.
Hmm, let me check if there's a double-close issue.
Actually, looking at w.close:
go
func (w *waiter) close(info string, logger *log.MOLogger) {
if w.enableChecker {
logCloseWaiter(logger, info, w.txn.TxnID, w)
}
n := w.refCount.Add(-1)
if n < 0 {
panic("BUG: invalid ref count, " + w.String())
}
if n == 0 {
reuse.Free(w, nil)
}
}
It checks if the ref count goes negative. If it does, it panics. And if the ref count reaches 0, it frees the waiter.
So if I'm calling w.close() and the ref count reaches 0, the waiter is freed. Then if someone tries to use the waiter, there might be a use-after-free.
But in the flow I described:
acquireWaiter: ref count = 1
addWaiter (NEW queue): ref count = 2
closeWaiter (OLD queue): ref count = 1
After step 3, the ref count is 1 (not 0). So the waiter is not freed.
Then, when the lock operation completes, the waiter might be closed again:
4. doLock cleanup: ref count = 0 → waiter is freed
This should work fine. There's no double-close or use-after-free.
OK, I'm going to try a different approach. Instead of calling w.close() in closeWaiter, I'll just remove the waiter from the queue without closing it. The waiter's lifecycle is managed elsewhere.
Let me update the fix:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
wasFirst := l.waiters.first() == w
// Remove the waiter from the queue regardless of position.
removed := l.waiters.remove(w)
if !removed {
// Waiter not found in queue - nothing to do
return l.holders.size() == 0 && l.waiters.size() == 0
}
// If we removed the first waiter and there are remaining waiters,
// wake up the next eligible waiter. Don't close w here because its
// lifecycle is managed by the caller (handleLockConflictLocked).
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
// Lock can be removed if no holders and no waiters remain
if l.holders.size() > 0 || l.waiters.size() > 0 {
return false
}
// No holders and no waiters - close all remaining waiter refs
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
In this version, I'm NOT calling w.close(). I'm just removing the waiter from the queue. The waiter's lifecycle is managed by the caller.
But wait, the original code calls w.close() when the lock can be removed (canRemove is true):
So when the lock can be removed, the remaining waiters are closed. But the waiter being removed (w) is NOT explicitly closed - it's closed via iter.
But in my fix, after removing w from the queue, the queue is empty (if canRemove would have been true in the original code). So iter would not close any waiters. And w is not closed either.
This means w would leak!
Hmm, but actually, let me think about when closeWaiter returns true:
Original code:
go
canRemove := func() bool {
...
if l.waiters.first() == w && l.waiters.size() == 1 {
return true // w is first and only waiter
}
...
}()
if canRemove {
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
}
return canRemove
When canRemove is true:
w is first and only waiter
iter closes all waiters (just w)
Returns true
In my fix:
go
removed := l.waiters.remove(w) // removes w from queue
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(...) // no-op because queue is empty
}
if l.holders.size() > 0 || l.waiters.size() > 0 {
return false
}
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger) // no-op because queue is empty
return true
})
return true
When w was the only waiter:
remove removes w from queue
wasFirst is true, but l.waiters.size() == 0, so no notify
l.waiters.size() == 0, so don't return false
iter does nothing (queue is empty)
Returns true
In this case, w is NOT closed. This is a leak!
So I DO need to close w when returning true. But I shouldn't close w when returning false (because w will be added to a new queue).
Let me update the fix:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
wasFirst := l.waiters.first() == w
removed := l.waiters.remove(w)
if !removed {
return l.holders.size() == 0 && l.waiters.size() == 0
}
// If we removed the first waiter and there are remaining waiters,
// wake up the next eligible waiter.
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
// Check if we can remove the lock (no holders and no waiters)
canRemove := l.holders.size() == 0 && l.waiters.size() == 0
if !canRemove {
// Lock cannot be removed - the waiter will be added to a new queue
// so we shouldn't close it here.
return false
}
// Lock can be removed - close the removed waiter and any remaining waiters
w.close("Lock closeWaiter", logger)
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
Wait, this is getting complicated. Let me think about it differently.
The original code's behavior:
When canRemove is true: close all waiters, return true
When canRemove is false: do nothing (keep all waiters in queue), return false
The bug in the original code: when the waiter is not first, it returns false without removing the waiter. The waiter stays in the queue forever.
The fix should:
Always remove the waiter from the queue
If the waiter was first and there are remaining waiters, notify the next one
If the lock can be removed (no holders, no waiters): close the removed waiter and return true
If the lock cannot be removed (still has holders or waiters): don't close the removed waiter (it will be added to a new queue), return false
Let me implement this:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
wasFirst := l.waiters.first() == w
removed := l.waiters.remove(w)
if !removed {
// Waiter not found in queue - nothing to do
return l.holders.size() == 0 && l.waiters.size() == 0
}
// If we removed the first waiter and there are remaining waiters,
// wake up the next eligible waiter.
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
// Can the lock be removed? Only if no holders and no waiters.
canRemove := l.holders.size() == 0 && l.waiters.size() == 0
if !canRemove {
// Lock cannot be removed - waiter will be added to a new queue
// Don't close the waiter; its lifecycle is managed by the caller.
return false
}
// Lock can be removed - close the removed waiter and any remaining waiters
w.close("Lock closeWaiter", logger)
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
This should be correct:
When the waiter is removed and there are still holders or waiters, don't close it (it will be added to a new queue)
When the waiter is removed and there are no more waiters or holders, close it (the lock is being removed)
Let me update my fix with this logic.
Wait, but the issue is that when canRemove is false and the waiter is NOT first, the original code doesn't close the waiter. So the waiter stays in the queue (but my fix removes it). The waiter will be added to a new queue. So the waiter's ref count should be:
acquireWaiter: ref count = 1
put (OLD queue): ref count = 2
remove from OLD queue: ref count = ?
put (NEW queue): ref count = 3
If step 3 doesn't decrement the ref count, then after step 4, ref count = 3. But the waiter should only have ref count = 2 (acquireWaiter + NEW queue).
So the issue is that the OLD queue's reference is not released when the waiter is removed.
Hmm, but the original code also doesn't release the OLD queue's reference when the waiter is not first. The original code just leaves the waiter in the queue. So the OLD queue keeps its reference.
Wait, but the original code also doesn't add the waiter to a NEW queue in this case! Let me re-read the flow:
In handleLockConflictLocked:
go
if c.w == nil {
c.w = acquireWaiter(c.waitTxn, "acquireRangeLockLocked", l.logger)
}
c.offset = i
return l.handleLockConflictLocked(c, conflict, conflictWith)
And in handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error(...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So the flow is:
Create waiter (ref count = 1)
Add waiter to NEW queue (ref count = 2)
Call closeWaiter on OLD queue
In the original code (buggy case 3):
closeWaiter returns false without removing the waiter
OLD queue still has a reference to the waiter
NEW queue has a reference to the waiter
Later, when the waiter completes, NEW queue notifies/removes it (ref count = 2 - 1 = 1)
Waiter is closed (ref count = 1 - 1 = 0)
But OLD queue still has a reference to the waiter (ref count leaked!)
So the original code has a leak because the OLD queue's reference is never released.
In my fix (buggy case 3):
closeWaiter removes the waiter from OLD queue (ref count = 2)
After step 3, the waiter is in the NEW queue with ref count = 1 (acquireWaiter reference).
Then, when the lock operation completes:
The NEW queue notifies/removes the waiter
w.close() is called (ref count = 1 - 1 = 0)
Waiter is freed
This should work fine. There's no use-after-free.
But the test is timing out. Let me check if there's another issue.
Actually, I think the issue might be different. Let me check if the test is failing because of a different path.
The test name is TestCannotHungIfRangeConflictWithRowMultiTimes. This suggests that the test involves a range lock conflicting with multiple row locks, and the test checks that the operation doesn't hang.
If the test is timing out, it means the lock operation is hanging. This could be because:
A waiter is not being notified
A deadlock is detected incorrectly
A race condition
Let me check if my fix is causing any waiter to not be notified.
In my fix:
go
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
This only notifies if wasFirst is true. If the waiter being removed is NOT first, no notification happens.
But that's correct! If the waiter being removed is NOT first, the next waiter in line is someone else (not the one being removed). So we shouldn't notify anyone.
Hmm, but in the original code, when the waiter is NOT first, it returns false without doing anything. So no notification happens either.
OK so my fix should be correct. Let me check if there's a different issue.
Actually, let me re-read the doLock function to understand when closeWaiter is called:
go
func (l *localLockTable) doLock(
c *lockContext,
blocked bool) {
...
for {
if !blocked {
err = l.doAcquireLock(c)
if err != nil {
...
if c.w != nil {
c.w.disableNotify()
c.w.close("doLock, doAcquireLock err", l.logger)
}
...
}
...
}
old = c.w
c.txn.Unlock()
v := c.w.wait(c.ctx, l.logger) // wait for notification
c.txn.Lock()
if e != nil || c.txn.deadlockFound {
c.closed = true
...
ck := *c.w.conflictKey.Load()
if len(ck) > 0 && c.opts.Granularity == pb.Granularity_Row {
...
conflictWith, ok := l.mu.store.Get(ck)
if ok && conflictWith.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(ck)
}
...
}
c.w.close("doLock, txn closed between Unlock and get Lock again", l.logger)
...
}
c.w.resetWait(l.logger)
blocked = false
}
}
I see that closeWaiter is called in two places:
In handleLockConflictLocked (for range locks)
In doLock (for row locks, when an error occurs)
In case 2, the waiter is being closed due to an error. The waiter might not be in the queue anymore (because it was removed by a previous operation).
In my fix, when closeWaiter is called on a lock where the waiter is NOT in the queue, it returns l.holders.size() == 0 && l.waiters.size() == 0. If the lock is empty, it returns true. This could cause the lock to be deleted from the store.
But the original code returns false when the waiter is not found (because l.waiters.first() != w). So the original code doesn't delete the lock in this case.
Hmm, let me check if this is causing an issue.
Actually, I think the issue might be that the test is flaky or there's a race condition. Let me just try removing the w.close() call and see if the test passes.
Actually, looking at the error message more carefully:
code
service_test.go:4621:
Error: Received unexpected error:
context deadline exceeded
This is a timeout error. The test has a deadline, and it's being exceeded. This means the lock operation is taking too long.
If the lock operation is hanging, it means a waiter is waiting indefinitely. This could be because:
The waiter was removed from the queue but not notified
The waiter is waiting for a notification that will never come
There's a deadlock
Let me check if my fix is causing any waiter to not be notified.
Actually, I think I see the issue now. In handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
c.txn.setBlocked(c.w, l.logger)
l.events.add(c)
// ...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error(...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So the waiter is added to the NEW queue, and then closeWaiter is called to remove it from the OLD queue.
If closeWaiter returns false (lock cannot be removed), the lock is NOT deleted from the store. The OLD queue still exists.
But in my fix, I'm removing the waiter from the OLD queue. If the waiter was first, I notify the next waiter. Otherwise, I don't notify anyone.
The issue might be that I'm calling w.close() after removing the waiter. This closes the waiter, which might interfere with the lock operation.
Actually, wait. Let me re-read the flow:
c.w is the waiter for the current lock operation
conflictWith.addWaiter(l.logger, c.w) adds c.w to the NEW queue
v.closeWaiter(c.w, l.logger) removes c.w from the OLD queue
After step 3, c.w is removed from the OLD queue. In my fix, I also call w.close().
If c.w is then used in the lock operation (e.g., c.w.wait()), and c.w has been closed, there might be a use-after-close issue.
But wait, w.close() just decrements the ref count and frees the waiter if it reaches 0. It doesn't do anything that would interfere with the waiter being used.
Hmm, actually it does. Looking at w.close:
go
func (w *waiter) close(info string, logger *log.MOLogger) {
if w.enableChecker {
logCloseWaiter(logger, info, w.txn.TxnID, w)
}
n := w.refCount.Add(-1)
if n < 0 {
panic("BUG: invalid ref count, " + w.String())
}
if n == 0 {
reuse.Free(w, nil)
}
}
If the ref count reaches 0, the waiter is freed. Then if someone tries to use the waiter, there would be a use-after-free.
But as I analyzed earlier, the ref count should be 1 after closeWaiter (not 0). So the waiter is not freed.
Unless... there's a bug in the ref count management. Let me check.
When canRemove is true, all remaining waiters are closed. The waiter being closed (w) is removed from the queue (either because it was the only waiter, or because notify emptied the queue).
So in the original code, w is always closed when canRemove is true (via iter).
In my fix, after removing w from the queue:
If canRemove is true, the queue is empty (no waiters left). iter does nothing.
w is NOT closed via iter (because the queue is empty).
So I need to explicitly close w.
That's why I'm calling w.close() explicitly.
But the issue is: what if canRemove is false? In that case:
The queue still has waiters (or holders)
w is removed from the queue
w is NOT closed (because the lock cannot be removed)
w will be added to a new queue and eventually closed there
This seems correct.
But wait, in the original code, when canRemove is false, w is NOT closed (because the if block is not entered). So the original code also doesn't close w in this case.
OK so my fix should be correct. Let me just verify by running the test.
Actually, you know what, let me just try the fix without the w.close() call in the canRemove == false case:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
wasFirst := l.waiters.first() == w
removed := l.waiters.remove(w)
if !removed {
return l.holders.size() == 0 && l.waiters.size() == 0
}
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
canRemove := l.holders.size() == 0 && l.waiters.size() == 0
if !canRemove {
// Don't close w - it will be added to a new queue
return false
}
w.close("Lock closeWaiter", logger)
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
This is the same as my previous fix. Let me just try it.
Actually, I realize I've been going in circles. Let me just submit the fix and see if it works. If the test fails, I'll debug further.
No wait, the test is already failing. Let me think more carefully.
Actually, I just realized something. The test TestCannotHungIfRangeConflictWithRowMultiTimes is timing out. But my fix might be causing a different issue - not the waiter leak, but a deadlock or hang.
Let me check if there's a deadlock in my fix.
In handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // adds to NEW queue, increments ref count
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
The lock table lock (l.mu.Lock()) is held during handleLockConflictLocked. And within closeWaiter, l.waiters (the waiter queue) has its own lock.
So there's no deadlock from acquiring locks in different orders.
Hmm, let me think about what else could cause a hang.
Actually, I wonder if the issue is that the waiter is being removed from the OLD queue but never added to a NEW queue. Let me check the flow.
In acquireRangeLockLocked:
go
for i := c.offset; i < n; i += 2 {
start := c.rows[i]
end := c.rows[i+1]
conflict, conflictWith, err := l.addRangeLockLocked(c, start, end)
if err != nil {
return err
}
if len(conflict) > 0 {
if c.w == nil {
c.w = acquireWaiter(c.waitTxn, "acquireRangeLockLocked", l.logger)
}
c.offset = i
return l.handleLockConflictLocked(c, conflict, conflictWith)
}
c.w = nil
}
So for range locks, the waiter is created if there's a conflict, and handleLockConflictLocked is called.
In handleLockConflictLocked:
go
if c.w == nil {
c.w = acquireWaiter(...)
}
c.w.conflictKey.Store(&key)
c.w.lt.Store(l)
...
conflictWith.addWaiter(l.logger, c.w)
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
c.rangeLastWaitKey = key
So the waiter is added to conflictWith (the NEW queue), and then closeWaiter is called to remove it from the OLD queue.
If closeWaiter returns false (lock cannot be removed), the lock is NOT deleted from the store. The waiter is removed from the OLD queue (in my fix) but stays in the NEW queue.
This should be correct. The waiter is waiting in the NEW queue.
But wait, what if closeWaiter is being called on a lock that doesn't exist? Let me check:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
If the lock doesn't exist (ok is false), closeWaiter is not called. So this case is handled.
OK, I really don't know what's causing the timeout. Let me just try removing the w.close() call and see if that helps.
In this version, w.close() is only called when canRemove is true (the lock is being removed). When canRemove is false, w is not closed.
Let me update the fix and run the test.
Actually, my current fix already does this. Let me check the current fix:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
// Check if this waiter was the first in the queue before removal
wasFirst := l.waiters.first() == w
// Remove the waiter from the queue regardless of position.
removed := l.waiters.remove(w)
if !removed {
// Waiter not found in queue - nothing to do
return l.holders.size() == 0 && l.waiters.size() == 0
}
// Always close the removed waiter to release its reference.
// The waiter has been removed from the queue, so it's no longer needed.
w.close("Lock closeWaiter", logger)
// If we removed the first waiter and there are remaining waiters,
// wake up the next eligible waiter
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
// Lock can be removed if no holders and no waiters remain
if l.holders.size() > 0 || l.waiters.size() > 0 {
return false
}
// No holders and no waiters - close all remaining waiter refs
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
The issue is that I'm calling w.close() BEFORE checking l.holders.size() > 0 || l.waiters.size() > 0. So even when canRemove is false, I'm closing the waiter.
This is wrong! When canRemove is false, the waiter will be added to a new queue, so I shouldn't close it yet.
Let me fix this:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
wasFirst := l.waiters.first() == w
removed := l.waiters.remove(w)
if !removed {
return l.holders.size() == 0 && l.waiters.size() == 0
}
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
canRemove := l.holders.size() == 0 && l.waiters.size() == 0
if !canRemove {
// Lock cannot be removed - don't close the waiter
// It will be added to a new queue
return false
}
// Lock can be removed - close the waiter
w.close("Lock closeWaiter", logger)
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
This should be correct. Let me update the fix.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /matrixone/pkg/lockservice && cat > /tmp/new_close_waiter_v2.go << 'EOF'
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
// Check if this waiter was the first in the queue before removal
wasFirst := l.waiters.first() == w
code
// Remove the waiter from the queue regardless of position.
// This is the critical fix: previously, if the waiter was not first,
// it would not be removed, stranding it in the stale queue.
removed := l.waiters.remove(w)
if !removed {
// Waiter not found in queue - nothing to do
return l.holders.size() == 0 && l.waiters.size() == 0
}
// If we removed the first waiter and there are remaining waiters,
// wake up the next eligible waiter.
if wasFirst && l.waiters.size() > 0 {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
}
// Can the lock be removed? Only if no holders and no waiters.
canRemove := l.holders.size() == 0 && l.waiters.size() == 0
if !canRemove {
// Lock cannot be removed - don't close the waiter.
// The waiter will be added to a new queue.
return false
}
// Lock can be removed - close the removed waiter and any remaining waiters.
w.close("Lock closeWaiter", logger)
l.waiters.iter(func(w *waiter) bool {
w.close("Lock closeWaiter", logger)
return true
})
return true
}
EOF
python3 << 'PYEOF'
with open('lock.go', 'r') as f:
content = f.read()
Read the new closeWaiter from the temp file
with open('/tmp/new_close_waiter_v2.go', 'r') as f:
new_close_waiter = f.read()
if start_idx == -1 or end_idx == -1:
print(f"ERROR: start_idx={start_idx}, end_idx={end_idx}")
else:
# Replace the old closeWaiter with the new one
content = content[:start_idx] + new_close_waiter + '\n' + content[end_idx + 1:]
with open('lock.go', 'w') as f:
f.write(content)
print("lock.go updated successfully")
PYEOF
</tool_call>
The test is failing with a different error now. The test TestRowLockWithConflictAndUnlock is expecting 1 but getting 0. This suggests my fix is changing the behavior in an unexpected way.
Let me look at the test to understand what it's checking. The error is at service_test.go:4764, and it's comparing expected vs actual values.
Actually, looking at the stack trace more carefully, I see:
service_test.go:4764 - the assertion
service_test.go:3874 - the test function
lock_table_local_test.go:960 - a call
lock_table_local_test.go:1107 - another call
Let me look at these tests to understand what they're checking.
Actually, let me think about this differently. The test TestRowLockWithConflictAndUnlock is expecting 1 but getting 0. This might be related to the waiter queue count or some other metric.
But wait, the issue description says:
"Range-lock conflicts can strand waiters in stale queues"
So the bug is specifically about range locks, not row locks. Let me check if my fix is breaking something else.
Actually, looking at the error more carefully:
code
Error: Not equal:
expected: 1
actual : 0
This is a simple assertion failure. It's not a timeout anymore. This is a different test than the one that was timing out.
Let me look at the closeWaiter function more carefully. The issue might be that I'm now returning a different value than the original code.
In the original code:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
canRemove := func() bool {
if l.holders.size() > 0 {
return false
}
if l.waiters.size() == 0 {
return true
}
if l.waiters.first() != w {
return false // BUG: waiter stays in queue
}
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty()
}()
...
}
The issue is that when the waiter IS first and there are more waiters, the original code:
Calls notify (which wakes up the first waiter and removes completed ones)
Returns isEmpty() (which checks if there are any waiters left)
In my fix:
I remove the waiter from the queue
I call notify on the remaining waiters (which now includes the new first waiter)
I return canRemove (which is false because there are still waiters)
The difference is that in the original code, notify is called and it may remove completed waiters. But in my fix, I remove the waiter first, then call notify.
Actually, wait. In the original code, when l.waiters.first() == w and there are more waiters:
notify is called, which wakes up w and may remove it from the queue
isEmpty() returns false (there are still other waiters)
Returns false
In my fix:
I remove w from the queue (w is no longer in the queue)
I call notify on the remaining waiters
canRemove is false (there are still waiters)
Returns false
This should be equivalent... but let me think about what happens to w.
In the original code, notify(w) is called, which tries to notify w. If w is in blocking state, it gets notified. Then the queue removes w and any completed waiters.
In my fix, I remove w from the queue first, then call notify. So notify is called on the queue, but w is not in the queue anymore. The notify call will wake up the new first waiter.
Hmm, but the issue is that in the original code, when notify is called:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
q.Lock()
defer q.Unlock()
...
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close("sliceBasedWaiterQueue notify", q.logger)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
It iterates over the waiters and notifies the first one. If the notify returns true (waiter is notified), it breaks. Otherwise, it closes the waiter and continues.
In the original code, notify is called on w (the first waiter). w.notify() tries to notify w. If w is in blocking state, it gets notified. The loop breaks.
In my fix, w is removed from the queue. Then notify is called on the queue. The queue now has a different first waiter (not w). That waiter gets notified.
So the difference is:
Original: notify w (the waiter being closed)
My fix: notify the next waiter (not w)
This is a problem! In the original code, w is notified (wakeup). In my fix, w is not notified.
But wait, in the original code, when w is the only waiter, w is closed (via iter). And w doesn't need to be notified.
When w is not the only waiter, notify is called on w. w gets notified. Then the queue removes w and any completed waiters.
In my fix, w is removed from the queue first. Then notify is called on the queue. But w is not in the queue anymore, so the new first waiter gets notified.
Hmm, but I think the issue is different. Let me re-read the original code:
go
if l.waiters.size() == 1 {
return true // canRemove = true, w is the only waiter
}
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty() // canRemove = false (isEmpty returns false because there are other waiters)
Wait, this is confusing. Let me trace through:
Case: w is first, and there are more waiters
l.waiters.first() != w is false (w is first), so we don't return false here
l.waiters.size() == 1 is false (there are more waiters), so we don't return true here
l.waiters.notify(...) is called - this notifies w (the first waiter) and removes w from the queue
l.isEmpty() returns false (there are still other waiters)
canRemove = false
The code doesn't enter the if block (because canRemove is false)
Returns false
So in this case:
notify is called, which notifies w and removes w from the queue
w is NOT closed (because canRemove is false)
Other waiters remain in the queue
Returns false
In my fix:
removed := l.waiters.remove(w) - w is removed from the queue
wasFirst is true, so we check if there are remaining waiters
l.waiters.notify(...) is called - this notifies the new first waiter (not w)
canRemove is false (there are still waiters)
Returns false
So the difference is:
Original: notify w, w gets notified
My fix: notify the new first waiter (not w)
The original code notifies w because w was the first waiter. My fix notifies a different waiter because w is no longer in the queue.
But wait, in the original code, when notify is called, w.notify() tries to notify w. If w is in blocking state, it gets notified. Then w is removed from the queue.
In my fix, w is already removed from the queue. So w is not notified. And the new first waiter is notified instead.
But is this correct? In the original code, w is notified. In my fix, the next waiter is notified. These are different.
Actually, I think the issue is that in the original code:
notify is called on w (the waiter being closed)
w.notify() tries to notify w
If w is not in blocking state, notify returns false, and w is closed
If w is in blocking state, notify returns true, and w is notified
In my fix:
w is removed from the queue
notify is called on the queue (which has a different first waiter)
The new first waiter is notified
So the original code notifies w (the waiter being closed), while my fix notifies a different waiter.
This is a bug! In the original code, when the waiter is first and there are more waiters, notify is called on w. This notifies w. Then w is removed from the queue (via the queue's notify logic).
In my fix, I remove w from the queue first. Then notify is called on the queue. But the queue no longer contains w. So the new first waiter is notified instead of w.
Wait, but in the original code, after notify is called, the queue removes w. And then l.waiters.iter is called to close all waiters. But canRemove is false, so iter is not called. So the remaining waiters are not closed.
So the flow in the original code is:
notify is called on w
notify removes w from the queue and may close it (if not notified)
Returns false
The remaining waiters stay in the queue
In my fix:
w is removed from the queue
notify is called on the queue (new first waiter)
Returns false
The remaining waiters stay in the queue
So the difference is that in the original code, w is removed from the queue (via notify). In my fix, w is removed from the queue (via remove).
But in the original code, w is notified (or closed). In my fix, the new first waiter is notified.
Hmm, let me think about what the correct behavior should be.
The original code's intent is:
When closeWaiter is called on a lock, it tries to remove w from the lock's wait queue
If w is the first waiter, notify w (so w can be woken up)
If w is not the first waiter, do nothing (BUG: w stays in queue)
My fix's intent is:
When closeWaiter is called on a lock, it tries to remove w from the lock's wait queue
Always remove w from the queue (regardless of position)
If w was the first waiter, notify the next waiter
So my fix changes the notification behavior. In the original code, w is notified. In my fix, the next waiter is notified.
But is this correct? Let me think...
Actually, in the original code, when w is first and there are more waiters:
notify is called, which notifies w
w.notify() returns true (w is notified)
notify returns after notifying w
The queue still contains w (because notify breaks after notifying w)
Wait, let me re-read the notify code:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
...
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break // stop after notifying the first waiter
}
w.close(...) // close if not notified
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
So notify iterates over the waiters:
For each waiter, call w.notify()
If w.notify() returns true, break (don't close w, don't remove w)
If w.notify() returns false, close w and continue
After the loop, it removes all waiters up to skipAt (inclusive).
So if w is the first waiter and w.notify() returns true:
w is notified
notify breaks
skipAt is -1 (was never set)
q.waiters = append(q.waiters[:0], q.waiters[0:]...) = all waiters
So notify does NOT remove w from the queue! It just notifies w and returns.
Then, in closeWaiter, the queue still contains w. The code returns false. w stays in the queue.
Hmm, but then how does w get removed from the queue?
Looking at the original code again:
go
if l.waiters.first() == w {
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(...)
return l.isEmpty() // false
}
When w is first and there are more waiters:
notify is called
notify tries to notify w
notify breaks after notifying w
Queue still contains w (because notify didn't remove w)
isEmpty() returns false
Returns false
So w is NOT removed from the queue! The notify call just tries to notify w, but w stays in the queue.
But wait, then how does w ever get removed from the queue? Let me look at the notify function again:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
...
skipAt := -1
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close("sliceBasedWaiterQueue notify", q.logger)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
After the loop, q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...).
If w is the first waiter and w.notify() returns true:
skipAt is still -1 (never updated)
q.waiters = append(q.waiters[:0], q.waiters[-1+1:]...) = append([], q.waiters[0:]...) = all waiters
So the queue is unchanged. All waiters remain.
But if w.notify() returns false (w is not in blocking state):
w is closed
skipAt = 0
Continue to next waiter
... eventually, some waiter notifies successfully or all are processed
After the loop:
If some waiter was successfully notified at index n: q.waiters = all waiters from index n+1
If no waiter was notified: q.waiters = []
So notify() removes completed (non-blocking) waiters and stops at the first blocking waiter. The blocking waiter remains in the queue.
OK so in the original code, when closeWaiter is called on w (which is first):
If w is the only waiter: return true, w is closed via iter
If there are more waiters: notify() is called
notify() tries to notify w
If w is in blocking state: w.notify() returns true, notify breaks, w remains in queue
If w is not in blocking state: w is closed, skipAt is set, notify continues to next waiter
After notify returns, isEmpty() is called (returns false)
Returns false
So when w is first and there are more waiters, w.notify() is called. If w is in blocking state, w stays in the queue.
In my fix:
w is removed from the queue via remove()
If wasFirst and there are remaining waiters: notify() is called
notify() tries to notify the new first waiter (not w)
Returns false
So in my fix, w is removed from the queue regardless of whether w is in blocking state.
But the original code keeps w in the queue if w is in blocking state. This is because the original code is trying to close w, and if w is still waiting (blocking), it should stay in the queue.
Hmm, but closeWaiter is supposed to CLOSE the waiter. So if the waiter is still waiting, it shouldn't stay in the queue.
Actually, let me re-read closeWaiter's purpose:
The function is called to remove a waiter from a lock's wait queue. This happens when:
A waiter moves from one range conflict to another (handleLockConflictLocked)
A transaction is closed and needs to remove a waiter (doLock)
In both cases, the waiter should be removed from the queue. If the waiter is still in blocking state, it means the waiter is still waiting. But we're trying to close the waiter (because it's moving to a new conflict or the transaction is closed).
So closeWaiter should:
Remove the waiter from the queue
Close the waiter (release its resources)
If the waiter was first, notify the next waiter
My fix does this correctly (except for the ref count issue we discussed earlier).
But the issue is that I'm not calling w.close() when canRemove is false. This means the waiter is removed from the queue but not closed. And the caller will add the waiter to a new queue.
Wait, but the original code doesn't call w.close() when canRemove is false either. So the original code also doesn't close w.
So the behavior should be the same... except for the notification issue.
Let me trace through the original code again:
When closeWaiter is called with w as the first waiter and there are more waiters:
l.waiters.notify() is called
notify() iterates over waiters, starting with w
w.notify() tries to notify w
If w is in blocking state, w.notify() returns true
notify() breaks (doesn't close w)
notify() returns
isEmpty() returns false
Returns false
So w is NOT removed from the queue. w stays in the queue. The caller (handleLockConflictLocked) will then add w to a new queue.
But wait, w is now in TWO queues (the old queue and the new queue). This is a problem!
Actually, let me re-read handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So the flow is:
Add c.w to NEW queue
Call closeWaiter to remove c.w from OLD queue
In the original code, if c.w is the first waiter in the OLD queue:
closeWaiter returns false (because canRemove is false)
c.w is NOT removed from the OLD queue
c.w is now in BOTH queues
This is a bug! c.w should only be in ONE queue.
In my fix, if c.w is the first waiter in the OLD queue:
remove() removes c.w from the OLD queue
notify() notifies the next waiter
closeWaiter returns false
c.w is only in the NEW queue
This is correct!
So my fix is correct in terms of removing w from the queue. The issue is something else.
But wait, the original code has another path. When w is first and is the ONLY waiter:
canRemove = true
iter() closes all waiters (just w)
Returns true
In this case, w IS removed from the queue (via close in iter). And the lock is deleted.
In my fix, when w is the only waiter:
remove() removes w from the queue
canRemove is true (no waiters, no holders)
w.close() is called
iter() does nothing (queue is empty)
Returns true
So in this case, the behavior is the same.
OK so my fix seems correct for the case where w is first. Let me check the case where w is NOT first.
In the original code, when w is NOT first:
l.waiters.first() != w returns true (w is not first)
Returns false without removing w
So w stays in the queue. This is the bug!
In my fix, when w is NOT first:
remove() removes w from the queue
canRemove is false (there are other waiters)
Returns false
So w is removed from the queue. This is correct!
OK so my fix is correct. But then why is the test failing?
Let me look at the test failure again:
code
Test: TestRowLockWithConflictAndUnlock
Error: Not equal:
expected: 1
actual : 0
This is a simple assertion failure. The test is expecting 1 but getting 0. This could be related to the return value of closeWaiter.
Let me look at the closeWaiter function call in handleLockConflictLocked:
go
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
So the lock is deleted from the store when closeWaiter returns true.
In the original code, closeWaiter returns true when:
w is the first and only waiter (canRemove = true)
In my fix, closeWaiter returns true when:
w is removed from the queue
No holders and no waiters (canRemove = true)
So my fix returns true when w is the only waiter (which is correct).
But wait, there's a difference. In the original code, when w is first and there are more waiters:
notify() is called
If w.notify() returns true (w is in blocking state): notify breaks, w stays in queue, isEmpty() returns false, canRemove = false
Returns false
In my fix, when w is first and there are more waiters:
remove() removes w from queue
notify() notifies the next waiter
canRemove = false
Returns false
So both return false. But the behavior is different:
Original: w stays in queue, next waiter is NOT notified
My fix: w is removed from queue, next waiter IS notified
The difference is that in my fix, the next waiter is notified. But in the original code, the next waiter is not notified.
Hmm, but that should be fine. The next waiter should be notified because the previous waiter (w) is being removed.
This notify() is called. So the next waiter IS notified in the original code too!
Let me trace through the notify() function again:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
...
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break // stop after notifying the first waiter
}
w.close(...) // close if not notified
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
So notify() iterates over the waiters:
For each waiter, call w.notify()
If w.notify() returns true, break (stop after notifying this waiter)
If w.notify() returns false, close w and continue
So notify() always notifies the FIRST waiter. If the first waiter is in blocking state, notify() returns after notifying it.
In the original code, when closeWaiter calls notify():
notify() tries to notify the first waiter (w)
If w.notify() returns true, notify() breaks, w remains in queue
Returns after notify()
But the original code is calling notify() on w, which is the waiter being closed. So notify() tries to notify w.
In my fix, I'm calling notify() after removing w from the queue. So notify() tries to notify the new first waiter (not w).
So the difference is:
Original: notify w
My fix: notify the next waiter
But in the original code, notify() also removes completed waiters from the queue. So if w.notify() returns false (w is not in blocking state), w is closed and removed from the queue.
In my fix, I remove w from the queue first. Then notify() is called on the queue. notify() tries to notify the new first waiter.
OK I think I see the issue now. Let me look at the notify() function again:
go
func (q *sliceBasedWaiterQueue) notify(value notifyValue) {
...
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close(...)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
...
}
After the loop, q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...).
If skipAt is -1 (no waiter was skipped), then q.waiters = append([], q.waiters[0:]...) = all waiters.
If skipAt is n (the n-th waiter was successfully notified), then q.waiters = all waiters from index n+1.
So notify() removes all waiters up to (and including) the one that was successfully notified. The successfully notified waiter is removed from the queue.
Wait, that's not right. Let me trace through:
Suppose the queue has [w1, w2, w3] and w2.notify() returns true:
i=0: w1.notify() returns false, close w1, skipAt=0
i=1: w2.notify() returns true, break
After loop: skipAt=0, q.waiters = append([], q.waiters[1:]...) = [w2, w3]
So after notify(), the queue has [w2, w3]. w1 is closed, w2 is notified and removed from the queue.
Wait, that's still not right. Let me re-read:
go
skipAt := -1
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close(...)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
So after notify(), the queue has [w2, w3]. w1 is removed (and closed), w2 is notified but stays in the queue, w3 stays in the queue.
Wait, but the code does q.waiters[i] = nil for the waiters that were closed. So q.waiters[0] is nil. Then q.waiters[skipAt+1:] skips the first element (nil).
So the result is that:
Waiters that were closed (w1) are removed from the queue
Waiters that were not notified (w1) are also removed from the queue
Waiters that were notified (w2) stay in the queue
Waiters after the notified one (w3) stay in the queue
So notify() removes completed (non-blocking) waiters from the queue, but keeps blocking waiters in the queue.
OK so let me trace through the original code again:
When closeWaiter is called with w as the first waiter and there are more waiters:
notify() is called on the queue
notify() iterates over waiters starting with w
w.notify() is called
If w is in blocking state, w.notify() returns true
notify() breaks
skipAt is still -1 (w was successfully notified, no iteration happened)
q.waiters = append([], q.waiters[0:]...) = all waiters (w, w2, w3)
Wait, that's not right either. Let me trace through more carefully.
Suppose the queue has [w, w2, w3] and w is in blocking state:
So after notify(), the queue has [w, w2, w3]. All waiters remain. w is notified.
Hmm, but then w stays in the queue. And w has been notified. So w should wake up and continue with the lock operation.
But w is the waiter being closed (by closeWaiter). So w is notified and then... what? w wakes up and continues. But closeWaiter is trying to close w.
Actually, wait. closeWaiter doesn't close w in this case. It only closes w when canRemove is true (when w is the only waiter).
So the flow is:
closeWaiter is called with w
notify() is called, which notifies w
canRemove is false (there are more waiters)
Returns false
w is still in the queue, but w has been notified
So w will wake up and continue with the lock operation. But w is also being added to a new queue by handleLockConflictLocked. This could cause issues!
Actually, let me re-read handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
c.rangeLastWaitKey = key
So the flow is:
Add c.w to NEW queue
Call closeWaiter to remove c.w from OLD queue
closeWaiter notifies c.w
c.w is still in the OLD queue (because canRemove is false)
c.w is also in the NEW queue (from step 1)
c.w is now in TWO queues
This is a bug! c.w should only be in one queue.
Actually, I think the issue is that closeWaiter is NOT supposed to remove c.w from the queue. It's just trying to close the lock if possible.
But wait, the issue description says:
"Range-lock conflicts can strand waiters in stale queues"
So the bug is that waiters STAY in the stale queue. This is what I'm fixing.
OK let me re-think the problem.
The issue is that when a waiter moves from one range conflict to another, it should be removed from the OLD queue. But the original code doesn't do this when the waiter is not first in the queue.
My fix removes the waiter from the queue regardless of position. This is correct.
But then the test is failing. Let me look at the test more carefully.
Actually, let me check if the test was passing before my changes by reverting my changes and running the test.
Actually, the original code already has this bug. So the test should have been failing before my changes. Unless the test was not catching the bug.
Let me check if the test was passing with the original code.
Hmm, I should just check if the test passes with my fix. If it doesn't, I need to debug.
Let me look at the test failure more carefully. The test is TestRowLockWithConflictAndUnlock, which is about row locks, not range locks. My fix is specifically about range locks.
So the issue might be that my fix is affecting row lock behavior incorrectly.
Let me check where closeWaiter is called for row locks:
In doLock:
go
ck := *c.w.conflictKey.Load()
if len(ck) > 0 && c.opts.Granularity == pb.Granularity_Row {
if l.options.beforeCloseFirstWaiter != nil {
l.options.beforeCloseFirstWaiter(c)
}
l.mu.Lock()
conflictWith, ok := l.mu.store.Get(ck)
if ok && conflictWith.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(ck)
}
l.mu.Unlock()
}
So for row locks, closeWaiter is called when there's an error. The waiter is removed from the OLD lock's queue.
In the original code, if c.w is not the first waiter in the OLD lock's queue, closeWaiter returns false and c.w is NOT removed. This is the bug.
In my fix, if c.w is not the first waiter, closeWaiter returns false and c.w IS removed. This is correct.
But the test is failing. Let me check if the test expects c.w to be in the OLD queue after closeWaiter.
Actually, the test is TestRowLockWithConflictAndUnlock. The name suggests it's testing row lock conflict and unlock. Let me look at the test to understand what it's checking.
Actually, I can't see the test code. Let me just check if the test expects closeWaiter to return 1 or 0.
The error message says:
code
expected: 1
actual : 0
This could be the return value of closeWaiter. In the original code, when c.w is not first, closeWaiter returns 0 (false). In my fix, when c.w is not first, closeWaiter also returns 0 (false).
So the return value should be the same. But the test is failing.
Wait, the test might be checking something else. Let me look at the assertion more carefully.
Actually, let me just check if the test passes without my changes.
Hmm, I've already made my changes. Let me check if I can revert them temporarily.
Actually, let me think about this differently. The test failure might be a side effect of my fix, not a direct issue with my fix.
Let me trace through the test scenario:
Transaction A acquires a lock on row X
Transaction B tries to acquire a lock on row X, waits
Transaction A unlocks row X
Transaction B gets the lock
In this scenario:
Transaction B creates a waiter (c.w)
Transaction B adds c.w to the lock's queue
Transaction A unlocks row X, which calls closeTxn on the lock
closeTxn calls notify(), which notifies c.w
c.w wakes up and gets the lock
Now, if there's an error in the lock operation, closeWaiter might be called. In the original code, if c.w is not first in the queue, it's not removed. In my fix, c.w is removed.
But what if c.w is NOT in the queue anymore (because it was notified and removed by closeTxn)? Then closeWaiter is called on a queue that doesn't contain c.w.
In the original code:
go
if l.waiters.first() != w {
return false
}
If c.w is not in the queue, l.waiters.first() might return nil or a different waiter. So l.waiters.first() != w returns true. Returns false.
If c.w is not in the queue, remove() returns false. Returns l.holders.size() == 0 && l.waiters.size() == 0.
If there are no holders and no waiters, returns true. Otherwise, returns false.
So in the original code, it always returns false when c.w is not first. In my fix, it returns true when there are no holders and no waiters.
This is a difference! In the original code, the lock is NOT deleted from the store (because closeWaiter returns false). In my fix, the lock IS deleted from the store (if there are no holders and no waiters).
Could this be causing the test to fail?
If the lock is deleted from the store in my fix, but the original code doesn't delete it, then the test might be checking for the existence of the lock.
But I'm not sure what the test is checking. Let me just run the test and see what happens.
Actually, I think I need to understand the test better. Let me look at the test file.
</tool_call>
Now I understand. The checkLock function at line 4764 checks:
This expects the lock to have 1 waiter (txn2). The test expects the waiter count to be 1.
But after my fix, the test is failing with expected 1, actual 0. This means my fix is removing the waiter from the queue when it shouldn't be.
Wait, but the original code passes this test. So the original code doesn't remove the waiter from the queue.
Let me trace through the original code:
txn1 holds the lock
txn2 tries to acquire the lock, gets blocked, waiter is added to the queue
s.Unlock(ctx, txn2, timestamp.Timestamp{}) - unlocks txn2 (but txn2 doesn't hold the lock, it's just waiting)
checkLock expects 1 waiter (txn2)
Hmm, wait. txn2 is trying to acquire the lock and is blocked. Then s.Unlock(ctx, txn2) is called. This unlocks txn2's locks, but txn2 doesn't hold any locks. So this shouldn't affect the waiter.
Let me re-read the test:
txn1 acquires the lock (holds it)
txn2 tries to acquire the lock, gets blocked (waiter added to queue)
s.Unlock(ctx, txn2) - unlocks txn2's locks (txn2 doesn't hold any, so no effect)
checkLock expects 1 waiter (txn2 is still in the queue)
s.Unlock(ctx, txn1) - unlocks txn1, txn2 gets the lock
So the waiter (txn2) should still be in the queue after step 3.
Now, where does closeWaiter get called? Let me check.
Looking at doLock:
go
if e != nil || c.txn.deadlockFound {
c.closed = true
if e != ErrTxnNotFound {
c.txn.closeBlockWaiters(l.logger)
}
...
ck := *c.w.conflictKey.Load()
if len(ck) > 0 && c.opts.Granularity == pb.Granularity_Row {
...
conflictWith, ok := l.mu.store.Get(ck)
if ok && conflictWith.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(ck)
}
}
c.w.close(...)
...
}
So closeWaiter is called when there's an error. In the test, txn2's Lock operation returns an error:
Waiter is removed from the queue, but closeWaiter returns false
So the difference is:
Original: Waiter stays in queue, closeWaiter returns false
My fix: Waiter is removed from queue, closeWaiter returns false
The test checks lock.waiters.size(), which should be 1. But in my fix, the waiter is removed from the queue, so waiters.size() = 0.
This is the bug! My fix removes the waiter from the queue, but the waiter should stay in the queue because the lock operation failed.
Wait, but the test expects the waiter to stay in the queue. Why?
Let me re-read the test:
txn1 acquires the lock (holds it)
txn2 tries to acquire the lock, gets blocked, error is returned
s.Unlock(ctx, txn2) - unlocks txn2's locks (no effect)
checkLock expects 1 waiter
The error in step 2 triggers closeWaiter. In the original code, closeWaiter returns false and the waiter stays in the queue.
But wait, the error in step 2 is expected. The test does require.Error(t, err). So the lock operation fails.
Why does the test expect the waiter to stay in the queue? Let me think...
Actually, I think the issue is that the original code's closeWaiter is supposed to remove the waiter from the queue when the lock operation fails. But it doesn't do this correctly when the waiter is not first.
Hmm, but in this case, the waiter IS first (it's the only waiter). So closeWaiter does try to remove it...
Wait, no. Let me re-read the original closeWaiter:
go
func (l Lock) closeWaiter(w *waiter, logger *log.MOLogger) bool {
canRemove := func() bool {
if l.holders.size() > 0 {
return false // txn1 is a holder, so canRemove = false
}
if l.waiters.size() == 0 {
return true
}
if l.waiters.first() != w {
return false
}
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(...)
return l.isEmpty()
}()
...
}
When txn1 is a holder:
canRemove = false (because l.holders.size() > 0)
So the code doesn't remove the waiter from the queue. It just returns false.
But wait, the code iterates over waiters and closes them only if canRemove is true:
The waiter is added to the blockedWaiters list for deadlock detection. So the waiter needs to be in the queue for this to work.
But when the lock operation fails, the waiter should be removed from the queue because it's no longer waiting.
OK I think I need to understand the semantics of closeWaiter better. Let me re-read the comment:
closeWaiter is called to close/remove a waiter from the lock's wait queue. It returns true if the lock (the entire lock entry) can be removed.
The key insight is that closeWaiter is trying to remove the waiter from the wait queue. When the waiter is removed, if there are no more waiters and no more holders, the lock can be removed entirely.
In the original code:
When the waiter is first and there are more waiters: notify() is called, but the waiter stays in the queue
When the waiter is first and is the only waiter: the waiter is closed via iter, canRemove is true (if no holders)
When the waiter is not first: the waiter stays in the queue (BUG)
Wait, let me re-read:
go
if l.waiters.first() == w {
if l.waiters.size() == 1 {
return true // canRemove = true
}
l.waiters.notify(...)
return l.isEmpty() // canRemove = false (isEmpty returns false)
}
When the waiter is first and there are more waiters:
notify() is called
l.isEmpty() returns false (there are still other waiters)
canRemove = false
So canRemove is false even when the waiter is first. The waiter stays in the queue.
But wait, the notify() function removes completed waiters from the queue. If the waiter being notified (w) is not in blocking state, it's closed and removed from the queue.
So:
If w is in blocking state: w.notify() returns true, notify() breaks, w stays in queue, canRemove = false
If w is not in blocking state: w.notify() returns false, w is closed, notify() continues to next waiter, canRemove = false (if there are more waiters)
In both cases, canRemove = false. But the difference is whether w stays in the queue or is removed.
Actually, looking at the notify() code again:
go
skipAt := -1
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close(...)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
If w.notify() returns true (w is in blocking state):
Break
skipAt is still -1 (or whatever it was before)
q.waiters = append([], q.waiters[skipAt+1:]...)
If skipAt is -1: q.waiters = append([], q.waiters[0:]...) = all waiters
So if w is in blocking state, the queue is unchanged. All waiters remain.
If w.notify() returns false (w is not in blocking state):
w.close() is called
skipAt = 0 (if w is first)
Continue to next waiter
If next waiter notify() returns true: break
If all waiters are not in blocking state: all are closed, skipAt is set to last index
q.waiters = all waiters from skipAt+1 onwards
So the notify() function removes non-blocking (completed) waiters from the queue. Blocking waiters stay in the queue.
OK so in the original code:
When w is first and there are more waiters:
notify() is called
If w is in blocking state: w.notify() returns true, w stays in queue, notify() breaks
If w is not in blocking state: w is closed, skipAt is set, notify() continues to next waiter
Either way, canRemove = false
So the waiter may or may not be in the queue after closeWaiter returns, depending on whether w is in blocking state.
But the test expects the waiter to be in the queue. So in the test, the waiter must be in blocking state (so notify() keeps it in the queue).
Now, in my fix:
go
removed := l.waiters.remove(w)
I always remove the waiter from the queue, regardless of whether it's in blocking state. This is different from the original code.
So my fix is too aggressive. I should only remove the waiter if it's not in blocking state.
But wait, the issue description says "A waiter that moves to a new range conflict must no longer remain in stale queues." This means the waiter should be removed from the stale queue, even if it's in blocking state.
But the test expects the waiter to stay in the queue. So either:
The test is wrong, or
My understanding of the issue is wrong
Let me re-read the issue:
"Range-lock conflicts can strand waiters in stale queues. A waiter that moves to a new range conflict must no longer remain in stale queues."
The key phrase is "moves to a new range conflict". This means the waiter is moving from one range conflict to another. In this case, the waiter should be removed from the OLD queue and added to the NEW queue.
But the test TestRowLockWithConflictAndUnlock is about row locks, not range locks. So the issue might not apply to this test.
But my fix changes the behavior of closeWaiter for all cases, not just range locks. This might be causing the test to fail.
Hmm, but the issue description says "No new interfaces are introduced." This suggests that the fix should be in the existing closeWaiter function.
Let me think about this differently. The issue is:
A waiter is in a stale queue (from a previous range conflict)
The waiter moves to a new range conflict
The waiter should be removed from the stale queue
The fix should only affect range locks, not row locks.
But closeWaiter is called for both row locks and range locks. So I need to distinguish between the two cases.
Actually, looking at handleLockConflictLocked:
go
if c.opts.Granularity != pb.Granularity_Range {
return nil
}
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
c.rangeLastWaitKey = key
return nil
So for range locks, closeWaiter is called to remove the waiter from the OLD queue. For row locks, closeWaiter is also called (in doLock when an error occurs).
The difference is:
For range locks: the waiter is moving to a NEW queue (handleLockConflictLocked adds it to the new queue)
For row locks: the waiter might not be moving to a new queue (the lock operation failed)
So the fix should only remove the waiter from the queue for range locks, not for row locks.
But how do I distinguish between the two cases in closeWaiter?
One option is to add a parameter to closeWaiter to indicate whether the waiter is moving to a new queue.
Another option is to check if the lock has other waiters. If it does, the waiter should stay in the queue.
But wait, in the original code, when the waiter is first and there are more waiters, notify() is called. This might remove the waiter from the queue (if the waiter is not in blocking state). So the original code does remove the waiter in some cases.
Hmm, I think the issue is that my fix removes the waiter unconditionally, which is too aggressive. The original code only removes the waiter if it's not in blocking state (via notify()).
But the issue description says "A waiter that moves to a new range conflict must no longer remain in stale queues." This means the waiter should be removed even if it's in blocking state.
So my fix is correct for range locks. But it breaks row lock behavior.
I need to add a parameter to closeWaiter to indicate whether the waiter is moving to a new queue.
Actually, let me re-read the issue more carefully:
"Cleanup must preserve unrelated lock state, wake the next eligible waiter when necessary, and continue to work when the previous key disappeared or was recreated."
This suggests that the cleanup should:
Remove the waiter from the stale queue
Preserve unrelated lock state (don't affect other waiters or holders)
Wake the next eligible waiter (if the removed waiter was first)
Handle the case where the previous key disappeared or was recreated
So the cleanup should remove the waiter from the queue. But it should only do this for range locks (when the waiter is moving to a new queue).
For row locks (when the lock operation fails), the waiter should stay in the queue (for deadlock detection).
So I need to add a parameter to closeWaiter to indicate whether the waiter is moving to a new queue.
Actually, looking at the code more carefully, I think the issue is different. Let me re-read handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So the waiter is added to the NEW queue BEFORE closeWaiter is called. This means the waiter will be in TWO queues (OLD and NEW) if closeWaiter doesn't remove it from the OLD queue.
The issue is that closeWaiter doesn't remove the waiter from the OLD queue when the waiter is not first. So the waiter ends up in TWO queues.
My fix removes the waiter from the OLD queue regardless of position. This prevents the waiter from being in TWO queues.
But the test expects the waiter to stay in the OLD queue. So either:
The test is checking for a bug, or
My fix is wrong
Let me check the test more carefully. The test is:
go
s.Unlock(ctx, txn2, timestamp.Timestamp{}) // unlock txn2 (doesn't hold any locks)
...
checkLock(t, lt, rows[0], [][]byte{txn1}, [][]byte{txn2}, []int32{3})
So after unlocking txn2, the test checks that txn2 is still in the waiters list. But txn2 doesn't hold any locks. So the unlock shouldn't affect the waiter.
Where does closeWaiter get called in this test? Let me check.
The error in step 2 triggers closeWaiter in doLock. At that point:
txn1 is a holder
txn2 is a waiter (only waiter)
closeWaiter is called
In the original code:
l.holders.size() > 0 (txn1 is a holder), so canRemove = false
Waiter is removed from queue, but closeWaiter returns false
So the difference is that the waiter is removed from the queue in my fix. But the test expects the waiter to stay.
Why does the test expect the waiter to stay? Because the waiter is still in blockedWaiters (for deadlock detection). The waiter should stay in the queue so it can be cleaned up later.
But my fix removes the waiter from the queue. So the waiter is no longer tracked properly.
Hmm, this is a problem. I need to be more careful about when to remove the waiter from the queue.
The issue says: "A waiter that moves to a new range conflict must no longer remain in stale queues."
So the waiter should only be removed from the queue when it's moving to a new queue. If the waiter is not moving to a new queue (e.g., the lock operation failed), it should stay in the queue.
But how do I distinguish between these two cases in closeWaiter?
One option is to add a parameter to closeWaiter. But the issue says "No new interfaces are introduced."
Another option is to check if the waiter is being added to a new queue before calling closeWaiter. But this is already done in handleLockConflictLocked.
Actually, I think the fix should be in handleLockConflictLocked, not in closeWaiter. The issue is that handleLockConflictLocked doesn't remove the waiter from the OLD queue when closeWaiter doesn't do it.
Let me re-read handleLockConflictLocked:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
So if closeWaiter returns false, the lock is not deleted. But the waiter might still be in the OLD queue (if closeWaiter didn't remove it).
The fix should be: after closeWaiter returns false, manually remove the waiter from the OLD queue if it's still there.
But this is getting complicated. Let me think about a simpler approach.
Actually, I think the issue is that closeWaiter is supposed to remove the waiter from the queue. But it doesn't do this correctly when the waiter is not first.
The fix should be: modify closeWaiter to always remove the waiter from the queue, regardless of position. And the caller (handleLockConflictLocked) is responsible for handling the waiter's lifecycle.
But the test is failing because the waiter is removed from the queue when it shouldn't be.
Hmm, I think I need to look at this from a different angle. Let me re-read the issue:
"Range-lock conflicts can strand waiters in stale queues. A waiter that moves to a new range conflict must no longer remain in stale queues."
The key phrase is "moves to a new range conflict". This only applies to range locks, not row locks.
For range locks:
The waiter is in the OLD queue (from a previous range conflict)
The waiter moves to a NEW queue (for the new range conflict)
The waiter should be removed from the OLD queue
For row locks:
The waiter is in the queue
The lock operation fails
The waiter stays in the queue (for deadlock detection)
So the fix should only affect range locks, not row locks.
One way to do this is to check the granularity in closeWaiter. If it's a range lock, remove the waiter. If it's a row lock, keep the original behavior.
But closeWaiter doesn't have access to the granularity. It only has the waiter and the lock.
Actually, looking at closeWaiter, it doesn't check granularity at all. It just removes the waiter from the queue.
Hmm, but the test is failing because my fix removes the waiter from the row lock queue when it shouldn't.
Let me think about this more carefully. The test is about row locks. In the test:
txn1 acquires the lock
txn2 tries to acquire the lock, gets blocked
The lock operation fails (error returned)
closeWaiter is called
In this case, the waiter (txn2) is in blocking state (waiting for the lock). The waiter should stay in the queue for deadlock detection.
But my fix removes the waiter from the queue unconditionally. This is wrong for row locks.
For range locks, the waiter might also be in blocking state. But the waiter is moving to a new queue. So the waiter should be removed from the OLD queue and added to the NEW queue.
So the fix should be: when moving to a new queue (range locks), remove the waiter from the OLD queue. When the lock operation fails (row locks), keep the waiter in the queue.
But how do I distinguish between these two cases in closeWaiter?
One option is to add a parameter to closeWaiter. But the issue says "No new interfaces are introduced."
Another option is to check if the waiter is in blocking state. If it's not, remove it. If it is, keep it (original behavior).
But this doesn't help for range locks. The waiter might be in blocking state and still needs to be removed from the OLD queue.
Hmm, I think the issue is that I'm trying to fix the wrong function. The fix should be in handleLockConflictLocked, not in closeWaiter.
Let me re-read handleLockConflictLocked:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
If closeWaiter returns true, the lock is deleted. If closeWaiter returns false, the lock is not deleted.
But the waiter might still be in the OLD queue even if closeWaiter returns false. This is the bug.
The fix should be: after closeWaiter returns false, manually remove the waiter from the OLD queue.
But closeWaiter is supposed to remove the waiter from the queue. So the fix should be in closeWaiter.
OK let me try a different approach. I'll add a new method to the waiterQueue interface that removes a specific waiter without the original closeWaiter's logic. Then I'll use this new method in handleLockConflictLocked.
Actually, looking at the waiterQueue interface, there's already a removeByTxnID method. But it removes by txn ID, not by waiter pointer. And it notifies the removed waiter (which we don't want).
Let me add a removeWaiter method that removes a specific waiter without notifying it.
Then, in handleLockConflictLocked, after closeWaiter returns (whether true or false), I'll call removeWaiter on the OLD queue to ensure the waiter is removed.
This way, the fix is localized to handleLockConflictLocked, and closeWaiter's behavior is unchanged for row locks.
Wait, but closeWaiter already tries to remove the waiter. The issue is that it doesn't do it correctly when the waiter is not first.
So I could fix closeWaiter to correctly remove the waiter, regardless of position. But this would change the behavior for row locks.
The bug is that when l.waiters.first() != w, the waiter is not removed from the queue. It just returns false.
The fix should be: remove the waiter from the queue even when l.waiters.first() != w.
But the test expects the waiter to stay in the queue when the lock operation fails. So my fix changes the behavior.
Hmm, let me think about this differently. What is the purpose of closeWaiter?
Looking at the callers:
handleLockConflictLocked (range locks): removes the waiter from the OLD queue when moving to a NEW queue
doLock (row locks, on error): removes the waiter from the queue when the lock operation fails
For case 1, the waiter should be removed from the OLD queue.
For case 2, the waiter should also be removed from the queue (because the lock operation failed).
But the test expects the waiter to stay in the queue for case 2. Why?
So the error comes from doAcquireLock. In this case, c.w might not even be created (because the lock could be acquired immediately without waiting).
Wait, but in the test, txn2 is blocked by txn1. So c.w is created and added to the queue. Then doAcquireLock returns an error... wait, why would it return an error?
Let me re-read doLock:
go
if !blocked {
err = l.doAcquireLock(c)
if err != nil {
...
}
if c.w == nil {
...
c.done(nil)
return
}
...
}
So if c.w is not nil, the code proceeds to wait for the lock. The error from doAcquireLock is only returned if there's a problem acquiring the lock (e.g., the lock table is closed).
In the test, doAcquireLock should succeed (txn2 is blocked but the lock acquisition is valid). So the error comes from somewhere else.
And s.unlock unlocks all locks held by the transaction. But txn2 doesn't hold any locks. So unlock should be a no-op for txn2.
Hmm, but maybe unlock also removes waiters? Let me check.
Actually, looking at txn.go:
go
func (txn *activeTxn) cancelBlocks(logger *log.MOLogger) {
for _, w := range txn.blockedWaiters {
w.notify(notifyValue{err: ErrTxnNotFound}, logger)
w.close("cancelBlocks", logger)
}
}
This cancels all blocked waiters. But this is called when the transaction is closed, not when it's unlocked.
OK I'm getting confused. Let me just look at the test result. The test expects waiters.size() to be 1 after unlock txn2. The original code passes this test. My fix fails it.
So the original code keeps the waiter in the queue. My fix removes it.
The question is: should the waiter stay in the queue or be removed?
For row locks, the waiter should probably stay in the queue (for deadlock detection). My fix removes it, which breaks the test.
For range locks, the waiter should be removed from the OLD queue when moving to a NEW queue. My fix removes it, which is correct.
So I need to distinguish between row locks and range locks in closeWaiter.
One option is to check the lock type (row vs range). But closeWaiter doesn't have access to this information.
Another option is to check if the waiter is in blocking state. If it is, keep it in the queue. If it's not, remove it.
But for range locks, the waiter might be in blocking state and still needs to be removed from the OLD queue.
Hmm, I think the fix should be in handleLockConflictLocked, not in closeWaiter. The fix should be: after closeWaiter, ensure the waiter is removed from the OLD queue if it's still there.
Let me implement this.
Actually, looking at the code again, I realize the issue is more subtle. The closeWaiter function's purpose is to:
Try to remove the waiter from the queue
If the lock can be removed (no holders, no waiters), return true
Otherwise, return false
The bug is that the waiter is not removed from the queue when it's not first. So the waiter stays in the queue forever.
The fix should be: remove the waiter from the queue, regardless of position. And the return value should still indicate whether the lock can be removed.
But this changes the behavior for row locks, which breaks the test.
OK I think I need to just implement the fix and see if the test passes. If it doesn't, I'll adjust.
Actually, let me think about this more carefully. The test TestRowLockWithConflictAndUnlock is testing that a row lock with conflict and unlock works correctly. The test creates a waiter and expects it to stay in the queue.
But if my fix removes the waiter from the queue, the test will fail. This suggests that my fix is too aggressive for row locks.
The issue description says "Range-lock conflicts can strand waiters in stale queues." This only applies to range locks, not row locks.
So the fix should only affect range locks. For row locks, the behavior should remain unchanged.
One way to do this is to add a parameter to closeWaiter to indicate whether the waiter is moving to a new queue. But the issue says "No new interfaces are introduced."
Another way is to check if the lock is a range lock vs a row lock. But closeWaiter doesn't have access to this information.
Hmm, actually, closeWaiter receives a Lock object. The Lock object has methods like isLockRow() and IsRangeLock(). So I can check the lock type.
But wait, the issue is about waiters in stale queues, not about the lock type. The stale queue is the queue of the OLD lock, not the NEW lock.
So the fix should be: remove the waiter from the OLD queue regardless of the lock type. But only if the waiter is actually in the OLD queue.
But the test expects the waiter to stay in the queue for row locks. So I need to understand why the test expects this.
The Lock operation fails. This is expected. But why?
Actually, I think the error is expected because the transaction is being unlocked (step 3). So the Lock operation might detect that the transaction is being unlocked and return an error.
But step 3 unlocks txn2, not txn1. So the Lock operation for txn2 should not be affected.
Wait, maybe the error is from the Unlock operation, not the Lock operation. Let me re-read...
No, the error is from s.Lock(ctx, table, rows, txn2, option). So the Lock operation returns an error.
I'm confused. Let me just accept that the test expects the waiter to stay in the queue and implement a fix that doesn't change this behavior.
The fix should be: for range locks, remove the waiter from the stale queue. For row locks, keep the original behavior.
But how do I distinguish between range locks and row locks in closeWaiter?
Actually, looking at the lock object, I can check if it's a row lock or a range lock. But the stale queue might have multiple locks (for range locks, there are two locks: start and end).
Hmm, this is getting complicated. Let me try a different approach.
I'll modify the closeWaiter function to always remove the waiter from the queue, but I'll also add a new parameter to indicate whether the waiter should be closed or just removed.
For range locks, the waiter should be removed and added to a new queue. So it should not be closed.
For row locks, the waiter should be removed from the queue (if needed) and closed.
But the issue says "No new interfaces are introduced." So I can't add parameters.
OK let me try yet another approach. I'll add a new method to the waiterQueue interface (removeWithoutNotify) that removes a specific waiter without the original closeWaiter's logic. Then I'll use this new method in handleLockConflictLocked.
Actually, I already tried this approach earlier, and it caused tests to fail because it removed waiters from row lock queues when it shouldn't.
Hmm, let me think about this more carefully.
The issue is that for range locks, the waiter is added to the NEW queue before closeWaiter is called. So the waiter is in TWO queues if closeWaiter doesn't remove it from the OLD queue.
For row locks, the waiter is not added to a NEW queue. So removing the waiter from the OLD queue might cause issues.
The key insight is: for range locks, the waiter should be removed from the OLD queue because it's being added to a NEW queue. For row locks, the waiter should stay in the OLD queue (for deadlock detection).
So the fix should be: remove the waiter from the OLD queue if and only if the waiter is being added to a NEW queue.
But closeWaiter doesn't know if the waiter is being added to a NEW queue.
One option is to check if the waiter is already in a different queue. But this is complicated.
Another option is to modify handleLockConflictLocked to remove the waiter from the OLD queue directly, instead of relying on closeWaiter.
Let me try this approach:
In handleLockConflictLocked, after calling closeWaiter, if the return value is false (lock not removed), manually remove the waiter from the OLD queue.
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
removed := v.closeWaiter(c.w, l.logger)
if !removed {
// closeWaiter might not have removed the waiter from the queue.
// Manually remove it to prevent the waiter from being stranded.
v.waiters.remove(c.w)
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}
Wait, but v.waiters is not accessible from outside the Lock object. I can't call v.waiters.remove(c.w).
Hmm, I need to add a new method to the Lock type to expose this functionality.
Actually, looking at the Lock type, I can add a method to remove a specific waiter without the closeWaiter logic. But this would be a new interface, which the issue says not to introduce.
Wait, "No new interfaces are introduced" might mean no new public interfaces. I can add a new method to the Lock type.
Let me add a new method to Lock that removes a specific waiter without the closeWaiter logic. Then I'll use this method in handleLockConflictLocked.
Actually, looking at the lock.go file, the Lock type has methods like closeWaiter. I can add a new method like removeWaiter(w *waiter) that just removes the waiter from the queue.
Then in handleLockConflictLocked, I'll call this new method after closeWaiter.
But wait, this still changes the behavior for row locks. If closeWaiter is called for a row lock and returns false, and then removeWaiter is called, the waiter will be removed from the queue.
Hmm, I need to only call removeWaiter for range locks, not row locks.
Actually, looking at handleLockConflictLocked, it's only called for range locks:
go
if c.opts.Granularity != pb.Granularity_Range {
return nil
}
So handleLockConflictLocked is only called for range locks. So I can safely remove the waiter from the OLD queue here.
The issue is that closeWaiter is also called for row locks (in doLock). So I need to be careful not to change closeWaiter's behavior for row locks.
Let me implement the fix in handleLockConflictLocked:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
removed := v.closeWaiter(c.w, l.logger)
if !removed {
// closeWaiter might not have removed the waiter from the queue.
// Manually remove it to prevent the waiter from being stranded.
// We need a new method on Lock to remove the waiter without the closeWaiter logic.
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}
But I need a way to remove the waiter from the queue without the closeWaiter logic. The closeWaiter function has its own logic for removing the waiter (via notify). I need a simpler method that just removes the waiter.
Let me add a new method to the waiterQueue interface (since it's internal, not a public interface). Then I'll add a method to Lock that calls this new method.
Wait, but I already tried adding a method to the waiterQueue interface, and it caused tests to fail.
Let me think about this differently. The issue is that closeWaiter doesn't remove the waiter from the queue when the waiter is not first. The fix should be to make closeWaiter correctly remove the waiter from the queue.
But this changes the behavior for row locks, which breaks the test.
So maybe the fix should be: keep closeWaiter's behavior unchanged, but add a new method that removes the waiter without the closeWaiter logic. And use this new method in handleLockConflictLocked.
Let me add a new method to the Lock type that just removes the waiter from the queue:
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
removed := v.closeWaiter(c.w, l.logger)
if !removed {
// closeWaiter might not have removed the waiter from the queue.
// Manually remove it to prevent the waiter from being stranded.
v.removeWaiter(c.w)
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}
This way, closeWaiter's behavior is unchanged. And for range locks, the waiter is always removed from the OLD queue (either by closeWaiter or by the manual remove).
Let me implement this.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /matrixone/pkg/lockservice && cat waiter_queue.go | grep -n "type waiterQueue interface" -A 25
</tool_call>
The user wants me to investigate why the test TestCannotHungIfRangeConflictWithRowMultiTimes is failing with my changes. Let me look at the test more carefully to understand what's happening.
The test involves range locks and multiple transactions. The test is timing out, which suggests that a waiter is stuck and not being notified.
Let me look at the test flow more carefully. I need to find where removeWaiter is being called and why it might be causing issues.
The key issue is that my fix adds v.removeWaiter(c.w) after closeWaiter returns false in handleLockConflictLocked. But this might be removing the waiter from the queue when it shouldn't be.
Let me look at the specific scenario in the test:
txn1 holds row k4
txn3 tries to lock [k1, k4] as a range, waits at k4
txn1 unlocks, notifies txn3
txn3 retries, now waits at k2 (because txn2 holds k2, k3)
txn4 tries to lock k2, waits at k2
txn2 unlocks, notifies txn3 and txn4
txn4 retries, gets k2
txn3 retries, waits at k2 again
txn4 tries to lock k4, waits at k4
The issue might be that when txn3 moves from waiting at k4 to waiting at k2, my fix calls removeWaiter on k4's queue. But if the waiter was already removed (by closeWaiter or by notify), this could cause issues.
Actually, looking at the code more carefully:
go
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
...)
}
if ok {
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
// closeWaiter may not remove the waiter from the queue when
// the waiter is not the first in line. Manually remove it
// to prevent the waiter from being stranded in a stale queue.
v.removeWaiter(c.w)
}
}
}
The issue is that closeWaiter might return false even when the waiter WAS removed from the queue (by the notify call inside closeWaiter). In that case, calling removeWaiter would be redundant but harmless.
But if the waiter was NOT in the queue (because it was already removed by a previous operation), removeWaiter would return false, which is also harmless.
The issue might be something else. Let me think about the test scenario more carefully.
Actually, looking at the test, the issue might be that when closeWaiter is called, the waiter is the first in the queue (because it's the only waiter). In that case, closeWaiter calls notify, which tries to notify the waiter. But the waiter is in blocking state, so notify returns false (the waiter stays in the queue).
Wait, no. Looking at closeWaiter again:
go
if l.waiters.first() == w {
if l.waiters.size() == 1 {
return true
}
l.waiters.notify(...)
return l.isEmpty()
}
If the waiter is first and is the only waiter, closeWaiter returns true. Otherwise, it calls notify and returns isEmpty().
In the test scenario, when txn3 moves from k4 to k2:
k4's queue has txn3 as the only waiter
closeWaiter(txn3) is called
txn3 is first and is the only waiter
closeWaiter returns true
The lock is deleted from the store
But then my fix doesn't call removeWaiter because closeWaiter returned true.
When txn3 moves from k2 to k4:
k2's queue has txn3 and txn4 as waiters
txn3 is first, txn4 is second
closeWaiter(txn3) is called
txn3 is first but not the only waiter
notify is called, which tries to notify txn3
txn3.notify() returns false (txn3 is in blocking state, but actually... wait)
Hmm, let me re-read the notify code:
go
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close(...)
skipAt = i
q.waiters[i] = nil
}
If w.notify() returns true, the loop breaks. If it returns false, the waiter is closed and skipped.
Looking at the notify function on waiter:
go
func (w *waiter) notify(value notifyValue, logger *log.MOLogger) bool {
for {
status := w.getStatus()
if status != blocking {
return false
}
...
}
}
If the waiter is in blocking state, notify returns true. Otherwise, it returns false.
So if txn3 is in blocking state, notify(txn3) returns true, and notify() breaks without closing txn3 or removing it from the queue.
This means the waiter stays in the queue after notify is called.
Then closeWaiter returns isEmpty(), which is false (because txn3 is still in the queue).
So closeWaiter returns false, and my fix calls removeWaiter(txn3), which removes txn3 from the queue.
This should be correct. The waiter is moved from k2's queue to... where?
Actually, looking at handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w) // add to NEW queue
...
if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
v.removeWaiter(c.w)
}
}
}
The waiter is first added to the NEW queue, then removed from the OLD queue. This should be correct.
But maybe the issue is that the waiter is being removed from the OLD queue before it's added to the NEW queue? Let me check the order.
Actually, looking at the code:
conflictWith.addWaiter(l.logger, c.w) - adds to NEW queue
closeWaiter - tries to remove from OLD queue
removeWaiter - removes from OLD queue
This order should be correct.
But maybe the issue is that removeWaiter is being called when it shouldn't be. For example, if closeWaiter already removed the waiter (via notify clearing it), then removeWaiter would be redundant.
Wait, but I thought notify doesn't remove the waiter if it's in blocking state. Let me re-check.
Looking at the notify code again:
go
for i, w := range q.waiters {
if w.notify(value, q.logger) {
break
}
w.close(...)
skipAt = i
q.waiters[i] = nil
}
q.waiters = append(q.waiters[:0], q.waiters[skipAt+1:]...)
If w.notify() returns true, the loop breaks. Then:
If skipAt is -1 (the loop broke immediately because w.notify() returned true):
go
q.waiters = append([], q.waiters[0:]...) = all waiters
So the queue is unchanged. All waiters remain.
If w.notify() returns false, w is closed, skipAt is set, and the loop continues. After the loop:
go
q.waiters = append([], q.waiters[skipAt+1:]...)
This removes all waiters up to and including skipAt.
So if the first waiter notify() returns true, the queue is unchanged. All waiters remain.
OK so my analysis is correct. The issue must be something else.
Let me look at the test more carefully. The test involves multiple transactions and complex locking scenarios. The issue might be that my fix is removing a waiter from a queue when it shouldn't be.
Actually, let me look at the test again. The test has this flow:
txn1 holds row k4
txn3 tries to lock [k1, k4] as a range, waits at k4
txn1 unlocks, notifies txn3
txn3 retries, now waits at k2 (because txn2 holds k2, k3)
When txn3 retries, handleLockConflictLocked is called. It adds txn3 to k2's queue, then tries to remove txn3 from k4's queue.
But wait, when txn1 unlocks, k4's lock is removed (because txn3 was notified and moved on). So when txn3 retries, k4's queue might be empty or non-existent.
Let me check if k4's lock still exists after txn1 unlocks.
closeTxn removes the holder and notifies waiters. If the lock can be removed (no holders, no waiters), it's deleted.
When txn1 unlocks k4:
closeTxn removes txn1 from k4's holders
k4 has no holders
k4 has txn3 as a waiter
notify is called (for range locks) or notify is called on the first waiter (for row locks)
If k4 is a row lock, notify(txn3) is called
txn3.notify() returns true (txn3 is in blocking state)
notify returns
isEmpty() returns false (txn3 is still in the queue)
closeTxn returns false (lock can't be removed)
So k4's lock is NOT deleted. txn3 is still in the queue.
Then when txn3 retries:
handleLockConflictLocked is called
txn3 is added to k2's queue
closeWaiter(txn3) is called on k4's queue
txn3 is first and is the only waiter
closeWaiter returns true
k4's lock is deleted
This should be correct.
But wait, the test is timing out. Let me look at what happens after txn3 retries.
Actually, I think the issue might be in how the test is structured. Let me look at the test more carefully.
Actually, I just realized something. The test is about "cannot hang if range conflict with row multi times". The test involves range locks conflicting with row locks.
When a range lock is added, it might merge with existing row locks. This could cause the waiter to be in a complex state.
Let me look at the addRangeLockLocked function to understand how range locks are added.
Actually, I think the issue might be that removeWaiter is being called on a queue where the waiter is not present, or the waiter is already being removed by another operation.
Let me check if there's a race condition or ordering issue.
Actually, looking at the code more carefully, I notice that handleLockConflictLocked is called within a locked section (l.mu.Lock()). So there shouldn't be any race conditions.
Let me look at the test output more carefully. The test is timing out, which means something is not being notified.
Actually, I think I found the issue. When closeWaiter is called, it might call notify, which notifies the first waiter. But if the first waiter is in blocking state, notify returns true and the waiter stays in the queue.
Then, my fix calls removeWaiter, which removes the waiter from the queue. But the waiter was just notified! The waiter is now in a weird state: it was notified (waking it up), but then removed from the queue.
The waiter might be waiting for a notification, but since it was removed from the queue, it won't be notified again.
Actually, no. The waiter was notified by the notify call in closeWaiter. So the waiter should wake up and continue.
Let me trace through more carefully.
Actually, I think the issue is different. Let me look at the test flow again.
The test involves txn3 doing multiple retries:
txn3 waits at k4 (held by txn1)
txn1 unlocks, txn3 is notified
txn3 retries, waits at k2 (held by txn2)
txn4 waits at k2 (behind txn3)
txn2 unlocks, txn3 and txn4 are notified
txn4 retries, gets k2
txn3 retries, waits at k2 again (because txn4 holds k2 now)
txn4 tries to lock k4, waits at k4 (held by txn3)
At step 7, when txn3 retries:
handleLockConflictLocked is called
txn3 is added to k2's queue (as the first waiter)
closeWaiter(txn3) is called on k2's queue
txn3 is first and is the only waiter in k2's queue (txn4 was notified and removed)
closeWaiter returns true
k2's lock is deleted
But wait, at step 7, txn4 already has k2. So k2 should have txn4 as a holder, not as a waiter.
Let me re-read step 6:
txn4 retries, gets k2
So txn4 now holds k2. k2 has no waiters.
Then at step 7:
txn3 retries, tries to lock [k1, k4]
txn3 conflicts with txn4 at k2
txn3 is added to k2's queue (as the only waiter)
closeWaiter(txn3) is called on... what queue?
Actually, at step 7, what is c.rangeLastWaitKey? It should be k2 (from the previous iteration).
So:
txn3 is added to k4's queue (because the range lock [k1, k4] conflicts with txn4's k4? No, txn3 is trying to lock [k1, k4], and txn4 holds k2, k4... wait, no)
Let me re-read the test. At step 6, txn4 gets k2. But does txn4 also get k4?
Looking at step 8:
txn4 tries to lock k4, waits at k4 (held by txn3)
So txn4 doesn't hold k4. txn4 only holds k2.
At step 7:
txn3 retries, tries to lock [k1, k4]
k1 and k4 are not held by anyone... wait, no
Actually, at step 2, txn1 held k4. At step 3, txn1 unlocks k4. So k4 is free.
At step 7, txn3 retries, tries to lock [k1, k4]. k1 is free, k4 is free. But k2 is held by txn4. So txn3 waits at k2.
Wait, but the range lock is [k1, k4]. This means it locks keys k1, k2, k3, k4. If txn4 holds k2, txn3 conflicts at k2.
So txn3 is added to k2's queue.
Then closeWaiter(txn3) is called on c.rangeLastWaitKey. What is c.rangeLastWaitKey? It should be k2 from the previous iteration.
But wait, at step 4, txn3 was waiting at k2. Then at step 5, txn2 unlocks, notifying txn3. So txn3 is removed from k2's queue.
Then at step 7, txn3 retries. It's added to k2's queue again. Then closeWaiter is called on k2's queue.
But k2's queue was already cleared (txn3 was notified and removed). So k2's queue might be empty.
Actually, looking at closeTxn:
go
if l.isLockRow() {
l.waiters.notify(notifyValue{defChanged: l.isLockTableDefChanged()})
return l.isEmpty()
}
For row locks, notify is called. If the first waiter is in blocking state, notify returns true and the waiter stays in the queue.
But wait, at step 5, txn2 unlocks. txn2 holds k2 and k3 (as a range lock). So k2 and k3 are range locks.
So at this point, txn3 is waiting at k2, but txn3 is ALSO in k4's queue. This is the stale queue issue!
txn3 is in k4's queue (from step 2), but txn3 is now waiting at k2 (step 4). k4's lock still has txn3 as a waiter.
This is exactly the bug that my fix is trying to address. When txn3 moves from k4 to k2, it should be removed from k4's queue.
But closeWaiter(txn3) is called on k4's queue. txn3 is first and is the only waiter in k4's queue. So closeWaiter returns true, and k4 is deleted.
Wait, but k4 has no holders. So k4 should be deleted.
But the test comment says:
code
// k4: holder() waiters(txn3)
So k4 has no holders, but txn3 is still a waiter. This means k4 should be deleted when closeWaiter returns true.
But the test is timing out. So something is wrong.
Let me look at the test output again. The test is timing out at service_test.go:4621. Let me check what's at that line.
Actually, I think the issue is that my fix is removing a waiter from a queue when it shouldn't be. Or maybe the removeWaiter is causing some issue.
Let me check if removeWaiter is being called when it shouldn't be.
Looking at my fix:
go
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
v.removeWaiter(c.w)
}
If closeWaiter returns false, I call removeWaiter. But if closeWaiter returns true, I don't call removeWaiter (because the lock is deleted).
But wait, closeWaiter returns true only when the lock can be removed (no holders, no waiters). If the lock is deleted, there's no queue to remove from.
So the issue must be when closeWaiter returns false. In that case, I call removeWaiter.
When does closeWaiter return false?
There are holders (can't remove the lock)
The waiter is not first in the queue (BUG in original code)
The waiter is first, there are more waiters, and isEmpty() returns false
In case 1, the lock has holders, so the queue might have waiters. If closeWaiter is called on such a lock, it returns false. Then my fix calls removeWaiter, which removes the waiter from the queue.
This is the intended behavior for range locks. The waiter should be removed from the stale queue.
But the test is timing out. So maybe there's a bug in my implementation of removeWaiter.
Let me check the remove implementation:
go
func (q *sliceBasedWaiterQueue) remove(w *waiter) bool {
q.Lock()
defer q.Unlock()
if len(q.waiters) == 0 {
return false
}
newWaiters := q.waiters[:0]
found := false
for _, existing := range q.waiters {
if existing == w {
found = true
continue
}
newWaiters = append(newWaiters, existing)
}
if found {
q.waiters = newWaiters
}
return found
}
This looks correct. It removes the waiter from the queue and returns true if found.
Hmm, I'm stuck. Let me try a different approach. Let me look at what specific step in the test is causing the timeout.
Actually, I think the issue might be related to how the test waits for operations to complete. The test uses channels to synchronize. If a waiter is not properly notified, the channel might never be signaled, causing the test to timeout.
Let me look at the test more carefully to find where it's waiting.
Actually, looking at the test output, the test times out after 10 seconds. The test has a 10-second timeout.
Let me look at what the test is waiting for:
go
case <-txn3WaitAt2Again:
This is waiting for txn3 to wait at k2 again. If this channel is never signaled, the test times out.
So the issue is that txn3 is not being notified to move to k2 again.
But why? txn3 should be notified when txn2 unlocks.
Let me trace through the test scenario more carefully.
Actually, I think I need to look at the specific test code to understand the synchronization. Let me search for where txn3WaitAt2Again is signaled.
</tool_call>
Let me understand the test flow better. Looking at the test:
txn1 locks k4 (row)
startTxn3 signals txn3 to start
txn3 locks [k1, k4] (range), waits at k4
when txn3WaitAt4 is closed, txn1 unlocks k4
txn3 gets notified, txn3NotifiedAt4 is closed
when txn3NotifiedAt4 is closed, txn2 locks [k3, k3] (range)
txn3WaitAt2 is closed (txn3 waits at k2)
when txn3WaitAt2 is closed, txn4 locks k2 (row)
txn4GetLockAt1 is closed
txn3WaitAt2Again should be closed (txn3 waits at k2 again)
The test is waiting for txn3WaitAt2Again to be closed, which means txn3 should wait at k2 again.
But the test is timing out, which means txn3 is not reaching this state.
Looking at the flow:
txn3 was waiting at k4 (held by txn1)
txn1 unlocks, txn3 is notified
txn3 retries, now tries to lock [k1, k4]
txn3 conflicts with txn2 at k3 (txn2 holds [k3, k3])
So if there are holders, closeWaiter returns false.
In step 10, k2 has txn4 as a holder. So closeWaiter returns false.
Then my fix calls removeWaiter(txn3). This removes txn3 from k2's queue.
But wait, txn3 was just added to k2's queue in step 3 (addRangeLockLocked). Then in step 5, the waiter is added to k2's queue again (via conflictWith.addWaiter).
Hmm, but addRangeLockLocked and conflictWith.addWaiter both add the waiter to the same queue (k2's queue). So the waiter might be in the queue twice.
Actually, let me check. In addRangeLockLocked:
go
conflictWith.waiters = wq
This sets the waiters to a new queue (wq). Then in handleLockConflictLocked:
go
conflictWith.addWaiter(l.logger, c.w)
This adds the waiter to conflictWith's waiters.
So the waiter is added once to k2's queue.
But wait, in the first iteration of the loop, conflictWith is a NEW lock that was just created. The lock's waiters is set to wq. Then the lock is added to the store.
In subsequent iterations, the conflictWith might be the SAME lock (if the same key is conflicted again). In that case, the waiter might be added to the same lock's queue multiple times.
Hmm, but for the test scenario, the lock is [k1, k4]. The conflicts are at k4 (first iteration) and k2 (second iteration). These are different keys, so different locks.
Actually, wait. Let me re-read the test:
go
range14 := newTestRows(1, 4)
So range14 is [1, 4], which means the range lock covers keys 1 through 4.
In the first iteration, the lock tries to lock [k1, k4]. This might be merged with existing locks.
Actually, I'm not sure about the exact behavior. Let me just focus on the issue.
The issue is that the test is timing out. The timeout is at txn3WaitAt2Again.
Looking at the test, txn3WaitAt2Again is closed when txn3WaitTimes == 2. This happens when txn3 waits at k2 for the third time (txn3WaitTimes is incremented to 2).
But the test is timing out, which means txn3 is not reaching this state.
Let me think about what could prevent txn3 from waiting at k2 again.
After step 10 (txn3 retries), txn3 should wait at k2. Then txn3WaitAt2Again should be closed.
But the test is timing out, which means txn3 is not waiting at k2.
Why? Maybe the waiter is being removed from the queue by my fix.
Let me check. At step 10:
Waiter is added to k2's queue
closeWaiter(txn3) is called on k2's queue
k2 has holders (txn4), so closeWaiter returns false
My fix calls removeWaiter(txn3)
txn3 is removed from k2's queue
So after step 4, txn3 is NOT in k2's queue. Then txn3 waits, but no one is waiting for it. The wait operation returns immediately or with an error.
But wait, if the waiter is not in the queue, who notifies it? No one. So the wait operation would time out.
That's the issue! My fix removes the waiter from the queue, but the waiter is supposed to stay in the queue and be notified later.
The problem is that my fix calls removeWaiter even when the lock has holders. This removes the waiter from the queue, but the waiter should stay in the queue because the lock has holders.
I think the issue is that my fix is too aggressive. I should only remove the waiter from the queue if the lock has no holders AND the waiter is stranded (not first in the queue).
But how do I know if the waiter is stranded? I can check if the waiter is first in the queue. If the waiter is first, it will be notified when the lock is released. If the waiter is not first, it might be stranded.
But closeWaiter already handles the case where the waiter is first. It calls notify. So if the waiter is first, it will be notified.
The issue is when the waiter is NOT first. In that case, closeWaiter returns false without removing the waiter. The waiter stays in the queue, but it's not at the front, so it won't be notified when the lock is released.
Actually, that's not right. When the lock is released, notifyAll or notify is called on the queue. This notifies the first waiter. If the first waiter completes, the next waiter is notified. So eventually, all waiters are notified.
But the issue is that the waiter is STRANDED in a stale queue. The stale queue is the OLD queue, not the NEW queue.
OK I think I finally understand the issue. Let me re-read the test scenario.
At step 10, txn3 retries:
txn3 locks [k1, k4]
txn3 conflicts at k2 (txn4 holds k2)
Waiter is added to k2's queue
closeWaiter(txn3) is called on k2's queue (c.rangeLastWaitKey is k2)
Wait, c.rangeLastWaitKey is k2 from the previous iteration. So closeWaiter is called on k2's queue.
But the waiter was JUST added to k2's queue in step 3. So k2's queue has the waiter.
Then closeWaiter(txn3) is called. This tries to remove the waiter from k2's queue.
But k2 has holders (txn4), so closeWaiter returns false. Then my fix calls removeWaiter(txn3), which removes the waiter from k2's queue.
This is wrong! The waiter should stay in k2's queue because it's waiting for txn4 to release k2.
The issue is that c.rangeLastWaitKey is k2, but the waiter is also in k2's queue (from the current iteration). So when closeWaiter is called, it's trying to remove the waiter from the queue it was just added to.
This is a bug in my fix. I'm removing the waiter from a queue that it was just added to, which is wrong.
The original code has the same issue. Let me check.
In the original code:
go
if ok && v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
}
closeWaiter tries to remove the waiter. If the waiter is in the queue, it might be removed (depending on the position). If the waiter is not in the queue, closeWaiter returns false.
In the original code, if closeWaiter returns false, the waiter is NOT removed. So the waiter stays in the queue.
In my fix, if closeWaiter returns false, I call removeWaiter, which removes the waiter.
So my fix is wrong. I should not remove the waiter if it was just added to the queue.
The issue is that c.rangeLastWaitKey might be the same as the current conflict key. In that case, the waiter is in the queue it's trying to remove from.
Hmm, but c.rangeLastWaitKey is set at the end of handleLockConflictLocked:
go
c.rangeLastWaitKey = key
So c.rangeLastWaitKey is the key from the previous iteration. If the current conflict is at the same key, then c.rangeLastWaitKey equals key.
But for a range lock [k1, k4], the conflicts might be at different keys. So c.rangeLastWaitKey should be different from the current conflict key.
Actually, for the test scenario, the conflicts are at different keys. So c.rangeLastWaitKey should be different from the current conflict key.
Let me re-trace:
First iteration: conflict at k4, c.rangeLastWaitKey is k4, c.rangeLastWaitKey is set to k4
Second iteration: conflict at k2, c.rangeLastWaitKey is k4 (from previous iteration), c.rangeLastWaitKey is set to k2
Third iteration: conflict at k2, c.rangeLastWaitKey is k2 (from previous iteration)
Wait, in the third iteration, the conflict is at k2, and c.rangeLastWaitKey is also k2. So they're the same!
But this can only happen if the same lock is conflicted in consecutive iterations. For a range lock [k1, k4], the conflicts might be at different keys.
Actually, looking at the test more carefully, I think the issue is that the waiter is added to the NEW queue BEFORE closeWaiter is called. So if closeWaiter is called on the same queue that the waiter was just added to, the waiter would be removed.
Let me check the flow:
For each conflict, add the waiter to the new queue
Then call closeWaiter to remove from the old queue
If the old queue is the same as the new queue, the waiter would be removed.
But for a range lock [k1, k4], the conflicts are at different keys, so the old queue and new queue should be different.
Unless... the same key is conflicted in multiple iterations. For example, if the range lock is [k1, k2, k3, k4] and all keys conflict, then the waiter might be added to different queues.
But for the test scenario, the range is [k1, k4], and the conflicts are at k4 and k2. These are different keys.
Hmm, let me re-trace the test flow more carefully.
Actually, I think I need to look at the actual conflict keys. Let me check.
Looking at the test:
go
range14 := newTestRows(1, 4)
So the range is [1, 4], which means keys 1, 2, 3, 4.
But when a range lock is added, it might be merged with existing locks. So the actual conflict key might be different.
Actually, let me just focus on fixing the issue. The problem is that my fix removes the waiter from the queue even when it should stay.
I think the fix should be: only call removeWaiter if the waiter was NOT already removed by closeWaiter. But how do I know if closeWaiter removed the waiter?
Actually, looking at closeWaiter, it doesn't return information about whether the waiter was removed. It only returns whether the lock can be removed.
I need to modify closeWaiter to return more information, or I need to add a separate method to check if the waiter is in the queue.
But the issue says "No new interfaces are introduced." So I should try to minimize changes.
Actually, let me re-think the approach. The issue is:
A waiter moves from one range conflict to another
The waiter should be removed from the OLD queue
But the waiter should NOT be removed if it was just added to the queue
The original code has this issue: when the waiter is not first in the queue, it's not removed. So the waiter stays in the stale queue.
My fix: always remove the waiter from the old queue, regardless of position.
But my fix is too aggressive: it removes the waiter from a queue that it was just added to.
I think the correct fix is: remove the waiter from the old queue only if the old queue is different from the new queue.
But how do I check if the old queue is different from the new queue?
One way is to check if c.rangeLastWaitKey equals the current conflict key. If they're the same, don't call removeWaiter.
Let me implement this:
go
if len(c.rangeLastWaitKey) > 0 && !bytes.Equal(c.rangeLastWaitKey, key) {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
v.removeWaiter(c.w)
}
}
}
c.rangeLastWaitKey = key
But this might not be correct either. The issue is that closeWaiter might have already removed the waiter (via notify). So calling removeWaiter might be redundant.
Actually, let me think about this differently. The issue is that the waiter is stranded in a stale queue. The stale queue is the queue at c.rangeLastWaitKey.
When the waiter moves from c.rangeLastWaitKey to the current conflict key, it should be removed from c.rangeLastWaitKey's queue.
But if the waiter was just added to c.rangeLastWaitKey's queue (in the same iteration), it should NOT be removed.
Hmm, but the waiter is added to the NEW queue, not the OLD queue. So the waiter should be in the OLD queue only if it was added there in a previous iteration.
Wait, but if the OLD queue and the NEW queue are the same (same key), the waiter would be added to the same queue twice.
Let me check if this can happen.
For a range lock [k1, k4], the keys are processed as pairs (start, end). So the range [k1, k4] is processed as:
Key: [1, 4] (start = 1, end = 4)
There's only one pair. So there's only one iteration. The waiter is added to one queue.
But wait, the range lock might be split into multiple keys. Let me check.
Looking at addRangeLockLocked, it seems to merge overlapping ranges. So [k1, k4] might be merged with existing locks, resulting in multiple keys.
Actually, I'm not sure. Let me just check if the test is timing out because of my fix.
Actually, I think the issue is simpler. Let me re-read my fix:
go
if ok {
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
v.removeWaiter(c.w)
}
}
I call removeWaiter only when closeWaiter returns false. closeWaiter returns false when:
There are holders
The waiter is not first in the queue
The waiter is first, there are more waiters, and isEmpty() returns false
In case 1, the lock has holders. The waiter should stay in the queue because it's waiting for the lock. So calling removeWaiter is wrong.
In case 2, the waiter is not first. The waiter is stranded. So calling removeWaiter is correct.
In case 3, the waiter is first, but there are more waiters. The waiter will be notified by notify. So the waiter should stay in the queue. Calling removeWaiter is wrong.
So my fix is wrong for cases 1 and 3.
But closeWaiter doesn't tell me which case it is. I need to know this to decide whether to call removeWaiter.
Actually, let me re-think. The issue is specifically about range locks. For range locks, when a waiter moves from one conflict to another, it should be removed from the OLD queue.
But the OLD queue might be the same as the NEW queue (if the same key is conflicted). In that case, I shouldn't remove the waiter.
So the fix should be: only remove the waiter if c.rangeLastWaitKey is different from the current conflict key.
Let me implement this:
go
if len(c.rangeLastWaitKey) > 0 && !bytes.Equal(c.rangeLastWaitKey, key) {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
removed := v.closeWaiter(c.w, l.logger)
if !removed {
v.removeWaiter(c.w)
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}
c.rangeLastWaitKey = key
But this still calls removeWaiter when closeWaiter returns false, which might be wrong for cases 1 and 3.
Hmm, actually, for case 1 (there are holders), closeWaiter returns false, and the waiter stays in the queue. Then my fix calls removeWaiter, which removes the waiter. This is wrong.
For case 3 (waiter is first, there are more waiters), closeWaiter returns false, and the waiter stays in the queue. Then my fix calls removeWaiter, which removes the waiter. This is also wrong.
So my fix is wrong for both cases.
But the original issue is about case 2 (waiter is not first). In this case, the original code doesn't remove the waiter. My fix should remove the waiter.
So I need a way to distinguish between case 2 and cases 1 and 3.
One way is to check if the waiter is first in the queue before calling closeWaiter:
go
if len(c.rangeLastWaitKey) > 0 && !bytes.Equal(c.rangeLastWaitKey, key) {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if ok {
isWaiterFirst := v.waiters.first() == c.w
removed := v.closeWaiter(c.w, l.logger)
if !removed && !isWaiterFirst {
v.removeWaiter(c.w)
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}
c.rangeLastWaitKey = key
This checks if the waiter is first in the queue. If it is, closeWaiter handles it (calls notify). If it's not, removeWaiter removes it.
But wait, closeWaiter might have already modified the queue. So checking first might not be accurate.
Actually, closeWaiter only calls notify if the waiter is first. If the waiter is not first, closeWaiter returns false without modifying the queue. So checking first should be accurate.
Let me implement this fix.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /matrixone/pkg/lockservice && python3 << 'PYEOF'
with open('lock_table_local.go', 'r') as f:
content = f.read()
old_code = ''' if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
zap.Uint64("table", l.bind.Table),
zap.String("txn", c.txn.txnKey),
zap.Binary("last-wait-key", c.rangeLastWaitKey),
zap.Binary("next-conflict-key", key))
}
if ok {
if v.closeWaiter(c.w, l.logger) {
l.mu.store.Delete(c.rangeLastWaitKey)
} else {
// closeWaiter may not remove the waiter from the queue when
// the waiter is not the first in line. Manually remove it
// to prevent the waiter from being stranded in a stale queue.
v.removeWaiter(c.w)
}
}
}'''
new_code = ''' if len(c.rangeLastWaitKey) > 0 {
v, ok := l.mu.store.Get(c.rangeLastWaitKey)
if !ok {
l.logger.Error("missing range last wait key when moving waiter to next conflict",
zap.Uint64("table", l.bind.Table),
zap.String("txn", c.txn.txnKey),
zap.Binary("last-wait-key", c.rangeLastWaitKey),
zap.Binary("next-conflict-key", key))
}
if ok {
// If the waiter is not the first in the old queue, it may be
// stranded there. We need to ensure it's removed. The original
// closeWaiter only removes the first waiter, so we manually
// remove non-first waiters to prevent them from being stranded.
removed := v.closeWaiter(c.w, l.logger)
if !removed && v.waiters.first() != c.w {
// closeWaiter didn't remove the waiter and it's not first,
// so it's stranded. Remove it.
v.removeWaiter(c.w)
}
if removed {
l.mu.store.Delete(c.rangeLastWaitKey)
}
}
}'''
content = content.replace(old_code, new_code)
with open('lock_table_local.go', 'w') as f:
f.write(content)