Skip to content

fix(lock): preserve bounded ranges for large DML batches - #26706

Merged
XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-26630-lock-range
Aug 24, 2026
Merged

XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-26630-lock-range

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #26630

Root cause

The former planner-side whole-table promotion serialized disjoint large DML, while a per-call row threshold could not bound keys accumulated by a large or multi-statement transaction. The enforceable budget belongs to the physical lock owner and must preserve ownership semantics: only non-sharded Exclusive ownership can be conservatively replaced by its observed [min,max] range.

The original implementation closed the row-budget path but left system-level gaps around remote deadlock snapshots, mixed-version ownership bookkeeping, table-by-table owner cleanup, proxy handoff atomicity, transaction generations, bind refresh, and Shared-to-Exclusive reentry.

Design and correctness closure

  • Keep Exclusive DML and FOR UPDATE row-scoped in the planner. At the authoritative owner, cumulatively coarsen only all-Exclusive, non-sharded ownership after distinct retained keys exceed MaxLockRowCount.
  • Keep Shared ownership exact. Cardinality-known oversized Shared plans start with a table lock; underestimated/runtime batches retain exact rows up to the fixed bookkeeping ceiling rather than performing an unsafe mid-transaction Shared conversion.
  • Revalidate eligibility after waits and make every representation change atomic across lock-store state, waiter order, transaction bookkeeping, cancellation, and failure rollback.
  • Add lock protocol v27 with an explicit successful-Lock capability bit and a dedicated owner-local transaction waiting-list RPC. The physical owner is the authoritative wait-for source; the RPC uses its own bounded queue/workers so recursive snapshot traffic cannot saturate ordinary waiting-list workers. Current main already uses v18-v26 for unrelated protocol features.
  • Preserve rolling-upgrade safety. Legacy owners keep exact probe ledgers, lost-response retries reconcile NewLockAdd=false, existing proxies dynamically bypass their cache after protocol downgrade, and proxy mode is enabled only when table-scoped owner cleanup is negotiated.
  • Send one owner Unlock per physical table and validate the exact recorded bind generation. Cleanup never applies an old transaction to a rebound table; stale remote generations are resolved through the allocator.
  • Make proxy holder handoff prepare/revalidate/commit atomic. It is first-mutation-wins, idempotent for the same origin, rejects self replacement and incompatible origins, preserves the source on failure, and repairs a physical replacement holder only when the matching transaction ledger is live.
  • Serialize closure by exact transaction ID, including every ReplaceTo participant, without coupling unrelated hash collisions. Source generations remain registered and closing until every physical table acknowledges cleanup; successful tables are removed from the retry ledger and are never replayed.
  • Return deterministic owner/business cleanup errors instead of retrying forever. Only ambiguous transport failures retry with bounded backoff and cancellation.
  • Support row and exact-range Shared-to-Exclusive promotion by waiting until the requester is the sole holder, then atomically updating both range endpoints.
  • Make closing state atomically visible to bind fencing. Bind publication still synchronously fences every open transaction, but never waits on a closing transaction that already rejects later Lock calls; this removes cleanup-to-bind-refresh lock-order cycles without weakening the publication barrier.

Deep-review fixes

  • Rebased onto current main and integrated the upstream stale empty-lock repair, irregular UPDATE lock ordering, and remote LAST_INSERT_ID changes.
  • Moved the new capability from the now-occupied v26 to v27.
  • Removed a hot-path allocation regression in transaction-closure admission. The first version raised ordinary Lock+Unlock from 27 to 33 allocations/op; the final single-source path uses an owned pooled entry and a value guard, restoring 27 allocations/op while keeping cancellation and exact-ID serialization.

Unhappy-path closure

  • Cancellation before admission, while waiting, and immediately after token acquisition releases every token/reference and leaves no admission-map growth.
  • Ambiguous remote responses retain a bounded cleanup route; deterministic remote errors fail without infinite retry.
  • Failed multi-table cleanup keeps only unacknowledged tables retryable; acknowledged tables are not replayed.
  • Delayed Lock, same-ID transaction reuse, bind replacement, service shutdown, and proxy handoff failure cannot open a second live generation or lose the source holder.
  • Owner-local wait snapshots run in a separate bounded worker pool; deadlock traversal filters self edges and chooses a deterministic single victim.
  • Pre-v27 peers fall back to the legacy remote path and never activate table-scoped proxy handoff semantics.

Compatibility

  • This change introduces lock wire protocol v27; generated protobuf code is included.
  • Older peers do not use the new owner-local snapshot or table-scoped proxy handoff semantics.
  • Existing MaxLockRowCount <= MaxFixedSliceSize configurations remain valid.
  • There is no on-disk or checkpoint format change.

Validation

