Skip to content

[Bug]: cross-CN row lock waiters strand forever on holderless keys after an accepted wake #30361

Closed as not planned

Description

@iamlinjunhong

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, CGo enabled per repository configuration (native jemalloc built with make -C thirdparties jemalloc)
  • Others: reproduced with a Go white-box concurrency test inside pkg/lockservice only — two full lock services in one test process talk over real RPC (runLockServiceTests(t, []string{"s1", "s2"}, ...)), no mo-service needed.

Actual Behavior

Six transactions drive a deadlock-free, range-free row-key contention workload (two-key/three-key batches over keys 7/9/11, each batch acquiring keys in one global ascending order, so no wait-for cycle can exist — the deadlock detector never aborts anyone). Three transactions run on the owning CN (s1), three on a second CN (s2), so half of all lock requests take the remote (cross-CN RPC) path.

In 5 of 5 runs (4 plain + 1 -race) the run freezes for the full 90s request deadline, and the lock-table dump taken at that moment shows a structurally impossible state: row keys with an empty holder set but live waiters parked in their queues. Nobody holds the key, so no future unlock can ever notify the waiters; requests stuck there also hold previously granted keys, dragging the whole dependency chain into the freeze. Waiter refcounts are healthy and the reuse checker's end-of-test FreeOSMemory sweep reports no missing-free, so this is a pure lost-wakeup, not a leak.

  1. Plain run 1 — txn 06 holds key 07 and is parked on key 09, which has NO holders:
svc 3 worker 4 round 29 pattern xrows-fwd: unexpected lock error: context deadline exceeded
key=07 Exclusive(row): holder(06), waiters(04-0xe57819a6000(4) 02-0xe578081f600(4) 05-0xe578081f400(2) 03-0xe5781892400(2))
key=09 Shared(row): holder(), waiters(06-0xe5781cb6300(3))
  1. Plain run 2 — key 07 left Exclusive with an empty holder set and THREE permanently parked waiters:
svc 4 worker 5 round 43 pattern srows-ab: unexpected lock error: context deadline exceeded
key=07 Exclusive(row): holder(), waiters(06-0x4cbade5a8500(4) 02-0x4cbadd90b800(3) 04-0x4cbadd90b600(4))
  1. Plain run 4 — same shape:
svc 4 worker 5 round 39 pattern srows-ab: unexpected lock error: context deadline exceeded
key=07 Exclusive(row): holder(), waiters(02-0x4d62a9241300(4) 06-0x4d62a9c6c700(4) 04-0x4d62a9c6c400(3))
  1. -race run — identical state (and notably the race detector reports no data races; the stall is a plain lost wake):
svc 4 worker 5 round 19 pattern srows-ab: unexpected lock error: context deadline exceeded
key=07 Exclusive(row): holder(02), waiters(04-0xc000474500(4) 06-0xc000474600(4))
key=09 Shared(row): holder(), waiters(02-0xc000325a00(3))

A secondary observation, seen in 2 of the 9 cross-CN row-contention runs at this commit (including the reversed-batch variant of the same stress where deadlock cycles are allowed): an active remote transaction's Lock returns invalid state txn not found (ErrTxnNotFound) instead:

svc 3 worker 4 round 1 pattern xrows-a: unexpected lock error: invalid state txn not found
2026/10/16 11:49:41.514287 +0800 ERROR cn-service.lockservice failed to lock on remote {"uuid": "", "binding": "0-0(0)-1792122581459805000s1-1792122581458683000-42449c6c-bd19-451a-bb53-e9d797b2cd13", "txn": "02()", "rows": "[]", "row count": 3, "opts": "Exclusive-Row-Wait", "remote": "0-0(0)-1792122581459805000s1-1792122581458683000-42449c6c-bd19-451a-bb53-e9d797b2cd13", "error": "invalid state txn not found"}

Reproduction rate at this commit:

Workload Runs Frozen at ctx deadline Leak panics
Deadlock-free row chain, 2 CN (remote path) 4 plain + 1 race 5/5 0
Deadlock-free row chain, 1 CN (local control) 4 plain + 1 race 0/5 (all pass) 0
Row contention with reversed batches, 2 CN 5 5/5 0

Expected Behavior

  • After the last holder of a row key releases, either the head waiter's retry completes (it becomes the new holder and its queue entry is removed) or the key entry is cleaned up. A row key must never rest with zero holders while waiters remain in its queue with nobody left holding the wake responsibility.
  • Every lock request must terminate by itself (grant, clean error, deadlock detection, or the orphan-check fallback in waiter_events.check). It must not depend on the caller's context deadline to drain a broken table state.
  • The single-CN control demonstrates the same queue and notify protocol admits and wakes correctly when the waiter's wake is consumed directly by its parked goroutine (5/5 clean), so the cross-CN behavior should match.

