Skip to content

fix(lockservice): fence orphan txn unlocks - #25563

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
LeftHandCold:agent/lockservice-fenced-orphan-unlock-25553
Jul 10, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
LeftHandCold:agent/lockservice-fenced-orphan-unlock-25553

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jul 9, 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 #25553

refs #22115
refs #22791

What this PR does / why we need it:

This PR prevents lockservice orphan cleanup from releasing a holder while its TN Commit can still finish, and ensures every exceptional orphan unlock carries a timestamp that fences stale waiters.

Root cause

The incident follows the single-TN-shard 1PC branch and is a race between the TN Commit handler and lockservice orphan cleanup:

  1. TN receives Commit and LockTableAllocator.Valid records the transaction as committing.
  2. Commit remains in flight while CN/TN communication is abnormal.
  3. cleanCommitState fails to obtain the CN active transaction list and deletes the service's commit-control state.
  4. A waiter classifies the same holder as orphan. CannotCommit no longer sees the in-flight Commit and incorrectly reports that the holder is safe to unlock.
  5. The holder lock is released, but the original TN Commit subsequently succeeds. A waiter can execute from state that did not include that Commit, breaking hotspot-row serialization.

The previous fence-only implementation also used the raw HLC upper bound. A timestamp such as (110, 0) does not dominate (110, 7), so it was not a strict fence for all logical timestamps at the same physical time.

Fix

  1. Track the full in-flight Commit lifecycle in the allocator.
    • Every successful Valid increments a per-transaction reference count.
    • TN Commit defers exactly one FinishCommit for every successful Valid.
    • Duplicate or concurrent Commit requests remain protected until the final reference finishes.
    • Normal completed state is removed immediately and does not wait for the periodic cleaner.
  2. Make commit-state cleanup conservative.
    • Cleaner never removes an in-flight Commit.
    • Before each GetActiveTxn call, cleaner captures that service's state-generation watermark and only applies the response to states at or below that watermark.
    • Creating or refreshing cannotCommit, and a late Valid rejected by that tombstone, advances the generation so an older active-txn snapshot cannot delete it.
    • A failed active-transaction query does not erase cannotCommit tombstones.
    • Permanently disconnected services still use the existing 24-hour retention boundary, so state cannot grow forever.
  3. Return a strict allocator fence from CannotCommit.
    • The fence is (upper.PhysicalTime + 1, 0), which dominates every logical timestamp at the current upper-bound physical time.
    • Clock absence or physical overflow returns no fence and fails closed.
  4. Require both proofs before orphan unlock: the transaction is not committing and the allocator returned a non-empty fence.
    • The CN local-clock fallback is removed.
    • Waiter, timeout, stale-bind, local, and remote orphan paths all skip unlock when either proof is missing.

Scope and risk

The normal Commit path adds only allocator-local state operations; it adds no RPC and removes state as soon as the final Commit attempt returns. Normal lock acquisition, isolation semantics, lock wait timeouts, and ordinary commit/unlock are unchanged. The fix does not introduce or depend on 2PC: committing/cannotCommit are lockservice allocator arbitration states around the current 1PC Commit handler.

The deployment invariant for this hotfix is one TN shard per transaction (len(TNShards) == 1). The retained multi-TN asynchronous Commit branch is outside this PR's supported scope; this PR does not claim to fix that branch's commit-reference lifetime.

If a TN Commit itself never returns, the holder remains protected. Unlocking it would be unsafe because that Commit may still become visible; TN recovery must resolve that condition. This PR does not turn an uncertain Commit into an early unlock.

Main changes

Area Change
proto/lock.proto, generated lock protobuf Add FenceTS to CannotCommitResponse
lock_table_allocator.go Reference-count in-flight Commit, generation-aware cleaner behavior, strict HLC fence
service_cn_handler.go Pair successful Valid with deferred FinishCommit
orphan cleanup call sites Remove local timestamp fallback and fail closed without allocator proof
tests Cover duplicate Commit references, two-service stale cleaner snapshots, cleaner failures, strict HLC ordering, missing fence, and TN lifecycle pairing

Validation

  • go test ./pkg/lockservice -count=1
  • go test -race ./pkg/lockservice -run 'Test(CannotCommitWaitsForAllCommitAttempts|CleanCommitStateKeepsInflightCommit|CleanerPreservesCannotCommitOnActiveTxnQueryError|CleanerDoesNotDeleteTombstoneCreatedAfterServiceSnapshot|CannotCommitGenerationRefresh|NewFenceTS)' -count=1
  • CGo-configured go test ./pkg/txn/service -run TestCommitWithLockTables -count=1
  • go vet ./pkg/lockservice
  • CGo-configured go vet ./pkg/txn/service
  • go build ./pkg/lockservice

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

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

Reviewed the lockservice orphan-cleanup path from first principles: CannotCommit ordering, remote/local timeout cleanup, stale bind heartbeat cleanup, waiter wake-up timestamp propagation, mixed empty-FenceTS fallback, and repeated CannotCommit races.

No blocking issues found. The change is directionally correct: orphan cleanup should not unlock with an empty commit timestamp after TN has only proven cannot-commit safety. Returning an allocator HLC upper-bound as a fence, and only unlocking when CannotCommit does not report the txn as committing, closes the unsafe stale-snapshot path while keeping normal commit/unlock behavior unchanged.

I also checked the unhappy paths: CannotCommit RPC errors keep the lock; committing txns are not unlocked; the second CannotCommit check in checkTxnTimeout avoids a race where the first check becomes stale; empty FenceTS falls back to a local clock value for compatibility instead of reintroducing empty unlocks.

This PR should be viewed as the lockservice orphan-unlock fix for #25553, not as standalone proof that the full TPCC chaos scenario is solved end-to-end. The code-level coverage is solid for this layer.

Local validation passed on the PR head:

  • targeted fenced orphan/CannotCommit tests from the PR body
  • broader orphan cleanup regressions including communication interruption, service restart, bind heartbeat missing, unstable network, and ValidTxn paths

CI is green across UT, Coverage, BVT, multi-CN, upgrade, and benchmark checks.

@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 931748dd5 after the generation-aware cleanup changes.

The previous blocking stale-cleaner race is fixed correctly. The cleaner now captures a per-service generation watermark immediately before each GetActiveTxn request, and commitState creation/refresh/in-flight transitions advance the generation. Cleanup therefore only removes states that existed at or before the snapshot boundary and did not change while the RPC round was in flight. The new two-service interleaving test deterministically covers the original failure mode.

I also rechecked the surrounding state machine and unhappy paths:

  • every successful lock-table Valid in the TN Commit handler is paired with deferred FinishCommit;
  • duplicate/concurrent Commit attempts remain protected by the in-flight reference count;
  • CannotCommit cannot replace a live committing state;
  • failed active-txn queries preserve tombstones, while disconnected-service expiry remains fail-closed for newer generations;
  • generation overflow intentionally preserves state;
  • the strict fence still dominates equal-physical/higher-logical timestamps, and missing/overflowed clocks produce no fence and no orphan unlock;
  • waiter, timeout, local, remote, and stale-bind cleanup paths require both allocator proofs before unlocking.

Performance is non-blocking: the normal Commit path adds no RPC or I/O, state is removed on completion, and the extra operations are small allocator-local map/mutex operations. Valid already serialized bind validation under l.mu; the new cost is a low constant factor plus a per-service FinishCommit critical section.

Compatibility remains fail-closed in the safety-critical direction: a new CN talking to an older allocator receives an empty fence and skips exceptional unlock. An old CN does not gain the fenced behavior until it is upgraded, which is an expected rollout limitation rather than a new regression.

Local validation on the latest head:

go test ./pkg/lockservice -count=1
ok (124.063s)

go test -race ./pkg/lockservice -run generation/fence/in-flight tests -count=10
ok

go test ./pkg/txn/service -run ^TestCommitWithLockTables$ -count=10
ok

git diff --check and gofmt -l on touched Go files
clean

Approved. CI for the fresh head is still running and should remain the merge gate.

@aptend

aptend commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

I found one remaining lifecycle gap in the latest head: the new commit reference is released too early on the 2PC path.

Commit registers the attempt through Valid and defers FinishCommit, but after prepare succeeds it only schedules startAsyncCommitTask and returns. The defer therefore runs as soon as the handler returns, while the background task may not yet have executed storage.Committing, sent CommitTNShard to the other shards, or completed the coordinator storage.Commit.

A concrete interleaving is:

  1. Valid registers txn X as committing.
  2. All prepares succeed and startAsyncCommitTask is scheduled, but the task has not completed.
  3. The Commit handler returns and deferred FinishCommit removes X from allocator commit control.
  4. Orphan cleanup now receives not-committing plus a fence and releases X's CN lock.
  5. The async task subsequently makes X committed/visible.

This recreates the same unlock-before-commit-completion window that this PR is intended to close. The fence orders timestamps, but it does not make an asynchronously pending commit visible before the waiter proceeds.

Please transfer ownership of the successful Valid reference to the async commit task and call FinishCommit only when that task reaches its terminal point, while keeping exactly-once release on scheduling failure and prepare/rollback paths. A deterministic regression test can block the async commit task after startAsyncCommitTask returns and assert that AddCannotCommit continues to report X as committing until the task is released and finishes. The current TestCommitWithLockTables uses one TN shard and covers only the synchronous 1PC path.

Operational scope: this is not reachable in a deployment that strictly guarantees len(Txn.TNShards) == 1 for every transaction. However, it remains a blocker for the general upstream 2PC-supported path unless that limitation is explicitly accepted and tracked as a known gap.

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Chaos TPCC (4056142): durable consistency corruption — Payment ytd split + NewOrder duplicate o_id (1062)

6 participants