Skip to content

fix(lockservice): fence unlock after unknown commit result - #25722

Merged
XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
LeftHandCold:agent/fix-unknown-commit-unlock
Jul 15, 2026
Merged

XuPeng-SH merged 13 commits into
matrixorigin:mainfrom
LeftHandCold:agent/fix-unknown-commit-unlock

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jul 14, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #25704

Related: #25553, #22115, #22139

What this PR does / why we need it:

An ErrTxnUnknown means TN may already have accepted the Commit while CN lost the response. Releasing its pessimistic locks with an empty or synthetic timestamp can therefore allow a conflicting writer to proceed before TN has resolved the original Commit.

This PR makes unknown-result cleanup fail closed without changing the normal Commit or Rollback path:

  • The multi-request sender classifies an ambiguous Commit Stream.Send completion failure as ErrTxnUnknown; known pre-send failures and Rollback retain their existing behavior.
  • The txn operator transfers only pessimistic ErrTxnUnknown lock cleanup to lockservice. Optimistic unknown results retain their workspace/status handling but do not retain lock-resolution admission because they own no pessimistic locks.
  • The resolver keeps the source txn registered, retries bounded remote cleanup, and unlocks only after CannotCommit returns a non-empty allocator fence timestamp.
  • Resolver-owned user transactions continue consuming their existing MaxActiveTxn slots until terminal lock cleanup. Allocator outages therefore backpressure new user transactions through the existing cancellable queue.
  • Internal pessimistic Commits reserve a separate finite safety slot before workspace preparation and before Commit can be sent to TN. The limit is max(MaxActiveTxn, 1024) in production. At saturation, a new internal Commit returns the existing CN-busy error and performs full Rollback/Unlock before any Commit request is sent. Known outcomes release immediately; unknown outcomes transfer the slot to the resolver until terminal cleanup. This bounds internal resolver pending entries, active holders, retained locks, and retry work without putting normal user transactions on the internal quota.
  • Every new Commit carries an absolute deadline and a source-lockservice-local monotonic sequence. TN applies its configured HLC max-offset before treating this CN-derived deadline as expired. Unknown-result fences preserve each (sequence, expiry) pair while the frontier is below 1024 entries. At saturation, they collapse to one conservative per-source fence using the maximum sequence and latest expiry.
  • Proxy holder handoff is published locally only after owner acknowledgement. A response-lost handoff records its replacement as pending, and retries preserve that representative even if later local shared holders join.
  • The owner holder map migrates its key together with the replacement value, so the replacement is recognized as holder for subsequent Unlock.

This is not a transaction 2PC change. Normal user Commit, known terminal errors, Rollback, and optimistic lock cleanup do not enter the resolver or add lockservice RPCs.

Validation:

  • GOFLAGS='-mod=mod' go test ./pkg/lockservice -count=1
  • GOFLAGS='-mod=mod' go test ./pkg/txn/client -count=1
  • GOFLAGS='-mod=mod' go test ./pkg/txn/rpc ./pkg/frontend/test/mock_lock -count=1
  • GOFLAGS='-mod=mod' go test -race ./pkg/txn/client -run 'Test(OptimisticCommitUnknownReleasesAdmission|CommitUnknownScheduleFailureReleasesAdmission|InternalCommitUnknownAdmissionIsBounded|CommitUnknownRetainsAdmissionUntilResolution|CommitUnknownResolvedBeforeCloseReleasesAdmissionOnce)$' -count=20
  • GOFLAGS='-mod=mod' go test -race ./pkg/lockservice -run 'TestResolveCommitUnknownWaitsForAllocatorFence$' -count=1
  • GOFLAGS='-mod=mod' go test ./pkg/lockservice -run 'TestResolveCommitUnknown(WaitsForAllocatorFence|CompletesWhenTxnAlreadyUnlocked)$' -count=1
  • git diff --check

go test ./pkg/txn/service -run '^TestCommitRequestExpired$' -count=1 is blocked locally before package compilation because this host lacks the repository CGo dependencies (usearch.h, roaring.h, and xxhash.h).

@mergify mergify Bot added kind/bug Something isn't working kind/test-ci labels Jul 14, 2026
@LeftHandCold
LeftHandCold marked this pull request as ready for review July 14, 2026 11:01
@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 →

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Blocking correctness review on the latest head. The allocator-side Valid/FinishCommit serialization and the fail-closed retry behavior are sound, and all existing ordinary/race suites pass. However, three P1 gaps remain across the transport/fence/cleanup boundaries. Two deterministic scratch regressions fail on this head: a post-flush Commit send error is returned as raw EOF, and a CannotCommit tombstone is removed by the live-service cleaner before a delayed Commit arrives. The resolver also places a non-cancelable remote unlock loop inside a stopper-owned task.

