Skip to content

[Bug]: lockservice Lock can acquire an uncontended lock after context cancellation #25790

Closed

Description

@Ariznawlll

环境

  • 分支:origin/main
  • Commit:f8aaa25e670d0936b14602becd70d5966b1a87a1
  • Commit 时间:2026-07-16T03:49:36+00:00
  • Go:go1.26.4 darwin/arm64
  • 组件:pkg/lockservice

问题描述

Lock(ctx, ...) 没有在入口或真正加锁前检查 ctx.Err()。即使 context 在调用 Lock 之前已经取消,只要本地锁没有冲突,Lock 仍会返回 nil 并真实持有锁。

对于尚未缓存 bind 的表,问题还会进一步放大:创建 lock table 时会复用 service.mu.allocating 中的 channel 等待另一个并发请求完成 bind 分配。这个等待直接执行 <-waitC,没有监听 ctx.Done()。

结果不只是取消响应延迟:当 bind 随后发布时,请求会继续向下执行;如果本地锁没有冲突,localLockTable 不会在加锁前检查已经取消的 context,最终 Lock 返回 nil 并真实持有锁。

也就是说,一个已经取消的 SQL/事务请求仍可能在取消后成功加锁。

白盒复现一:已缓存 bind,无并发等待

测试使用真实 lockservice 和 lock table allocator:

  1. 先正常加锁和解锁一次,确保目标表的 bind 已经缓存。
  2. 创建 context,并在调用 Lock 前取消。
  3. 对无冲突的相同行执行 Lock。
  4. 如果错误实现成功取得锁,先调用 Unlock 清理,再断言应返回 context.Canceled。

核心测试:

func TestLockDoesNotAcquireAfterContextAlreadyCanceled(t *testing.T) {
    runLockServiceTests(t, []string{"s1"},
        func(_ *lockTableAllocator, services []*service) {
            s := services[0]
            table := uint64(25790)
            rows := newTestRows(1)

            warmupTxn := []byte("warm-bind")
            _, err := s.Lock(context.Background(), table, rows, warmupTxn,
                newTestRowExclusiveOptions())
            require.NoError(t, err)
            require.NoError(t, s.Unlock(context.Background(), warmupTxn,
                timestamp.Timestamp{}))

            ctx, cancel := context.WithCancel(context.Background())
            cancel()
            canceledTxn := []byte("already-canceled")
            _, lockErr := s.Lock(ctx, table, rows, canceledTxn,
                newTestRowExclusiveOptions())
            if lockErr == nil {
                require.NoError(t, s.Unlock(context.Background(), canceledTxn,
                    timestamp.Timestamp{}))
            }
            require.ErrorIs(t, lockErr, context.Canceled,
                "Lock acquired an uncontended local lock after its context was already canceled")
        })
}

白盒复现二:等待并发 bind 分配

测试使用真实 lockservice 和 lock table allocator:

  1. 为一个新表在 s.mu.allocating 中预置未关闭的 waitC,模拟另一个请求正在分配相同表的 bind。
  2. 创建并立即取消 context。
  3. 使用这个已取消 context 调用 s.Lock(...)。
  4. 等待 50ms,确认 Lock 没有返回。
  5. 模拟并发分配者发布本地 bind 并关闭 waitC。
  6. 读取 Lock 结果,并清理可能获得的锁,避免测试泄漏。

核心测试:

