Skip to content

fix(clone): preserve foreign key metadata across alter copy - #26330

Merged
mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:codex/clone-fk-repro
Jul 29, 2026
Merged

mergify[bot] merged 8 commits into
matrixorigin:mainfrom
gouhongshen:codex/clone-fk-repro

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Jul 28, 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:

Closes #26328

What this PR does / why we need it:

COPY-mode ALTER TABLE replaces a relation with a new physical table. The old implementation could lose or split foreign-key metadata while doing that:

  • mo_catalog.mo_foreign_keys rows owned by the source child were deleted before the replacement inherited them;
  • catalog-only forward references created under FOREIGN_KEY_CHECKS=0 were absent from TableDef, so reconstructing the temporary table could not recreate them;
  • self references could leave multiple RefChildTableDef values whose add/remove/replace paths disagreed;
  • databases and historical snapshots/PITR corrupted by an older binary retained the FK in SHOW CREATE TABLE but lacked the catalog dependency used by clone and restore ordering.

This PR:

  • applies ALTER FK mutations to the source catalog rows, transfers those rows around the source drop, and restores the original logical table name after the physical replacement;
  • keeps parent-side names stable during COPY so self references never point at the temporary relation;
  • centralizes reverse-reference add/remove/restore/replace into one canonical mutation that emits exactly one RefChildTableDef, deduplicates IDs, preserves the self-reference sentinel 0, and is also used by TRUNCATE TABLE;
  • derives dependency edges from historical source table DDL in addition to mo_foreign_keys for database clone, snapshot restore, PITR restore, and dropped-account timestamp restore; table DDL repairs resolved historical constraints while the catalog remains necessary for unresolved forward references;
  • enumerates ordinary snapshot source databases by MO_TS under the source account instead of resolving the snapshot name there. Snapshot metadata belongs to the system account, so name resolution under a dropped source account incorrectly reported mo_snapshots missing;
  • adds unit and BVT coverage for repeated COPY ALTERs, altered parents/children, sibling and multi-level FKs, composite/multiple-parent FKs, self references plus external children, FK recreation, both forward-reference paths, snapshot clone, clone-after-clone, table/column renames, missing historical catalog rows, canonical TRUNCATE replacement, and timestamp-based source enumeration.

The generated clone_fk_after_alter result was manually audited: all 17 recorded errors are intentional FK enforcement checks; there are no unexpected errors.

Validation

  • affected Go packages (./pkg/frontend ./pkg/sql/compile ./pkg/sql/plan) pass with the repository CGo test environment;
  • clone_fk_after_alter: 240/240;
  • snapshot_restore_to_table_fk_2: 484/484;
  • restore_dropped_account_to_new: 20/20;
  • restore_dropped_account_with_account_sp: 34/34;
  • restore_database_using_cluster_sp: 557/557;
  • release-to-target compatibility check from the initial fix:
    • binary at 1ca928aefd reproduced the old corruption (mo_foreign_keys count changed from 1 to 0 after COPY ALTER while SHOW CREATE TABLE retained the FK);
    • after restarting the same data directory with this PR, cloning both the live database and a snapshot created by the old binary succeeded;
    • invalid child inserts into both clones were rejected by the restored FK.
  • post-main-merge FK topo-sort signature sync: focused pkg/frontend tests pass.

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

Copy link
Copy Markdown
Contributor Author

I did a destructive review of the FK metadata paths. I do not think this is merge-ready yet; there are two compatibility/data-integrity blockers and one invariant bug.

1. Existing corrupted deployments and historical snapshots are not repaired

Issue #26328 confirms that already-deployed v4.1.4 databases can have missing mo_foreign_keys rows. This PR changes only future COPY ALTER writes. There is no upgrade/reconciliation step, so upgrading an already-affected database and cloning it immediately will still fail.

Historical snapshots/PITR are a harder form of the same problem: the restore paths query mo_foreign_keys at the requested timestamp (snapshot.go:getFkDeps, snapshot_restore_with_ts.go:getFkDepsWithTS, and pitr.go:getFkDepsInPitrRestore). A current catalog write cannot repair a pre-fix timestamp. The new snapshot BVT takes the snapshot after running ALTER on the fixed code, so it does not cover this compatibility case.

This needs an explicit source-of-truth/reconciliation design, plus a release-to-target compatibility test that creates the corruption with the old release and clones/restores it with the new binary. Requiring users to ALTER every affected table again would not be an acceptable repair.

2. COPY ALTER still silently loses catalog-only forward references

The engine explicitly supports forward references with FOREIGN_KEY_CHECKS=0. When the parent is absent, getForeignKeyData sets ForwardRefer=true; buildCreateTable writes the relationship to mo_foreign_keys but deliberately does not add it to TableDef.Fkeys.

COPY ALTER reconstructs the temporary table from TableDef, so such an FK produces no temporary-table FK row. Dropping the source deletes the only catalog row, and the new copy-table rename statements update zero rows. Creating the parent later can no longer discover and attach the constraint, silently removing data-integrity enforcement.

A minimal regression case is:

set foreign_key_checks = 0;
create database d;
create table d.child (
  id int,
  parent_id int,
  constraint fk_forward foreign key (parent_id) references d.parent(id)
);
alter table d.child add column payload int;
create table d.parent (id int primary key);
set foreign_key_checks = 1;
-- the FK must still be present and enforceable

The same case should be tested after dropping an existing parent under FOREIGN_KEY_CHECKS=0, ALTERing the child, and recreating the parent.

3. RefChildTableDef is not canonicalized

A self-referencing temporary copy already gets a RefChildTableDef{Tables:[0]} from CreateTable. restoreNewTableRefChildTbls then blindly appends another RefChildTableDef. The new reconcileParentRefChildTableID updates only the first definition and returns; removeChildTblIdFromParentTable also stops at the first, while disttae table-def reconstruction lets the last definition win.

Concrete sequence: self-referencing parent + external child → ALTER parent → DROP child. The parent can retain the deleted child ID and remain incorrectly blocked as “referenced”.

Please centralize add/remove/restore/replace behind one canonical mutation that emits exactly one RefChildTableDef, deduplicates table IDs, and handles the 0 sentinel consistently.

There is also a root-cause evidence gap around the reverse-reference change: on the normal path, temporary-table CREATE already calls AddChildTblIdToParentTable with the new physical ID, and the internal source DROP uses IgnoreForeignKey, so the old cleanup should remove the old ID while leaving the new one. The new unit tests prove the helper in isolation, but do not reproduce a production path where the replacement ID is actually absent. If another path/cache behavior causes that absence, it should be captured by an integration regression test.

Verification on this head:

  • pkg/sql/compile and pkg/sql/plan tests pass through the repository CGo wrapper.
  • git diff --check passes.
  • At review time, the GitHub upgrade compatibility jobs are skipped and the main UT/BVT jobs are still pending.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed all three blockers in d7a7d02513:

  1. Existing data and historical snapshots: clone now unions dependencies parsed from the source SHOW CREATE TABLE DDL with mo_foreign_keys. The DDL is the durable source for resolved constraints; the catalog remains the source for unresolved forward references. I reproduced the corruption with pre-fix commit 1ca928aefd (catalog count 1 → 0 after ALTER), created a snapshot with that binary, restarted the same data directory on this PR, and verified both live-database clone and old-snapshot clone. Both cloned FKs reject invalid inserts. An automated topology test covers the missing-catalog-row case.
  2. Catalog-only forward references: COPY ALTER now applies FK ALTER actions to the source rows, transfers those child-owned rows across the source drop, then restores the logical source name. BVT covers both an initially missing parent and drop-parent → ALTER child → recreate-parent; both rows survive and enforcement resumes.
  3. RefChildTableDef invariant: add/remove/restore/replace now use one canonical mutation, emit exactly one definition, deduplicate IDs, and preserve sentinel 0. Unit tests cover multiple definitions/duplicates for every mutation; BVT covers self-referencing parent + external child → ALTER parent → DROP child/parent.

The root-cause gap was also corrected: the implementation no longer assumes the temporary CREATE omitted the replacement reverse ID. It preserves source-owned catalog metadata explicitly and canonicalizes whatever reverse-reference state CREATE produced.

Validation: affected Go packages pass; clone_fk_after_alter is 240/240, with all 17 recorded errors manually confirmed as intentional FK enforcement checks.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

第二轮破坏性 review(head d7a7d0251):仍有 2 个 blocker,暂不能 approve。

  1. [compatibility / data loss] 历史缺失 mo_foreign_keys 的恢复只接到了 database clone,普通 snapshot/PITR restore 仍未修复。

    doRestoreSnapshot 仍调用 fkTablesTopoSort(..., nil)(pkg/frontend/snapshot.go:665),PITR 的 fkTablesTopoSortInPitrRestore 也只读 mo_foreign_keys(pkg/frontend/pitr.go:1675);dropped-account 的 TS restore 同样只读 catalog。这里和 fkTablesTopoSort 中“restore and clone reconcile both representations”的注释不一致。

    对旧版本 COPY ALTER 已经丢掉 catalog row、但 SHOW CREATE TABLE 仍保留 FK 的快照:topo 结果为空,fkTableMap 为空,表会按 relname 顺序进入普通恢复。若 child 排在 parent 前,recreateTable 创建 child 失败后会把 no such table 显式改成 nil 并返回(snapshot.go:1553-1558),后续没有重试;PITR 有完全相同的吞错逻辑(pitr.go:1493-1498)。最终 restore 可以成功返回,但 child 表和数据消失。TS restore 则直接失败。

    建议把“schema DDL + catalog”的依赖收集做成所有 clone/snapshot/PITR source 共用的单一入口,并增加从旧损坏 snapshot/PITR 恢复的回归测试(不只测试 clone old snapshot)。

  2. RefChildTableDef 的 mutation 还没有真正收口。

    TRUNCATE TABLE 仍通过 updateRefChildTableConstraintIDs 直接逐项改 RefChildTableDef.Tables(pkg/sql/compile/ddl.go:3231,3266-3280),没有走本次新增的 canonical helper。对旧版本遗留的多个 RefChildTableDef / 重复 table ID,truncate child 后仍保留多个 definition 和重复的新 ID;而 TableDef materialization 遇到多个 definition 时是后者覆盖前者,行为仍依赖 definition 顺序。

    建议让 truncate 也复用同一个 canonical replace primitive,并补一个“多个 definition + 重复 ID -> truncate child -> 恰好一个 canonical definition”的测试,避免兼容性修复只覆盖部分写入口。

本地验证:git diff --check 通过;./pkg/frontend ./pkg/sql/compile ./pkg/sql/plan -count=1 全部通过。上述两个问题是调用链/状态兼容性缺口,现有 UT 没有覆盖。

@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 exact head 127bd41. The COPY ALTER FK catalog-transfer/canonical reverse-reference changes and historical restore/clone dependency reconstruction are internally consistent, including self references and unresolved forward references. Focused CGo tests passed for ./pkg/frontend ./pkg/sql/compile ./pkg/sql/plan.

@mergify mergify Bot added the queued label Jul 29, 2026
@mergify

mergify Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-29 04:12 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-29 04:47 UTC · at eb6244fb3700b536ff0b1d2290010b4214095b05 · squash

This pull request spent 35 minutes 32 seconds in the queue, including 35 minutes 16 seconds 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 Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • 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

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 DATABASE CLONE fails after ALTER TABLE on a foreign-key child table

3 participants