Skip to content

fix(lockservice): converge stale remote lock binds after CN replacement - #28343

Merged
XuPeng-SH merged 4 commits into
mainfrom
fix/27707-stale-lock-keeper-convergence
Sep 7, 2026
Merged

XuPeng-SH merged 4 commits into
mainfrom
fix/27707-stale-lock-keeper-convergence

Conversation

@aptend

@aptend aptend commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #27707

What this PR does / why we need it:

PR #28115 stopped a missing LockService owner from crashing a replacement CN and fenced transactions that depended on the departed exact bind. However, transaction-owned remoteBindRefs intentionally remain until transaction cleanup, and the keeper still treated those retained references as heartbeat-eligible. A fenced transaction could therefore keep the departed generation in every keeper round, matching the latest stability report of continuous failed to keep remote locks after all replacement CNs were Ready.

This follow-up separates reference lifetime from keeper eligibility:

  • invalidates an unusable exact remote-bind generation while retaining its ref-counted tombstone until normal transaction cleanup, preserving the cleanup ownership and ABA protection introduced by fix(lockservice): recover from departed lock owners #28115;
  • excludes invalidated generations from future keeper rounds without affecting a replacement generation for the same table;
  • rejects new transaction admission to an invalidated exact tombstone before the remote Lock RPC, while allowing the same bind to be admitted again after the old owners finish cleanup;
  • treats owner-side ErrLockTableBindChanged, ErrLockTableNotFound, and NewBind as authoritative rejection of the exact generation, even when the allocator temporarily returns the same stale bind;
  • rejects a request routed to a replacement CN with a different UUID using ErrLockTableBindChanged instead of terminating the replacement CN;
  • covers missing/changed owners, stale allocator responses, already-published replacement generations, invalidated-tombstone admission, delayed cleanup, transient owner-side allocator failure, and same-endpoint replacement routing.

There is no wire-format or public API change.

Validation on the current head:

  • focused keeper, replacement-CN, invalidated-admission, and transient-NotFound regressions passed;
  • the two review counterexamples passed with -race -count=100;
  • full pkg/lockservice passed with -short in normal mode (87.132s) and race mode (90.880s);
  • make dev-build passed;
  • make static-check-analysis GOLANGCI_LINT_CONCURRENCY=4 passed with 0 issues;
  • git diff --check passed.

The original convergence path was also validated with a real local two-CN reproduction using the built image: an active transaction on CN1 held a lock whose owner was CN2, then CN2 was replaced at the same endpoint with a new UUID. There was no fatal log or restart. Transient keeper/rejection counters stopped changing during an additional 20-second steady-state window; the replacement CN remained running, the uncommitted value was not exposed, and rollback preserved the original committed value.

@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 exact head b9910a4f38a236fba6ef76abb579e32298b62a22. Separating reference lifetime from heartbeat eligibility is useful, and rejecting a stale routed request instead of terminating the replacement CN is appropriate. One admission/lifecycle gap remains.

[P1] Do not admit new transactions onto an invalidated, non-heartbeating exact bind

service.go:1473-1480 (acquireRemoteBindRefLocked) increments an existing ref even when ref.invalidated is true. The Lock admission path at service.go:525-564 checks the transaction's fence and current route, but never checks that tombstone. Meanwhile the new collectRemoteLockBinds unconditionally omits the entire invalidated key.

Trigger sequence:

  1. Transaction A acquires a ref for exact bind B (refs are acquired before the remote Lock RPC), and keeper invalidation fences A while retaining B's tombstone until A cleans up.
  2. Allocator refresh still returns B, a state explicitly covered by this PR. A subsequent lookup can republish B into the route cache.
  3. A new transaction C passes the current-route check and increments B's existing tombstone. Its own bindChanged is false: it was created after the fence pass.
  4. If the owner accepts C's Lock, C's dependency is nevertheless excluded from every keeper round while A keeps the tombstone alive. C can then lose owner-side lease liveness despite otherwise healthy connectivity.

It is not safe to assume every rejection makes B permanently unusable: getLocalLockTableWithContext maps non-context allocator failures while creating a missing local table to ErrLockTableNotFound. That failure can recover with the same allocator bind/version. In particular, a pre-RPC source intent may be heartbeated before the owner has instantiated its table; an allocator failure during that lookup is transient, not proof that a later Lock cannot succeed. The new invalidation now also persists when refresh succeeds with that same bind.

Please couple tombstone state to admission under the existing bind-change/ref locking discipline. Fail closed before remote Lock on an invalidated generation (with the normal retry/fencing error), or implement an explicit safe reactivation protocol that distinguishes new lease ownership from old cleanup references. Do not simply clear invalidated on ref increment: that would resume the stale A heartbeat this PR is trying to stop.

Add a regression that retains A's invalidated ref, republishes the same exact allocator bind, then attempts a fresh transaction C. Assert that C is rejected before RPC or has a correctly maintained independently valid lease; after releasing A, verify recovery. Include the transient owner-side allocator-error/NotFound case and a delayed A cleanup so an old release cannot decrement a new generation's ownership.

Other checks: changed-generation fencing remains owner/group/table scoped; keeper refresh does not publish a late response directly; the replacement-CN path returns the existing error without a wire change; tests cover old-generation quiescence, replacement generation and cleanup refcounts. Those tests do not exercise new admission to the same invalidated exact key. Evidence for the finding is the exact-head admission/ref/keeper/owner-handler source path; I did not claim a fresh native reproduction, race run, or production data-corruption observation. The concrete risk is admitting an active dependency with no lease renewal, not merely missing tests.

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

Reviewed exact head b9910a4f38a236fba6ef76abb579e32298b62a22.

[P1] Do not admit a new transaction through an invalidated remote-bind tombstone

pkg/lockservice/service.go:1473-1480 increments an existing exact remoteBindRef without checking or changing ref.invalidated. The same PR makes collectRemoteLockBinds permanently omit that ref at service.go:1526-1535. The Lock admission path holds bindChangeMu and validates only the route and transaction state before calling acquireTxnBindRef (service.go:525-565); it does not reject an invalidated exact key.

Trigger: transaction A holds exact remote bind B. A KeepRemoteLock rejection (including ErrLockTableNotFound) causes maybeHandleRemoteBindChanged to invalidate B even when allocator refresh returns the unchanged B (lock_table_keeper.go:467-509). The route is detached, but A retains B tombstone for delayed cleanup. If allocator later republishes B and a new transaction C locks through it, C increments A tombstone and can successfully issue its remote Lock. Every subsequent keeper round skips B, however, so C has no owner-side lease renewal while A remains open. This can make a healthy, newly admitted remote lock lose liveness when the owner expires its remote-bind lease.

Please fail closed at admission for an invalidated generation, or create a separately safe lease-generation/reactivation protocol; simply clearing invalidated during C admission would resume A stale heartbeat. Add a regression that keeps A cleanup delayed, republishes the same exact B, and verifies C is rejected before the RPC or receives an independently heartbeated lease. It should cover the transient owner-side allocator-error/NotFound path, then verify cleanup cannot decrement new ownership.

@aptend

aptend commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed both P1 reviews in 4e687e33ac.

The common transaction-bind admission boundary now fails closed with ErrLockTableBindChanged when the exact remoteBindRef is an invalidated tombstone. The check and first intent/ref publication are coupled under the existing bindChangeMu / transaction / service-ref locking discipline, so failed admission creates neither cleanup ownership nor a remote Lock RPC. The tombstone is not reactivated: old transactions remain its only owners until the last cleanup deletes it, after which the same exact allocator bind can establish a fresh heartbeat-eligible ref.

Regression coverage now verifies:

  • A remains open with an invalidated B tombstone, allocator republishes the same B, and new transaction C is rejected before RPC without increasing B's refcount.
  • Delayed A cleanup removes the tombstone; C can then retry successfully and B is included in keeper heartbeats.
  • Owner-side allocator failure can transiently surface as ErrLockTableNotFound, and the same bind succeeds once the allocator recovers, so NotFound is not treated as proof that the generation can never recover.

Current-head validation: focused regressions passed; both new counterexamples passed with -race -count=100; full pkg/lockservice passed with -short in normal and race modes; make dev-build passed; make static-check-analysis GOLANGCI_LINT_CONCURRENCY=4 completed with 0 issues; git diff --check passed.

@XuPeng-SH
XuPeng-SH merged commit e201dc5 into main Sep 7, 2026
22 of 25 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/27707-stale-lock-keeper-convergence branch September 7, 2026 17:18
mergify Bot pushed a commit that referenced this pull request Sep 7, 2026
### Root cause

Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent.

The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order.

### Changes

- Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts.
- Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution.
- Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction.
- Preserve existing explicit user-transaction validation and ownership semantics.
- Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests.
- Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions.

### Issue-to-test proof

`TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers:

- database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs;
- DIFF while an unrelated database DROP runs;
- PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate;
- completion, result correctness, and unrelated-drop visibility after every interleaving.

The exact external regression set from #26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs.

### Validation

- rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged
- focused frontend admission and retry tests, including rollback/begin/gate error propagation
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3`
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1`
- full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed
- full `./pkg/frontend`
- full `./pkg/tests/issues`
- exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL`
- `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment
- `make build`
- exact ten-case MOTR command from #26404 with `--repeat 20 -j 9`
- `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored
- `git diff --check`

After upstream #28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream #28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed.

The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers.

Workflow run 34125753066 exposed one stale assertion in the existing #27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated #28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved #28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers.

After rebasing onto upstream #28343's remote-bind convergence change and #28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN #26404 regression and the adjacent #27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with #28356's executor-owned temporary ALTER COPY transaction fix, which resolved #28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing.

Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only #28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed.

### Residual risk

The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload.

Approved by: @XuPeng-SH
XuPeng-SH pushed a commit that referenced this pull request Sep 10, 2026
…#28474)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #27707

Keep the issue open until the complete fixed image passes the field
acceptance gate below; merging this PR alone is not the closure
criterion.

## What this PR does / why we need it:

This follow-up closes two recovery gaps left after #28115 and #28343,
without weakening their transaction fences:

- **DN departed-owner recovery:** check the local raw CN inventory
before GetActiveTxn. If no endpoint exists, retain
admission/cannot-commit fences but skip futile RPCs, backend resets and
repeated missing-owner errors. Recheck membership every normal sweep,
including pending-admission CNs.
- **Safe eventual expiry:** preserve the first disconnect timestamp
rather than extending the 24-hour retention on each failure. Cleanup
validates ctl identity, recovery epoch, transaction watermark and
inactive timestamp against Resume, fresh state and replacement ctl.
In-flight Commit and persistent unknown-Commit fences keep their
independent lifetime protection.
- **CN route recovery:** a stale allocator reply can republish an
invalidated exact bind after keeper detachment. New requests then reject
before reaching the RPC refresh path, while the keeper correctly skips
the invalidated ref. Rejection now detaches only that exact cached
route, allowing subsequent discovery to fetch the converged bind. Lock,
ForwardLock and RemoteLock-on-Shared-proxy use the same helper.
- **Preserved ownership:** old transactions remain fenced; invalidated
refs remain until their consumers release them. The helper pins ref
lifetime through constant-time route detachment, preserves
newer/metadata-distinct routes and same-key valid reacquisition, and
closes outside mutation locks.

No wire/API/storage-format change, new retry layer/background worker,
pressure-policy change or configuration-default change.

Validation:

- Deterministic expiry/Resume/Commit/ctl-replacement and
missing-membership counterexamples; negative controls fail on unfixed
behavior.
- Actual Lock and forwarded/proxied handler rejection; cancellation, new
route/allocator/routing metadata, ref release/reacquisition, and close
ownership controls.
- Individual adaptive race stress, including 100 repetitions for the
route and membership recovery tests.
- Delivery integrates main `f0c31cd4b8` at `56fe252fd7`; CI checks out
the PR head, so the current dependency graph is tested explicitly. PR
head `07a73ab3e7` differs from the tested revision only in the evidence
document.
- Integrated owning package: `-short -count=1` passed (86.463s); `-short
-race -count=1` passed (91.534s). All ten exact route/membership/expiry
race tests were remeasured and repeated individually (nine at 100
repetitions, persistent-disconnect expiry at 47); all passed.
- `make build`, `make err-check`, and repository-configured
owning-package golangci passed (0 lint issues).
- Full-repository `make static-check-analysis
GOLANGCI_LINT_CONCURRENCY=2` passed (exit 0): err-check, all-package
molint and all-package golangci; golangci reported 0 issues under
unchanged repository rules/exclusions (11m21s).
- Additional repository license-header check passed (exit 0): 5,264
files checked, 0 invalid, 0 modified.
- Integrated real LogService + DN + two CN processes
(`dn-expiry-compare-vrbvaws6`, exit 0), two sequential CN replacements:
both 65-second windows completed 33 SQL commits. Departed-owner DN error
counters stayed `[6] -> [6]` and `[6,6] -> [6,6]`; the second transition
had one transient 20702, then progress. Old uncommitted values stayed
invisible, both DN fences remained, and the original locked row could be
rewritten/committed and read from the other CN. All test-owned processes
exited, with no CN fatal/panic. Binary SHA-256:
`0d65214a27aafbfd5cc0d574b71ecdbde0ba7f9539ec82bae92986b9f256f4c8`.

Limits are explicit: the real test keeps default 24-hour DN retention
and 20-second cleaner cadence but uses a 10-second CN remote-lock lease.
It is not a default-10-minute-lease test, a 24-hour soak or a field
15-minute acceptance run. The non-short `TestIssue3288` deadline also
fails at the clean investigation baseline; no assertion was weakened.
Owning-package molint diagnostics match the clean baseline. Full
evidence and the closure checklist are in
`docs/design/evidence/27707_dn_inactive_expiry.md`.

Field acceptance before issue closure: use an immutable image containing
the complete fix, replace both CNs with active remote-lock transactions,
verify completed rollout/SQL and original-row recovery/data safety, and
keep each departed owner's error counters flat for at least 15 minutes
after membership convergence. This PR intentionally does not auto-close
the issue.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH pushed a commit that referenced this pull request Sep 15, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #27291
issue #27293

## What this PR does / why we need it:

This is a focused backport of the merged upstream #27296 fix to
`4.2-dev`.

A stale empty row/range lock can reach `tryHold`. The old `4.2-dev` path
panics (`BUG: try hold on empty lock`) and can leave the following
admission blocked. This backport:

- returns `errEmptyLock` instead of panicking;
- removes or repairs stale row/range endpoints before retry;
- preserves structural range pairing and merge/restart behavior;
- adds direct lockservice regression coverage.

It also closes the empty-endpoint lifecycle hole in the batch cleanup
path. `closeRangeWaiterLocked` can snapshot multiple empty endpoints
before deleting them; `deleteEmptyLockLocked` re-reads the current store
entry and verifies the value, creation timestamp, and backing
holders/waiter identity before dereferencing or releasing state.

The current formal P1 repair closes the remaining Start-first orphan
sequence. For a live `[1,10]` plus orphan `End(5)` and `Start(7)`,
structural cleanup now crosses an unmatched orphan end and rejects a
candidate `End` that already has an earlier matching `Start`. This
prevents either cleanup order from copying the live pooled state into an
orphan key. The regression uses real `service.Lock([1,10])`, both
Start-first and End-first cleanup orders, real owner `Unlock`,
returned-state traps, and an empty-store assertion.

The companion remote-bind lifecycle fixes #28115 and #28343 are
intentionally not included. They address departed-owner/CN-replacement
fencing, require an adapted ordered backport, and were not established
as the cause of this incident. They should be reviewed separately.

QA required: yes. This changes distributed LockService/CN failure and
cleanup behavior; after merge it requires dev two-CN validation of the
original panic path and post-cleanup admission.

## Validation

- Exact tested base: `matrixorigin/matrixone:4.2-dev` at
`b122da6dc20985cbfcb2fcc642ae6729d70d8516`.
- Current backport head: `babbdc7bdf0bedec18822a3f774fc48f21644e94`.
- Exact committed base-to-head diff SHA-256:
`4196ac635372fa22eec6a7bab304d1cc43b239a569e82f4e869b12981e79df6a`.
- Schema-v7 semantic preflight: PASS; exact-content hash
`a58df1faf1c94c16a9151454c6cf2caa8174bd19b3f16c6af184ab2fb032de82`.
- Red/green P1 proof: the new Start-first regression failed on the prior
exact head `551700dfad0ecf97d9f6acd2e4f66d6e5f74eb29` because the orphan
endpoint remained; the repaired head passes.
- Focused LockService structural/cleanup set, including both cleanup
orders, enclosing/multiple/mixed orphan endpoints, mismatched repair,
stale batch snapshots, merge restart, waiter-reference clearing, and
interleaved range locks: PASS.
- New regression after exact-base rebase: normal PASS; focused `-race
-count=100` PASS with 100 pass records and no race report.
- Full `./pkg/lockservice` normal: PASS (`111.826s`). Full
`./pkg/lockservice` `-race`: PASS (`115.861s`).
- `go list -mod=readonly ./pkg/lockservice ./pkg/sql/colexec/lockop`:
PASS.
- `gofmt` and `git diff --check`: PASS.
- `mo-cgo-test` clean-worktree wrapper: `BLOCKED_ENVIRONMENT` because
this candidate worktree lacks `thirdparties/install`. Controlled direct
CGo execution with explicit native paths passed the lockservice
normal/race tests. `go build`/`go vet` for lockservice+lockop remain
environment-blocked in `pkg/common/docfilter` by unavailable
`C.mo_cbitmap_*`/`C.mo_croaring_*` bindings; no build/vet PASS is
claimed.
- BVT: N/A for this internal LockService/CN lifecycle fix; there is no
SQL result contract reachable through BVT. The equivalent package
regression is provided, and the required post-merge two-CN SQL/admission
QA is called out above.
- New-head required GitHub checks are running after this update; prior
green checks belonged to an older head and are not reused as current
evidence.

The PR does not modify GitOps/Kubernetes or deploy to dev. Full dev
rollout and SQL validation remain post-merge QA gates.

---------

Co-authored-by: davis zhen <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…nt (matrixorigin#28343)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

## What this PR does / why we need it:

PR matrixorigin#28115 stopped a missing LockService owner from crashing a
replacement CN and fenced transactions that depended on the departed
exact bind. However, transaction-owned `remoteBindRefs` intentionally
remain until transaction cleanup, and the keeper still treated those
retained references as heartbeat-eligible. A fenced transaction could
therefore keep the departed generation in every keeper round, matching
the latest stability report of continuous `failed to keep remote locks`
after all replacement CNs were Ready.

This follow-up separates reference lifetime from keeper eligibility:

- invalidates an unusable exact remote-bind generation while retaining
its ref-counted tombstone until normal transaction cleanup, preserving
the cleanup ownership and ABA protection introduced by matrixorigin#28115;
- excludes invalidated generations from future keeper rounds without
affecting a replacement generation for the same table;
- rejects new transaction admission to an invalidated exact tombstone
before the remote Lock RPC, while allowing the same bind to be admitted
again after the old owners finish cleanup;
- treats owner-side `ErrLockTableBindChanged`, `ErrLockTableNotFound`,
and `NewBind` as authoritative rejection of the exact generation, even
when the allocator temporarily returns the same stale bind;
- rejects a request routed to a replacement CN with a different UUID
using `ErrLockTableBindChanged` instead of terminating the replacement
CN;
- covers missing/changed owners, stale allocator responses,
already-published replacement generations, invalidated-tombstone
admission, delayed cleanup, transient owner-side allocator failure, and
same-endpoint replacement routing.

There is no wire-format or public API change.

Validation on the current head:

- focused keeper, replacement-CN, invalidated-admission, and
transient-NotFound regressions passed;
- the two review counterexamples passed with `-race -count=100`;
- full `pkg/lockservice` passed with `-short` in normal mode (87.132s)
and race mode (90.880s);
- `make dev-build` passed;
- `make static-check-analysis GOLANGCI_LINT_CONCURRENCY=4` passed with 0
issues;
- `git diff --check` passed.

The original convergence path was also validated with a real local
two-CN reproduction using the built image: an active transaction on CN1
held a lock whose owner was CN2, then CN2 was replaced at the same
endpoint with a new UUID. There was no fatal log or restart. Transient
keeper/rejection counters stopped changing during an additional
20-second steady-state window; the replacement CN remained running, the
uncommitted value was not exposed, and rollback preserved the original
committed value.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…28325)

### Root cause

Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent.

The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order.

### Changes

- Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts.
- Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution.
- Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction.
- Preserve existing explicit user-transaction validation and ownership semantics.
- Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests.
- Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions.

### Issue-to-test proof

`TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers:

- database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs;
- DIFF while an unrelated database DROP runs;
- PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate;
- completion, result correctness, and unrelated-drop visibility after every interleaving.

The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs.

### Validation

- rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged
- focused frontend admission and retry tests, including rollback/begin/gate error propagation
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3`
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1`
- full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed
- full `./pkg/frontend`
- full `./pkg/tests/issues`
- exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL`
- `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment
- `make build`
- exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9`
- `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored
- `git diff --check`

After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed.

The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers.

Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers.

After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing.

Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed.

### Residual risk

The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28474)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

Keep the issue open until the complete fixed image passes the field
acceptance gate below; merging this PR alone is not the closure
criterion.

## What this PR does / why we need it:

This follow-up closes two recovery gaps left after matrixorigin#28115 and matrixorigin#28343,
without weakening their transaction fences:

- **DN departed-owner recovery:** check the local raw CN inventory
before GetActiveTxn. If no endpoint exists, retain
admission/cannot-commit fences but skip futile RPCs, backend resets and
repeated missing-owner errors. Recheck membership every normal sweep,
including pending-admission CNs.
- **Safe eventual expiry:** preserve the first disconnect timestamp
rather than extending the 24-hour retention on each failure. Cleanup
validates ctl identity, recovery epoch, transaction watermark and
inactive timestamp against Resume, fresh state and replacement ctl.
In-flight Commit and persistent unknown-Commit fences keep their
independent lifetime protection.
- **CN route recovery:** a stale allocator reply can republish an
invalidated exact bind after keeper detachment. New requests then reject
before reaching the RPC refresh path, while the keeper correctly skips
the invalidated ref. Rejection now detaches only that exact cached
route, allowing subsequent discovery to fetch the converged bind. Lock,
ForwardLock and RemoteLock-on-Shared-proxy use the same helper.
- **Preserved ownership:** old transactions remain fenced; invalidated
refs remain until their consumers release them. The helper pins ref
lifetime through constant-time route detachment, preserves
newer/metadata-distinct routes and same-key valid reacquisition, and
closes outside mutation locks.

No wire/API/storage-format change, new retry layer/background worker,
pressure-policy change or configuration-default change.

Validation:

- Deterministic expiry/Resume/Commit/ctl-replacement and
missing-membership counterexamples; negative controls fail on unfixed
behavior.
- Actual Lock and forwarded/proxied handler rejection; cancellation, new
route/allocator/routing metadata, ref release/reacquisition, and close
ownership controls.
- Individual adaptive race stress, including 100 repetitions for the
route and membership recovery tests.
- Delivery integrates main `f0c31cd4b8` at `56fe252fd7`; CI checks out
the PR head, so the current dependency graph is tested explicitly. PR
head `07a73ab3e7` differs from the tested revision only in the evidence
document.
- Integrated owning package: `-short -count=1` passed (86.463s); `-short
-race -count=1` passed (91.534s). All ten exact route/membership/expiry
race tests were remeasured and repeated individually (nine at 100
repetitions, persistent-disconnect expiry at 47); all passed.
- `make build`, `make err-check`, and repository-configured
owning-package golangci passed (0 lint issues).
- Full-repository `make static-check-analysis
GOLANGCI_LINT_CONCURRENCY=2` passed (exit 0): err-check, all-package
molint and all-package golangci; golangci reported 0 issues under
unchanged repository rules/exclusions (11m21s).
- Additional repository license-header check passed (exit 0): 5,264
files checked, 0 invalid, 0 modified.
- Integrated real LogService + DN + two CN processes
(`dn-expiry-compare-vrbvaws6`, exit 0), two sequential CN replacements:
both 65-second windows completed 33 SQL commits. Departed-owner DN error
counters stayed `[6] -> [6]` and `[6,6] -> [6,6]`; the second transition
had one transient 20702, then progress. Old uncommitted values stayed
invisible, both DN fences remained, and the original locked row could be
rewritten/committed and read from the other CN. All test-owned processes
exited, with no CN fatal/panic. Binary SHA-256:
`0d65214a27aafbfd5cc0d574b71ecdbde0ba7f9539ec82bae92986b9f256f4c8`.

Limits are explicit: the real test keeps default 24-hour DN retention
and 20-second cleaner cadence but uses a 10-second CN remote-lock lease.
It is not a default-10-minute-lease test, a 24-hour soak or a field
15-minute acceptance run. The non-short `TestIssue3288` deadline also
fails at the clean investigation baseline; no assertion was weakened.
Owning-package molint diagnostics match the clean baseline. Full
evidence and the closure checklist are in
`docs/design/evidence/27707_dn_inactive_expiry.md`.

Field acceptance before issue closure: use an immutable image containing
the complete fix, replace both CNs with active remote-lock transactions,
verify completed rollout/SQL and original-row recovery/data safety, and
keep each departed owner's error counters flat for at least 15 minutes
after membership convergence. This PR intentionally does not auto-close
the issue.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…nt (matrixorigin#28343)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

## What this PR does / why we need it:

PR matrixorigin#28115 stopped a missing LockService owner from crashing a
replacement CN and fenced transactions that depended on the departed
exact bind. However, transaction-owned `remoteBindRefs` intentionally
remain until transaction cleanup, and the keeper still treated those
retained references as heartbeat-eligible. A fenced transaction could
therefore keep the departed generation in every keeper round, matching
the latest stability report of continuous `failed to keep remote locks`
after all replacement CNs were Ready.

This follow-up separates reference lifetime from keeper eligibility:

- invalidates an unusable exact remote-bind generation while retaining
its ref-counted tombstone until normal transaction cleanup, preserving
the cleanup ownership and ABA protection introduced by matrixorigin#28115;
- excludes invalidated generations from future keeper rounds without
affecting a replacement generation for the same table;
- rejects new transaction admission to an invalidated exact tombstone
before the remote Lock RPC, while allowing the same bind to be admitted
again after the old owners finish cleanup;
- treats owner-side `ErrLockTableBindChanged`, `ErrLockTableNotFound`,
and `NewBind` as authoritative rejection of the exact generation, even
when the allocator temporarily returns the same stale bind;
- rejects a request routed to a replacement CN with a different UUID
using `ErrLockTableBindChanged` instead of terminating the replacement
CN;
- covers missing/changed owners, stale allocator responses,
already-published replacement generations, invalidated-tombstone
admission, delayed cleanup, transient owner-side allocator failure, and
same-endpoint replacement routing.

There is no wire-format or public API change.

Validation on the current head:

- focused keeper, replacement-CN, invalidated-admission, and
transient-NotFound regressions passed;
- the two review counterexamples passed with `-race -count=100`;
- full `pkg/lockservice` passed with `-short` in normal mode (87.132s)
and race mode (90.880s);
- `make dev-build` passed;
- `make static-check-analysis GOLANGCI_LINT_CONCURRENCY=4` passed with 0
issues;
- `git diff --check` passed.

The original convergence path was also validated with a real local
two-CN reproduction using the built image: an active transaction on CN1
held a lock whose owner was CN2, then CN2 was replaced at the same
endpoint with a new UUID. There was no fatal log or restart. Transient
keeper/rejection counters stopped changing during an additional
20-second steady-state window; the replacement CN remained running, the
uncommitted value was not exposed, and rollback preserved the original
committed value.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…28325)

### Root cause

Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent.

The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order.

### Changes

- Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts.
- Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution.
- Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction.
- Preserve existing explicit user-transaction validation and ownership semantics.
- Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests.
- Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions.

### Issue-to-test proof

`TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers:

- database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs;
- DIFF while an unrelated database DROP runs;
- PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate;
- completion, result correctness, and unrelated-drop visibility after every interleaving.

The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs.

### Validation

- rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged
- focused frontend admission and retry tests, including rollback/begin/gate error propagation
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3`
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1`
- full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed
- full `./pkg/frontend`
- full `./pkg/tests/issues`
- exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL`
- `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment
- `make build`
- exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9`
- `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored
- `git diff --check`

After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed.

The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers.

Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers.

After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing.

Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed.

### Residual risk

The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28474)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

Keep the issue open until the complete fixed image passes the field
acceptance gate below; merging this PR alone is not the closure
criterion.

## What this PR does / why we need it:

This follow-up closes two recovery gaps left after matrixorigin#28115 and matrixorigin#28343,
without weakening their transaction fences:

- **DN departed-owner recovery:** check the local raw CN inventory
before GetActiveTxn. If no endpoint exists, retain
admission/cannot-commit fences but skip futile RPCs, backend resets and
repeated missing-owner errors. Recheck membership every normal sweep,
including pending-admission CNs.
- **Safe eventual expiry:** preserve the first disconnect timestamp
rather than extending the 24-hour retention on each failure. Cleanup
validates ctl identity, recovery epoch, transaction watermark and
inactive timestamp against Resume, fresh state and replacement ctl.
In-flight Commit and persistent unknown-Commit fences keep their
independent lifetime protection.
- **CN route recovery:** a stale allocator reply can republish an
invalidated exact bind after keeper detachment. New requests then reject
before reaching the RPC refresh path, while the keeper correctly skips
the invalidated ref. Rejection now detaches only that exact cached
route, allowing subsequent discovery to fetch the converged bind. Lock,
ForwardLock and RemoteLock-on-Shared-proxy use the same helper.
- **Preserved ownership:** old transactions remain fenced; invalidated
refs remain until their consumers release them. The helper pins ref
lifetime through constant-time route detachment, preserves
newer/metadata-distinct routes and same-key valid reacquisition, and
closes outside mutation locks.

No wire/API/storage-format change, new retry layer/background worker,
pressure-policy change or configuration-default change.

Validation:

- Deterministic expiry/Resume/Commit/ctl-replacement and
missing-membership counterexamples; negative controls fail on unfixed
behavior.
- Actual Lock and forwarded/proxied handler rejection; cancellation, new
route/allocator/routing metadata, ref release/reacquisition, and close
ownership controls.
- Individual adaptive race stress, including 100 repetitions for the
route and membership recovery tests.
- Delivery integrates main `f0c31cd4b8` at `56fe252fd7`; CI checks out
the PR head, so the current dependency graph is tested explicitly. PR
head `07a73ab3e7` differs from the tested revision only in the evidence
document.
- Integrated owning package: `-short -count=1` passed (86.463s); `-short
-race -count=1` passed (91.534s). All ten exact route/membership/expiry
race tests were remeasured and repeated individually (nine at 100
repetitions, persistent-disconnect expiry at 47); all passed.
- `make build`, `make err-check`, and repository-configured
owning-package golangci passed (0 lint issues).
- Full-repository `make static-check-analysis
GOLANGCI_LINT_CONCURRENCY=2` passed (exit 0): err-check, all-package
molint and all-package golangci; golangci reported 0 issues under
unchanged repository rules/exclusions (11m21s).
- Additional repository license-header check passed (exit 0): 5,264
files checked, 0 invalid, 0 modified.
- Integrated real LogService + DN + two CN processes
(`dn-expiry-compare-vrbvaws6`, exit 0), two sequential CN replacements:
both 65-second windows completed 33 SQL commits. Departed-owner DN error
counters stayed `[6] -> [6]` and `[6,6] -> [6,6]`; the second transition
had one transient 20702, then progress. Old uncommitted values stayed
invisible, both DN fences remained, and the original locked row could be
rewritten/committed and read from the other CN. All test-owned processes
exited, with no CN fatal/panic. Binary SHA-256:
`0d65214a27aafbfd5cc0d574b71ecdbde0ba7f9539ec82bae92986b9f256f4c8`.

Limits are explicit: the real test keeps default 24-hour DN retention
and 20-second cleaner cadence but uses a 10-second CN remote-lock lease.
It is not a default-10-minute-lease test, a 24-hour soak or a field
15-minute acceptance run. The non-short `TestIssue3288` deadline also
fails at the clean investigation baseline; no assertion was weakened.
Owning-package molint diagnostics match the clean baseline. Full
evidence and the closure checklist are in
`docs/design/evidence/27707_dn_inactive_expiry.md`.

Field acceptance before issue closure: use an immutable image containing
the complete fix, replace both CNs with active remote-lock transactions,
verify completed rollout/SQL and original-row recovery/data safety, and
keep each departed owner's error counters flat for at least 15 minutes
after membership convergence. This PR intentionally does not auto-close
the issue.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…nt (matrixorigin#28343)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

## What this PR does / why we need it:

PR matrixorigin#28115 stopped a missing LockService owner from crashing a
replacement CN and fenced transactions that depended on the departed
exact bind. However, transaction-owned `remoteBindRefs` intentionally
remain until transaction cleanup, and the keeper still treated those
retained references as heartbeat-eligible. A fenced transaction could
therefore keep the departed generation in every keeper round, matching
the latest stability report of continuous `failed to keep remote locks`
after all replacement CNs were Ready.

This follow-up separates reference lifetime from keeper eligibility:

- invalidates an unusable exact remote-bind generation while retaining
its ref-counted tombstone until normal transaction cleanup, preserving
the cleanup ownership and ABA protection introduced by matrixorigin#28115;
- excludes invalidated generations from future keeper rounds without
affecting a replacement generation for the same table;
- rejects new transaction admission to an invalidated exact tombstone
before the remote Lock RPC, while allowing the same bind to be admitted
again after the old owners finish cleanup;
- treats owner-side `ErrLockTableBindChanged`, `ErrLockTableNotFound`,
and `NewBind` as authoritative rejection of the exact generation, even
when the allocator temporarily returns the same stale bind;
- rejects a request routed to a replacement CN with a different UUID
using `ErrLockTableBindChanged` instead of terminating the replacement
CN;
- covers missing/changed owners, stale allocator responses,
already-published replacement generations, invalidated-tombstone
admission, delayed cleanup, transient owner-side allocator failure, and
same-endpoint replacement routing.

There is no wire-format or public API change.

Validation on the current head:

- focused keeper, replacement-CN, invalidated-admission, and
transient-NotFound regressions passed;
- the two review counterexamples passed with `-race -count=100`;
- full `pkg/lockservice` passed with `-short` in normal mode (87.132s)
and race mode (90.880s);
- `make dev-build` passed;
- `make static-check-analysis GOLANGCI_LINT_CONCURRENCY=4` passed with 0
issues;
- `git diff --check` passed.

The original convergence path was also validated with a real local
two-CN reproduction using the built image: an active transaction on CN1
held a lock whose owner was CN2, then CN2 was replaced at the same
endpoint with a new UUID. There was no fatal log or restart. Transient
keeper/rejection counters stopped changing during an additional
20-second steady-state window; the replacement CN remained running, the
uncommitted value was not exposed, and rollback preserved the original
committed value.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…28325)

### Root cause

Mixed DATA BRANCH and CLONE workflows used inconsistent lock order. DIFF, PICK, MERGE, and ordinary CLONE could first acquire catalog/view/object locks and only later enter nested scratch/restore/drop paths that acquire the existing lineage-owner lifecycle row lock. Concurrent DROP, SNAPSHOT, and branch operations acquire the lineage lock first and then catalog/view/object locks. Across CNs these two orders can form a distributed wait cycle even when the business database names are independent.

The previous revision of this PR tried to merge the view and lineage gates. That changed the restore catalog contract and caused both unit and broad BVT regressions when `mo_feature_registry` was unavailable in tenant/PITR restore contexts. This revision restores the two existing gates and corrects only composite-operation admission order.

### Changes

- Add one shared mutation-admission helper that acquires the existing lineage-owner lifecycle lock before composite autocommit work starts.
- Admit table/database CLONE and DATA BRANCH DIFF/PICK/MERGE before endpoint/catalog resolution.
- Reacquire the lineage lifecycle lock when database-clone target-lock retry restarts its owned transaction.
- Preserve existing explicit user-transaction validation and ownership semantics.
- Add deterministic two-CN regression coverage plus focused admission/retry failure-path unit tests.
- Update the existing concurrent `IF NOT EXISTS` clone regression to observe the new leading lineage lifecycle gate while preserving its transaction-order and result assertions.

### Issue-to-test proof

`TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock` runs authenticated SQL through a real two-CN cluster. It uses lock-service waiter barriers rather than timing sleeps and covers:

- database CLONE with table data, full-text index, and view metadata while an unrelated database DROP runs;
- DIFF while an unrelated database DROP runs;
- PICK and MERGE with a destination-row conflict while an unrelated database DROP waits on the lineage gate;
- completion, result correctness, and unrelated-drop visibility after every interleaving.

The exact external regression set from matrixorigin#26404 was also run for 20 rounds at concurrency 9: 200/200 cases and 4,840/4,840 statements passed, with no deadlock or `20701` in runner/server logs.

### Validation

- rebased cleanly onto `main@0b195e4`; `git range-diff` confirms both issue commits are unchanged
- focused frontend admission and retry tests, including rollback/begin/gate error propagation
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-count=3`
- `TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock`: `-race -count=1`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: `-count=3`
- `TestIssue27040ConcurrentIfNotExistsDatabaseClone`: focused frontend coverage mode and `-race -count=1`
- full `./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend` after the shared SNAPSHOT/View-gate change landed
- full `./pkg/frontend`
- full `./pkg/tests/issues`
- exact adjacent regressions: `TestIssue26087ConcurrentDataBranchQuota`, `TestIssue26640AccountPITRUsesCatalogRestoreHandlers`, and `TestIssue28317ViewSnapshotGateOrderSQL`
- `go vet ./pkg/frontend ./pkg/tests/issues` with the repository CGo environment
- `make build`
- exact ten-case MOTR command from matrixorigin#26404 with `--repeat 20 -j 9`
- `temporary_table_clone` BVT after the temporary-DDL transaction change: 166/166 statements passed with JDBC metadata ignored
- `git diff --check`

After upstream matrixorigin#28322 unified SNAPSHOT -> View locking, the shared lock packages, frontend/compile packages, the real two-CN issue test, all three adjacent regressions, and the race case were rerun successfully. After upstream matrixorigin#28332 made temporary DDL transaction-independent, focused/full frontend and compile tests, the real two-CN issue test, `make build`, and the existing 166-statement temporary-clone BVT were rerun. The local machine has JDK 17 rather than the tester-required JDK 8: normal BVT comparison reported 12 JDBC display-width-only differences, each inspected against the SQL and expected data/DDL/error semantics; `-n` then proved all 166 semantic results. No result file was regenerated or changed.

The old-head Ubuntu UT, UT coverage, and pessimistic multi-CN BVT failures in workflow run 34098109436 all traced to the discarded shared-gate revision; local exact regression tests pass with this revision. They are not unrelated CI blockers.

Workflow run 34125753066 exposed one stale assertion in the existing matrixorigin#27040 regression: it still expected the second clone to wait at the target `mo_database` key, but this PR intentionally admits clone at the lineage lifecycle gate first. Commit `d71f4dbd` updates only that observation point; the original early-return, commit-order, uniqueness, and payload assertions remain intact. The same job also reproduced the unrelated matrixorigin#28313 shuffle-pool failure, while its pessimistic BVT job reproduced the then-unresolved matrixorigin#28352 temporary-table ALTER failure; the aggregate Coverage failure was a consequence of those failed producers.

After rebasing onto upstream matrixorigin#28343's remote-bind convergence change and matrixorigin#28096's frontend `MEMBER OF` support, the eight focused frontend admission/retry/error-path tests and the full `pkg/frontend` package passed. The real two-CN matrixorigin#26404 regression and the adjacent matrixorigin#27040 clone regression each passed three normal runs and one race run, validating the current lockservice dependency rather than reusing the older topology evidence. Main then advanced with matrixorigin#28356's executor-owned temporary ALTER COPY transaction fix, which resolved matrixorigin#28352. A second `range-diff` remained unchanged; the eight focused frontend tests and both two-CN regressions were rerun on `main@fdc1e0c`, with three normal runs per regression and a combined race run passing.

Pre-rebase workflow run 34150466865 passed Linux UT, coverage UT, SCA, Proxy and pessimistic multi-CN BVT, and aggregate Coverage; the remaining completed jobs were successful, neutral, or intentionally skipped. Main then added only matrixorigin#28355's correlated scalar-aggregate planner optimization. A third `range-diff` remained unchanged, and the eight focused frontend tests plus both real two-CN regressions passed on `main@0b195e4`; the existing race evidence remains valid because neither the PR's synchronization code nor its lockservice dependency changed.

### Residual risk

The corrected order intentionally serializes these composite autocommit workflows at the existing global lineage lifecycle boundary for their owned transaction. The 20-round exact workload completed without stalls. Explicit user-transaction behavior is unchanged and is outside the reported autocommit workload.

Approved by: @XuPeng-SH
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28474)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#27707

Keep the issue open until the complete fixed image passes the field
acceptance gate below; merging this PR alone is not the closure
criterion.

## What this PR does / why we need it:

This follow-up closes two recovery gaps left after matrixorigin#28115 and matrixorigin#28343,
without weakening their transaction fences:

- **DN departed-owner recovery:** check the local raw CN inventory
before GetActiveTxn. If no endpoint exists, retain
admission/cannot-commit fences but skip futile RPCs, backend resets and
repeated missing-owner errors. Recheck membership every normal sweep,
including pending-admission CNs.
- **Safe eventual expiry:** preserve the first disconnect timestamp
rather than extending the 24-hour retention on each failure. Cleanup
validates ctl identity, recovery epoch, transaction watermark and
inactive timestamp against Resume, fresh state and replacement ctl.
In-flight Commit and persistent unknown-Commit fences keep their
independent lifetime protection.
- **CN route recovery:** a stale allocator reply can republish an
invalidated exact bind after keeper detachment. New requests then reject
before reaching the RPC refresh path, while the keeper correctly skips
the invalidated ref. Rejection now detaches only that exact cached
route, allowing subsequent discovery to fetch the converged bind. Lock,
ForwardLock and RemoteLock-on-Shared-proxy use the same helper.
- **Preserved ownership:** old transactions remain fenced; invalidated
refs remain until their consumers release them. The helper pins ref
lifetime through constant-time route detachment, preserves
newer/metadata-distinct routes and same-key valid reacquisition, and
closes outside mutation locks.

No wire/API/storage-format change, new retry layer/background worker,
pressure-policy change or configuration-default change.

Validation:

- Deterministic expiry/Resume/Commit/ctl-replacement and
missing-membership counterexamples; negative controls fail on unfixed
behavior.
- Actual Lock and forwarded/proxied handler rejection; cancellation, new
route/allocator/routing metadata, ref release/reacquisition, and close
ownership controls.
- Individual adaptive race stress, including 100 repetitions for the
route and membership recovery tests.
- Delivery integrates main `f0c31cd4b8` at `56fe252fd7`; CI checks out
the PR head, so the current dependency graph is tested explicitly. PR
head `07a73ab3e7` differs from the tested revision only in the evidence
document.
- Integrated owning package: `-short -count=1` passed (86.463s); `-short
-race -count=1` passed (91.534s). All ten exact route/membership/expiry
race tests were remeasured and repeated individually (nine at 100
repetitions, persistent-disconnect expiry at 47); all passed.
- `make build`, `make err-check`, and repository-configured
owning-package golangci passed (0 lint issues).
- Full-repository `make static-check-analysis
GOLANGCI_LINT_CONCURRENCY=2` passed (exit 0): err-check, all-package
molint and all-package golangci; golangci reported 0 issues under
unchanged repository rules/exclusions (11m21s).
- Additional repository license-header check passed (exit 0): 5,264
files checked, 0 invalid, 0 modified.
- Integrated real LogService + DN + two CN processes
(`dn-expiry-compare-vrbvaws6`, exit 0), two sequential CN replacements:
both 65-second windows completed 33 SQL commits. Departed-owner DN error
counters stayed `[6] -> [6]` and `[6,6] -> [6,6]`; the second transition
had one transient 20702, then progress. Old uncommitted values stayed
invisible, both DN fences remained, and the original locked row could be
rewritten/committed and read from the other CN. All test-owned processes
exited, with no CN fatal/panic. Binary SHA-256:
`0d65214a27aafbfd5cc0d574b71ecdbde0ba7f9539ec82bae92986b9f256f4c8`.

Limits are explicit: the real test keeps default 24-hour DN retention
and 20-second cleaner cadence but uses a 10-second CN remote-lock lease.
It is not a default-10-minute-lease test, a 24-hour soak or a field
15-minute acceptance run. The non-short `TestIssue3288` deadline also
fails at the clean investigation baseline; no assertion was weakened.
Owning-package molint diagnostics match the clean baseline. Full
evidence and the closure checklist are in
`docs/design/evidence/27707_dn_inactive_expiry.md`.

Field acceptance before issue closure: use an immutable image containing
the complete fix, replace both CNs with active remote-lock transactions,
verify completed rollout/SQL and original-row recovery/data safety, and
keep each departed owner's error counters flat for at least 15 minutes
after membership convergence. This PR intentionally does not auto-close
the issue.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants