Skip to content

fix(clone): skip external tables in database clone - #28146

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27103-eb967920
Sep 5, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-27103-eb967920

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Sep 4, 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:

Related to #27103

What this PR does / why we need it:

Root cause

Database CLONE enumerated external relations with the source table list. The
general clone loop excluded views and sequences only, so an external relation
was sent through the base-table clone path and failed with is not BASE TABLE.
The same unfiltered list also drove DATA BRANCH source authorization, table
quota accounting, source locking, and timestamp revalidation.

Changes

  • Define one cloneable relation set from the existing bulk-restore external
    table policy and reuse it for database-clone execution, foreign-key routing,
    DATA BRANCH authorization, and quota accounting.
  • Keep external catalog rows in the DATA BRANCH lifecycle lock and timestamp
    revalidation fence because post-lock view dependency planning reads their
    metadata; this prevents concurrent DROP/ALTER from changing the generation
    being resolved.
  • Skip external relations while preserving the target database and all
    supported ordinary tables. An external-only source therefore creates an
    empty target database without copying external files or data.
  • Compute the omitted external/view dependency closure with the existing SQL
    AST walker. SQL UDFs and stored procedures that directly or transitively
    depend on an omitted relation or routine are omitted; independent SQL
    routine families are copied and rewritten for the target database.
  • Track visible CTE names, including nested and recursive WITH scopes, so
    unqualified CTE references are not falsely collected as base-table
    dependencies while qualified references remain visible.
  • Treat UDF overloads with the same database, name, and kind as one conservative
    family. If dependency inspection omits one overload, the whole family is
    omitted because clone-time metadata inspection cannot safely resolve overload
    types at every call site. This contract is documented in the clone guide and
    covered by mixed-overload/caller propagation tests.
  • Uninspectable routines are conservatively omitted when the source contains an
    omitted relation.
  • Document the external-table and dependent-object contract in the clone guide.
  • Replace fixed BVT sleep with catalog readiness polling and deterministic
    cleanup assertions, using a valid one-second polling interval for mo-tester.
  • Return early from dependency-closure analysis when no relation is initially
    omitted, avoiding a second parse of every view in the normal clone path.

Issue-to-test proof

  • test/distributed/cases/git4data/clone/issue_27103_clone_external_table.sql
    uses a local-file external table plus an ordinary table and covers live and
    snapshot database CLONE. It verifies the target database, ordinary rows,
    absence of external-table metadata, skipped dependent views, independent SQL
    UDF/procedure execution, omission of direct and transitive dependent UDFs and
    procedures, and source external-table readability after live cloning.
  • The same BVT covers an external-only source and a non-admin DATA BRANCH source
    where SELECT is granted only on the ordinary table; both succeed and omit the
    external relation.
  • Frontend UTs cover the cloneable relation set, routine dependency closure,
    nested/recursive CTE scoping, mixed UDF overload-family conservatism and
    caller propagation, lifecycle inclusion of external dependency rows, branch
    quota accounting, source locking, timestamp revalidation, and SQL routine
    rewriting.

Tests

  • Reproduced the reported mixed-source failure before the change: CREATE DATABASE ... CLONE returned is not BASE TABLE and left no target database.
  • source /Users/ghs-mo/.zshrc && moenv && GOWORK=off go test -mod=readonly ./pkg/frontend -count=1
    (pass).
  • Focused go test -race after the review fix (pass), including CTE scope,
    overload-family, routine, lifecycle-fence, quota, locking, revalidation, and
    rewrite tests.
  • source /Users/ghs-mo/.zshrc && moenv && make build (pass).
  • The inspected issue_27103_clone_external_table.sql result passed twice
    immediately on the same rebuilt service at head a428213146: 98/98
    successful, 0 failures, 0 abnormal results, and an empty error report on
    each run.
  • The branch was rebased conflict-free onto latest origin/main 2f11b2bd48; the reviewed 10-file PR diff is unchanged by the base update.
  • git diff --check (pass).

Residual risks

External tables, their external files/data, dependent views, and dependent SQL
routines are intentionally not recreated by database CLONE. This matches the
existing snapshot/PITR bulk-restore policy and is documented in the clone
guide. Explicit single-table CLONE of an external table remains unsupported.
Routine dependency inspection is AST-based; when a routine cannot be safely
inspected in the presence of an omitted relation, it is omitted rather than
persisted with an unverifiable source dependency. UDF overloads sharing a
database/name/kind are intentionally handled as one conservative family.

Review follow-up at 7c80e4c

  • DML WITH scopes now flow through the shared remap context for INSERT, MultiInsert, UPDATE, DELETE, and MERGE bodies, including nested query expressions.
  • INSERT, REPLACE, UPDATE, DELETE, and MERGE RETURNING expressions are visited by the same walker used for dependency collection and SQL rewriting. Qualified SQL UDF references are remapped with their database component.
  • Executable USE in routine dependency analysis now fails closed when omitted source relations are present, because path-dependent default-database state cannot be assigned safely to one source database. The clone guide documents this contract.
  • Validation on this head: full pkg/frontend UT passed; focused dependency/remap UT passed under -race; make build passed; git diff --check passed. The exact target-clone BVT remains covered by the existing same-instance 98/98 evidence from the preceding reviewed head.

Review follow-up at 06bdb84

  • The omission analysis now uses one bidirectional dependency graph for external objects, views, SQL UDF families, and stored procedures. Omitted routines propagate back to dependent views, including transitive view chains, so view restoration never attempts metadata whose routine dependency was omitted.
  • Reverse dependency edges are processed with a work queue, giving one propagation step per discovered dependency instead of repeated full scans of every object in a long chain.
  • The clone pipeline applies the complete omission set before view sorting and routine rewriting. The clone guide documents the two-way omission contract.
  • Added a frontend regression for external table to SQL UDF to view propagation, plus live and snapshot public-path BVT assertions that the dependent view is absent while independent metadata remains usable.
  • Validation on this head: full pkg/frontend UT passed (26.970s); focused dependency/remap UT passed under race; make build passed; git diff --check passed; the target clone BVT passed twice immediately on one rebuilt service with 104/104 success, 0 failures, 0 abnormal results, and an empty error report each run.
  • No workflow, permission, or unrelated files were changed.

Rebase follow-up at 44d330e

  • Rebased the same PR branch conflict-free onto latest origin/main 0cee094. The reviewed clone changes remain intact; no workflow or permission files were touched.
  • Revalidated the rebased head: full pkg/frontend UT passed in 27.876s; focused dependency/remap UT passed under race in 3.423s; make build passed; git diff --check passed.
  • The exact issue_27103_clone_external_table.sql BVT passed twice immediately on the same rebuilt rebased service: 104/104 each run, 0 failures, 0 abnormal results, and an empty error report.

CI follow-up at 627a1b3

  • Linux/arm64 SCA failed because the refactor left the now-unused omittedCloneDatabaseObjects wrapper in pkg/frontend/clone_database_source.go.
  • Removed only that obsolete wrapper; clone behavior and the reviewed dependency graph are unchanged.
  • Package-level golangci-lint passed with 0 issues; focused frontend race UT passed; git diff --check passed.

Rebase follow-up at 70794bc

  • Rebased the existing PR branch conflict-free onto latest origin/main 845fff8. The reviewed clone diff is unchanged by the base update; no workflow or permission files were touched.
  • Revalidated the rebased head with the focused frontend race UT (pass, 4.490s) and git diff --check.
  • The previous head's Linux/arm64 SCA passed after 627a1b3; the unrelated Iceberg UT Coverage failure is tracked in issue 28260 and remains outside this PR.

Review follow-up at 63d299e

  • The dependency graph now distinguishes inspected SQL routines, safely opaque non-SQL UDFs, and genuinely uninspectable routines. Supported inline non-SQL UDFs are preserved when an external relation seeds the omission closure; imported non-SQL UDF packages remain rejected before target creation by the existing snapshot-versioning guard.
  • Added frontend coverage for an external table plus an independent inline Python UDF, including the explicit opaque/uninspectable status contract. The issue_27103_clone_external_table.sql BVT and result now assert that the Python UDF remains in both live and snapshot target catalogs.
  • Updated clients/python/docs/clone_guide.rst to document the language-specific omission boundary.
  • Validation on this head: full pkg/frontend UT passed (28.253s); focused dependency/remap UT passed under race (2.958s); make build passed; git diff --check passed.
  • The BVT result was updated from the deterministic case contract; local execution was not run because port 6001 is occupied by an unrelated Docker service, so the new CI run must validate the rebuilt service.
  • No workflows, permissions, or unrelated files were changed.

@mergify mergify Bot added the kind/bug Something isn't working label Sep 4, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 4, 2026
@gouhongshen
gouhongshen force-pushed the agent/issue-27103-eb967920 branch from 0a143a7 to cd36eb4 Compare September 4, 2026 08:53
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Mergify infrastructure note (preserved from the pre-rebase head):

The check Rule: Auto update branch (update) failed because the Mergify GitHub App could not update .github/workflows/sca-go-module-cache.yaml without the workflows permission. GitHub returned: “refusing to allow a GitHub App to create or update workflow .github/workflows/sca-go-module-cache.yaml without workflows permission”. Check details: https://dashboard.mergify.com/event-logs?pullRequestNumber=28146&login=matrixorigin&repository=matrixone

I rebased this branch locally onto the latest origin/main and pushed the clean rebased head with --force-with-lease; no workflow or permission changes were made in this PR.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

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

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

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep review against 5e296a779f98c84bb82509c32caad9d64d4b9332.

The base-table routing fix is directionally sound, and the exact-head Linux UT/BVT/SCA checks are green, but the selected “skip external relations” contract is not closed across all consumers:

  1. [P1 correctness] Filter the DATA BRANCH authorization set with the actual clone set. authenticateDataBranchCreateDatabaseSourceTables still iterates every entry in source.srcTblInfos (pkg/frontend/data_branch_privilege.go:169-179). This PR excludes external relations from execution, quota, locks, and timestamp revalidation, but not authorization. Consequently a non-admin user who can create the target and read every object that will actually be cloned can still have DATA BRANCH CREATE DATABASE rejected solely because they lack SELECT on an external table that will never exist in the target. This also contradicts the privilege design’s “source read on every cloned source table/view” invariant. Please derive one authoritative cloneable-object predicate/set and reuse it for authorization, accounting, locking/revalidation, and execution; add a non-admin DATA BRANCH regression test for an ordinary + external source.

  2. [P1 correctness/contract] Close dependency handling before silently reporting clone success. Views that depend on the omitted external table are skipped, but all SQL UDFs and stored procedures are still rewritten from the source DB name to the target and persisted (clone.go:1145-1159, 1339-1347; clone_database_source.go:301-370). A routine such as CREATE PROCEDURE src.p() 'BEGIN SELECT * FROM src.ext_t; END' therefore becomes a successfully cloned target routine that deterministically fails when called because dst.ext_t was omitted. Before this change the whole clone failed atomically; after it, users can receive success with broken metadata. The linked issue explicitly required product-owner approval and explicit documentation if omission is the chosen contract, but neither approval nor durable user-facing documentation is present. Please define/document the contract and make dependent routines consistent (skip/report them, or reject the clone explicitly), with live and snapshot coverage.

  3. [P2 test reliability/performance] Remove the fixed -- @sleep:2. A two-second delay neither proves prior asynchronous DDL cleanup completed nor remains reliable on a slower runner, while it unconditionally adds two seconds to this BVT group. It also weakens the claimed same-instance rerun evidence by hiding the boundary being validated. Use unique names or a deterministic readiness/cleanup condition, then run the case twice immediately in the same service.

I did not find a new hot-path performance regression in the production diff: the added relation-kind checks are O(1) per catalog object and avoid unnecessary clone/lock work. The blockers above are semantic completeness and deterministic coverage, not the core external-table predicate.

@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 at exact head 86c49f07a98c28bbaeb393ef9c99f4320e60e71b against base 2bf4dddb3c7b6ff279da16b31c98928d3041f0b4.

The current commit has the same stable patch-id as the previously reviewed 5e296a779f98c84bb82509c32caad9d64d4b9332; it is a rebase, not a response to review 5115450470. All three prior blockers remain, and full closure tracing exposes one additional generation-fence consequence of the same fragmented object-set design.

P1 — authorization still uses a different source set from execution

authenticateDataBranchCreateDatabaseSourceTables still authorizes every item in source.srcTblInfos at pkg/frontend/data_branch_privilege.go:169-179. The PR now excludes external relations from quota, locking, timestamp revalidation, and both table execution loops, but not from authorization.

Reachable counterexample: a non-admin has CREATE DATABASE plus SELECT on every ordinary table that will be cloned, but not on an external table that will be omitted. DATA BRANCH CREATE DATABASE is rejected solely for an object absent from the target. This violates the privilege design contract at docs/design/data_branch_privilege.md:301-304, which requires source read on every cloned source table or view.

Please derive one authoritative cloneable object set or predicate and reuse it for execution, quota, authorization, and the relevant lifecycle operations. Add a real non-admin DATA BRANCH BVT for ordinary plus external input; the current BVT exercises only ordinary CREATE DATABASE ... CLONE.

P1 — the chosen omission contract leaves successfully cloned broken routines

External table metadata is omitted at pkg/frontend/clone.go:1301-1317, but every SQL UDF and stored procedure is still rewritten from source DB to target DB and persisted at pkg/frontend/clone.go:1145-1159 and 1339-1347. Persistence does not validate table dependencies. A procedure whose body selects from src.ext_t is therefore installed as a target procedure selecting from the nonexistent dst.ext_t; clone reports success and the procedure deterministically fails when called.

Views happen to be skipped later when target binding reports a missing dependency, but routines do not share that handling. The issue explicitly records that choosing omission rather than metadata recreation requires a product-owner decision and explicit documentation. No such decision or durable user-facing contract is present; a PR body and BVT comment are not product documentation.

Define the complete object/dependency contract first. Then either recreate the external definition, omit or report all dependent metadata consistently, or reject the clone atomically before target creation. Cover live and snapshot SQL routines, including a stored procedure and SQL UDF that reference the external relation.

P1 — excluding external relations from the source lifecycle fence breaks live DATA BRANCH clone under concurrent DDL

The new condition at pkg/frontend/clone.go:513-514 removes the external relation from source locking, yet source views are still rebound later:

  1. collectCloneDatabaseSource captures the external relation and dependent view at generation T0.
  2. No shared mo_tables row lock is acquired for the external relation.
  3. A concurrent DROP or incompatible ALTER can commit.
  4. tryToIncreaseTxnPhysicalTS advances the clone snapshot to T1 at pkg/frontend/clone.go:1207-1213.
  5. sortedViewInfos rebuilds the source view at T1 at pkg/frontend/snapshot.go:1789-1818.

If the external dependency is now missing or incompatible, the sort returns the plan error before restoreViews reaches its missing-dependency skip. The whole DATA BRANCH clone fails. The transaction rolls back, so this is not partial publication, but it defeats the source catalog-generation fence that the surrounding locks are designed to provide.

Either keep locking/revalidation for every source object still consulted by dependency resolution, or compute and freeze the omitted dependency closure so no later phase reads the skipped object. Add a deterministic barrier-based test for DROP or ALTER between source collection and the post-lock snapshot advance.

P2 — the BVT still uses a fixed two-second sleep

test/distributed/cases/git4data/clone/issue_27103_clone_external_table.sql:4-6 still delays every run by two seconds. It neither proves asynchronous cleanup is complete nor remains reliable on a slow runner, and it masks the same-instance rerun boundary. Use collision-resistant isolation or an observable cleanup/readiness condition, assert teardown postconditions, and rerun immediately on the same service.

The base-table and FK-loop routing checks themselves are directionally correct, nil-safe, and O(1) per catalog object. I found no new hot-path CPU, memory-growth, lock-leak, or partial-commit issue: the background transaction remains the effective owner of acquired locks and rollback closes the error paths. The blocker is that execution, authorization, dependency, and generation-fence consumers do not share one coherent clone object closure.

Evidence: complete seven-file diff and all reverse consumers reviewed; git diff --check passes. Remote shared build is green; other CI suites are still running, but none can close these deterministic source-level counterexamples.

REQUEST_CHANGES.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed in the rebased head 86ea9a8539.

  • DATA BRANCH authorization, quota accounting, and table/FK execution now use
    the same cloneable relation set, so a non-admin needs SELECT only for objects
    that are materialized. External catalog rows remain in the separate source
    lifecycle fence because live DATA BRANCH view dependency planning reads their
    metadata after the timestamp advance; locking and timestamp revalidation now
    cover those rows as well. The deterministic lifecycle UT models an ALTER/drop
    barrier between source collection and post-lock validation.
  • The omission contract is now explicit in clients/python/docs/clone_guide.rst.
    The AST-based dependency closure omits views, SQL UDFs, and stored procedures
    that directly or transitively depend on an omitted external relation or
    routine, while independent SQL routines are copied and rewritten.
  • The fixed BVT sleep is replaced by catalog cleanup/readiness polling and
    teardown assertions. The BVT now covers live and snapshot clones, an
    external-only source, direct/transitive routine dependencies, and a real
    non-admin DATA BRANCH with no SELECT grant on the external table.

Validation after the rebase:

  • GOWORK=off go test -mod=readonly ./pkg/frontend -count=1 passed.
  • Focused go test -race for routine, lifecycle-fence, quota, locking,
    revalidation, and rewrite tests passed.
  • make build passed.
  • The inspected issue_27103_clone_external_table.sql result passed twice on
    the same rebuilt service: 48/48 successful, 0 failures and 0 abnormal results
    each run; the error report was empty.

The existing Mergify workflow-permission failure remains preserved as
infrastructure evidence; this change does not modify workflows or permissions.

@gouhongshen

gouhongshen commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Latest head a428213146 is rebased conflict-free onto origin/main 2f11b2bd48; the reviewed code is unchanged by the base update. Validation on this head remains green: frontend UT, focused race UT, and make build passed; the target clone BVT passed twice immediately on the same rebuilt service with 98/98 successful, 0 failures, 0 abnormal results, and an empty error report on each run. Review requests have been refreshed for XuPeng-SH, LeftHandCold, and aptend.

@gouhongshen

gouhongshen commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Review ledger for current head a428213146 (all four comments addressed):

  • P1 authorization: fixed with cloneableTableInfos() shared by DATA BRANCH authorization, quota accounting, and materialization/FK execution; the BVT proves a non-admin without SELECT on the external table can clone the ordinary table.
  • P1 metadata contract: fixed with documented omission semantics and AST-based dependency closure for external-dependent views, SQL UDFs, and stored procedures; live and snapshot BVT assertions cover independent routines and omitted direct/transitive routines. CTE-aware collection now excludes visible nested/recursive CTE names, and same-name UDF overloads are handled as one documented conservative family with mixed-overload/caller coverage.
  • P1 generation fence: fixed by retaining external catalog rows in the DATA BRANCH lock/timestamp-revalidation lifecycle set because post-lock view planning consults them; the deterministic barrier UT covers revalidation only after the lifecycle fence.
  • P2 reliability: fixed by replacing the fixed sleep with catalog cleanup/readiness polling and teardown assertions; the exact BVT passed twice immediately on one rebuilt service (98/98 each).

No inline threads are unresolved. Review requests remain active for XuPeng-SH, LeftHandCold, and aptend.

@gouhongshen

gouhongshen commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Unrelated CI blocker remains tracked in #28260. The original run 33961743746 failed the Iceberg coverage test TestLocalE2EWaitForLifecycleFaultWaitersHonorsDeadline; PR #28146 does not touch test/iceberg, lifecycle fault waiters, or the coverage harness. On the required attempt-2 retry, the Iceberg coverage producer passed and the assertion did not reproduce. Its separate coverage-merge job only rejected the stale pre-rebase head 627a1b3 versus current 70794bc. The current rebased-head CI run 33963805586 was rerun to recover from concurrency cancellation; no unrelated code is being added to this PR.\n\n

@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 of exact head 5a6dcd4ba0c50fd1b614b4071f84e2d1ff1bb0b4.

The latest head closes the four previously reported paths: authorization/materialization now share the cloneable set; external catalog rows remain inside the lifecycle fence; direct/transitive external dependencies and dynamic PREPARE ... FROM string/@var fail closed; and the BVT no longer uses a fixed sleep. I also found no leak, partial-publication, or hot execution-path regression. Two deterministic metadata-loss counterexamples remain in the new dependency graph, however.

  1. [P1 correctness] Make table dependency collection CTE-scope aware. collectCloneRoutineReferences and collectCloneViewTableDependencies reuse remapTableName, whose callback is invoked for every tree.TableName (pkg/frontend/remap_db.go:932-940). The callback then maps every unqualified name to srcDBName (pkg/frontend/clone_database_source.go:159-169, 267-276) without excluding visible CTE names. For example, with an external source table named ext_t, this independent SQL UDF is classified as depending on that external table and is silently omitted:

    WITH ext_t AS (SELECT 1 AS n) SELECT n FROM ext_t

    The same false edge can mark a view as omitted for routine propagation. This contradicts the documented and PR-body contract that independent SQL routines are copied. Track CTE scope (including nested/recursive shadowing) when collecting relation dependencies, and add direct routine plus view-to-routine regression tests.

  2. [P1 correctness] Preserve UDF overload identity, or explicitly define a safe family-level contract. MatrixOne supports overloads by (name, db, arg_types), but cloneRoutineKey contains only kind/database/name (pkg/frontend/clone_database_source.go:125-127). Consequently, if f(INT) depends on an omitted external relation while independent f(VARCHAR) does not, the first overload inserts the shared name-only key into skippedRoutines; final filtering then omits both overloads (pkg/frontend/clone_database_source.go:368-383, 419-427) and propagates the false omission to every same-name caller. This is another successful clone that loses independent metadata. Model the signature/resolved overload in the graph, or deliberately treat the overload family as one conservative unit and document/report that limitation rather than claiming independent routines are preserved. Add mixed-overload and caller propagation coverage.

Performance note (non-blocking once correctness is closed): when there are no external or already-unservable objects, omittedCloneDatabaseObjects still parses every view a second time before discovering the omission set is empty. An early return after seeding the initial omission set would avoid redundant O(total view SQL) clone work without changing coverage.

git diff --check passes. I did not treat the still-running CI as evidence for or against these source-level counterexamples. A local exact-head frontend test could not be started because this worktree has no matching CGo artifact and primary-worktree reuse was correctly rejected; no test result is claimed.

REQUEST_CHANGES.

@gouhongshen

gouhongshen commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed in rebased head a428213146.

  • Dependency collection now tracks visible CTE names across nested and recursive WITH scopes. Unqualified CTE references are excluded from base-table dependencies; qualified references remain collected. Coverage includes direct routine references and view-to-routine propagation.
  • UDF overload identity is handled by an explicit conservative family contract: same database/name/kind overloads are one family, so an omitted overload omits the family rather than silently preserving a potentially invalid sibling. The clone guide documents this behavior, and the UT covers mixed overloads plus caller propagation.
  • The dependency closure now returns before reparsing views when there is no initial omission set.

Validation on this code:

  • full pkg/frontend UT passed;
  • focused go test -race passed;
  • make build passed;
  • the target clone BVT passed twice immediately on one rebuilt service, 98/98 each run, with an empty error report.

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

The previous CTE-name collision and overload-policy comments are addressed for plain SELECTs, and the no-omission fast path is a good improvement. However, the same underlying walker is still incomplete for supported routine SQL. I found one systemic correctness blocker with three reachable manifestations:

  1. [P1] Outer WITH scope is lost for DML bodies. In remapDbInStmt, INSERT/MultiInsert/UPDATE/DELETE call remapDbInWith, but then walk the DML body with the original context. Unlike remapDbInSelect, the visible CTE names are never applied to the body. For example, with an external source table named ext_t, the valid procedure body BEGIN WITH ext_t AS (SELECT 1 AS n) INSERT INTO source_db.sink SELECT n FROM ext_t; END is classified as depending on source_db.ext_t and is silently omitted even though it is independent. The same failure shape exists in supported WITH UPDATE/DELETE/MERGE/MultiInsert forms.

  2. [P1] RETURNING expressions are not audited or rewritten for INSERT/REPLACE/UPDATE/DELETE. Those ASTs all have Returning, but the corresponding cases above never walk it; only MERGE does. A procedure such as BEGIN UPDATE source_db.control_t SET id=id RETURNING source_db.f_external(id); END therefore does not record the f_external dependency. If that SQL UDF is omitted because it depends on the external table, the procedure is still copied. The rewrite pass uses the same walker, so source_db.f_external also remains unchanged: a live clone can cross back into the source database, while a snapshot clone can become broken after the source is dropped.

  3. [P2] Dependency collection ignores executable USE state. collectCloneRoutineReferences assigns every unqualified name to srcDBName; tree.Use is accepted as inspectable, but the current database is not threaded through subsequent statements. Thus BEGIN USE other_db; SELECT * FROM ext_t; END is incorrectly dropped whenever source_db.ext_t is external, even when other_db.ext_t is an ordinary table. Control flow can make more than one default database reachable, so a single mutable string would not be sufficient.

Please fix this at the walker/context level rather than with another SELECT-only special case: model DML CTE visibility for source/query expressions, visit every executable child including all RETURNING lists, and conservatively track possible default databases across routine control flow (or explicitly fail closed when USE makes that state ambiguous). Add table-driven dependency, rewrite, and filter tests for these forms so collection and persisted SQL cannot drift apart.

Evidence: the repository parser tests already cover WITH INSERT/UPDATE/DELETE/MERGE/MultiInsert and DML RETURNING syntax; the procedure interpreter executes unhandled statements such as USE through the normal SQL path. git diff --check is clean. Local focused execution could not start because this isolated macOS worktree has no cgo/libmo.dylib, and the repository wrapper correctly rejected reusing primary-worktree native artifacts because their inputs differ. CI is still running and is not the basis for this request.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed XuPeng-SH's review in commit 7c80e4c.

The three findings were valid and within this PR's clone dependency-contract scope:

  • DML WITH clauses now share their visible CTE scope with INSERT, MultiInsert, UPDATE, DELETE, and MERGE bodies, including nested query expressions.
  • INSERT, REPLACE, UPDATE, DELETE, and MERGE RETURNING expressions are walked by the common dependency/rewrite walker. Qualified SQL UDF references now have their database component remapped as well.
  • Routine dependency inspection fails closed on executable USE when omitted relations exist, because default-database state can be path-dependent. The clone guide documents this behavior.

Added regression coverage for all DML CTE forms, RETURNING dependency/rewrite, qualified UDF remapping, and USE fail-closed behavior.

Validation on 7c80e4c:

  • full pkg/frontend UT passed;
  • focused dependency/remap UT passed under -race;
  • make build passed;
  • git diff --check passed.

No workflows or permissions were changed.

@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 at exact head 7c80e4cf4203f65175ddd555436e37a7e09e59aa against base 2f11b2bd48a0f3971bc76cfeeb384ae6bfe84593.

The latest commit closes the previously reported DML CTE-scope, DML RETURNING, qualified-function walker, and executable-USE paths. Authorization, quota, materialization, lifecycle fencing, rollback ownership, and the fixed-sleep removal also remain sound. One P1 correctness blocker is still present in the dependency design.

P1 — propagate omitted routines back into dependent views

The omission graph is still directional. collectCloneViewTableDependencies records only TableName references, and the view fixed point at lines 199–229 therefore cannot see a view's SQL-UDF dependency. The routine filter subsequently omits an external-dependent UDF at lines 380–428, but no edge feeds that omission back to the view set.

A reachable counterexample is:

create database src;
create external table src.ext_t(id int) infile{...};
create function src.f_ext() returns int language sql as
  'select count(*) from src.ext_t';
create view src.v_ext as select f_ext();
create database dst clone src;

sortedViewInfos runs against the source before routine filtering, so v_ext binds successfully and is retained. f_ext is then omitted and functions are restored before views. Creating dst.v_ext consequently fails UDF resolution; canSkipRestoreViewError only tolerates missing tables/databases, so the transaction rolls back. An external table can therefore still abort the entire database clone, which is the linked issue's original failure contract. The repository's existing database_clone.sql already proves that views depending on SQL UDFs are supported; the new BVT covers the opposite edge (UDF -> view) but not view -> UDF.

Please model views and routines in one omission closure (or collect view function references and propagate skipped routine families back to views), including transitive view chains. Add live and snapshot public-path coverage for external table -> SQL UDF -> view, asserting that the clone succeeds and both dependent objects are omitted under the documented policy.

Performance note: while closing the graph, a reverse-edge work queue would make propagation O(V+E) and avoid the current repeated full scans on long dependency chains. This is not a separate blocker, but it keeps the fix scalable.

Exact-head CI is green and git diff --check passes. I found no new lock leak, deadlock edge, unbounded retained state, log storm, or ordinary-clone hot-path regression. The source transaction remains the single lock/rollback owner; the remaining blocker is dependency-closure correctness.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed the P1 review finding: propagate omitted routines back into dependent views.

The finding was valid and within this PR’s clone dependency-contract scope. Commit 06bdb84 now builds one bidirectional graph over external objects, views, SQL UDF families, and stored procedures. It records view-to-function/procedure edges, processes reverse edges with a work queue, and applies the complete omission set before sortedViewInfos and routine rewriting. Thus an external-dependent UDF omits its direct view and transitive view dependents before restoration; independent routines and views remain copyable.

Added frontend coverage for external table -> SQL UDF -> view -> view chain propagation. The public BVT covers the same dependency in both live and snapshot clones and asserts the dependent view is absent while independent metadata remains usable.

Validation on 06bdb84:

  • Full pkg/frontend UT passed in 26.970s.
  • Focused dependency/remap UT passed under race.
  • make build passed.
  • git diff --check passed.
  • The target clone BVT passed twice immediately on one rebuilt service: 104/104 each run, 0 failures, 0 abnormal results, empty error report.

No workflows or permissions were changed.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Rebased the existing PR branch conflict-free onto origin/main 0cee094; current head is 44d330e. The bidirectional omission fix is unchanged by the rebase. Revalidated on the rebased head: full frontend UT, focused race UT, make build, and two immediate issue_27103_clone_external_table.sql BVT runs passed; each BVT run was 104/104 with an empty error report. XuPeng-SH review was re-requested for the current 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 at exact head 70794bc609c88648991d33797b27cf27c1bb2088 against base 845fff8ee9cac962c5002a1007e0b0180efd591b.

The latest bidirectional graph closes the previous view -> omitted-routine propagation hole, and the earlier authorization, lifecycle-fence, CTE/DML, RETURNING, USE, overload-family, and deterministic-BVT findings remain addressed. I found one new correctness blocker by checking the opposite case: an object that is uninspectable but provably independent of SQL relation metadata.

P1 — do not silently omit every non-SQL routine merely because an external table exists

collectCloneRoutineReferences returns inspectable=false for every non-SQL routine at pkg/frontend/clone_database_source.go:432-434. Once any external relation seeds the omission queue, addRoutineDependencies turns that flag into an unconditional omission at lines 316-323. applyCloneDatabaseOmissionSet then removes the routine, even though no dependency edge to the external relation was found.

A reachable example is a database containing one external table and one independent, non-imported inline Python UDF such as py_add(x) = x + 1. CREATE DATABASE dst CLONE src reports success, but dst.py_add is silently absent. This contradicts the existing clone boundary in validateCloneUserDefinedFunctions: only imported non-SQL UDFs are rejected because their package object is not snapshot-versioned; inline bodies remain valid clone metadata. rewriteCloneUserDefinedFunctionBodies likewise intentionally preserves opaque languages. A Python UDF invocation sends its body and argument vectors to UdfService; it does not encode a MatrixOne table dependency that justifies deleting it when an unrelated external table is present.

Please separate “cannot parse this language as SQL” from “depends on an omitted SQL object.” At minimum, preserve supported non-imported inline Python UDFs; for any routine language that can execute SQL but cannot be analyzed, reject explicitly before target creation or define a language-specific policy rather than returning success after silently dropping an unrelated object. Add a regression with external table + independent inline Python UDF and assert the target catalog retains the function. The documentation should describe only omissions backed by a dependency or an explicit unsupported-clone boundary, not normalize unrelated metadata loss.

Performance/lifecycle audit: the reverse-edge queue is bounded by the finite object graph, terminates on cycles through the omission sets, and is O(V+E) after parsing; the no-seed early return avoids normal-path parsing. I found no new deadlock, goroutine/resource leak, unbounded growth, log storm, or partial-publication path—the background transaction still owns rollback and locks. Exact-head required CI is green and git diff --check passes, but current tests do not cover this counterexample.

REQUEST_CHANGES.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed XuPeng-SH's review in commit 63d299e.

The finding was valid and in scope. The omission walker now uses an explicit dependency status: inspected SQL routines contribute edges; accepted inline non-SQL UDFs are opaque and preserved; genuinely uninspectable routines remain conservatively omitted when the closure has an omitted relation. Imported non-SQL UDF packages are still rejected before target creation by the existing snapshot-versioning validation.

Added frontend coverage for the external-table plus inline Python-UDF case and live/snapshot BVT catalog assertions, and documented the language-specific contract. Full pkg/frontend UT, focused race UT, make build, and git diff --check passed locally. The new BVT will be verified by CI because port 6001 is occupied by an unrelated Docker service in this worktree environment.

@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 at exact head 63d299ed1b209bb7f64c579518d832e8f8515306 against base 845fff8ee9cac962c5002a1007e0b0180efd591b.

The latest change resolves the remaining metadata-loss counterexample: inline non-SQL UDFs are now modeled as opaque-but-cloneable, while imported packages are rejected before target creation and uninspectable stored routines remain fail-closed. The status is consumed only by the omission graph; opaque UDFs add no false external-relation edge, and genuine routine/view/table dependencies still propagate bidirectionally through the finite work queue.

The previously reviewed authorization/materialization set, external metadata lifecycle fence, CTE and DML/RETURNING walker coverage, executable USE handling, overload-family policy, rollback ownership, deterministic cleanup, and no-omission fast path remain intact. Q1-Q3 closure is sound: the background transaction owns rollback/locks, there are no new waits or goroutines, and graph memory/work is bounded by the finite source metadata with cycle deduplication. I found no material normal-path performance or compatibility regression.

Exact-head required CI is green: frontend-inclusive Linux UT, SCA, PROXY BVT, pessimistic multi-CN BVT, and coverage. The new live/snapshot BVT verifies cloned Python-UDF catalog preservation. No unresolved blocker found.

@mergify

mergify Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-05 15:16 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-09-05 15:17 UTC · at 7b6603be6a84acf328a7b7e7e96158eb47176c95 · squash

This pull request spent 13 seconds in the queue, including 1 second running CI.

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

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.

3 participants