Skip to content

fix(sql): keep foreign-key integrity through restore and deferred FK binding (#30615) - #31105

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
daviszhen:fix-30615-restore-fk-integrity
Oct 25, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
daviszhen:fix-30615-restore-fk-integrity

Conversation

@daviszhen

@daviszhen daviszhen commented Oct 25, 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:

issue #30615 (consolidates #30388 and #30604)

What this PR does / why we need it:

Consolidates the remaining deterministic defects folded into #30615 from #30388 (orphan rows on child-table restore / historical clone) and #30604 (parent-side enforcement lost on cyclic/mo-dump-style FK creation).

What was wrong

  1. Historical restore / clone could commit orphan FK rows ([Bug]: Historical table CLONE and snapshot/PITR restore can persist orphan FK child rows #30388). Every snapshot/PITR restore replays a table by CREATE TABLE dst CLONE src {MO_TS/SNAPSHOT ...}: the block-level copy in Scope.RestoreTable (pkg/sql/compile/ddl.go) bypasses row-wise foreign-key checks, and nothing validated the cloned child rows against the parent state reachable in the restore. Result: RESTORE TABLE child {snapshot=...}, RESTORE ... TABLE ... FROM PITR, and direct CREATE TABLE c2 CLONE c {SNAPSHOT=...} returned success while persisting rows whose referenced parent key no longer existed — the constraint visibly present (SHOW CREATE), the data invalid.

  2. Cyclic/deferred FK creation lost parent-side enforcement ([Bug]: cyclic FK mo-dump restore silently loses parent-update enforcement #30604). CREATE TABLE collects forward FK references (UnresolvedFkParents) and, once the referenced parent exists, publishes child bindings in publishCreateForwardForeignKeys (pkg/sql/compile/create_fk.go). Publication rewrote each child's constraint from the constraint snapshot taken at bind time — but createTable registers the child on the **direct-FK parents' RefChildTableDef between bind and publish. The stale-snapshot rebuild silently discarded that registration. With a mo-dump restore interleave (CREATE b (fwd ref); INSERT b; CREATE a (direct FK); INSERT aunderforeign_key_checks=0), updates/deletes on the parent of the direct FK were never rejected, even though catalogs and SHOW CREATE` displayed the constraint.

The fix

  • pkg/sql/compile/clone_fk_integrity.go (new): after the block clone completes, validateClonedTableFKIntegrity checks every outgoing FK of the freshly created destination relation — read from the engine-side constraint (creation refreshes column ids, so plan-side ids are never mixed in) — by probing for cloned child rows whose non-NULL key set has no match in the parent relation visible to the same transaction. Any hit fails the statement with a clear error naming the constraint, a sample orphan key value, and the parent; the surrounding restore transaction rolls back, so no partial state is committed. NULL key components are exempt (matches ordinary FK semantics), self-references are excluded, a parent invisible to the transaction is skipped (preserves the documented dangling-reference behavior), and ordinary same-time clones keep their cost profile (the check runs for restore sessions and historical clones only). Database/account restores validate against their own freshly restored parents because FK topological order is respected within one restore transaction.
  • pkg/sql/compile/create_fk.go: publishCreateForwardForeignKeys now reads each child's current constraint at publish time and merges the freshly bound FK defs into it (keyed by name, idempotent under re-publication). The RefChildTableDef entries registered in between survive, so parent-side enforcement works for deferred/cyclic creation exactly as for schema-first creation.

Tests

  • Unit (pkg/sql/compile, 13 new cases):
    • create_fk_test.go: publication preserves a same-transaction RefChildTableDef registration, is idempotent under re-publication, maps referenced columns to parent ids, propagates constraint read/write errors; bind struct slimmed accordingly.
    • clone_fk_integrity_test.go: 100% coverage of the validator (gate, probe SQL shape single/composite, NULL/self-FK/dangling-parent skips, every error path, multi-FK loop); publisher coverage 95.3%. Whole-diff coverage ≈ 95%.
  • BVT (new, deterministic):
    • test/distributed/cases/snapshot/issue_30615_snapshot_restore_fk_orphan.{sql,result}: orphan-producing child snapshot restore → error with constraint name + sample key; state preserved; historical clone same; retry after repairing the parent succeeds and stays orphan-free; canonical controls (valid restore), NULL-FK rows, and the self-FK master-guard refusal.
    • test/distributed/cases/foreign_key/fk_issue_30615_cyclic_fk_enforcement.{sql,result}: mo-dump-style interleave, schema-first ordering, checks=0-then-1 binding, and a plain checks=0 pair — every ON UPDATE/DELETE RESTRICT parent mutation and orphan insert is rejected, rows unchanged, zero orphans.
  • Existing goldens replayed (single-node, replayed on a pristine upstream/main instance and on the fixed build, byte-identical between the two): 26 files — all FK-bearing snapshot/cluster restores (restore_fk_table, snapshot_restore_table_with_fk, snapshot_restore_to_table_fk, snapshot_restore_to_table_fk_2, restore_table_referenced_by_fk, restore_cluster_fk, restore_fk_restore_master_table), the foreign_key suite subset, and the git4data/clone FK cases.
  • gofmt / go vet / molint / golangci-lint (2.14.0) / license-eye: clean; go test ./pkg/sql/compile/ -count=1: pass.

Live verification (single-node, Linux container)

Binary built from this head, sha256 2f484ba623fcd1e3939180fe87ab206b899471c37af2d188c06ff87f3e7eb118 (independently rebuilt, byte-identical).

Note on scope

The PITR baseline-readiness race (restore silently degrading before materialization completes) remains tracked by #30616 as a separate issue per the consolidation comments; it does not reproduce against this head in this environment.

…binding (matrixorigin#30615)

- historical CREATE ... CLONE (snapshot/PITR table replay and direct
  snapshot/MO_TS clone) now validates every outgoing FK of the destination
  relation against the parent visible in the same transaction; an operation
  that would persist orphan child rows fails clearly and rolls back instead
  of committing invalid data (matrixorigin#30388)
- publishCreateForwardForeignKeys merges freshly bound forward FK defs into
  each child's current constraint instead of the stale bind-time snapshot,
  so same-transaction RefChildTableDef registration survives deferred
  (cyclic) FK binding as used by logical dump restore (matrixorigin#30604)
@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 commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 910b70d125d69bdaae09bd24628790d7ee6fd49f

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 910b70d125d69bdaae09bd24628790d7ee6fd49f

Assessment: approve

Reviewed the complete delta and affected callers. The design appropriately validates historical rows at the shared clone/restore boundary and merges deferred foreign keys into current constraints, removing the stale snapshot. Transaction visibility, rollback and parent-write serialization held in SQL validation. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Isolation preflight passed; 192 native inputs matched retained artifacts and repository provenance verification passed.

  • Full pkg/sql/compile tests, targeted go vet, formatting and diff checks passed. Source remained unchanged.

  • Replayed all 137 statements from both new SQL golden files through the canonical single-CN fixture; results and errors matched.

  • Additional SQL tests passed for composite keys, NULL exemption, failed-restore rollback, whole-database restore, and parent-delete serialization during an uncommitted historical clone.

  • Reconciled nine successful command/source/exit receipts with retained logs. Evidence: /home/xupeng/.local/state/mo-bot/jobs/671a76a5ab810ab36cddd1cf/attempt-1/review-evidence.json.

Limitations:

  • Historical clone/restore adds one validation query per outgoing FK and may scan child and parent data. Large-table latency and memory costs were not benchmarked; ordinary clones and normal SELECT/DML paths avoid these scans.

  • Local execution used one CN. Account/PITR-specific and multi-CN behavior were traced through shared owners but not independently replayed.

  • Frozen evidence supplied green CI metadata but no retained author execution logs or full linked-issue bodies; those assertions were not treated as independently verified execution.

@mergify

mergify Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Queued — the merge queue status continues in this comment ↓.

@mergify mergify Bot added the kind/bug Something isn't working label Oct 25, 2026
@mergify mergify Bot added the queued label Oct 25, 2026
@mergify

mergify Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-25 14:01 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-25 15:10 UTC · at 9fb64636bc46424ed118a6d1b7433f476ffe65a3

This pull request spent 1 hour 8 minutes 53 seconds in the queue, with no time running CI.

Reason

Pull request #31105 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.

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.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@XuPeng-SH
XuPeng-SH merged commit 20860c7 into matrixorigin:main Oct 25, 2026
26 of 28 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 25, 2026
@daviszhen
daviszhen deleted the fix-30615-restore-fk-integrity branch October 25, 2026 15:21
XuPeng-SH added a commit that referenced this pull request Oct 26, 2026
…31142)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #29562.

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

Recent [SCA job
121193349037](https://github.com/matrixorigin/matrixone/actions/runs/40201453562/job/121193349037)
silently ran a full graph because Node was missing from the shell PATH,
despite an existing incremental selector. Its frozen PR inputs would
have selected 34 of 507 packages.

- Preserve compatibility with deployed CI: when Node is absent,
explicitly report the reason, validate the complete graph and run both
analyzers over `./...`. Node-present CI retains incremental selection;
selector failures stay fatal. Local invocations still run the complete
graph.
- Explain conservative fallback decisions and report selected/total
package counts on stderr, keeping stdout exclusively package arguments.
- Reuse existing immutable-input selection, package ownership and
reverse-import graph. Preserve full-scan overrides, discovery failures,
analyzer failures and both analyzers' identical package scope.
- Add regression coverage at the real Make/Go discovery boundary for
missing runtime, dirty/ignored inputs, closure thresholds and transitive
test imports.

Companion CI PR: matrixorigin/CI#469. It exposes
the runner's existing Node without a download and safely restores
incremental license selection. Both merge orders are supported; older CI
uses complete checks until the runtime enhancement is deployed.

### Validation

- `node --test .github/ci/*.test.cjs`: 36 passed on the compatibility
correction, including real Go discovery, missing-Node full execution,
graph failure, and both analyzer failure paths.
- Both configured analyzers passed in matched full/incremental
experiments under 4 CPU / 8 GiB, with warmed compiled exports and
separate cold analyzer caches: elapsed **313.54s → 113.54s (-63.8%)**;
peak working set **7.95 GiB → 5.75 GiB (-27.6%)**; raw cgroup peak
**8.00 GiB → 5.96 GiB**; no OOM.
- The benchmark uses PR #31105's historical changed-file list against
the same frozen application source. It bypasses dirty-checkout rejection
only to measure selection; the public-interface fixtures separately
verify immutable provenance. These are local measurements, not promised
hosted-CI timings.
- `git diff --check` passed. No Go implementation changes, so Go race
detection is not applicable; JavaScript fixture tests cover this delta.
- Existing molint pin/rules, analyzer concurrency and GC settings are
unchanged. Hosted CI remains pending. Coverage UT admission and
linter-driver upgrades are separate work.

### CI compatibility correction

[Failed job
121266163435](https://github.com/matrixorigin/matrixone/actions/runs/40225473222/job/121266163435)
used CI `30b0e58`, before the companion PR exposed Node on PATH. The
hard runtime prerequisite has been removed: missing Node now retains
complete validation with an explicit diagnostic. Incremental savings
require deployment of the companion runtime enhancement; this correction
does not claim savings on older CI. Hosted verification of the
correction remains pending.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch had an error being deployed

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

Labels

dequeued 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