Final rebased head: 28f80f34c144d0583a10b0add8eed1c619660066 (base cdf7888344df65136f6d0c9c35ead4940d69a793)

  • complete pkg/lockservice: PASS, 102.385s
  • complete pkg/lockservice -race: PASS, 108.281s
  • closure handoff ordering and delayed-Unlock generation tests under -race -count=100: PASS
  • complete pkg/sql/colexec/lockop and pkg/sql/plan: PASS; both also PASS under -race
  • focused v27 mixed-version/proxy capability tests: PASS
  • affected-package go build, go vet, and git diff --check: PASS
  • performance: ordinary Lock+Unlock 27 allocs/op, 3673-3683 B/op; single-source closure admission 96.3-96.7 ns/op, 0 B/op, 0 allocs/op

The remaining roughly 5-10% single-core CPU overhead versus main is the measured cost of the required closing-generation fence, cumulative budget check, and retryable cleanup lifecycle. The avoidable allocation regression has been removed.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner August 4, 2026 16:24
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Aug 4, 2026
@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-26630-lock-range branch from c24747a to d0d2aef Compare August 4, 2026 16:27
@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-26630-lock-range branch from 9817e6c to a151b4f Compare August 4, 2026 23:52
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Updated exact head 7f440e24db522e635b83e16f4eccc00cd21f2a19, rebased onto current main at 53f6aa6f0bbdc59f924072e823cdcd48ff43a981.

Systematic rebase/fix summary:

  • range-diff preserves all nine PR commits. The only rebase delta is intentional: current main deleted legacy build_update.go, so its obsolete fallback call was dropped; the active QueryBuilder.createQuery integration remains intact. Main's newer ESQL/SQL TVF planner changes are preserved. Protocol slots remain collision-free: main ends at MORPC v26 / lock method 19; this PR uses v27 / method 20.
  • Rechecked @aunjgr's synchronous-close ABA finding. The holder-published generation is captured under the shard publication barrier, then both generation and txnID are revalidated after acquiring the txn mutex and again after async-drain waits. The forced same-ID pooled-reuse regression passes under race repetition.
  • Fixed the actual UT Coverage failure in TestHardwareCPU. The prior helper included Linux Iowait (non-busy and allowed to decrease) and double-counted Guest/GuestNice, which are already included in User/Nice. Busy time now sums only User + System + Nice + Irq + Softirq + Steal. A deterministic pre-fix counterexample fails with 101 < 110; the corrected test and live collector pass under -race -count=100.
  • Re-audited Q1 ownership (txn generations, pool reuse, handoff ledgers, drain refs, waiter refs), Q2 termination/cancellation (closure admission, async drain, retryable cleanup, lock ordering), and Q3 bounds (row ledgers, owner-local routes, admission entries, worker queues). No additional blocker was found.

Fresh exact-tree validation:

  • make generate-pb; no generated drift
  • full pkg/common/reuse, pkg/lockservice, pkg/pb/lock, pkg/sql/colexec/lockop, pkg/sql/plan, pkg/util/metric: PASS
  • full pkg/lockservice -race: PASS (110.746s)
  • full affected reuse/lockop/plan/metric race suites: PASS
  • generation/handoff/waiter/retry-ledger focused race set: 20x PASS
  • changed planner and lockop focused race sets: 100x PASS
  • affected-package go vet, go build, git diff --check, and changed-file gofmt: PASS
  • Lock+Unlock benchmark remains at 23 allocs/op, 3170 B/op

The force update used an exact lease against old remote head 36fbf4d326; no concurrent remote commit was overwritten. CI has been triggered on the new head and was not awaited for this code update.

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head 7f440e24db522e635b83e16f4eccc00cd21f2a19 after the generation-fence update.

[P1] Apply the generation snapshot to the owner-side remote Lock paths too. The local service.Lock now captures getActiveTxnWithGeneration and verifies both generation and ID after acquiring the transaction mutex (service.go:483-494), which fixes the reported ABA. However, both remote handlers still call getActiveTxn(..., true, ...), wait on the pooled mutex, and validate only bytes.Equal(txn.txnID, req.Lock.TxnID) (service_remote.go:419-426 and 569-576).

The same concrete interleaving remains reachable on a physical owner: remote request R1 fetches generation N's pointer and blocks on its mutex; Unlock deletes N and returns that still-locked object to the pool; a new remote Lock with the same transaction ID reuses and initializes the object as generation N+1; then R1 acquires the mutex, the ID comparison succeeds, and the stale N request mutates N+1. Depending on ordering, old work can acquire/publish locks in the new transaction or affect its terminal result.

Use getActiveTxnWithGeneration (or an equivalent sealed admission token) in both ordinary and forwarded remote Lock handlers and reject a changed generation after locking, exactly as the local path does. Extend the deterministic forced-reuse regression through each remote handler; the current test exercises only ordinary service.Unlock/local holder access and does not close the remote mutation paths.

@iamlinjunhong iamlinjunhong left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed for exact head 7f440e24db522e635b83e16f4eccc00cd21f2a19 against merge base 53f6aa6f0bbdc59f924072e823cdcd48ff43a981.

Requesting changes for one confirmed P1 correctness/lifecycle defect.

[P1] Fence both owner-side remote Lock handlers by transaction generation.

At pkg/lockservice/service_remote.go:419-426 and pkg/lockservice/service_remote.go:569-576, handleRemoteLock and handleForwardLock fetch an activeTxn, wait for its pooled mutex, and validate only txnID. The local service.Lock path now captures getActiveTxnWithGeneration and validates both generation and ID after locking (pkg/lockservice/service.go:483-494), but that lifetime fence was not applied to these two remote mutation paths.

A concrete interleaving remains reachable: R1 obtains the generation N pointer and blocks on its mutex; Unlock closes N, deletes it from the holder, and returns the still-locked object to the pool; a new remote Lock with the same transaction ID reuses and initializes that exact pointer as generation N+1; then R1 acquires the mutex. Because the ID matches again, the current checks pass and the stale N request calls beginLockOpLocked, coarsens, and locks against N+1. Old remote work can therefore acquire or publish locks in the new transaction generation or change its terminal result.

Capture the holder-published generation under the shard barrier and reject a changed generation after taking the transaction mutex in both handlers, matching service.Lock. Extend the deterministic forced-reuse regression through ordinary remote Lock and forwarded Lock. The current TestDelayedOrdinaryUnlockDoesNotCloseReusedSameIDGeneration exercises only ordinary Unlock and local holder access, so all 26 green terminal checks do not cover these paths.

I also rechecked the complete diff covering planner fallback, owner ledger and range replacement, proxy handoff, remote cleanup, v27 compatibility, waiter cleanup, reuse-checker scopes, and Q1-Q3 termination and bounds. No additional confirmed finding remained. This P1 is independent of the current main rebase conflict reported by GitHub.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep re-review completed on exact head 7f440e2. Since my prior approval at 72ace6f, I read all historical reviews, author follow-ups and resolved thread state, compared the nine-commit range-diff, and rechecked the complete current diff. The local generation snapshot closes the reported synchronous-close ABA, but both owner-side remote mutation handlers still use an unfenced pooled transaction pointer; requesting changes for the inline P1s. Independent validation passed for the full lockservice suite normally and under race, all other affected packages normally and under race, go vet, and git diff --check. A deterministic forced-reuse counterexample proved both handlers mutate the replacement generation under -race -count=20; its temporary test was removed. Current main also has separate merge conflicts in deadlock.go and deadlock_test.go.

s.incRef(bind.Group, bind.Table)
}
txnID := append([]byte(nil), req.Lock.TxnID...)
ctx, finishLockOp := txn.beginLockOpLocked(ctx)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Capture and validate the transaction generation before admitting this remote operation

txn was fetched at line 419 with getActiveTxn, so this beginLockOpLocked can run on a recycled generation after waiting for the pooled mutex. I forced this interleaving on the exact head: an old-origin remote Lock captured generation N, concurrent Unlock deleted/reset it, the exact pointer was republished for a new-origin transaction with the same ID as N+1, and then the delayed request resumed. The txn-ID-only check passed, the RPC returned success, and the requested row appeared in N+1 ledger and physical ownership. This reproduced 20/20 under race. Capture the holder-published generation with the pointer and validate both generation and ID after txn.Lock, as the local service.Lock path now does.

s.incRef(bind.Group, bind.Table)
}
txnID := append([]byte(nil), req.Lock.TxnID...)
ctx, finishLockOp := txn.beginLockOpLocked(ctx)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Apply the same generation fence to forwarded owner operations

This handler repeats the same unfenced getActiveTxn plus txn-ID-only validation at lines 569-576. The forced-reuse counterexample through handleForwardLock also reproduced 20/20 under race: a request from the retired origin generation acquired a row in the republished same-ID generation and returned success. Please snapshot and revalidate the generation here before calling beginLockOpLocked or mutating bookkeeping.

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed exact head 3bbda1a577c3c3e8a51b4d09d4bcb4a282826a2d against merge base b89a639b0c4ac30ae143cae3b67925678d347d3b.

The previous owner-side remote ABA blocker is closed. Both handleRemoteLock and handleForwardLock now snapshot pointer plus generation under the holder publication barrier and verify generation and transaction ID after acquiring the pooled transaction mutex. The deterministic regression forces deletion, reset, reuse, and republication of the exact pointer with the same ID through both handlers, and proves the stale request returns ErrTxnNotFound without marking, locking, or deleting the replacement generation.

I re-walked the N → close/delete → pool reset → N+1 publication boundary, async lock-operation drain, service admission ownership, callback completion, and bind fencing. The rebase also moves the capability consistently to v28, leaving main's v27 ASOF protocol slot untouched, and preserves main's canonical one-victim deadlock semantics. Q1 generation ownership, Q2 callback/cancellation termination, and Q3 admission/ledger bounds are closed. No remaining blocker found. Approved.

This branch was previously deployed

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

Labels

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance] Poor throughput for JDBC / SQL INSERT INTO ... VALUES bulk writes (TPC-C load vs PostgreSQL)

6 participants