GitHub does not allow the PR author account to submit Request changes on its own PR, so this COMMENT review records the blocking verdict.

Comment thread pkg/txn/rpc/sender.go Resolved
Comment thread pkg/lockservice/unknown_commit.go Resolved
Comment thread pkg/lockservice/unknown_commit.go Resolved

@XuPeng-SH XuPeng-SH 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.

Requesting changes on the current head 71b86ff.

[P1] Bound resolver-owned state while the CannotCommit allocator is unreachable.

The new 1024-entry frontier collapse fixes the case where the allocator is reachable, but there is still no end-to-end bound before any fence can be installed. When notifyCannotCommit returns a connection error, resolvePending keeps every entry in unknownCommitResolver.pending and unlockUnknownCommit is never reached. The corresponding source-local entries remain in activeTxnHolder with their locks, and local timeout cleanup depends on the same unavailable CannotCommit RPC.

I reproduced this deterministically by making the lockservice remote client return an immediate connection error and passing 2,048 distinct active transactions through ResolveCommitUnknown. After failed resolution attempts, pending contained all 2,048 entries and activeTxnHolder contained all 2,048 entries. The growth is linear; there is no capacity or expiry on either map. The txn client does not provide the missing bound because ClosedEvent removes the operator and decrements the user count immediately, so new user transactions can continue to enter while these resolver-owned transactions remain.

Under a sustained response-path failure or partition, this grows retained locks, active transaction state, retry scan work, and memory without a bound. Dropping entries is not safe because the fail-closed invariant requires retaining them. Please add explicit admission/backpressure that continues to count resolver-owned unknown transactions until cleanup reaches a terminal state, and add an outage regression that proves the retained state reaches a finite limit, new admission is blocked or rejected at that limit, and capacity is restored after allocator recovery.

I also rechecked the previously reported proxy handoff, holder-key migration, sequence/expiry frontier, clock-offset, shutdown cancellation, and frontier-overflow paths. Those are fixed on this head. Focused proxy and overflow tests passed 20x, focused race tests passed 5x, the full lockservice package passed, and txn client/rpc, TN deadline, and vet checks passed. I found no second blocker.

@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.

Blocking review on head 26acdfe after tracing the complete Commit transport, txn-client admission, resolver, allocator-fence, and lock-owner cleanup lifecycles. Two P1 issues remain:

  1. Optimistic unknown Commits permanently consume MaxActiveTxn slots.

operator.doWrite sets commitNeedsResolution for ErrTxnUnknown in every transaction mode. However, unknown resolution is scheduled only from the pessimistic unlock path because needUnlockLocked returns false for optimistic transactions. txnClient.closeTxn nevertheless retains the user admission slot whenever commitNeedsResolution is true. Therefore an optimistic unknown Commit removes the operator from activeTxns but leaves users incremented forever, with no resolver callback capable of releasing it. After MaxActiveTxn such response losses, every new user transaction remains in the wait queue.

I reproduced this deterministically under -race with MaxActiveTxn=1: after one optimistic unknown Commit the state is users=1, active=0, the resolver was never called, and the next user New call times out.

Please separate unknown-result workspace/status handling from lock-resolution admission retention. Retain the slot only when pessimistic cleanup has actually been transferred to the resolver, and add an optimistic MaxActiveTxn=1 regression.

  1. Resolver-owned internal transactions remain unbounded while the allocator is unreachable.

The new backpressure only counts UserTxn transactions. Internal SQL executor transactions are created without WithUserTxn and therefore bypass MaxActiveTxn, but pessimistic internal transactions with unknown Commit results still enter unknownCommitResolver.pending and retain activeTxn state, locks, and retry work. When CannotCommit cannot reach the allocator, resolvePending keeps every entry, and source-local active transactions have no remote-service timeout cleanup. New internal transactions can continue to be created, so after N ambiguous Commits the retained state grows linearly to N and can eventually OOM the CN.

Please add an end-to-end finite quota/admission mechanism for all resolver-owned transactions, including internal ones. The outage regression should prove that pending entries, active transactions, retained locks, and retry work stay bounded, that new admission blocks or fails safely at the bound, and that capacity is restored after allocator recovery.

The full lockservice, txn/client, and txn/rpc package tests pass, as do the focused race suites. The latest proxy handoff convergence and allocator frontier-collapse paths also check out; these two admission/boundedness gaps are the remaining blockers.

Comment thread pkg/txn/client/client.go Resolved

@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.

Re-reviewed the latest update at 6b27409. The two previously reported admission-control issues are resolved, and the affected tests, focused race tests, and static checks pass. No remaining blocking findings.

@XuPeng-SH XuPeng-SH 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.

Requesting changes on current head 6b2740945fcc1ccc82d1b74c82893bdcd5bedfac.

[P1] Block local shared admission while a last-holder handoff is unacknowledged.

The pending-representative logic only records pendingRemoteHolders[row] when ReplaceTo is non-empty. That leaves an unsafe state for the last proxy holder:

  1. S2 has one proxied shared holder U; S1 owns the actual shared lock for U.
  2. S1 applies the empty-ReplaceTo Unlock and removes U, but the response is lost. S2 correctly retains U in currentHolder, but line 225 records no pending state because the replacement is empty.
  3. An owner-local transaction X acquires an exclusive lock on S1.
  4. A late shared transaction L arrives on S2. hasRemoteHolderLocked still sees U, so the proxy fast path grants L locally without contacting S1.

At that point X holds the owner-side exclusive lock while L simultaneously owns a proxy-side shared lock. I reproduced this with a deterministic two-service regression 10/10 times: the exclusive acquisition succeeds first, then the late shared acquisition incorrectly returns nil.

The existing TestProxyUnlockRetryIgnoresNewOwnerAfterLostLastHolderResponse covers the empty-replacement/new-owner half, while TestProxyRetryPreservesAppliedHandoffRepresentative covers late sharers only when there is a non-empty pending replacement. The missing Cartesian combination is exactly the unsafe case above.

Please represent an unacknowledged last-holder removal explicitly; an empty replacement cannot also mean that no handoff is pending. While that state is unresolved, new local shared transactions must not use the local fast path: they need to wait for convergence or acquire at the owner. Add a regression that proves the owner-exclusive and proxy-shared states cannot coexist across this schedule.

Please make that regression deterministic through observable holder/waiter state. Avoid using a short Never window as the proof. I observed TestProxyRetryPreservesAppliedHandoffRepresentative hit its whole-test 5-second context once under concurrent loaded verification, although it passed 20 isolated repetitions, so the terminal timeout should be a slow-CI guard rather than the synchronization mechanism.

Audit notes: the latest user/internal admission fixes now release exactly once on normal, error, inline-resolution, and schedule-failure paths; resolver pending and allocator frontier state are bounded; remote unknown cleanup is cancelable on shutdown; and TN admission/deadline/sequence fencing is closed. I found no second product blocker.

Verification on this head:

  • affected full packages passed: ./pkg/lockservice ./pkg/txn/client ./pkg/txn/rpc ./pkg/txn/service
  • focused resolver/proxy/admission tests passed under -race
  • go vet passed for all four packages
  • git diff --check passed
  • a virtual merge with current origin/main completed without conflicts

@XuPeng-SH XuPeng-SH 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 the latest head 160ccfe7ca, focusing on the new last-holder handoff fence. The added pendingLastHolderUnlocks state closes the stale-local-sharer window I flagged on 6b2740945f: while the proxy is still retrying an already-applied empty-ReplaceTo unlock, new sharers are routed through the owner instead of attaching to the stale local representative, and the retry preserves that empty replacement until the owner acknowledges it. The new regression covers the exclusivity case, and I also exercised a focused local repro to confirm the late sharer can still unlock cleanly after the handoff converges. I do not see a remaining high-confidence correctness, performance, or unhappy-path blocker in the latest delta.

@mergify

mergify Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-15 10:46 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-07-15 10:59 UTC · at 9ce2587c6ea9a1e3133de0fda0b09d0475a9c958

This pull request spent 12 minutes 14 seconds in the queue, with no time running CI.

Reason

The pull request can't be updated

This pull request seems to come from a fork, and Mergify needs the author's permission to update its branch.
The author needs to enable "Allow edits from maintainers" on this pull request, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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

kind/bug Something isn't working kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Chaos (2865ed6): TPCC New-Order 1062 Duplicate entry on bmsql_oorder after DN network chaos + 20638 unknown commit

5 participants