Repository navigation
fix(sql): keep foreign-key integrity through restore and deferred FK binding (#30615) - #31105
Conversation
…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 reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
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.
|
Queued — the merge queue status continues in this comment ↓. |
Merge Queue Status
This pull request spent 1 hour 8 minutes 53 seconds in the queue, with no time running CI. ReasonPull 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.
HintYou 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. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
…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>
What type of PR is this?
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
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 inScope.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 directCREATE 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.Cyclic/deferred FK creation lost parent-side enforcement ([Bug]: cyclic FK mo-dump restore silently loses parent-update enforcement #30604).
CREATE TABLEcollects forward FK references (UnresolvedFkParents) and, once the referenced parent exists, publishes child bindings inpublishCreateForwardForeignKeys(pkg/sql/compile/create_fk.go). Publication rewrote each child's constraint from the constraint snapshot taken at bind time — butcreateTableregisters the child on the **direct-FK parents'RefChildTableDefbetween 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 andSHOW CREATE` displayed the constraint.The fix
pkg/sql/compile/clone_fk_integrity.go(new): after the block clone completes,validateClonedTableFKIntegritychecks 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:publishCreateForwardForeignKeysnow 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). TheRefChildTableDefentries registered in between survive, so parent-side enforcement works for deferred/cyclic creation exactly as for schema-first creation.Tests
pkg/sql/compile, 13 new cases):create_fk_test.go: publication preserves a same-transactionRefChildTableDefregistration, 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%.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 — everyON UPDATE/DELETE RESTRICTparent mutation and orphan insert is rejected, rows unchanged, zero orphans.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.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).orphan_count = 1. After: both are rejected (internal error: cannot restore table v_orphan.c: foreign key constraintfk_pwould leave orphan row(s) (key value 1) ...), current state preserved; restoring after repairing the parent succeeds with zero orphans and active enforcement (ERROR 1452on the orphan insert).UPDATE b SET id=3succeeded after the interleaved restore, orphaninga.b_id=2. After: rejected (ERROR 1217) for both tables, both directions, deletes rejected as well; rows unchanged; schema-first ordering identical.CONSTRAINT fk1 FOREIGN KEY ...) plus the deleted row, enforcement active (ERROR 1452); repeated restores (3x) produce identical data. FK/index/view PITR metadata loss described in the original report does not reproduce at upstream/main 83fa4d7: after fix(frontend): fail PITR before DROP on FK metadata errors #30448 the degraded continuation on failed FK metadata lookup was removed; the remaining baseline-materialization tracking stays in [Bug]: PITR RESTORE DATABASE silently returns wrong data when the restore-point baseline is not yet materialized — first-executed restores degrade to current/partial state with no warning (order-dependent) #30616.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.