func TestLockReturnsPromptlyWhenContextCanceledWhileWaitingForBindAllocation(t *testing.T) {
    runLockServiceTests(t, []string{"s1"},
        func(alloc *lockTableAllocator, services []*service) {
            s := services[0]
            group := uint32(0)
            table := uint64(25787)
            waitC := make(chan struct{})
            s.mu.Lock()
            s.mu.allocating[group] = map[uint64]chan struct{}{table: waitC}
            s.mu.Unlock()

            ctx, cancel := context.WithCancel(context.Background())
            cancel()
            done := make(chan error, 1)
            txnID := []byte("canceled-bind-wait")
            go func() {
                _, err := s.Lock(ctx, table, newTestRows(1), txnID,
                    newTestRowExclusiveOptions())
                done <- err
            }()

            returnedPromptly := false
            var lockErr error
            select {
            case lockErr = <-done:
                returnedPromptly = true
            case <-time.After(50 * time.Millisecond):
            }

            bind := pb.LockTable{
                Group: group, Table: table, OriginTable: table,
                ServiceID: s.serviceID, Valid: true,
                Version: alloc.version, AllocatorID: alloc.allocatorID,
            }
            s.bindChangeMu.Lock()
            s.tableGroups.set(group, table, s.createLockTableByBind(bind))
            s.bindChangeMu.Unlock()
            s.mu.Lock()
            delete(s.mu.allocating[group], table)
            s.mu.Unlock()
            close(waitC)

            if !returnedPromptly {
                lockErr = <-done
            }
            if lockErr == nil {
                require.NoError(t, s.Unlock(context.Background(), txnID,
                    timestamp.Timestamp{}))
            }
            require.True(t, returnedPromptly,
                "Lock ignored context cancellation while waiting for another bind allocation; final error: %v",
                lockErr)
        })
}

执行命令

已缓存 bind、context 预先取消:

go test ./pkg/lockservice \
  -run '^TestLockDoesNotAcquireAfterContextAlreadyCanceled$' \
  -count=10 -v

go test -race ./pkg/lockservice \
  -run '^TestLockDoesNotAcquireAfterContextAlreadyCanceled$' \
  -count=5 -v

等待并发 bind 分配,普通重复测试:

go test ./pkg/lockservice \
  -run '^TestLockReturnsPromptlyWhenContextCanceledWhileWaitingForBindAllocation$' \
  -count=10 -v

Race 重复测试:

go test -race ./pkg/lockservice \
  -run '^TestLockReturnsPromptlyWhenContextCanceledWhileWaitingForBindAllocation$' \
  -count=5 -v

相邻基线:

go test ./pkg/lockservice -run '^TestRowLock$' -count=3

实际结果

  • 已缓存 bind、context 调用前已取消:普通测试 10/10 FAIL,Race 测试 5/5 FAIL;15 次均返回 nil 并真实取得本地锁
  • 等待并发 bind 分配:普通测试 10/10 FAIL,Race 测试 5/5 FAIL;15 次均无视取消继续等待,bind 发布后返回 nil 并真实取得本地锁
  • Race detector 未报告数据竞争
  • Lock 在 context 已经取消的情况下仍阻塞等待 bind
  • 相邻 TestRowLock 基线:3/3 PASS

代表性输出:

=== RUN   TestLockDoesNotAcquireAfterContextAlreadyCanceled
Error: Expected error with "context canceled" in chain but got nil.
Messages: Lock acquired an uncontended local lock after its context was already canceled
--- FAIL: TestLockDoesNotAcquireAfterContextAlreadyCanceled (0.01s)

=== RUN   TestLockReturnsPromptlyWhenContextCanceledWhileWaitingForBindAllocation
Error: Should be true
Messages: Lock ignored context cancellation while waiting for another bind allocation; final error: <nil>
--- FAIL: TestLockReturnsPromptlyWhenContextCanceledWhileWaitingForBindAllocation (0.06s)

根因

调用链:

service.Lock(ctx)
  -> getLockTableWithCreate(...)       // 没有 ctx 参数
     -> <-waitC                        // 无条件等待,不监听 ctx.Done()
  -> localLockTable.lock(ctx)
     -> doAcquireLock(...)             // 无冲突时不检查 ctx,直接成功

具体问题:

  1. service.Lock 在创建 active txn 之前和等待 bind 前都没有检查 ctx.Err()。
  2. getLockTableWithCreate 没有接收 context。
  3. 等待并发 bind 分配直接使用 <-waitC。
  4. 当前请求自己成为 bind 分配者时,调用的也是 getLockTableBind(context.Background(), ...),同样与调用方 context 脱离,最长受内部 10 秒 RPC timeout 控制。
  5. bind 返回后没有再次检查 context;本地无冲突加锁路径会返回成功。

