Repository navigation
Closed
Copy link
Labels
kind/bugSomething isn't workingseverity/s0Active / top priority for current sprint. Owner has committed to working on it now.
Milestone
Description
环境
- 分支:
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:
- 先正常加锁和解锁一次,确保目标表的 bind 已经缓存。
- 创建 context,并在调用
Lock前取消。 - 对无冲突的相同行执行
Lock。 - 如果错误实现成功取得锁,先调用
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:
- 为一个新表在
s.mu.allocating中预置未关闭的waitC,模拟另一个请求正在分配相同表的 bind。 - 创建并立即取消 context。
- 使用这个已取消 context 调用
s.Lock(...)。 - 等待 50ms,确认
Lock没有返回。 - 模拟并发分配者发布本地 bind 并关闭
waitC。 - 读取
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 -vRace 重复测试:
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,直接成功
具体问题:
service.Lock在创建 active txn 之前和等待 bind 前都没有检查ctx.Err()。getLockTableWithCreate没有接收 context。- 等待并发 bind 分配直接使用
<-waitC。 - 当前请求自己成为 bind 分配者时,调用的也是
getLockTableBind(context.Background(), ...),同样与调用方 context 脱离,最长受内部 10 秒 RPC timeout 控制。 - 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。
Metadata
Metadata
Assignees
Labels
kind/bugSomething isn't workingseverity/s0Active / top priority for current sprint. Owner has committed to working on it now.
Activity
[-][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[/+]fix(lockservice): honor context cancellation in lock waits (#25901)
Ariznawlll commentedon Jul 22, 2026
已在最新
main分支完成复验,已取消的 context 不再成功获得 lockservice 锁。测试版本
mainc0486a2446c84c6dd6bf142494fe85243877ddc5测试场景
覆盖三条与原问题直接相关的路径:
Lock前取消 context;执行命令:
实际结果
context.Canceled,没有取得无冲突本地锁;测试结论
Lock入口、bind allocation/readiness 等待和真正加锁前均已正确传播调用方 context。已取消请求不会继续等待、返回成功或遗留新锁,原问题验证通过。fix(lockservice): honor context cancellation in lock waits (matrixori…
fix(lockservice): honor context cancellation in lock waits (matrixori…
fix(lockservice): honor context cancellation in lock waits (matrixori…