Steps to Reproduce

  1. Build the thirdparties as required by the repo CGo config (macOS arm64: make -C thirdparties jemalloc).
  2. Save the Go test below as pkg/lockservice/loom_test_u3_stall_test.go (single-file version of what I ran; the helpers runLockServiceTests, newTestTxnID, newTestRowSharedOptions, newTestRowExclusiveOptions already exist in pkg/lockservice test files).
  3. Run (each trial takes ~90s because the stall consumes the whole per-request deadline):
go test ./pkg/lockservice/ -run TestLoomRemoteRowChainStress -count=1 -timeout 300s   # froze 4/4 for me
go test ./pkg/lockservice/ -run TestLoomRemoteRowChainStress -count=1 -race -timeout 600s   # froze 1/1 for me
go test ./pkg/lockservice/ -run TestLoomLocalRowChainStress -count=1 -timeout 300s   # passed 4/4 for me
go test ./pkg/lockservice/ -run TestLoomLocalRowChainStress -count=1 -race -timeout 600s   # passed 1/1 for me

The failing workers report unexpected lock error: context deadline exceeded together with a lock-table dump; look for the holder() lines carrying non-empty waiters(...).

Additional information

The state shown in the dumps cannot arise from any single legal transition, and the workload that produces it excludes the two other known failure modes on purpose:

Where the wake is lost, based on the code at this commit:

  1. Unlock of the last holder of a row key notifies the head waiter exactly once: Lock.closeTxn → l.waiters.notify(notify) (pkg/lockservice/lock.go:255-258) and then keeps the key iff waiters remain.
  2. sliceBasedWaiterQueue.notify (pkg/lockservice/waiter_queue.go:173-206) accepts the head (w.notify(...) CAS blocking→notified) and retains it at its queue position — the accepted head is expected to complete its own retry, take the holder set, and remove its entry (pkg/lockservice/lock_table_local.go:166-257, wait() consumes the buffered value at line 190).
  3. For a remote transaction the retry is not executed by an already-parked goroutine: doLock returns immediately on the async path (pkg/lockservice/lock_table_local.go:161-163), handing the wake to the waiter-events pipeline. mustSendNotification (pkg/lockservice/waiter.go:229-245) first pushes the lock context into waiter_events.eventC via event.notified() (pkg/lockservice/waiter_events.go:147-151) and only then buffers the notify value on w.c; the events goroutine later pops the context and reruns c.doLock() (pkg/lockservice/waiter_events.go:332-337 → lockContext.doLock).
  4. If that single in-flight event is lost, nothing re-derives it: a row key's only notify source is a releasing holder (closeTxn/removeWaiter), and now there is no holder left; the periodic waiter_events.check only removes non-blocking waiters and enforces timeouts/orphan checks — none of these rescued the strand during ~90s of freezes (dozens of check ticks). New arrivals keep queuing behind the stranded head (writer-fair admission), widening the freeze to the whole table's key range.
  5. Suspect weak points in that chain (for whoever debugs): event.notified() silently does nothing when e.eventC == nil — the context is armed per park in waiterEvents.add (pkg/lockservice/waiter_events.go:229-259), but waiter.resetWait (pkg/lockservice/waiter.go:247-254, clearing w.event = event{}) sits between a consumed wake and the next park, so any park/re-park interleaving that skips the re-arm loses the wake; and eventC <- e.c is a blocking send executed while the notifier holds the lock-table mutex before the value is buffered on w.c, a structurally fragile two-step delivery.
  6. A recovery would also fix the current behavior: re-notify heads of holderless keys during waiter_events.check, or assert the invariant (len(holders)==0 && waiters>0 ⇒ broken) when a table quiesces.

Both earlier manifestations I reported remain reproducible at this commit with different shapes (leak after deadlock-abort churn; local stall with the waiter entry missing entirely), and neither PR-level fix direction for those (e.g. PR #30321) covers this holderless remote strand, whose workload here is deadlock-free and leaves healthy refcounts.

Found by Loom bug hunt (module: custom-a6feb4cc37; tests: unit, white-box, concurrency)

Activity

  1. added
    kind/bug
    on Oct 16, 2026
  2. iamlinjunhong commented on Oct 17, 2026

    @iamlinjunhong
    ContributorAuthor

    Full reproduction, exactly as Loom's bug hunt ran it when this issue was filed (the issue body above only summarized it):

    White-box concurrency test inside pkg/lockservice (two lock services in-process, real RPC). Save as pkg/lockservice/loom_test_u3_stall_test.go and run:
    
    go test ./pkg/lockservice/ -run TestLoomRemoteRowChainStress -count=1 -timeout 300s
    go test ./pkg/lockservice/ -run TestLoomRemoteRowChainStress -count=1 -race -timeout 600s
    go test ./pkg/lockservice/ -run TestLoomLocalRowChainStress -count=1 -timeout 300s   # control, should pass
    go test ./pkg/lockservice/ -run TestLoomLocalRowChainStress -count=1 -race -timeout 600s
    
    Observed at bac18ed24: remote chain froze 4/4 plain and 1/1 race; local control passed 4/4 plain and 1/1 race.
    
    ```go
    // (white-box test; package lockservice)
    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 loomIsDeadlockErr(err error) bool {
    	return errors.Is(err, ErrDeadLockDetected) ||
    		moerr.IsMoErrCode(err, moerr.ErrDeadLockDetected)
    }
    
    // dumps the owner-side local lock table (used in failure messages)
    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()
    }
    
    // one transaction's lock/unlock rounds; ctx deadline doubles as the stall detector
    func loomRemoteStressWorker(
    	t *testing.T,
    	svcIndex int,
    	svc *service,
    	owner *service,
    	table uint64,
    	seed byte,
    	rounds int,
    	patterns []loomStressPattern,
    	errCh chan<- error,
    ) {
    	ctx, cancel := context.WithTimeout(context.Background(), 90*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 := svc.Lock(ctx, table, keys, txnID, opt)
    		switch {
    		case err == nil:
    			time.Sleep(time.Duration((r+int(seed))%4) * 100 * time.Microsecond)
    		case loomIsDeadlockErr(err):
    			// tolerated (cannot happen in the chain variant by construction)
    		default:
    			errCh <- fmt.Errorf("svc %d worker %d round %d pattern %s: unexpected lock error: %w\nlock table:\n%s",
    				svcIndex, seed, r, p.name, err, loomDumpLockTable(owner))
    			return
    		}
    
    		if err := svc.Unlock(ctx, txnID, timestamp.Timestamp{}); err != nil {
    			errCh <- fmt.Errorf("svc %d worker %d round %d: unlock: %w", svcIndex, seed, r, err)
    			return
    		}
    		if r%3 != 0 {
    			runtime.Gosched()
    		}
    	}
    	errCh <- nil
    }
    
    // Deadlock-free two-CN row contention: every batch acquires keys in the same
    // global ascending order (7, 9, 11), so no wait-for cycle can exist.
    func TestLoomRemoteRowChainStress(t *testing.T) {
    	patterns := []loomStressPattern{
    		{"srows-ab", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {11}}, newTestRowSharedOptions()
    		}},
    		{"xrows-fwd", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {9}}, newTestRowExclusiveOptions()
    		}},
    		{"xrows-fwd2", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {9}, {11}}, newTestRowExclusiveOptions()
    		}},
    		{"srows-cd", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{9}, {11}}, newTestRowSharedOptions()
    		}},
    	}
    	runLockServiceTests(
    		t,
    		[]string{"s1", "s2"},
    		func(_ *lockTableAllocator, ss []*service) {
    			// Bind the table to s1 deterministically so every s2 transaction
    			// takes the remote path.
    			bindCtx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
    			defer cancel()
    			binder := newTestTxnID(0xFE)
    			if _, err := ss[0].Lock(bindCtx, 0, [][]byte{{3}}, binder, newTestRowExclusiveOptions()); err != nil {
    				t.Fatalf("bind lock: %v", err)
    			}
    			if err := ss[0].Unlock(bindCtx, binder, timestamp.Timestamp{}); err != nil {
    				t.Fatalf("bind unlock: %v", err)
    			}
    
    			const workers = 6
    			const rounds = 300
    			errCh := make(chan error, workers)
    			var wg sync.WaitGroup
    			for i := 0; i < workers; i++ {
    				wg.Add(1)
    				go func(idx int) {
    					defer wg.Done()
    					loomRemoteStressWorker(
    						t, idx, ss[idx%len(ss)], ss[0], 0, byte(idx+1), rounds, patterns, errCh)
    				}(i)
    			}
    			wg.Wait()
    			close(errCh)
    			for err := range errCh {
    				require.NoError(t, err)
    			}
    		})
    }
    
    // local-only control: identical workload on ONE service
    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 TestLoomLocalRowChainStress(t *testing.T) {
    	patterns := []loomStressPattern{
    		{"srows-ab", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {11}}, newTestRowSharedOptions()
    		}},
    		{"xrows-fwd", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {9}}, newTestRowExclusiveOptions()
    		}},
    		{"xrows-fwd2", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{7}, {9}, {11}}, newTestRowExclusiveOptions()
    		}},
    		{"srows-cd", func(r int, _ byte) ([][]byte, pb.LockOptions) {
    			return [][]byte{{9}, {11}}, newTestRowSharedOptions()
    		}},
    	}
    	runLockServiceTests(
    		t,
    		[]string{"s1"},
    		func(_ *lockTableAllocator, ss []*service) {
    			loomRunStress(t, ss[0], 6, 300, patterns)
    		})
    }
    
    ```
    
    runLockServiceTests, newTestTxnID, newTestRowSharedOptions, newTestRowExclusiveOptions are existing test helpers in pkg/lockservice (service_test.go). macOS arm64 needs `make -C thirdparties jemalloc` for the CGo config first.
  3. XuPeng-SH commented on Oct 22, 2026

    @XuPeng-SH
    Contributor

    This report is now tracked together with #30315. The canonical issue retains explicit acceptance cases for the behavior described here. This is an administrative duplicate/consolidation closure only; the underlying defect is not claimed fixed. The original description and discussion remain available on this issue.

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

Metadata

Metadata

Assignees

Labels

kind/bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions