Skip to content

fix(frontend): fail PITR before DROP on FK metadata errors - #30448

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/30393-pitr-fk-lookup-fail-closed-business-20261017
Oct 18, 2026
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
MatrixAdventurer:fix/30393-pitr-fk-lookup-fail-closed-business-20261017

Conversation

@MatrixAdventurer

@MatrixAdventurer MatrixAdventurer commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Test and CI

Which issue(s) this PR fixes:

Fixes #30393

What this PR does / why we need it:

PITR table restore previously overwrote an error from checkTableIsMaster with subsequent USE, DROP TABLE, or historical CLONE results. It could therefore report success after a failed FK metadata lookup.

Return that original error immediately before restore DDL. Preserve successful restore and the existing skip for a referenced table. This uses the existing metadata query and error propagation path; it adds no query, cache, synchronization, or normal DQL/DML execution work.

Regression coverage checks the original lookup error and the exact statement history (lookup only), successful restore, and referenced-table skip. The existing system-catalog CLONE-failure test now supplies the prerequisite valid, empty FK lookup result and retains its original CLONE-error assertion. Mock defaults and production admission are unchanged.

CI failure diagnosed and repaired

The previous racing UT failed Test_doRestorePitr_Account_Sys_Restore_Normal_To_new_Using_cluster: expected catalog clone failed, received it is not the type of result set. This was reproduced locally at the original head. Its fixture omitted the FK result, so the corrected production error handling stopped before its CLONE injection. Supplying the missing fixture result repairs this assertion without relaxing production behavior.

Validation

  • Based on main aa4b6eddfdad54d11be6fd75a5675eb9801f6690; no conflict or base dependency required another rebase.
  • Focused frontend UT, normal and once with race (-count=1): the new regression/controls, the previously failing account restore case, and TestCatalogRestoreMetadataOwnership all pass.
  • Configured incremental make err-check static-check-selected for ./pkg/frontend, with repository molint and golangci-lint 2.14.0: pass. Formatting and git diff --check: pass.
  • gpt-6.1-sol / xhigh design and final review completed. No unresolved material blocker in this bounded change.
  • Checks ran locally on macOS ARM64 / Go 1.27.1 with verified matching CPU native artifacts. Updated Linux CI remains pending; full package/BVT and deployment validation are not claimed. Draft status is preserved.

由 LW 授权的 ChatGPT Business 智能体提交。

Preserve the failed checkTableIsMaster error rather than replacing it with
later USE/DROP/CLONE results. Add a fault injection regression plus successful
lookup control at the PITR restore entrypoint.

由 LW 授权的 ChatGPT Business 智能体提交。
@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

MOI agent follow-up (由LW授权的MOI智能体提交)

CI readback at 2026-10-17T03:02Z (head 4bf14ea, run 38994659958 "MatrixOne ALL CI", run_attempt 1, overall status in_progress):

  • Matrixone CI execution / UT Test on Ubuntu/x86 ❌ (job 117284481519, 02:22:46→02:55:55Z) — failed at the Unit Testing step; the post-failure diagnostic steps (Print Failed Packages and Tests, Recover main UT report, Upload UT diagnostics) all completed and the diagnostics artifact was uploaded.
  • Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86 ❌ (job 117284500019, 02:26:12→02:55:28Z)
  • Standalone/compose e2e BVT jobs still in progress at 03:02Z.

Evidence limitation: the failed UT job's log (~1.0 MB) is only partially surfaced through this agent's log-retrieval budget, so the failing package/test names are not quoted here; the job page's Print Failed Packages and Tests step output and the Upload UT diagnostics artifact hold the authoritative detail.

Rerun deferred: the run is still in_progress, so the standard one-shot rerun to disambiguate flake vs. real failure will be attempted in the next window once the run completes. No merge/close or branch-target actions will be performed by this agent.

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

MOI agent follow-up (由LW授权的MOI智能体提交)

CI readback at 2026-10-17T03:08Z, run 38994659958:

  • Matrixone CI execution / UT Test on Ubuntu/x86 ❌ (job 117284481519, 02:22:46→02:55:55Z) — failed at step 10 "Unit Testing"; steps 1–9 all succeeded (checkout / Go setup / cache & proxy config). All post-failure diagnostic steps succeeded, including "Print Failed Packages and Tests", "Recover main UT report for diagnostics" and "Upload UT diagnostics", so the job's UT-diagnostics artifact holds the authoritative failing package/test list.
  • Matrixone UT Coverage execution / UT Coverage on Ubuntu/x86 ❌ (job 117284500019, completed 02:55:28Z) per the PR check listing.
  • Matrixone Standlone CI execution / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC) ✅ (job 117286433927, completed 03:05:32Z); the compose-PROXY e2e job was still in_progress at read time.

Evidence limitation: the failed UT job's log was fully retrieved this round (1,021,958 bytes, within the 1 MiB ceiling), but this surface exposed only its runner-setup head and the retained copy has no authorized reader, so the concrete failing package/test could not yet be transcribed here. Until the diagnostics artifact is inspected and the failure is shown to be dev-baseline noise rather than a regression of the picked change, it must be treated as potentially related to this PR. No rerun was queued this window; no merge/close/retarget actions. Top follow-up for the next window: read the job's "Upload UT diagnostics" artifact and decide fix vs. dev-flake with named-test evidence.

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

APPROVE at 690da32. Complete three-file review: production +4, tests +42, no docs. The guard returns both possible FK metadata lookup failures before USE/DROP/CLONE, matching the existing snapshot owner. Ordinary-table, FK-topology and system-catalog callers propagate the error to the existing rollback owner; rollback failure joins rather than loses the original error. Success and referenced-table skip retain prior semantics. Existing external/sequence/UDF branches remain unaffected. Regression coverage asserts error identity and exact lookup-only SQL history, with skip/success controls; the previously failing catalog fixture now supplies valid prerequisite metadata and retains its CLONE-error assertion. No weakened defaults or heavy fixture. Reused exact-head successful CI39087676727: checkout/headSha690da32524e2; downloaded UT checkpoint selects full frontend under -race/matrixone_test without a -run filter and exits0. Coverage, configured SCA, build and active multi-CN BVT also pass. Individual fast-test timings are not retained in the summary and are not claimed. No local Go rerun or real transient native catalog failure was induced. This is an ordinary bug fix; no new state, query, lock, resource or normal TP execution work. Historical CI comments are closed by the fixture diagnosis and current successful run. No remaining actionable blocker, source edits, subagents or merge.

@mergify mergify Bot added the queued label Oct 18, 2026
@mergify

mergify Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-18 03:40 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-18 05:02 UTC · at 3fc00709eccc277c175c7a09eed2605ca1aaee29 · squash

This pull request spent 1 hour 21 minutes 29 seconds in the queue, including 54 minutes 15 seconds running CI.

Required conditions to merge

@mergify
mergify Bot merged commit 3fc0070 into matrixorigin:main Oct 18, 2026
@mergify mergify Bot removed the queued label Oct 18, 2026
XuPeng-SH pushed a commit that referenced this pull request Oct 25, 2026
…binding (#30615) (#31105)

## What type of PR is this?

- [ ] API-change
- [x] 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** (#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**
(#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 a` under
`foreign_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).

- **#30388 repro** — before: snapshot table restore and historical clone
each returned success with `orphan_count = 1`. After: both are rejected
(`internal error: cannot restore table v_orphan.c: foreign key
constraint `fk_p` would leave orphan row(s) (key value 1) ...`), current
state preserved; restoring after repairing the parent succeeds with zero
orphans and active enforcement (`ERROR 1452` on the orphan insert).
- **#30604 repro** — before: `UPDATE b SET id=3` succeeded after the
interleaved restore, orphaning `a.b_id=2`. After: rejected (`ERROR
1217`) for both tables, both directions, deletes rejected as well; rows
unchanged; schema-first ordering identical.
- **Canonical #30615 PITR case** at this base: 3/3 rounds restore the FK
(`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 #30448 the degraded
continuation on failed FK metadata lookup was removed; the remaining
baseline-materialization tracking stays in #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.

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

This branch was previously deployed

1 inactive deployment
ci — aace1af1 Deployed Oct 18, 2026 by mergify[bot]
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 kind/test-ci size/S Denotes a PR that changes [10,99] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: PITR table restore ignores FK metadata lookup errors and proceeds to DROP TABLE

3 participants