Skip to content

fix: make IF NOT EXISTS table clone a no-op - #27056

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27039-8b73875c
Aug 13, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27039-8b73875c

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • FEATURE
  • ENHANCEMENT
  • DOC
  • TEST
  • CHORE
  • PERFORMANCE
  • REFACTOR

Which issue(s) this PR fixes:

Fixes #27039

What this PR does / why we need it:

CREATE TABLE IF NOT EXISTS dst CLONE src treated a successful CreateTable call as proof that dst had been created. For an existing target, CreateTable correctly returned success for the IF NOT EXISTS no-op, but TableClone then unconditionally entered RestoreTable. That block-clone path could append source physical objects to dst, bypassing primary-key enforcement.

This change exposes the authoritative physical-create boundary to the clone caller. TableClone restores source objects only when this invocation created the destination; an existing IF NOT EXISTS target returns success with no clone-side work. Normal CreateTable callers retain their API and behavior.

Regression coverage proves:

  • overlapping primary keys retain the original target rows, schema, and zero duplicate keys;
  • an incompatible source cannot affect an existing target;
  • a secondary-index target retains metadata, query results, and hidden index-table contents;
  • temporary-table clones follow the same no-op rule;
  • the no-IF NOT EXISTS table-exists error remains atomic; and
  • IF NOT EXISTS still performs a normal clone when it creates a new target.

Tests:

  • Rebased onto 6a29b7d47eae06b414cce51ede4a129b6da9b68a before final verification.
  • Built a fresh local mo-service from the rebased head; generated and manually inspected test/distributed/cases/git4data/clone/clone_table_if_not_exists.result against an isolated single-process instance.
  • BVT compare run: 56/56 successful assertions.
  • GOWORK=off CGO_CFLAGS="-I$PWD/cgo -I$PWD/thirdparties/install/include" go build -mod=readonly ./pkg/sql/compile
  • GOWORK=off CGO_CFLAGS="-I$PWD/cgo -I$PWD/thirdparties/install/include" go vet -mod=readonly ./pkg/sql/compile
  • .agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s ./pkg/sql/compile

Risk:

The change gates clone restoration on the existing authoritative creation outcome. It adds no catalog format, plan, synchronization, cleanup, or fallback behavior. The BVT covers both the existing-target no-op and newly-created-target restore paths.

@gouhongshen
gouhongshen force-pushed the agent/issue-27039-8b73875c branch from 2d48ded to 63bbdb6 Compare August 12, 2026 16:59
@gouhongshen
gouhongshen marked this pull request as ready for review August 12, 2026 16:59
@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

CI blocker is unrelated to this PR's clone change. In run 31620340116, the coverage-enabled pessimistic BVT job reached its configured 75-minute job limit during an unrelated snapshot case. This PR's clone_table_if_not_exists.sql had already passed there (56/56). The red Coverage check only failed its prerequisite guard because that producer was cancelled. Tracked in #27071; attempt 1 will be retried once as required.

@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-reviewed at bc82f78. The creation signal is taken at the authoritative Database.Create boundary: existing regular and temporary IF NOT EXISTS targets return before it, while a newly created target continues through the existing RestoreTable path. Public CreateTable behavior is unchanged. Regression BVT covers rows/schema, incompatible schemas, secondary-index metadata and hidden-table contents, temporary tables, the non-IF-NOT-EXISTS error path, and the new-target control. Local GOWORK=off build/vet and the CGo-linked full ./pkg/sql/compile test suite pass. No blocking findings.

@XuPeng-SH
XuPeng-SH merged commit 1cd1b9b into matrixorigin:main Aug 13, 2026
0 of 4 checks passed
XuPeng-SH pushed a commit that referenced this pull request Aug 14, 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:

Fixes #27042

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

### Root cause

`CREATE TEMPORARY TABLE dst CLONE src` created the destination under its
generated session-local physical name, but the clone operator and
indexed-table restore path still opened the user alias. The block clone
therefore returned `no such table` after `CreateTable` had already
published the alias. Transaction rollback removed the physical table,
while the session alias remained and made every later `CREATE TEMPORARY
TABLE dst ...` report that the table already existed.

Three adjacent ownership gaps could produce the same class of stale
state:

- Late frontend/commit failures happened after compile-side alias
registration, and session-close cleanup used the closing session's
background executor without the owning tenant in its context.
- The alias maps were session side state, not part of the engine
workspace. Temporary create/drop mutations inside an explicit
transaction therefore survived `RollbackLastStatement`, full `ROLLBACK`,
and known commit failure even though their physical relations were
discarded.
- The grammar admitted `TO ACCOUNT` and `COPY GRANTS` combinations
without a coherent temporary-table ownership model. The former separates
the physical tenant from the owning session; the latter creates
persistent privilege rows whose identity and cleanup do not match a
session-owned physical relation.

### Changes

- Centralize generated temporary physical-name selection and pass that
name to the clone operator.
- Resolve temporary clone restore metadata from the created physical
relation, including hidden FULLTEXT/IVF index tables.
- Remove only aliases introduced by a failed clone after background
transaction commit/rollback completes; preserve pre-existing aliases.
- Journal all session temporary-alias mutations by engine transaction
and statement. Successful statements retain transaction rollback state;
statement rollback restores only that statement; commit keeps the final
mapping; full rollback and known commit failure restore the
pre-transaction mapping. Unknown commit results retain aliases so
disconnect cleanup can still reach a possibly committed physical
relation.
- Attribute aliases changed by background executors to the originating
user session while retaining the background/shared engine transaction
identity.
- Run asynchronous session-close cleanup through the service internal
SQL executor with the owning account/user/role and safely quoted
physical identifiers.
- Reject temporary clone destinations combined with `TO ACCOUNT` or
`COPY GRANTS` before clone execution creates any state.
- Add focused compile/frontend tests and a distributed same-session
regression covering the reported reproduction and directly related
transaction, lifecycle, option, and account boundaries.
- Rebase onto `bdbd613fde`; resolve the overlap with #27056 by retaining
upstream's authoritative `createTable` callback/no-op handling and
removing this PR's duplicate mutable scope state and duplicate
permanent-destination tests.

### Issue-to-test proof

- Physical destination selection:
`TestConstructTableCloneUsesPhysicalTemporaryDestination` asserts the
operator receives the generated physical name.
- Restore validation:
`TestScopeRestoreTemporaryCloneValidatesPhysicalDestination` covers
missing session/alias state and proves database and physical-relation
lookup errors are preserved.
- Failure atomicity:
`TestScopeCreateTemporaryTableRollsBackAliasAfterLateFailure` and
`TestRemoveFailedTemporaryCloneAlias` cover compile-side rollback,
new-alias removal, pre-existing-alias preservation, and success. The BVT
injects a late clone failure, asserts no physical catalog row, and
immediately reuses the alias.
- Transaction ownership: `TestSessionTempTableTransactionJournal` proves
statement-local inverse restoration, full transaction rollback, commit
preservation, and generation isolation.
`TestTempTableAliasesFollowTransactionLifecycle` drives the real
transaction terminal paths for commit, rollback, statement rollback,
known commit failure, and unknown commit result.
- Explicit transaction SQL: `temporary_table_clone.sql` proves a
committed clone remains queryable, a rolled-back clone leaves no
physical row or alias and permits immediate reuse, `IF NOT EXISTS`
preserves pre-existing mappings across commit/rollback, and
transactional drop restores on rollback and releases on commit.
- Disconnect cleanup:
`TestSessionCloseDropsTemporaryTablesAsOwningTenant` asserts
account/user/role execution options and identifier quoting; the BVT
closes a live account session and polls until the physical temporary
relation is gone.
- Unsupported option boundary:
`TestHandleCloneTableRejectsUnsupportedTemporaryOptionsBeforeExecution`
passes nil execution dependencies and covers `TO ACCOUNT`, `COPY
GRANTS`, `IF NOT EXISTS ... COPY GRANTS`, and combined-option
precedence, proving rejection precedes all execution/state creation. The
BVT exercises the sys-to-account snapshot form and both `COPY GRANTS`
forms; it proves immediate name reuse, preservation of a pre-existing
temporary table, session close, and absence of a target-account physical
relation or alias.
- End-to-end SQL semantics: `temporary_table_clone.sql` additionally
covers exact schema/rows, same-session duplicate creates and `IF NOT
EXISTS`, second-session isolation, drop/reuse, source shadowing, empty
and auto-increment sources, temporary sources, unsupported FK/partition
failure atomicity, FULLTEXT/IVFFLAT hidden tables, unsupported option
atomicity, and disconnect cleanup.

### Tests run

- `GOWORK=off go list -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- CGo-configured `go build -mod=readonly ./pkg/sql/compile
./pkg/frontend`
- CGo-configured `go vet -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=600s
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=20m
./pkg/frontend`
- Directly affected compile/frontend regressions under `-race
-count=100`, including the new alias-journal and transaction-terminal
tests.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1
-timeout=600s ./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=30m
./pkg/frontend`
- `make build`
- Manual explicit-transaction SQL against the rebuilt binary: clone
commit, clone rollback/reuse, pre-existing `IF NOT EXISTS`, and
temporary drop commit/rollback all matched the intended mapping and
physical-relation lifecycle.
- Distributed BVT against the rebuilt binary in an isolated
single-process cluster using canonical `matrixorigin/mo-tester` main:
163/163 statements passed. The generated output and checked-in result
were manually checked against the intended SQL semantics.

### Residual risks

Session-close physical cleanup remains asynchronous by design, is
bounded by a one-minute context, and logs per-table failures while
continuing cleanup. The distributed regression waits for and observes
successful cleanup. An unknown commit outcome deliberately retains the
alias because the physical relation may have committed; this keeps it
reachable for session use or disconnect cleanup rather than risking an
untracked physical leak. `TO ACCOUNT` and `COPY GRANTS` remain explicit
invalid-input boundaries for temporary clone destinations because their
cross-tenant and persistent privilege state cannot be owned coherently
by a session-local relation.

---------

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
## What type of PR is this?

- [x] BUG
- [ ] FEATURE
- [ ] ENHANCEMENT
- [ ] DOC
- [ ] TEST
- [ ] CHORE
- [ ] PERFORMANCE
- [ ] REFACTOR

## Which issue(s) this PR fixes:

Fixes matrixorigin#27039

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

`CREATE TABLE IF NOT EXISTS dst CLONE src` treated a successful
`CreateTable` call as proof that `dst` had been created. For an existing
target, `CreateTable` correctly returned success for the `IF NOT EXISTS`
no-op, but `TableClone` then unconditionally entered `RestoreTable`.
That block-clone path could append source physical objects to `dst`,
bypassing primary-key enforcement.

This change exposes the authoritative physical-create boundary to the
clone caller. `TableClone` restores source objects only when this
invocation created the destination; an existing `IF NOT EXISTS` target
returns success with no clone-side work. Normal `CreateTable` callers
retain their API and behavior.

Regression coverage proves:

- overlapping primary keys retain the original target rows, schema, and
zero duplicate keys;
- an incompatible source cannot affect an existing target;
- a secondary-index target retains metadata, query results, and hidden
index-table contents;
- temporary-table clones follow the same no-op rule;
- the no-`IF NOT EXISTS` table-exists error remains atomic; and
- `IF NOT EXISTS` still performs a normal clone when it creates a new
target.

## Tests:

- Rebased onto `6a29b7d47eae06b414cce51ede4a129b6da9b68a` before final
verification.
- Built a fresh local `mo-service` from the rebased head; generated and
manually inspected
`test/distributed/cases/git4data/clone/clone_table_if_not_exists.result`
against an isolated single-process instance.
- BVT compare run: 56/56 successful assertions.
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go build -mod=readonly
./pkg/sql/compile`
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go vet -mod=readonly
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s
./pkg/sql/compile`

## Risk:

The change gates clone restoration on the existing authoritative
creation outcome. It adds no catalog format, plan, synchronization,
cleanup, or fallback behavior. The BVT covers both the existing-target
no-op and newly-created-target restore paths.

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 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:

Fixes matrixorigin#27042

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

### Root cause

`CREATE TEMPORARY TABLE dst CLONE src` created the destination under its
generated session-local physical name, but the clone operator and
indexed-table restore path still opened the user alias. The block clone
therefore returned `no such table` after `CreateTable` had already
published the alias. Transaction rollback removed the physical table,
while the session alias remained and made every later `CREATE TEMPORARY
TABLE dst ...` report that the table already existed.

Three adjacent ownership gaps could produce the same class of stale
state:

- Late frontend/commit failures happened after compile-side alias
registration, and session-close cleanup used the closing session's
background executor without the owning tenant in its context.
- The alias maps were session side state, not part of the engine
workspace. Temporary create/drop mutations inside an explicit
transaction therefore survived `RollbackLastStatement`, full `ROLLBACK`,
and known commit failure even though their physical relations were
discarded.
- The grammar admitted `TO ACCOUNT` and `COPY GRANTS` combinations
without a coherent temporary-table ownership model. The former separates
the physical tenant from the owning session; the latter creates
persistent privilege rows whose identity and cleanup do not match a
session-owned physical relation.

### Changes

- Centralize generated temporary physical-name selection and pass that
name to the clone operator.
- Resolve temporary clone restore metadata from the created physical
relation, including hidden FULLTEXT/IVF index tables.
- Remove only aliases introduced by a failed clone after background
transaction commit/rollback completes; preserve pre-existing aliases.
- Journal all session temporary-alias mutations by engine transaction
and statement. Successful statements retain transaction rollback state;
statement rollback restores only that statement; commit keeps the final
mapping; full rollback and known commit failure restore the
pre-transaction mapping. Unknown commit results retain aliases so
disconnect cleanup can still reach a possibly committed physical
relation.
- Attribute aliases changed by background executors to the originating
user session while retaining the background/shared engine transaction
identity.
- Run asynchronous session-close cleanup through the service internal
SQL executor with the owning account/user/role and safely quoted
physical identifiers.
- Reject temporary clone destinations combined with `TO ACCOUNT` or
`COPY GRANTS` before clone execution creates any state.
- Add focused compile/frontend tests and a distributed same-session
regression covering the reported reproduction and directly related
transaction, lifecycle, option, and account boundaries.
- Rebase onto `bdbd613fde`; resolve the overlap with matrixorigin#27056 by retaining
upstream's authoritative `createTable` callback/no-op handling and
removing this PR's duplicate mutable scope state and duplicate
permanent-destination tests.

### Issue-to-test proof

- Physical destination selection:
`TestConstructTableCloneUsesPhysicalTemporaryDestination` asserts the
operator receives the generated physical name.
- Restore validation:
`TestScopeRestoreTemporaryCloneValidatesPhysicalDestination` covers
missing session/alias state and proves database and physical-relation
lookup errors are preserved.
- Failure atomicity:
`TestScopeCreateTemporaryTableRollsBackAliasAfterLateFailure` and
`TestRemoveFailedTemporaryCloneAlias` cover compile-side rollback,
new-alias removal, pre-existing-alias preservation, and success. The BVT
injects a late clone failure, asserts no physical catalog row, and
immediately reuses the alias.
- Transaction ownership: `TestSessionTempTableTransactionJournal` proves
statement-local inverse restoration, full transaction rollback, commit
preservation, and generation isolation.
`TestTempTableAliasesFollowTransactionLifecycle` drives the real
transaction terminal paths for commit, rollback, statement rollback,
known commit failure, and unknown commit result.
- Explicit transaction SQL: `temporary_table_clone.sql` proves a
committed clone remains queryable, a rolled-back clone leaves no
physical row or alias and permits immediate reuse, `IF NOT EXISTS`
preserves pre-existing mappings across commit/rollback, and
transactional drop restores on rollback and releases on commit.
- Disconnect cleanup:
`TestSessionCloseDropsTemporaryTablesAsOwningTenant` asserts
account/user/role execution options and identifier quoting; the BVT
closes a live account session and polls until the physical temporary
relation is gone.
- Unsupported option boundary:
`TestHandleCloneTableRejectsUnsupportedTemporaryOptionsBeforeExecution`
passes nil execution dependencies and covers `TO ACCOUNT`, `COPY
GRANTS`, `IF NOT EXISTS ... COPY GRANTS`, and combined-option
precedence, proving rejection precedes all execution/state creation. The
BVT exercises the sys-to-account snapshot form and both `COPY GRANTS`
forms; it proves immediate name reuse, preservation of a pre-existing
temporary table, session close, and absence of a target-account physical
relation or alias.
- End-to-end SQL semantics: `temporary_table_clone.sql` additionally
covers exact schema/rows, same-session duplicate creates and `IF NOT
EXISTS`, second-session isolation, drop/reuse, source shadowing, empty
and auto-increment sources, temporary sources, unsupported FK/partition
failure atomicity, FULLTEXT/IVFFLAT hidden tables, unsupported option
atomicity, and disconnect cleanup.

### Tests run

- `GOWORK=off go list -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- CGo-configured `go build -mod=readonly ./pkg/sql/compile
./pkg/frontend`
- CGo-configured `go vet -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=600s
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=20m
./pkg/frontend`
- Directly affected compile/frontend regressions under `-race
-count=100`, including the new alias-journal and transaction-terminal
tests.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1
-timeout=600s ./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=30m
./pkg/frontend`
- `make build`
- Manual explicit-transaction SQL against the rebuilt binary: clone
commit, clone rollback/reuse, pre-existing `IF NOT EXISTS`, and
temporary drop commit/rollback all matched the intended mapping and
physical-relation lifecycle.
- Distributed BVT against the rebuilt binary in an isolated
single-process cluster using canonical `matrixorigin/mo-tester` main:
163/163 statements passed. The generated output and checked-in result
were manually checked against the intended SQL semantics.

### Residual risks

Session-close physical cleanup remains asynchronous by design, is
bounded by a one-minute context, and logs per-table failures while
continuing cleanup. The distributed regression waits for and observes
successful cleanup. An unknown commit outcome deliberately retains the
alias because the physical relation may have committed; this keeps it
reachable for session use or disconnect cleanup rather than risking an
untracked physical leak. `TO ACCOUNT` and `COPY GRANTS` remain explicit
invalid-input boundaries for temporary clone destinations because their
cross-tenant and persistent privilege state cannot be owned coherently
by a session-local relation.

---------

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
## What type of PR is this?

- [x] BUG
- [ ] FEATURE
- [ ] ENHANCEMENT
- [ ] DOC
- [ ] TEST
- [ ] CHORE
- [ ] PERFORMANCE
- [ ] REFACTOR

## Which issue(s) this PR fixes:

Fixes matrixorigin#27039

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

`CREATE TABLE IF NOT EXISTS dst CLONE src` treated a successful
`CreateTable` call as proof that `dst` had been created. For an existing
target, `CreateTable` correctly returned success for the `IF NOT EXISTS`
no-op, but `TableClone` then unconditionally entered `RestoreTable`.
That block-clone path could append source physical objects to `dst`,
bypassing primary-key enforcement.

This change exposes the authoritative physical-create boundary to the
clone caller. `TableClone` restores source objects only when this
invocation created the destination; an existing `IF NOT EXISTS` target
returns success with no clone-side work. Normal `CreateTable` callers
retain their API and behavior.

Regression coverage proves:

- overlapping primary keys retain the original target rows, schema, and
zero duplicate keys;
- an incompatible source cannot affect an existing target;
- a secondary-index target retains metadata, query results, and hidden
index-table contents;
- temporary-table clones follow the same no-op rule;
- the no-`IF NOT EXISTS` table-exists error remains atomic; and
- `IF NOT EXISTS` still performs a normal clone when it creates a new
target.

## Tests:

- Rebased onto `6a29b7d47eae06b414cce51ede4a129b6da9b68a` before final
verification.
- Built a fresh local `mo-service` from the rebased head; generated and
manually inspected
`test/distributed/cases/git4data/clone/clone_table_if_not_exists.result`
against an isolated single-process instance.
- BVT compare run: 56/56 successful assertions.
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go build -mod=readonly
./pkg/sql/compile`
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go vet -mod=readonly
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s
./pkg/sql/compile`

## Risk:

The change gates clone restoration on the existing authoritative
creation outcome. It adds no catalog format, plan, synchronization,
cleanup, or fallback behavior. The BVT covers both the existing-target
no-op and newly-created-target restore paths.

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 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:

Fixes matrixorigin#27042

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

### Root cause

`CREATE TEMPORARY TABLE dst CLONE src` created the destination under its
generated session-local physical name, but the clone operator and
indexed-table restore path still opened the user alias. The block clone
therefore returned `no such table` after `CreateTable` had already
published the alias. Transaction rollback removed the physical table,
while the session alias remained and made every later `CREATE TEMPORARY
TABLE dst ...` report that the table already existed.

Three adjacent ownership gaps could produce the same class of stale
state:

- Late frontend/commit failures happened after compile-side alias
registration, and session-close cleanup used the closing session's
background executor without the owning tenant in its context.
- The alias maps were session side state, not part of the engine
workspace. Temporary create/drop mutations inside an explicit
transaction therefore survived `RollbackLastStatement`, full `ROLLBACK`,
and known commit failure even though their physical relations were
discarded.
- The grammar admitted `TO ACCOUNT` and `COPY GRANTS` combinations
without a coherent temporary-table ownership model. The former separates
the physical tenant from the owning session; the latter creates
persistent privilege rows whose identity and cleanup do not match a
session-owned physical relation.

### Changes

- Centralize generated temporary physical-name selection and pass that
name to the clone operator.
- Resolve temporary clone restore metadata from the created physical
relation, including hidden FULLTEXT/IVF index tables.
- Remove only aliases introduced by a failed clone after background
transaction commit/rollback completes; preserve pre-existing aliases.
- Journal all session temporary-alias mutations by engine transaction
and statement. Successful statements retain transaction rollback state;
statement rollback restores only that statement; commit keeps the final
mapping; full rollback and known commit failure restore the
pre-transaction mapping. Unknown commit results retain aliases so
disconnect cleanup can still reach a possibly committed physical
relation.
- Attribute aliases changed by background executors to the originating
user session while retaining the background/shared engine transaction
identity.
- Run asynchronous session-close cleanup through the service internal
SQL executor with the owning account/user/role and safely quoted
physical identifiers.
- Reject temporary clone destinations combined with `TO ACCOUNT` or
`COPY GRANTS` before clone execution creates any state.
- Add focused compile/frontend tests and a distributed same-session
regression covering the reported reproduction and directly related
transaction, lifecycle, option, and account boundaries.
- Rebase onto `bdbd613fde`; resolve the overlap with matrixorigin#27056 by retaining
upstream's authoritative `createTable` callback/no-op handling and
removing this PR's duplicate mutable scope state and duplicate
permanent-destination tests.

### Issue-to-test proof

- Physical destination selection:
`TestConstructTableCloneUsesPhysicalTemporaryDestination` asserts the
operator receives the generated physical name.
- Restore validation:
`TestScopeRestoreTemporaryCloneValidatesPhysicalDestination` covers
missing session/alias state and proves database and physical-relation
lookup errors are preserved.
- Failure atomicity:
`TestScopeCreateTemporaryTableRollsBackAliasAfterLateFailure` and
`TestRemoveFailedTemporaryCloneAlias` cover compile-side rollback,
new-alias removal, pre-existing-alias preservation, and success. The BVT
injects a late clone failure, asserts no physical catalog row, and
immediately reuses the alias.
- Transaction ownership: `TestSessionTempTableTransactionJournal` proves
statement-local inverse restoration, full transaction rollback, commit
preservation, and generation isolation.
`TestTempTableAliasesFollowTransactionLifecycle` drives the real
transaction terminal paths for commit, rollback, statement rollback,
known commit failure, and unknown commit result.
- Explicit transaction SQL: `temporary_table_clone.sql` proves a
committed clone remains queryable, a rolled-back clone leaves no
physical row or alias and permits immediate reuse, `IF NOT EXISTS`
preserves pre-existing mappings across commit/rollback, and
transactional drop restores on rollback and releases on commit.
- Disconnect cleanup:
`TestSessionCloseDropsTemporaryTablesAsOwningTenant` asserts
account/user/role execution options and identifier quoting; the BVT
closes a live account session and polls until the physical temporary
relation is gone.
- Unsupported option boundary:
`TestHandleCloneTableRejectsUnsupportedTemporaryOptionsBeforeExecution`
passes nil execution dependencies and covers `TO ACCOUNT`, `COPY
GRANTS`, `IF NOT EXISTS ... COPY GRANTS`, and combined-option
precedence, proving rejection precedes all execution/state creation. The
BVT exercises the sys-to-account snapshot form and both `COPY GRANTS`
forms; it proves immediate name reuse, preservation of a pre-existing
temporary table, session close, and absence of a target-account physical
relation or alias.
- End-to-end SQL semantics: `temporary_table_clone.sql` additionally
covers exact schema/rows, same-session duplicate creates and `IF NOT
EXISTS`, second-session isolation, drop/reuse, source shadowing, empty
and auto-increment sources, temporary sources, unsupported FK/partition
failure atomicity, FULLTEXT/IVFFLAT hidden tables, unsupported option
atomicity, and disconnect cleanup.

### Tests run

- `GOWORK=off go list -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- CGo-configured `go build -mod=readonly ./pkg/sql/compile
./pkg/frontend`
- CGo-configured `go vet -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=600s
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=20m
./pkg/frontend`
- Directly affected compile/frontend regressions under `-race
-count=100`, including the new alias-journal and transaction-terminal
tests.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1
-timeout=600s ./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=30m
./pkg/frontend`
- `make build`
- Manual explicit-transaction SQL against the rebuilt binary: clone
commit, clone rollback/reuse, pre-existing `IF NOT EXISTS`, and
temporary drop commit/rollback all matched the intended mapping and
physical-relation lifecycle.
- Distributed BVT against the rebuilt binary in an isolated
single-process cluster using canonical `matrixorigin/mo-tester` main:
163/163 statements passed. The generated output and checked-in result
were manually checked against the intended SQL semantics.

### Residual risks

Session-close physical cleanup remains asynchronous by design, is
bounded by a one-minute context, and logs per-table failures while
continuing cleanup. The distributed regression waits for and observes
successful cleanup. An unknown commit outcome deliberately retains the
alias because the physical relation may have committed; this keeps it
reachable for session use or disconnect cleanup rather than risking an
untracked physical leak. `TO ACCOUNT` and `COPY GRANTS` remain explicit
invalid-input boundaries for temporary clone destinations because their
cross-tenant and persistent privilege state cannot be owned coherently
by a session-local relation.

---------

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
## What type of PR is this?

- [x] BUG
- [ ] FEATURE
- [ ] ENHANCEMENT
- [ ] DOC
- [ ] TEST
- [ ] CHORE
- [ ] PERFORMANCE
- [ ] REFACTOR

## Which issue(s) this PR fixes:

Fixes matrixorigin#27039

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

`CREATE TABLE IF NOT EXISTS dst CLONE src` treated a successful
`CreateTable` call as proof that `dst` had been created. For an existing
target, `CreateTable` correctly returned success for the `IF NOT EXISTS`
no-op, but `TableClone` then unconditionally entered `RestoreTable`.
That block-clone path could append source physical objects to `dst`,
bypassing primary-key enforcement.

This change exposes the authoritative physical-create boundary to the
clone caller. `TableClone` restores source objects only when this
invocation created the destination; an existing `IF NOT EXISTS` target
returns success with no clone-side work. Normal `CreateTable` callers
retain their API and behavior.

Regression coverage proves:

- overlapping primary keys retain the original target rows, schema, and
zero duplicate keys;
- an incompatible source cannot affect an existing target;
- a secondary-index target retains metadata, query results, and hidden
index-table contents;
- temporary-table clones follow the same no-op rule;
- the no-`IF NOT EXISTS` table-exists error remains atomic; and
- `IF NOT EXISTS` still performs a normal clone when it creates a new
target.

## Tests:

- Rebased onto `6a29b7d47eae06b414cce51ede4a129b6da9b68a` before final
verification.
- Built a fresh local `mo-service` from the rebased head; generated and
manually inspected
`test/distributed/cases/git4data/clone/clone_table_if_not_exists.result`
against an isolated single-process instance.
- BVT compare run: 56/56 successful assertions.
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go build -mod=readonly
./pkg/sql/compile`
- `GOWORK=off CGO_CFLAGS="-I$PWD/cgo
-I$PWD/thirdparties/install/include" go vet -mod=readonly
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -v -count=1 -timeout=120s
./pkg/sql/compile`

## Risk:

The change gates clone restoration on the existing authoritative
creation outcome. It adds no catalog format, plan, synchronization,
cleanup, or fallback behavior. The BVT covers both the existing-target
no-op and newly-created-target restore paths.

Co-authored-by: XuPeng-SH <[email protected]>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 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:

Fixes matrixorigin#27042

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

### Root cause

`CREATE TEMPORARY TABLE dst CLONE src` created the destination under its
generated session-local physical name, but the clone operator and
indexed-table restore path still opened the user alias. The block clone
therefore returned `no such table` after `CreateTable` had already
published the alias. Transaction rollback removed the physical table,
while the session alias remained and made every later `CREATE TEMPORARY
TABLE dst ...` report that the table already existed.

Three adjacent ownership gaps could produce the same class of stale
state:

- Late frontend/commit failures happened after compile-side alias
registration, and session-close cleanup used the closing session's
background executor without the owning tenant in its context.
- The alias maps were session side state, not part of the engine
workspace. Temporary create/drop mutations inside an explicit
transaction therefore survived `RollbackLastStatement`, full `ROLLBACK`,
and known commit failure even though their physical relations were
discarded.
- The grammar admitted `TO ACCOUNT` and `COPY GRANTS` combinations
without a coherent temporary-table ownership model. The former separates
the physical tenant from the owning session; the latter creates
persistent privilege rows whose identity and cleanup do not match a
session-owned physical relation.

### Changes

- Centralize generated temporary physical-name selection and pass that
name to the clone operator.
- Resolve temporary clone restore metadata from the created physical
relation, including hidden FULLTEXT/IVF index tables.
- Remove only aliases introduced by a failed clone after background
transaction commit/rollback completes; preserve pre-existing aliases.
- Journal all session temporary-alias mutations by engine transaction
and statement. Successful statements retain transaction rollback state;
statement rollback restores only that statement; commit keeps the final
mapping; full rollback and known commit failure restore the
pre-transaction mapping. Unknown commit results retain aliases so
disconnect cleanup can still reach a possibly committed physical
relation.
- Attribute aliases changed by background executors to the originating
user session while retaining the background/shared engine transaction
identity.
- Run asynchronous session-close cleanup through the service internal
SQL executor with the owning account/user/role and safely quoted
physical identifiers.
- Reject temporary clone destinations combined with `TO ACCOUNT` or
`COPY GRANTS` before clone execution creates any state.
- Add focused compile/frontend tests and a distributed same-session
regression covering the reported reproduction and directly related
transaction, lifecycle, option, and account boundaries.
- Rebase onto `bdbd613fde`; resolve the overlap with matrixorigin#27056 by retaining
upstream's authoritative `createTable` callback/no-op handling and
removing this PR's duplicate mutable scope state and duplicate
permanent-destination tests.

### Issue-to-test proof

- Physical destination selection:
`TestConstructTableCloneUsesPhysicalTemporaryDestination` asserts the
operator receives the generated physical name.
- Restore validation:
`TestScopeRestoreTemporaryCloneValidatesPhysicalDestination` covers
missing session/alias state and proves database and physical-relation
lookup errors are preserved.
- Failure atomicity:
`TestScopeCreateTemporaryTableRollsBackAliasAfterLateFailure` and
`TestRemoveFailedTemporaryCloneAlias` cover compile-side rollback,
new-alias removal, pre-existing-alias preservation, and success. The BVT
injects a late clone failure, asserts no physical catalog row, and
immediately reuses the alias.
- Transaction ownership: `TestSessionTempTableTransactionJournal` proves
statement-local inverse restoration, full transaction rollback, commit
preservation, and generation isolation.
`TestTempTableAliasesFollowTransactionLifecycle` drives the real
transaction terminal paths for commit, rollback, statement rollback,
known commit failure, and unknown commit result.
- Explicit transaction SQL: `temporary_table_clone.sql` proves a
committed clone remains queryable, a rolled-back clone leaves no
physical row or alias and permits immediate reuse, `IF NOT EXISTS`
preserves pre-existing mappings across commit/rollback, and
transactional drop restores on rollback and releases on commit.
- Disconnect cleanup:
`TestSessionCloseDropsTemporaryTablesAsOwningTenant` asserts
account/user/role execution options and identifier quoting; the BVT
closes a live account session and polls until the physical temporary
relation is gone.
- Unsupported option boundary:
`TestHandleCloneTableRejectsUnsupportedTemporaryOptionsBeforeExecution`
passes nil execution dependencies and covers `TO ACCOUNT`, `COPY
GRANTS`, `IF NOT EXISTS ... COPY GRANTS`, and combined-option
precedence, proving rejection precedes all execution/state creation. The
BVT exercises the sys-to-account snapshot form and both `COPY GRANTS`
forms; it proves immediate name reuse, preservation of a pre-existing
temporary table, session close, and absence of a target-account physical
relation or alias.
- End-to-end SQL semantics: `temporary_table_clone.sql` additionally
covers exact schema/rows, same-session duplicate creates and `IF NOT
EXISTS`, second-session isolation, drop/reuse, source shadowing, empty
and auto-increment sources, temporary sources, unsupported FK/partition
failure atomicity, FULLTEXT/IVFFLAT hidden tables, unsupported option
atomicity, and disconnect cleanup.

### Tests run

- `GOWORK=off go list -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- CGo-configured `go build -mod=readonly ./pkg/sql/compile
./pkg/frontend`
- CGo-configured `go vet -mod=readonly ./pkg/sql/compile ./pkg/frontend`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=600s
./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=20m
./pkg/frontend`
- Directly affected compile/frontend regressions under `-race
-count=100`, including the new alias-journal and transaction-terminal
tests.
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1
-timeout=600s ./pkg/sql/compile`
- `.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=30m
./pkg/frontend`
- `make build`
- Manual explicit-transaction SQL against the rebuilt binary: clone
commit, clone rollback/reuse, pre-existing `IF NOT EXISTS`, and
temporary drop commit/rollback all matched the intended mapping and
physical-relation lifecycle.
- Distributed BVT against the rebuilt binary in an isolated
single-process cluster using canonical `matrixorigin/mo-tester` main:
163/163 statements passed. The generated output and checked-in result
were manually checked against the intended SQL semantics.

### Residual risks

Session-close physical cleanup remains asynchronous by design, is
bounded by a one-minute context, and logs per-table failures while
continuing cleanup. The distributed regression waits for and observes
successful cleanup. An unknown commit outcome deliberately retains the
alias because the physical relation may have committed; this keeps it
reachable for session use or disconnect cleanup rather than risking an
untracked physical leak. `TO ACCOUNT` and `COPY GRANTS` remain explicit
invalid-input boundaries for temporary clone destinations because their
cross-tenant and persistent privilege state cannot be owned coherently
by a session-local relation.

---------

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.

[Bug]: CREATE TABLE IF NOT EXISTS ... CLONE mutates an existing table and creates duplicate primary keys

3 participants