Skip to content

fix: validate database clone existence - #27058

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27040-24422f62
Aug 14, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27040-24422f62

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 12, 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:

Fixes #27040
Fixes #27041

What this PR does / why we need it:

CREATE DATABASE ... CLONE was losing IF NOT EXISTS while parsing, so an
existing target eventually reached an unconditional CREATE DATABASE and
returned 1007. It also accepted a nonexistent source whenever the source
metadata query produced no table rows, creating an empty destination.

This PR preserves the clause in the clone AST and formatter; verifies source
database existence at the requested snapshot; and makes an existing target a
true no-op.

The follow-up review found three correctness holes in the original target
precheck. This revision addresses them as part of the same clone-existence
contract:

  • Catalog existence reads are scoped to the resolved account, including a
    snapshot tenant. A same-name database in another tenant can neither suppress
    a target clone nor prove a source exists.
  • Target-account resolution and cross-account authorization happen once,
    before an IF NOT EXISTS no-op is possible. Non-sys callers cannot use an
    existing foreign target as an account/database-name oracle.
  • An implicit IF NOT EXISTS database clone uses an owning pessimistic RC
    background transaction to exclusively lock the exact
    (account_id, database_name) catalog key. The lock is held through the
    destination CREATE and released by the existing commit/rollback path. After
    a lock-wait retry, the transaction restarts and rechecks the target, so a
    concurrent winner makes the later statement a no-op rather than a duplicate
    database error.
  • Source authorization for catalog system databases is preserved before the
    new account-scoped source-existence query. A non-sys caller therefore keeps
    the established authorization error instead of incorrectly seeing Unknown database for mo_catalog, system, or another system database.

The target-lock helper reuses the existing catalog lock-key encoding and lock
context mechanism; data-branch source locking is refactored only to share those
primitives. There are no new fallback paths or protocol/catalog-format
changes.

Regression proof:

  • [Bug]: CREATE DATABASE IF NOT EXISTS ... CLONE ignores IF NOT EXISTS for an existing target #27040: parser/formatter coverage retains IF NOT EXISTS; the distributed
    case proves an existing target is unchanged and successful with the clause,
    still returns 1007 without it, and clones schema and rows for an absent
    target. It also proves that a tenant-only same-name target does not suppress
    the sys target clone.
  • [Bug]: CREATE DATABASE ... CLONE accepts a nonexistent source and creates an empty target #27041: the same distributed case proves missing sources fail without target
    catalog residue (with and without IF NOT EXISTS), real empty sources
    succeed, snapshot-only sources succeed, and missing-table cloning leaves no
    table residue. A tenant-only source is explicitly rejected to sys without an
    empty destination.
  • Account authorization is covered both by a frontend unit test and the
    distributed case: a non-sys tenant cannot clone to an existing foreign target
    even with IF NOT EXISTS and a valid snapshot.
  • System-database source authorization is covered by a frontend unit test
    derived from every catalog.SystemDatabases entry (including case-folding);
    the existing distributed clone_privilege and
    clone_sys_db_table_to_new_db_table cases exercise the exact database-clone
    statements that exposed the regression.
  • A deterministic two-goroutine frontend regression proves the target-decision
    retry/recheck state machine; the target lock-process test proves it uses the
    owning background transaction. An embedded-cluster two-client integration
    test exercises the production lock boundary: the first real frontend
    transaction holds the target through commit, the second clone is observed in
    the real mo_database lock wait queue (across every CN, because the catalog
    table binding can be remote), and after commit it refreshes, succeeds as a
    no-op, and leaves exactly one target with one payload row.
  • Target-lock failure paths are unit-tested too: ordinary lock errors and
    retryable errors without an owning background transaction are returned
    without an existence lookup, and the real lock entry point rejects a
    non-background executor before allocating or locking catalog state.

Tests run:

  • ./run.sh -p <this-worktree>/test/distributed/cases/ -m genrs -i clone_database_existence
    followed by ./run.sh -p <this-worktree>/test/distributed/cases/ -i clone_database_existence
    — passed; generated result was inspected: tenant collision clones sys data,
    tenant-only source leaves count 0, and unauthorized cross-account no-op is
    rejected while the sentinel remains 8.
  • Local two-client concurrent CREATE DATABASE IF NOT EXISTS ... CLONE ...
    smoke test — both statements succeeded and each observed exactly one cloned
    payload row.
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout 120s -run '^(TestCheckDatabaseExistsAtSnapshot|TestCheckDatabaseExistsAtSnapshotPropagatesErrors|TestCheckDatabaseExistsAtSnapshotRequiresAccountContext|TestHandleCloneDatabaseWithSourceIfNotExistsSkipsExistingTarget|TestHandleCloneDatabaseWithSourceIfNotExistsPropagatesLookupErrors|TestHandleCloneDatabaseWithSourceAuthorizesTargetBeforeIfNotExistsCheck|TestCheckCloneDatabaseTargetSerializesConcurrentIfNotExistsDecisions|TestIsCloneDatabaseTargetLockRetry|TestValidateCloneDatabaseAccounts|TestCloneCatalogLockBatch|TestWithCloneLockContext|TestCloneDatabaseTargetLockProcessUsesOwningBackgroundTxn)$' ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout 180s -run '^(TestValidateCloneDatabaseSourceAccess|TestValidateCloneDatabaseAccounts|TestHandleCloneDatabaseWithSourceIfNotExistsSkipsExistingTarget|TestHandleCloneDatabaseWithSourceAuthorizesTargetBeforeIfNotExistsCheck|TestCheckCloneDatabaseTargetSerializesConcurrentIfNotExistsDecisions|TestCheckCloneDatabaseTargetReturnsLockErrors|TestNewCloneDatabaseTargetLockProcessRequiresBackgroundExecutor|TestLockCloneDatabaseTargetRequiresBackgroundExecutor|TestCheckDatabaseExistsAtSnapshot)$' ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -json -count=1 -timeout 120s -run '^TestCheckCloneDatabaseTargetSerializesConcurrentIfNotExistsDecisions$' ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout 120s -run '^TestCheckCloneDatabaseTargetSerializesConcurrentIfNotExistsDecisions$' ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout 20m ./pkg/frontend
  • .agents/skills/mo-dev/scripts/mo-cgo-test -json -count=1 -timeout=180s -run '^TestIssue27040ConcurrentIfNotExistsDatabaseClone$' ./pkg/tests/issues
    — passed (11.71s test, 13.03s package).
  • .agents/skills/mo-dev/scripts/mo-cgo-test -json -race -count=2 -timeout=240s -run '^TestIssue27040ConcurrentIfNotExistsDatabaseClone$' ./pkg/tests/issues
    — passed both iterations (30.30s and 1.65s).
  • .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout 120s ./pkg/sql/parsers/dialect/mysql ./pkg/sql/parsers/tree
  • GOWORK=off CGO_CFLAGS=... go build -mod=readonly ./pkg/frontend
  • GOWORK=off CGO_CFLAGS=... go vet -mod=readonly ./pkg/frontend
  • golangci-lint run -c .golangci.yml ./pkg/frontend
  • make build

Residual risk: the additional exact-key lock deliberately serializes only
concurrent implicit IF NOT EXISTS database clones for the same account and
name; waiting follows the existing session lock timeout. Explicit user
transactions retain their existing shared-transaction semantics.

@gouhongshen

gouhongshen commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

The Launch + Pessimistic BVT job did not build or execute MatrixOne: its Java
setup failed while downloading Temurin 8 after retries with socket hang up.
This external CI dependency failure is tracked in #27075. The Coverage job is
only a downstream failure: it skipped merging because that required BVT
producer failed, before evaluating changed-code coverage. Evidence:
https://github.com/matrixorigin/matrixone/actions/runs/31636329821/job/94247850876
https://github.com/matrixorigin/matrixone/actions/runs/31636329821/job/94258903413

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

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@iamlinjunhong Addressed all three findings in 60ec4a0.

  1. checkDatabaseExistsAtSnapshot now always resolves the effective account
    (including snapshot.Tenant) and adds account_id to the catalog query.
    The distributed regression creates colliding sys/tenant names: sys still
    clones its source, and a tenant-only source is rejected with no sys target.

  2. Database clone account resolution and validation are now a shared,
    single-step operation before the IF NOT EXISTS decision. The unit test and
    BVT cover a non-sys caller using a valid snapshot and an already-existing
    foreign target; it returns the existing only-sys error and the target
    sentinel remains unchanged.

  3. The destination decision now acquires the existing encoded
    (account_id, database_name) catalog-key lock on the owning background
    transaction. Implicit IF NOT EXISTS clones use pessimistic RC, retain the
    lock through CREATE, and restart/recheck after either RC lock-retry code.
    The deterministic two-goroutine test verifies the later decision waits for
    release and sees the created target; the lock-process ownership test and a
    two-client local smoke test cover the actual transaction boundary.

Focused/frontend race tests, parser/tree tests, the distributed BVT, go vet,
and make build pass. The PR description contains the complete behavior and
test matrix. There were no inline review threads to resolve. Please re-review.

@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/XL Denotes a PR that changes [1000, 1999] lines labels Aug 13, 2026
@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH @aptend Both requested-change reviews are valid for the reviewed
head 83119795887559e9ac3b6affd0a76edd04e2f024, and they identify the same
three P1s already addressed in 60ec4a0272:

  • mo_database existence checks now include the effective account_id;
  • clone account authorization runs before every existence-dependent no-op;
  • the target decision is serialized by the owning transaction's exact catalog
    key lock, with RC retry/recheck before CREATE.

The BVT now covers cross-tenant source/target name collisions and the foreign
target authorization path; the frontend concurrency regression plus a
two-client smoke test cover the target race. Full details and commands are in
the updated PR description. Re-requesting review on the new head.

@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 current head 19c5a41317c716acd356bb9fbc70272f2c7ca9db against merge-base bdbd613fdece966769eb68481a3e58bfbc36b30c and current origin/main.

The three P1 findings from my previous review are resolved in the current code: existence reads are account-scoped, cross-account authorization precedes the IF NOT EXISTS no-op, and implicit clones use the same encoded mo_database key in the owning pessimistic-RC background transaction with retry/recheck. I found no remaining P0/P1 blocker.

One P2 test gap remains. The production locking code appears consistent with lockMoDatabase, but the committed concurrency test replaces the exact lock boundary with a stub and therefore cannot prevent this race from regressing. The author's conversation reply and local two-client smoke result are noted, but neither is an automated regression. Details are on the inline comment.

Comment thread pkg/frontend/clone_test.go Resolved

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed the inline concurrency-regression request in b061811; the automated embedded-cluster test now exercises the production lock path with two real sessions.

@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 current head 01138a2eefe29bd33b65d0e680005b01d3ff0572 against merge-base bdbd613fdece966769eb68481a3e58bfbc36b30c after syncing current origin/main at a5288a6b0ad5cddff150f519680d1e24a91eb8dd.

Findings: none (P0/P1/P2/P3: 0).

The prior P2 at pkg/frontend/clone_test.go:631 is resolved. The author explicitly replied in the review thread, and b06181148a6acc3451976607c174c48dce8cb918 adds the requested embedded-cluster regression with two real SQL sessions and the production lock service; 01138a2eefe29bd33b65d0e680005b01d3ff0572 makes the waiter observation robust when the catalog lock table is bound to another CN. The test holds the first transaction through CREATE/commit, observes the second waiter, and verifies the second succeeds with exactly one target and the cloned payload.

I also rechecked the full 17-file diff and relevant call chain: account-scoped source/target existence reads, authorization before the target no-op, exact mo_database key compatibility with lockMoDatabase, owning-transaction lock lifetime, RC retry rollback/begin/relock/recheck, and error cleanup. I found no remaining correctness, concurrency/lifecycle, compatibility, performance, or regression-test issue. All 25 current checks are terminal with no failed conclusion.

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

Deep review of exact head 01138a2eefe29bd33b65d0e680005b01d3ff0572: no blocking findings. The prior account-scope, authorization-order, and check/create atomicity issues are closed. I verified exact-key compatibility with lockMoDatabase, owning-transaction lock lifetime, RC retry/relock/recheck, snapshot/subscription and cleanup paths, and the production two-session lock-service regression. Local frontend full/focused race, parser, vet/list, and TestIssue27040ConcurrentIfNotExistsDatabaseClone all pass.

@XuPeng-SH

Copy link
Copy Markdown
Contributor

@Mergifyio refresh

@mergify

mergify Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

refresh

✅ Pull request refreshed

This branch was previously deployed

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

Labels

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

Projects

None yet

5 participants