Skip to content

fix(sql): order snapshot and view lifecycle locks across DDL transactions - #28322

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
LeftHandCold:fix/ddl-lifecycle-gate-order-28317
Sep 7, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
LeftHandCold:fix/ddl-lifecycle-gate-order-28317

Conversation

@LeftHandCold

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 #28317

What this PR does / why we need it:

Root cause

An explicit CREATE / INSERT / DROP transaction and a copy-ALTER transaction
on unrelated databases can acquire two internal catalog gates in opposite order:

A: CREATE retains View gate -> DROP requests SNAPSHOT gate
B: ALTER retains SNAPSHOT gate -> copy CREATE requests View gate

The nightly TC-02 incident recorded this exact two-transaction cycle at
2026-09-07 03:17:08.932541 UTC. The deadlock detector correctly selects a victim;
the defect is the internal lock-order inversion, not deadlock detection.
Reordering only one DROP statement is insufficient because an earlier CREATE
in the same explicit transaction already owns the View gate.

Changes

  • Acquire the existing SNAPSHOT locking read before every View lifecycle gate,
    using the same transaction and system-tenant context.
  • Apply the order to compile-time revalidation/cleanup, background recovery,
    account inheritance, publication invalidation, Snapshot/PITR restore and
    account reconciliation, including the exported revalidation SQL sequence.
  • Preserve the original View gate, revalidation marker writes and lineage
    owner write barriers. The new read does not add an MVCC version or replace
    commit-time lineage validation.
  • Stop on either gate error and retain the existing transaction cleanup and
    typed catalog-not-ready handling.
  • Add deterministic two-CN public SQL coverage plus focused ordering and
    failure-propagation tests; update the existing metadata tests for the ordered
    lock prefix.

Validation

Tests used the repository CGo wrapper on macOS arm64 with Go 1.26.4, based on
main 6eee64625e:

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=8m \
  ./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -race -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^(TestIssue27718ConcurrentSnapshotQuota|TestIssue26120SnapshotBranchKeepsHistoricalParentIdentity)$' \
  ./pkg/tests/issues

git diff --check

All passed. The SQL regression reuses the shared two-CN fixture, uses minimal
rows, and synchronizes on an observed lifecycle-lock waiter instead of sleeps.
It checks successful DROP/COMMIT and ALTER, holder rollback, waiter cancellation,
and final schema/data on both CNs. The Snapshot quota control covers pessimistic
RC and optimistic SI.

The original cycle was independently reproduced before this patch on
9ae27d218 and the previously passing daily revision 845fff8ee9; this is not
attributed to the most recent day's commits. The fresh main base was not
separately rerun without the patch. The race run used the same production code
before final test-only cleanup-registration and assertion tightening; normal
mode was rerun afterward. Full evidence boundaries are recorded in
docs/ddl-lifecycle-lock-order.md.

Scope and risks

  • Ordinary DML execution paths are unchanged. There are no production test
    hooks, new background workers, retries, persisted formats or protocol changes.
  • A View gate acquisition adds one locking SELECT. View-only DDL transactions
    now retain SNAPSHOT until transaction completion, so long explicit DDL can
    increase waiting for Snapshot/lineage operations. This is a correctness fix,
    not a zero-cost performance optimization.
  • Keeping the original View gate preserves mutual exclusion with old CNs;
    old CNs can still introduce the original inversion during rolling upgrades.
    All participating CNs must be updated to eliminate that path.
  • This does not claim to eliminate all SQL deadlocks or fix the separate
    concurrent-primary-key ALTER timeout/convoy from the same nightly.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

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

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

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Sep 7, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Sep 7, 2026

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

Review conclusion: REQUEST CHANGES — one reproduced P1 regression below. The authenticated reviewer is also the PR author (LeftHandCold), so GitHub does not allow a formal REQUEST_CHANGES review; this COMMENT records the blocking conclusion without pretending to change the review state.

Scope: all 12 changed files at e1aef10 against main/merge-base 3d67664. Reviewed the transaction-wide SNAPSHOT -> View ordering, compile/background/frontend entry points, system-tenant resolution, preserved owner write barriers, typed catalog-readiness fallback, error propagation, transaction cleanup and new test oracles. This is a focused bug fix, not a feature/design-document gate.

Evidence: inspected existing terminal logs for the four package suites, two-CN issue28317 normal/race runs and Snapshot quota/historical-identity controls; their relevant changed production/test files match 523901e in the current head. The author documents the race run's earlier test-cleanup revision. These tests do not cover a non-sys restore. I added one temporary review-only public SQL test against the exact head: one ordinary tenant, one table, one row; it reaches RESTORE and returns 1146 for mo_feature_registry. Command: GOMAXPROCS=2 .agents/skills/mo-dev/scripts/mo-cgo-test -p=1 -v -count=1 -timeout=3m -run '^TestReview28322TenantRestore$' ./pkg/tests/issues. Terminal exit 1, package duration 11.968s (excluding compilation). Raw local evidence: /private/tmp/review28322-tenant-corrected.log. An initial attempt failed in the review fixture's DSN before the target path; that was corrected and is not product evidence. Native artifacts were reused through the checked wrapper; no parallel package runs or production cluster changes.

Audit Conclusion
Q1 ownership/cleanup Locks remain transaction-owned; successful executor results are closed; existing rollback/unlock ownership retained.
Q2 ordering/cancellation Existing sys-account two-gate cycle is addressed; waits keep existing context/transaction termination paths. Non-sys restore fails at the new gate due to tenant resolution.
Q3 growth/cost No new workers, caches or retry accumulation. One extra locking read and longer SNAPSHOT retention are acknowledged costs, not additional blockers.

Mixed-version CNs can still exhibit the original inversion; the stated requirement to update all participating CNs is accepted. No other verified blocker found in the reviewed scope.

Comment thread pkg/frontend/snapshot.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.

Deep review completed on exact head e1aef10. I read the complete review, inline-comment, reply, and thread state; audited the full 12-file diff and all gate call sites; and checked lock ownership, error propagation, cancellation, transaction cleanup, and boundedness.

The new SNAPSHOT -> View order itself is coherent for system-context callers, and the deterministic two-CN regression passed in normal and race modes. Two blockers remain: non-system Snapshot/PITR restore now fails at the new gate, and the newly added regression file fails the required license check.

Validation on this exact head:

  • focused catalog/frontend/compile lifecycle tests passed
  • TestIssue28317ViewSnapshotGateOrderSQL passed normally and with -race
  • a temporary public-SQL ordinary-tenant Snapshot restore test failed twice with error 1146 for mo_feature_registry
  • existing TestIssue26640AccountPITRUsesCatalogRestoreHandlers failed with the same error; the exact-head coverage job reports this test failing too
  • exact-head SCA reports issue_28317_test.go has no valid license header
  • git diff --check passed

The temporary review test was removed. No other blocking issue was verified.

Comment thread pkg/frontend/snapshot.go Resolved
Comment thread pkg/tests/issues/issue_28317_test.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.

Deep re-review completed on exact head 053005ed2c1254ffd29db913e53887f43e9c8fd3. I read the full review/comment/thread history, compared the increment from the previously reviewed e1aef1042e9a7ad30d577d82225cef5fa7ff8943, and rechecked the complete diff.

The previous blockers are closed in the implementation, not only in the author response: snapshot/PITR restore now performs the sys-only feature-registry read with a derived system-account context while preserving the caller context and the same transaction, and the new issue test has the full license header plus ordinary-tenant snapshot/PITR coverage. The latest test-only commit also replaces stale assumptions with assertions that observe the actual lifecycle-lock waiter and terminal commit/replacement-BEGIN/rollback outcomes.

I found no remaining blocking correctness, lifecycle, deadlock-order, or unbounded-growth issue. The code consistently acquires SNAPSHOT before view metadata locks, closes executor results, retains transaction ownership of locks, and covers cancellation and both success/failure release paths.

Validation on this exact head: native third-party/CGo build passed; affected catalog, frontend, databranchutils, compile-focused, cnservice, issue-26087, and issue-28317 tests passed; the three changed concurrency scenarios also passed individually with -race. A broader pkg/sql/compile run still hit the same unrelated pre-existing parquet fanout failures, while the affected compile tests passed.

@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 053005ed2c1254ffd29db913e53887f43e9c8fd3. No confirmed blocking issue found.

The fix applies the lock-order invariant at transaction scope, not merely within DROP: every inspected production View lifecycle entry now acquires SNAPSHOT before View, including the exported revalidation SQL sequence, recovery, account/publication mutation and restore paths. This prevents an earlier CREATE from retaining View while a later statement requests SNAPSHOT in the opposite order to COPY ALTER. The helper preserves the caller transaction and uses system-tenant resolution for the global rows.

I checked the full production diff, remaining direct View gate references, acquisition failure propagation, revalidation marker handling and result cleanup. The existing View gate and lineage owner write barriers are retained; the added locking read does not replace optimistic commit-time validation or manufacture a new MVCC version. Ordinary tenant restore coverage matters because mo_feature_registry is a system catalog object.

The tests exercise an observed real lock waiter rather than timing-only scheduling, followed by DROP/COMMIT, rollback, canceled waiter and final schema/data checks across CNs. The existing branch quota test was updated to assert the newly intended serialization and committed/rolled-back outcomes, rather than preserving an incompatible expectation that snapshot proceeds while the DDL holder is open. The cancellation test appropriately does not infer server rollback solely from a client cancellation error.

Performance and rollout qualifications are substantive: view-lifecycle DDL now holds the shared outer catalog gate for the entire transaction, so a long explicit DDL transaction can delay Snapshot/lineage work across unrelated databases. This is an acknowledged correctness/serialization trade-off, not a claim of no regression in waiting time. Retaining View preserves mutual exclusion with older CNs, but the inversion can still originate on an old CN until all participants are upgraded. Neither limitation is hidden or claimed solved universally.

Evidence in this review: full diff/call-site and test inspection plus git diff --check. The PR's native/race and historical falsification runs are author evidence; I did not rerun them or claim a fresh unpatched-base reproduction, and did not wait for CI. No code was changed during review.

@mergify mergify Bot added the queued label Sep 7, 2026
@mergify

mergify Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-07 11:50 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-07 11:51 UTC · at fe254b52b291c23adf0affdbac7d362e4193a996

This pull request spent 1 minute 13 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]

Reason

Pull request #28322 has been dequeued

Pull request from fork cannot be queued. This pull request comes 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.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, 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

@XuPeng-SH
XuPeng-SH merged commit e78ff09 into matrixorigin:main Sep 7, 2026
21 of 22 checks passed
@mergify mergify Bot added dequeued and removed queued labels Sep 7, 2026
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
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…ions (matrixorigin#28322)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#28317

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

### Root cause

An explicit `CREATE / INSERT / DROP` transaction and a copy-ALTER
transaction
on unrelated databases can acquire two internal catalog gates in
opposite order:

```text
A: CREATE retains View gate -> DROP requests SNAPSHOT gate
B: ALTER retains SNAPSHOT gate -> copy CREATE requests View gate
```

The nightly TC-02 incident recorded this exact two-transaction cycle at
2026-09-07 03:17:08.932541 UTC. The deadlock detector correctly selects
a victim;
the defect is the internal lock-order inversion, not deadlock detection.
Reordering only one DROP statement is insufficient because an earlier
CREATE
in the same explicit transaction already owns the View gate.

### Changes

- Acquire the existing SNAPSHOT locking read before every View lifecycle
gate,
  using the same transaction and system-tenant context.
- Apply the order to compile-time revalidation/cleanup, background
recovery,
account inheritance, publication invalidation, Snapshot/PITR restore and
account reconciliation, including the exported revalidation SQL
sequence.
- Preserve the original View gate, revalidation marker writes and
lineage
owner write barriers. The new read does not add an MVCC version or
replace
  commit-time lineage validation.
- Stop on either gate error and retain the existing transaction cleanup
and
  typed catalog-not-ready handling.
- Add deterministic two-CN public SQL coverage plus focused ordering and
failure-propagation tests; update the existing metadata tests for the
ordered
  lock prefix.

### Validation

Tests used the repository CGo wrapper on macOS arm64 with Go 1.26.4,
based on
main `6eee64625e`:

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=8m \
  ./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -race -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^(TestIssue27718ConcurrentSnapshotQuota|TestIssue26120SnapshotBranchKeepsHistoricalParentIdentity)$' \
  ./pkg/tests/issues

git diff --check
```

All passed. The SQL regression reuses the shared two-CN fixture, uses
minimal
rows, and synchronizes on an observed lifecycle-lock waiter instead of
sleeps.
It checks successful DROP/COMMIT and ALTER, holder rollback, waiter
cancellation,
and final schema/data on both CNs. The Snapshot quota control covers
pessimistic
RC and optimistic SI.

The original cycle was independently reproduced before this patch on
`9ae27d218` and the previously passing daily revision `845fff8ee9`; this
is not
attributed to the most recent day's commits. The fresh main base was not
separately rerun without the patch. The race run used the same
production code
before final test-only cleanup-registration and assertion tightening;
normal
mode was rerun afterward. Full evidence boundaries are recorded in
`docs/ddl-lifecycle-lock-order.md`.

### Scope and risks

- Ordinary DML execution paths are unchanged. There are no production
test
hooks, new background workers, retries, persisted formats or protocol
changes.
- A View gate acquisition adds one locking SELECT. View-only DDL
transactions
now retain SNAPSHOT until transaction completion, so long explicit DDL
can
increase waiting for Snapshot/lineage operations. This is a correctness
fix,
  not a zero-cost performance optimization.
- Keeping the original View gate preserves mutual exclusion with old
CNs;
old CNs can still introduce the original inversion during rolling
upgrades.
  All participating CNs must be updated to eliminate that path.
- This does not claim to eliminate all SQL deadlocks or fix the separate
  concurrent-primary-key ALTER timeout/convoy from the same nightly.

---------

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
…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
…ions (matrixorigin#28322)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#28317

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

### Root cause

An explicit `CREATE / INSERT / DROP` transaction and a copy-ALTER
transaction
on unrelated databases can acquire two internal catalog gates in
opposite order:

```text
A: CREATE retains View gate -> DROP requests SNAPSHOT gate
B: ALTER retains SNAPSHOT gate -> copy CREATE requests View gate
```

The nightly TC-02 incident recorded this exact two-transaction cycle at
2026-09-07 03:17:08.932541 UTC. The deadlock detector correctly selects
a victim;
the defect is the internal lock-order inversion, not deadlock detection.
Reordering only one DROP statement is insufficient because an earlier
CREATE
in the same explicit transaction already owns the View gate.

### Changes

- Acquire the existing SNAPSHOT locking read before every View lifecycle
gate,
  using the same transaction and system-tenant context.
- Apply the order to compile-time revalidation/cleanup, background
recovery,
account inheritance, publication invalidation, Snapshot/PITR restore and
account reconciliation, including the exported revalidation SQL
sequence.
- Preserve the original View gate, revalidation marker writes and
lineage
owner write barriers. The new read does not add an MVCC version or
replace
  commit-time lineage validation.
- Stop on either gate error and retain the existing transaction cleanup
and
  typed catalog-not-ready handling.
- Add deterministic two-CN public SQL coverage plus focused ordering and
failure-propagation tests; update the existing metadata tests for the
ordered
  lock prefix.

### Validation

Tests used the repository CGo wrapper on macOS arm64 with Go 1.26.4,
based on
main `6eee64625e`:

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=8m \
  ./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -race -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^(TestIssue27718ConcurrentSnapshotQuota|TestIssue26120SnapshotBranchKeepsHistoricalParentIdentity)$' \
  ./pkg/tests/issues

git diff --check
```

All passed. The SQL regression reuses the shared two-CN fixture, uses
minimal
rows, and synchronizes on an observed lifecycle-lock waiter instead of
sleeps.
It checks successful DROP/COMMIT and ALTER, holder rollback, waiter
cancellation,
and final schema/data on both CNs. The Snapshot quota control covers
pessimistic
RC and optimistic SI.

The original cycle was independently reproduced before this patch on
`9ae27d218` and the previously passing daily revision `845fff8ee9`; this
is not
attributed to the most recent day's commits. The fresh main base was not
separately rerun without the patch. The race run used the same
production code
before final test-only cleanup-registration and assertion tightening;
normal
mode was rerun afterward. Full evidence boundaries are recorded in
`docs/ddl-lifecycle-lock-order.md`.

### Scope and risks

- Ordinary DML execution paths are unchanged. There are no production
test
hooks, new background workers, retries, persisted formats or protocol
changes.
- A View gate acquisition adds one locking SELECT. View-only DDL
transactions
now retain SNAPSHOT until transaction completion, so long explicit DDL
can
increase waiting for Snapshot/lineage operations. This is a correctness
fix,
  not a zero-cost performance optimization.
- Keeping the original View gate preserves mutual exclusion with old
CNs;
old CNs can still introduce the original inversion during rolling
upgrades.
  All participating CNs must be updated to eliminate that path.
- This does not claim to eliminate all SQL deadlocks or fix the separate
  concurrent-primary-key ALTER timeout/convoy from the same nightly.

---------

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
…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
…ions (matrixorigin#28322)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes matrixorigin#28317

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

### Root cause

An explicit `CREATE / INSERT / DROP` transaction and a copy-ALTER
transaction
on unrelated databases can acquire two internal catalog gates in
opposite order:

```text
A: CREATE retains View gate -> DROP requests SNAPSHOT gate
B: ALTER retains SNAPSHOT gate -> copy CREATE requests View gate
```

The nightly TC-02 incident recorded this exact two-transaction cycle at
2026-09-07 03:17:08.932541 UTC. The deadlock detector correctly selects
a victim;
the defect is the internal lock-order inversion, not deadlock detection.
Reordering only one DROP statement is insufficient because an earlier
CREATE
in the same explicit transaction already owns the View gate.

### Changes

- Acquire the existing SNAPSHOT locking read before every View lifecycle
gate,
  using the same transaction and system-tenant context.
- Apply the order to compile-time revalidation/cleanup, background
recovery,
account inheritance, publication invalidation, Snapshot/PITR restore and
account reconciliation, including the exported revalidation SQL
sequence.
- Preserve the original View gate, revalidation marker writes and
lineage
owner write barriers. The new read does not add an MVCC version or
replace
  commit-time lineage validation.
- Stop on either gate error and retain the existing transaction cleanup
and
  typed catalog-not-ready handling.
- Add deterministic two-CN public SQL coverage plus focused ordering and
failure-propagation tests; update the existing metadata tests for the
ordered
  lock prefix.

### Validation

Tests used the repository CGo wrapper on macOS arm64 with Go 1.26.4,
based on
main `6eee64625e`:

```sh
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=8m \
  ./pkg/catalog ./pkg/frontend/databranchutils ./pkg/sql/compile ./pkg/frontend

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -race -v -count=1 -timeout=5m \
  -run '^TestIssue28317ViewSnapshotGateOrderSQL$' ./pkg/tests/issues

.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=5m \
  -run '^(TestIssue27718ConcurrentSnapshotQuota|TestIssue26120SnapshotBranchKeepsHistoricalParentIdentity)$' \
  ./pkg/tests/issues

git diff --check
```

All passed. The SQL regression reuses the shared two-CN fixture, uses
minimal
rows, and synchronizes on an observed lifecycle-lock waiter instead of
sleeps.
It checks successful DROP/COMMIT and ALTER, holder rollback, waiter
cancellation,
and final schema/data on both CNs. The Snapshot quota control covers
pessimistic
RC and optimistic SI.

The original cycle was independently reproduced before this patch on
`9ae27d218` and the previously passing daily revision `845fff8ee9`; this
is not
attributed to the most recent day's commits. The fresh main base was not
separately rerun without the patch. The race run used the same
production code
before final test-only cleanup-registration and assertion tightening;
normal
mode was rerun afterward. Full evidence boundaries are recorded in
`docs/ddl-lifecycle-lock-order.md`.

### Scope and risks

- Ordinary DML execution paths are unchanged. There are no production
test
hooks, new background workers, retries, persisted formats or protocol
changes.
- A View gate acquisition adds one locking SELECT. View-only DDL
transactions
now retain SNAPSHOT until transaction completion, so long explicit DDL
can
increase waiting for Snapshot/lineage operations. This is a correctness
fix,
  not a zero-cost performance optimization.
- Keeping the original View gate preserves mutual exclusion with old
CNs;
old CNs can still introduce the original inversion during rolling
upgrades.
  All participating CNs must be updated to eliminate that path.
- This does not claim to eliminate all SQL deadlocks or fix the separate
  concurrent-primary-key ALTER timeout/convoy from the same nightly.

---------

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
…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

This branch was previously deployed

1 inactive deployment
ci — fe254b52 Deployed Sep 7, 2026 by mergify[bot] via Matrixone Utils CI / Coverage #51310
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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Unrelated CREATE/DROP and ALTER transactions deadlock on inverted View/SNAPSHOT catalog gates

4 participants