生产影响

  • 所有本地无冲突加锁路径都可能接受调用前已经取消的请求,不需要 bind 竞争条件。
  • 首次访问或 bind 失效/迁移后的并发 SQL 还会进入不可取消的 bind 等待路径。
  • SQL 超时、客户端断开或上游取消后,goroutine 仍可能长时间等待 bind。
  • 已取消请求可能获得并保留真实锁,直到事务的其他清理路径将其释放。
  • 并发 bind 分配卡住时,等待时间不受调用方 deadline 控制;当前分配者本身也忽略调用方 context。
  • 在高并发和 allocator/RPC 抖动下可能放大请求堆积、锁占用及后续锁等待。

期望结果

  • Lock 收到已取消 context 时应立即返回 context.Canceled。
  • 等待共享 bind 分配时应同时监听 ctx.Done() 和 waitC。
  • allocator bind RPC 应继承调用方 context。
  • bind 返回、真正加锁之前应再次确认 context 仍有效。
  • 已取消请求绝不能返回成功或留下新锁。

建议修复方向

  • 为 Lock 使用的 getLockTableWithCreate/bind 等待路径传入 context。
  • 将裸 <-waitC 改为 select { case <-ctx.Done(): ...; case <-waitC: ... }。
  • 使用已有的 getLockTableBindWithContext(ctx, ...),不要在用户 Lock 路径使用 context.Background()。
  • 在创建 active txn 以及调用 l.lock 前增加 ctx.Err() 检查,并确保错误路径不会遗留空 active txn。

重复项检索

已按 waitLockTableBind、getLockTableWithCreate context、lockservice allocating channel canceled context、Lock context canceled returns nil acquires lock 检索 issue,并按相关函数名检索 PR;未发现覆盖该取消后成功加锁问题的现有 issue/PR。

Activity

  1. added this to the MO-202607 milestone on Jul 16, 2026
  2. added
    kind/bug
    on Jul 16, 2026
  3. added theissue type on Jul 16, 2026
  4. changed the title [-][Bug]: lockservice Lock ignores canceled context while waiting for bind allocation and can still acquire lock[/-] [+][Bug]: lockservice Lock can acquire an uncontended lock after context cancellation[/+] on Jul 16, 2026
  5. added
    severity/s0
    and removed on Jul 21, 2026
  6. added a commit that references this issue on Jul 21, 2026
    78d15d6
  7. assigned and unassigned on Jul 22, 2026
  8. Ariznawlll commented on Jul 22, 2026

    @Ariznawlll
    CollaboratorAuthor

    已在最新 main 分支完成复验,已取消的 context 不再成功获得 lockservice 锁。

    测试版本

    测试场景

    覆盖三条与原问题直接相关的路径:

    1. bind 已缓存且本地锁无冲突时,在调用 Lock 前取消 context;
    2. 等待另一个请求完成 bind allocation 时取消 context;
    3. service readiness 等待期间取消 context。

    执行命令:

    go test ./pkg/lockservice \
      -run '^(TestLockDoesNotAcquireAfterContextAlreadyCanceled|TestLockReturnsWhenCanceledDuringBindAllocationWait|TestLockReturnsWhenServiceReadinessWaitIsCanceled)$' \
      -count=20 -timeout=120s
    
    go test -race ./pkg/lockservice \
      -run '^(TestLockDoesNotAcquireAfterContextAlreadyCanceled|TestLockReturnsWhenCanceledDuringBindAllocationWait|TestLockReturnsWhenServiceReadinessWaitIsCanceled)$' \
      -count=5 -timeout=180s

    实际结果

    • 普通模式:三个场景各运行 20 次,全部通过;
    • Race 模式:三个场景各运行 5 次,全部通过;
    • 预先取消的请求返回 context.Canceled,没有取得无冲突本地锁;
    • bind allocation 和 readiness 等待均能及时响应取消;
    • 取消路径未留下 active txn、lock admission 或实际锁;
    • Race detector 未报告数据竞争。

    测试结论

    Lock 入口、bind allocation/readiness 等待和真正加锁前均已正确传播调用方 context。已取消请求不会继续等待、返回成功或遗留新锁,原问题验证通过。

  9. added 3 commits that reference this issue on Sep 17, 2026
    7065d2c
    58193fb
    6542312
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions