Skip to content

fix: support cloning into temporary tables - #27070

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27042-95f434d9
Aug 14, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27042-95f434d9

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 #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 fix: make IF NOT EXISTS table clone a no-op #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.

@gouhongshen

gouhongshen commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor Author

The attempt-2 Ubuntu UT job completed successfully on the same head, so #27073 no longer blocks this PR. The independently reproduced infrastructure issue remains open for triage.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Regarding review PRR_kwDOFEPiGM8AAAABJgVong, I confirmed both reported logical-name paths and the deeper ownership mismatch: COPY GRANTS persists table-object privilege rows, but a temporary destination is session-owned and cataloged under a generated physical name with no matching privilege-row cleanup lifecycle.

Addressed in afb9255ed8 by rejecting Temporary && CopyGrants at the entry to handleCloneTable, before request-context access, transaction creation, snapshot/account resolution, physical creation, or alias publication. The same table-driven unit test covers normal, IF NOT EXISTS, and combined TO ACCOUNT + COPY GRANTS precedence with nil execution dependencies.

The rebuilt distributed regression covers both SQL forms. The normal form is rejected and the name is immediately reusable; the IF NOT EXISTS form is rejected before its existing temporary table is inspected or changed, and its row remains intact. The isolated BVT passed 126/126; the focused regressions passed under -race -count=100, and both owning packages passed complete normal and race suites.

Please re-review the updated head.

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

Re-reviewed exact head afb9255ed8fe0aebc31bbd1812614eca74c843bb. The two prior blockers are closed at the semantic entry point: temporary clones now reject both TO ACCOUNT and COPY GRANTS before execution/state publication, including IF NOT EXISTS precedence. I also rechecked the temporary destination ownership path end to end: deterministic physical main/hidden-index names, restoration through the registered physical relation, late-error/commit-error alias rollback, preservation of pre-existing aliases, and disconnect cleanup via an independent executor scoped to the owning tenant. The distributed regression covers isolation, shadowing, late failure, allocator state, temporary sources, fulltext/IVF hidden tables, both rejected option families, and account-disconnect cleanup. Focused CGo-enabled frontend/compile regressions pass locally; exact-head coverage and BVT checks are green.

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

Blocking: temporary-clone alias ownership is still not transaction-aware.

statementCanBeExecutedInUncommittedTransaction explicitly allows CloneTable, and getBackExecutor uses the shared user transaction when TxnOptions().ByBegin is true. On a successful CREATE TEMPORARY TABLE dst CLONE src, createTable registers the alias immediately and this new defer sees err == nil, so it intentionally keeps the alias. A later user ROLLBACK discards the engine workspace (including the physical temporary relation), but rollbackUnsafe only advances the DDL version and never restores/removes session temporary aliases. Therefore this deterministic public path recreates the original ghost:

BEGIN;
CREATE TEMPORARY TABLE temp_dst CLONE src;
ROLLBACK;
SELECT * FROM temp_dst;                  -- physical relation is gone
CREATE TEMPORARY TABLE temp_dst(id INT); -- alias still returns 1050

The same ownership gap applies when the shared transaction ends in a known commit failure. Statement-error cleanup cannot close a transaction-terminal path. Please make temporary alias publication transaction-aware (preferably a shared temp-DDL journal/snapshot used by all temporary table creation/drop paths, not another CLONE-specific condition): commit preserves the committed mapping, while rollback/known failed commit restores the pre-transaction mapping. Add a public regression matrix for explicit BEGIN + commit, rollback, and pre-existing/IF NOT EXISTS controls; the current BVT only covers autocommit statement failure.

@aunjgr aunjgr 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 . The temporary-clone destination now consistently uses the session-owned physical relation, late failures remove only aliases introduced by the failed statement, and disconnect cleanup runs through an independent executor with the owning tenant identity and safely quoted names. The unsupported and combinations fail before execution or alias publication. Focused exact-head frontend and compile regressions pass locally; all required checks are green. No blocker found.

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

Corrected review summary for exact head afb9255ed8fe0aebc31bbd1812614eca74c843bb: the temporary-clone destination consistently uses the session-owned physical relation; late failures remove only aliases introduced by the failed statement; disconnect cleanup uses an independent executor with the owning tenant identity and safely quoted names; and TO ACCOUNT plus COPY GRANTS are rejected before execution or alias publication. Focused exact-head frontend and compile regressions pass locally, and all required checks are green. No blocker found.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Regarding review PRR_kwDOFEPiGM8AAAABJg8GgA, I reproduced and confirmed the transaction-ownership gap. The engine workspace rolled back the physical temporary relation, while the session alias map had no statement/transaction inverse state and therefore retained the name.

Addressed in b32b55d94c with a shared temporary-alias journal used by all session AddTempTable/RemoveTempTable paths, including mutations forwarded from background executors. Entries are keyed by the actual engine transaction and originating statement: successful statements retain only the transaction inverse; RollbackLastStatement restores that statement; commit keeps the final mapping; full rollback and known commit failure restore the pre-transaction mapping. Unknown commit results intentionally keep the alias so a possibly committed physical relation remains reachable for disconnect cleanup.

The public regression now covers explicit clone commit, clone rollback plus physical-row/alias reuse, pre-existing IF NOT EXISTS across rollback and commit, and temporary drop across rollback and commit. Unit coverage drives statement rollback, full rollback, commit, known commit failure, unknown outcome, and transaction-generation isolation.

Verification on the rebuilt head: isolated BVT 163/163; focused tests -race -count=100; complete pkg/frontend normal and race suites passed; make build passed. The PR description is updated. Please re-review the new head.

@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 re-review completed on exact head b32b55d. The shared temporary-table alias journal closes the prior transaction-ownership blocker across statement rollback, full rollback, normal commit, and known commit failure, including aliases mutated through shared/background sessions. I also rechecked clone cleanup ordering, pre-existing IF NOT EXISTS ownership, temporary DROP rollback/commit, reverse-map restoration, transaction-generation isolation, and the deliberately conservative unknown-commit path. Full pkg/frontend and pkg/sql/compile tests passed; focused lifecycle tests passed under race; an independent repeated-mutation regression passed 20/20 under race; git diff --check is clean. No remaining blocking issue found.

@mergify mergify Bot added the queued label Aug 14, 2026
@mergify

mergify Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-14 05:06 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-08-14 09:08 UTC · at 13b959a1bf5c14d9c297a0441b60f450ca738e4c

This pull request spent 4 hours 1 minute 52 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 #27070 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.

Failing checks:

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

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/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: CREATE TEMPORARY TABLE ... CLONE leaves an unqueryable session ghost after failing

5 participants