Repository navigation
Description
Consolidated scope: LockService waiter liveness
This issue tracks two independently reproduced wait failures in the lockservice waiter lifecycle. In the local mixed row/range stress described below, a parked request can disappear from every queue (and the same schedule can also hit a waiter-object leak panic). In #30361, a cross-CN row waiter can miss an accepted wake and remain queued on a key with no holders. These reports exercise different queue and notification paths; they are grouped under the shared invariant that every pending lock request must remain discoverable and eventually be granted, failed, cancelled, or detected as deadlocked.
Additional acceptance criteria
- A parked request always has a live, discoverable wait edge or has received a terminal result; no request may block invisibly after its queue entry is removed.
- Releasing the last holder eventually wakes/re-drives waiters, including the remote cross-CN event path; a holderless key must not retain waiters indefinitely.
- Run the mixed local row/range stress from this issue and the cross-CN row-contention stress from [Bug]: cross-CN row lock waiters strand forever on holderless keys after an accepted wake #30361 repeatedly and under
-race; both must finish without hangs, waiter leaks, invalid state, or lost notifications. - Cancellation and cleanup remove every queue entry and waiter object exactly once after any failure or wake race.
Additional report
- #30361 — cross-CN waiters can remain stranded on holderless row keys after an accepted wake; the report includes 5/5 reproductions and distinguishes this notification-path failure from the local queue-entry loss described here.
Branch Name
main
Commit ID
bac18ed (fix(vector): preserve constant selection grouping metadata (#30119))
Other Environment Information
- Hardware parameters: Apple M-series (arm64)
- OS type: macOS (darwin/arm64), Go 1.27.1
- Others: reproduced with a Go white-box concurrency test inside
pkg/lockservice(no mo-service needed). The same stress is the trigger for the related waiter-leak report; the two manifestations alternate depending on scheduling (about 3 stalls vs 8 leak panics in 11 runs at this commit).
Actual Behavior
Under concurrent row + range locking over one table (4 transactions x 100 rounds mixing shared rows, exclusive rows, exclusive range, shared range; one lock-unlock per round), an in-flight row lock request can become invisible: the pending request's waiter is not present in any lock queue. Nobody can notify it, and the local deadlock detector sees no wait edge for it, so the request stalls until an external deadline ends it (in the test: the request context; in production: the session's lock wait budget if any, otherwise indefinitely).
Three reproductions at this commit, each diagnosed with a lock-table dump captured at the moment the request hit its 60s deadline:
- (verbose mode) txn
02, exclusive range request, stopped at round 6 for 60s:
worker 2 round 6 pattern xrange: unexpected lock error: context deadline exceeded
lock table:
key=0b Exclusive(row): holder(01), waiters()
key=0c Shared(range-start): holder(01 03), waiters()
key=10 Shared(range-end): holder(01 03), waiters()
The prior log for that transaction was missing range last wait key when moving waiter to next conflict {txn: \^B, last-wait-key: 0x0D, last-wait-key-exists: false}.
- txn
03, exclusive row batch{11},{13},{18}, stopped at round 3 for 60s. Per the dump,{0x0b}is held by txn03itself,{12,16}is co-held by txn03and01(so every key of the request is re-entry or free), and no waiter exists anywhere in the table:
worker 3 round 3 pattern xrows: unexpected lock error: context deadline exceeded
lock table:
key=0b Exclusive(row): holder(03), waiters()
key=0c Shared(range-start): holder(01 03), waiters()
key=10 Shared(range-end): holder(01 03), waiters()
A request for keys the transaction already holds cannot legitimately block at all.
- txn
03, exclusive row batch, round 7, 60s stall; this time{11}legitimately belonged to txn01, but the stuck request has no waiter entry in{11}'s queue (the only queued waiter there belongs to another transaction and visibly shows a corrupt refcount of 4); additionally another transaction's waiter sits queued behind a range it co-holds (self-wait edge):
worker 3 round 7 pattern xrows: unexpected lock error: context deadline exceeded
lock table:
key=0b Exclusive(row): holder(01), waiters(04-0x228b7956c500(4))
key=0c Shared(range-start): holder(01 03), waiters(01-0x228b78978200(2))
key=10 Shared(range-end): holder(01 03), waiters(01-0x228b78978200(2))
Alongside, that same run emitted missing range last wait key when moving waiter to next conflict 5 times for txn 02.
Occurrence rate: 3 of 11 runs (~27%) with the attached test at this commit (another 7-8 of the same runs terminate via the waiter-object leak panic reported separately; essentially every run hits one of the two). The stall reproduces also with an earlier variant of the same stress on the prior main commit 8795f36.
Expected Behavior
A parked lock request must always remain reachable: its waiter stays registered in the queue of the lock it waits on until it is granted or failed; releases notify it; the deadlock detector sees its wait edge. A request for re-entrant (already-held) and free keys must never wait at all. The stress must complete ok.
Steps to Reproduce
Same stress test as the waiter-leak report (source below / see repro):
go test ./pkg/lockservice/ -run TestLoomConcurrentMixedLocksStress -count=1 -timeout 600s
Repeat the single run up to ~10 times. Outcomes alternate between:
panic: missing free for type: *lockservice.waiter, ...(leak manifestation, separate report), and- the stall:
--- FAIL: TestLoomConcurrentMixedLocksStress (60.01s)withunexpected lock error: context deadline exceededplus the lock-table dump showing the pending request has no waiter entry (hang manifestation, this report).
Test source (white-box, uses repo test helpers; the dump helper prints every hold and wait edge):
package lockservice
import (
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
pb "github.com/matrixorigin/matrixone/pkg/pb/lock"
"github.com/matrixorigin/matrixone/pkg/pb/timestamp"
"github.com/stretchr/testify/require"
)
type loomStressPattern struct {
name string
gen func(r int, seed byte) ([][]byte, pb.LockOptions)
}
func loomPatternXRange(r int, _ byte) ([][]byte, pb.LockOptions) {
if r%2 == 0 {
return [][]byte{{10}, {16}}, newTestRangeExclusiveOptions()
}
return [][]byte{{12}, {20}}, newTestRangeExclusiveOptions()
}
func loomPatternSRows(r int, _ byte) ([][]byte, pb.LockOptions) {
if r%2 == 0 {
return [][]byte{{11}, {12}, {14}}, newTestRowSharedOptions()
}
return [][]byte{{11}, {13}, {15}}, newTestRowSharedOptions()
}
func loomPatternXRows(r int, _ byte) ([][]byte, pb.LockOptions) {
return [][]byte{{11 + byte(r%3)}, {13}, {18}}, newTestRowExclusiveOptions()
}
func loomPatternSRange(r int, _ byte) ([][]byte, pb.LockOptions) {
return [][]byte{{12}, {15 + byte(r%2)}}, newTestRangeSharedOptions()
}
func loomIsDeadlockErr(err error) bool {
return errors.Is(err, ErrDeadLockDetected) ||
moerr.IsMoErrCode(err, moerr.ErrDeadLockDetected)
}
func loomDumpLockTable(s *service) string {
lt, err := s.getLockTable(context.Background(), 0, 0)
if err != nil {
return fmt.Sprintf("getLockTable: %v", err)
}
local := lt.(*localLockTable)
var sb strings.Builder
local.mu.RLock()
defer local.mu.RUnlock()
local.mu.store.Iter(func(key []byte, lock Lock) bool {
fmt.Fprintf(&sb, "key=%x %s\n", key, lock.String())
return true
})
return sb.String()
}
func loomRunStressWorker(t *testing.T, s *service, table uint64, seed byte,
rounds int, patterns []loomStressPattern, errCh chan<- error) {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
txnID := newTestTxnID(seed)
for r := 0; r < rounds; r++ {
p := patterns[(r+int(seed))%len(patterns)]
keys, opt := p.gen(r, seed)
_, err := s.Lock(ctx, table, keys, txnID, opt)
switch {
case err == nil:
time.Sleep(time.Duration((r+int(seed))%4) * 100 * time.Microsecond)
case loomIsDeadlockErr(err):
default:
errCh <- fmt.Errorf("worker %d round %d pattern %s: unexpected lock error: %w\nlock table:\n%s",
seed, r, p.name, err, loomDumpLockTable(s))
return
}
if err := s.Unlock(ctx, txnID, timestamp.Timestamp{}); err != nil {
errCh <- fmt.Errorf("worker %d round %d: unlock: %w", seed, r, err)
return
}
if r%3 != 0 {
runtime.Gosched()
}
}
errCh <- nil
}
func loomRunStress(t *testing.T, s *service, workers, rounds int, patterns []loomStressPattern) {
errCh := make(chan error, workers)
var wg sync.WaitGroup
for i := 1; i <= workers; i++ {
wg.Add(1)
go func(seed byte) {
defer wg.Done()
loomRunStressWorker(t, s, 0, seed, rounds, patterns, errCh)
}(byte(i))
}
wg.Wait()
close(errCh)
for err := range errCh {
require.NoError(t, err)
}
}
func TestLoomConcurrentMixedLocksStress(t *testing.T) {
patterns := []loomStressPattern{
{"xrange", loomPatternXRange},
{"srows", loomPatternSRows},
{"xrows", loomPatternXRows},
{"srange", loomPatternSRange},
}
runLockServiceTests(t, []string{"s1"}, func(_ *lockTableAllocator, ss []*service) {
loomRunStress(t, ss[0], 4, 100, patterns)
})
}Additional information
The invariant violated: while a lock request is parked in doLock's c.w.wait(...) (lock_table_local.go:190), its waiter must be a live entry in exactly the queue of the conflicting lock, so that (a) releases notify it and (b) fetchWhoWaitingMe-style deadlock detection sees the wait edge. The dumps above show parked requests with zero queue entries (occurrences 1 and 2) while another queued waiter in occurrence 3 shows a refcount of 4 and a transaction waiting behind a range it already co-holds, i.e. the queue bookkeeping around re-queued waiters is demonstrably inconsistent.
Where the entry accounting churns (line numbers at bac18ed):
sliceBasedWaiterQueue.notify(pkg/lockservice/waiter_queue.go:173-205) accepts the leading waiter but deliberately keeps its entry in the queue; the accepted waiter is expected to remove itself later. A waiter therefore routinely exists in a half-accepted state whose ownership is ambiguous while its request retries.- A notified row waiter that conflicts again is re-added to a queue via
handleLockConflictLocked(pkg/lockservice/lock_table_local.go:1225) without removing any previously retained entry; only the Range granularity removes the old entry first (:1201-1202->closeRangeWaiterLocked, whose fallback:1272-1299itself logsmissing range last wait key when moving waiter to next conflictwhen the old admission's lock is gone and then erases the waiter's entries from every lock in the table - which is exactly the kind of erase/re-add window in which a parked row waiter's last queue entry can disappear without any notification being sent to its owner). mergeContext(pkg/lockservice/lock_table_local.go:2014-2087) speculatively re-homes waiters between queues underbeginChange/commitChange/rollbackChangewindows;restart()/rollback()intentionally discard speculative puts (waiter_queue.go:268), andcommitcloses every waiter in the source queues, so any entry accounting that de-duplicates or assumes single membership during these windows directly risks losing a parked owner.- The same-interaction failure-detach path for row waiters (
lock_table_local.go:269-312) removes only the first matching entry of the waiter, which is the sibling asymmetry that produces the object-leak manifestation reported separately.
Suggested directions: make the waiter itself carry the identity/backend of the queue(s) it is enqueued in and assert that a blocking waiter always has at least one live queue entry (e.g. at notify/close/finalizer time); on any path that erases or re-homes a queued entry without the owner completing, send the owner a notification (wake or terminal error) instead of leaving the entry silently unlinked; and treat "request for keys entirely held by the same transaction blocks" (occurrence 2) as a state invariant broken loudly.
Both manifestations of this stress (leak and stall) must be fixed for the mixed row/range workload to be safe; they are reported separately because they terminate through different code branches, but the underlying trigger - queue entry re-homing across notify-kept-head admissions, conflict moves and range merges - is shared.
Found by Loom bug hunt (module: custom-a6feb4cc37; tests: unit, white-box, concurrency)
Activity
iamlinjunhong commentedon Oct 17, 2026
Verified the original reproduction on main commit
d304047724bea6104c5c2be496107928034b0778(macOS arm64, Go 1.27.1).I copied
TestLoomConcurrentMixedLocksStressfrom this issue unchanged, preserving the four workers, 100 rounds, mixed row/range patterns and 60-second context deadline. Using the repository CGo test wrapper:-count=10— 10/10 passed.-race -count=100— 100/100 passed in one process; the initial single-run race check also passed.No context deadline failure, waiter missing-free panic or race report occurred in these runs. The reported workload is fixed on this tested main revision by #30321, merged as
ac55588b8d4bf19c803a31bbd8248b7f63ad8122. Its changes preserve the conflict retry position, retire replaced waiters by identity, record complete physical range ownership and reset each unlock pair independently.No additional fix PR is needed for this reproduction. This is bounded verification of the reported workload; the issue remains open for reporter verification.
[-][Bug]: row lock request stalls indefinitely when its waiter is lost from the lock queue[/-][+][Bug]: LockService can strand row-lock waiters across queue transitions and cross-CN wake delivery[/+]fix(lockservice): retire waiter ownership across retries and range me…