Skip to content

fix(plan): rebind foreign keys to equivalent surviving keys on parent-key drop - #31628

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
aptend:fix/astra-meow-30248-30342
Oct 29, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
aptend:fix/astra-meow-30248-30342

Conversation

@aptend

@aptend aptend commented Oct 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:

Fixes #30342

What this PR does / why we need it:

MySQL 8.0 allows dropping the PRIMARY/UNIQUE key recorded by a child foreign key when another key covering the same columns survives, and keeps the FK enforced through the remaining key. MatrixOne rejected such drops with error 1553 even when an equivalent unique index remained - including the atomic DROP INDEX ..., ADD UNIQUE INDEX ... replacement and the PRIMARY-to-UNIQUE transition (issue #30342).

The equivalent-key transition stays planner-only up to the catalog rebinding (UpdateFkSqls); the stored constraints are repaired inside the same DDL transaction (no execution-engine, catalog-format, or wire change):

  • resolveForeignKeyBoundIndexDrops allows dropping the recorded key only when another covering PRIMARY/UNIQUE key survives the whole statement, and moves each affected binding to the surviving key through GetSqlForUpdateFkReferencedIndex in the same ALTER transaction. A same-statement ADD UNIQUE INDEX counts as the survivor regardless of SQL clause order - the deferred PRIMARY rebinding resolves after the COPY's final key set is assembled. Removing the last covering key still rejects with 1553. Legacy bindings keep the conservative rejection; standalone DROP INDEX ... ON p of a rebindable key routes through ALTER.
  • Reviews 5690727734 and 5691776262 hardening: a stale binding claim only counts when a real PRIMARY/UNIQUE key under that name still covers the foreign key's columns (a keyless table's fake physical primary and an index name reused on unrelated columns never satisfy it); legacy protection applies only to eligible dropped keys, so dropping an ordinary secondary index on the referencing columns works again; every catalog binding update rides the same DDL transaction as a durable UpdateConstraint of the referencing child, and a name recorded before rebinding heals to a covering survivor when the child is re-materialized instead of failing the recreation.
  • Review 5695003826 closure (self-references): the INPLACE path maps the durable zero self-reference sentinel to the ALTER's own table id so syncDurableForeignKeyIndexBindings also repairs the self-referencing child's stored ForeignKeyDef; the COPY path runs the snapshot-authoritative final restore and the same-transaction durable alignment of the published relation through one production boundary, finalizeAlterCopyForeignKeyState. Catalog binding and stored constraint agree immediately after both algorithm paths, with no later re-materialization required.
  • Reviews 5699738215 and 5700876116 closure (single-statement ADD + DROP): when one ALTER both adds a self-referencing FK and drops the key that FK's initial recording binds to, the rebinding now also rewrites the same-statement durable AddFk action - the payload the executor materializes into the stored constraints - to the surviving covering key, so the persisted ForeignKeyDef.ReferencedIndexName and the catalog row commit on the same survivor instead of the stored def silently keeping the dropped key name. Both clause orders are covered: ADD-then-DROP rewrites the action through the rebind resolution; DROP-then-ADD binds the survivor naturally at planning time. Dropping the last covering key still rejects with 1553, and recreating an equivalent key keeps the binding stable while re-arming atomic replacement.

Testing (pushed head, linearly rebased on current main):

  • Caller-level native tests executing the production boundaries (not hand-orchestrated): the INPLACE sentinel mapping resolves the altered table and aligns its own stored binding; the COPY boundary restores first and then aligns the published relation's durable def by its real table id; guard controls skip the alignment for temporary tables and statements that do not rebind; a durable write failure propagates out of the production caller with the input snapshot unmutated. Each test captures the actual UpdateConstraint def and round-trips it through the same MarshalBinary codec that persists schema.Constraint, asserting the surviving binding, the zero self sentinel, and the remapped column ids. 8/8 focused tests rc0 on the pushed head; both counterfactuals verified: disabling only the INPLACE sentinel mapping, or only the COPY post-restore alignment, makes the corresponding caller regressions fail (rc1), and SHA-verified restores return 8/8 rc0.
  • Planner FK family 6/6 rc0 and go vet ./pkg/sql/compile ./pkg/sql/plan rc0 on the pushed head. The compound producer case is a real SQL-to-plan regression: pre-fix it fails rc1 because the same-statement AddFk action persists the dropped key (expected the surviving uq_second, actual the removed uq_first), post-fix it passes rc0 for both clause orders while keeping the catalog rebinding SQL and the reversed-order control.
  • Consumer-fidelity witness rc0 (1 top level / 2 subtests) on the real Scope.AlterTableInplace: the run captures the actual durable UpdateConstraint request bytes handed to Relation.AlterTable and decodes them with the production constraint codec, asserting the persisted binding equals the planner-emitted binding verbatim, the plan-time zero self-reference sentinel survives, and a persist failure propagates out instead of degrading to catalog-only success. This, composed with the planner-side RED above, pins the producer/consumer contract as request bytes at the real caller boundary; the 8 caller tests above already cover the post-persist durable-alignment continuation (rel.UpdateConstraint).
  • Guarded two-CN runs (fresh audited starts on private 18000-18099 endpoints only, fail-closed prestart parse, unfiltered pre-SQL audit of owned TCP/UDP rows plus HAKeeper/seed/SQL ownership on both CNs, exact owned-PID teardown): the keyset/self-FK stage re-verified immediate rebinding (sk_a -> sk_b INPLACE, PRIMARY -> spk COPY), old-name reuse on equivalent columns not flipping the binding, orphan 1452, last-key and no-survivor 1553, cross-CN visibility; the compound stage re-verified per statement that both CNs see the survivor binding immediately, that the last covering key stays protected, and that recovery through a recreated key follows the rebinding. An extra manual single-connection recovery script stopped at the expected 1553 (the installed mysql client maps --execute and --force as mutually exclusive) and is reported as failed, not as a pass.
  • Persistent BVT in real CI comparison mode via an isolated mo-tester installation (shared tester config untouched): new fk_compound_self_rebind 24/24 statements rc0 with -m run -n -g -o -e pessimistic_transaction, covering the review counterexample (two equivalent unique keys; one statement adds the self FK and drops the recorded key), immediate binding rows, last-key 1553, orphan 1452, recovery through a recreated key, and the reversed clause order, with the frozen .result golden byte-identical before and after; new fk_self_rebind_durable 25/25 and retained fk_drop_rebind_index 40/40 rc0 unchanged (no frozen golden touched). CI checks on this new head are reported only as observed (pending/queued/skipped are not passes).

Limitations (explicitly not claimed as proven):

  • mo_catalog.mo_foreign_keys reads show the catalog binding; the stored ForeignKeyDef blob itself has no SQL seam. Durable correctness is proven by capturing the actual UpdateConstraint bytes at the production caller boundaries - including the in-place witness's Relation.AlterTable request decode - plus the live-service behavior above, not by a SQL read of the blob, and not as an integrated SQL-to-on-disk-blob proof.
  • Actual transaction rollback / mid-transaction crash is not separately end-to-end tested (no deterministic failure seam between the catalog update and commit); the same-DDL transaction contract is reused and the caller error propagation is verified.
  • Creating a same-column self-referencing FK (FOREIGN KEY (v) REFERENCES t(v)) is rejected by an existing rule and is not treated as a defect; covered self-FKs use distinct columns.

Scope: issue #30342.

@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 28, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 70dbd60c969e0a9bde8e1a0a6498bf847fc6b2ea

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: 70dbd60c969e0a9bde8e1a0a6498bf847fc6b2ea

Assessment: request_changes

Found three correctness defects in foreign-key rebinding and a BVT isolation defect. Review records, probes and validation receipts are retained; source remains unchanged.

Model: gpt-6-astra / xhigh

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

  • P1 pkg/sql/plan/build_ddl.go:6739: Drop a referenced PRIMARY KEY while an equivalent UNIQUE survives, then drop that UNIQUE. Rebinding updates mo_foreign_keys but leaves the child's durable ForeignKeyDef.ReferencedIndexName as PRIMARY.
    Impact: The fake physical primary key satisfies the name-only existence check, allowing removal of the last covering key. Reusing a dropped index name for unrelated columns produces the same failure. Persist child constraint bindings atomically with catalog updates and validate actual key eligibility and column coverage.
    Evidence: ResolveById reads engine metadata (frontend/compiler_context.go:685); COPY reconciliation changes only column/table IDs (compile/alter.go:3358). The rebind emits only catalog SQL (build_ddl.go:7928). The fake-PK and reused-name contract probes both fail in resolver-probe.log; ordinary controls pass. Detailed reachability is recorded in source-review.md.

  • P2 pkg/sql/plan/build_alter_add_primarykey.go:108: DROP PRIMARY KEY on a self-referencing table with an equivalent surviving UNIQUE.
    Impact: Passing CopyTableDef makes the rebind target the temporary copy's table name. COPY subsequently discards those temporary catalog rows and transfers the unchanged source rows, leaving the self-FK catalog binding as PRIMARY. Use the original table identity for catalog updates while selecting against the surviving copy schema.
    Evidence: build_alter_table.go:1401 assigns the temporary name; build_ddl.go:6701 uses that name for self references. compile/alter.go:2002 executes updates before GetSqlForTransferAlterCopyFk, whose first operation deletes temporary-child rows (build_dml_util.go:6191). Existing self-reference coverage tests only INPLACE index drops.

  • P2 pkg/sql/plan/build_ddl.go:6910: A legacy FK has an empty ReferencedIndexName, and its parent has both UNIQUE(u) and an ordinary secondary index on u. Drop the ordinary index.
    Impact: The new resolver rejects the drop with 1553 even though the secondary index cannot be the referenced key and the UNIQUE survives. Both DROP INDEX syntaxes are affected. Preserve the previous PRIMARY/UNIQUE eligibility filter before applying legacy binding protection.
    Evidence: The unchanged baseline checker requires index.Unique at build_ddl.go:6785. New callers collect Parts without that filter, and the legacy branch at 6733 rejects matching columns. The retained probe confirms baseline acceptance and candidate rejection.

  • P2 test/distributed/cases/foreign_key/fk_drop_rebind_index.sql:52: Run the new BVT on a shared instance or alongside another database containing foreign keys on tables named c2 or c3.
    Impact: The case leaves its database, eight tables and four FK constraints behind. Its catalog queries also omit db_name, allowing other fixtures' rows into expected results. Add database predicates and exit teardown, update the result file, and verify cleanup before a same-instance rerun.
    Evidence: Lines 32 and 42 filter only table_name; the file ends without teardown. The repository testing contract requires scoped deterministic outputs and removal of created databases. review-audit.log confirms entry cleanup only.

Validation:

  • Isolation preflight passed: checks/1793227361196693800-3.json and preflight.log.

  • Extracted production-helper probes ran with the supplied test-exec: two controls passed and three contract assertions failed; exit 1 matches checks/1793227421775488853-3.json and resolver-probe.log.

  • Static audit passed: frozen range, unchanged source, patch identity, formatting, extraction provenance, all discussion keys and 39 BVT statements; checks/1793227654751707285-4.json and review-audit.log.

  • Frozen-head CI reports successful build, UT, coverage, SCA and multi-CN BVT checks.

Limitations:

  • Local probes use extracted production functions with type/context/error stubs; they are not linked planner-package tests or SQL executions. Public reachability and the self-COPY defect were established by source tracing.

  • Detailed CI logs and author-run artifacts were not supplied; local_validation is empty.

@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 2abbf8351161c0234a1e107395f36f634c8e7af3

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: 2abbf8351161c0234a1e107395f36f634c8e7af3

Assessment: request_changes

One P2 concern from review 5699738215 remains confirmed by current-source tracing. The later general approval does not address this compound ALTER case. Earlier reported scenarios are resolved.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

  • P2 pkg/sql/compile/create_fk.go:288: Create t(id INT, pid INT, UNIQUE KEY a(id), UNIQUE KEY b(id)), then execute ALTER TABLE t ADD CONSTRAINT fk FOREIGN KEY(pid) REFERENCES t(id), DROP INDEX a.
    Impact: The statement commits catalog binding b while the persisted ForeignKeyDef still names removed index a, violating the required catalog/durable metadata alignment.
    Evidence: build_ddl.go:7399 stores the initially selected a in the AddFk action. Final rebinding at :7954 rewrites only CopyTableDef, absent for this INPLACE statement. ddl.go:1313 persists the unchanged action; adding the engine self-reference sentinel does not update qry.TableDef. This loop therefore traverses the empty original RefChildTbls and skips repair. Include newly added self-reference targets in durable synchronization or rewrite the final AddFk binding. Add a regression inspecting the persisted constraint immediately after the compound ALTER.

Validation:

  • Reviewed the complete 15-file delta, affected owners/consumers, linked issue 30342 and all 11 discussion entries; saved discussion-assessment.json and source-review.md.

  • Static audit passed: frozen clean head, matching patch, diff whitespace, formatting of nine Go files, 120 SQL/result statement pairs and complete discussion coverage. Receipt: checks/1793289508868434815-4.json; log: audit-review.log.

  • Retained both audit receipts; the initial audit's CI-reporting error was corrected. Frozen CI and author validation were assessed as reported evidence.

Limitations:

  • No new Go or database tests were run; the finding is established by source tracing. Prior probe and author-validation raw logs were unavailable in this job.

  • End-to-end injected transaction rollback was not independently tested. No FK-enforcement loss is claimed.

…-key drop

MySQL allows dropping the PRIMARY/UNIQUE key recorded by a child foreign key while another covering key survives; rebind each affected child binding to the surviving key inside the same ALTER transaction. Covers the atomic DROP+ADD replacement, the PRIMARY-to-UNIQUE transition, and standalone DROP INDEX routing through ALTER. Legacy metadata keeps the conservative rejection and the last covering key is still protected, including across stale cached child claims. Issue matrixorigin#30342.
…sition

TestTruncatePreservesMaterializedForeignKeyIdentity pinned the pre-matrixorigin#30342 rejection for dropping the recorded key while an equivalent unique survives; the fix legitimately rebinds the child binding, so the oracle now proves identity by the recorded key, the rebind to the surviving key, and last-covering-key rejection. Issue matrixorigin#30342.
…and copy rebinds

Review 5690727734: a stale binding claim must name a real PRIMARY/UNIQUE key that covers the foreign key's columns (a keyless table's fake physical primary and an index name reused on unrelated columns no longer satisfy it); legacy protection applies only to eligible PRIMARY/UNIQUE dropped keys so ordinary secondary indexes stay droppable, matching the baseline checker; a self-referencing DROP PRIMARY KEY rebinds the catalog row addressed to the original table since the COPY relation's temporary row is discarded by the transfer. Adds planner tests for all three, adjusts the truncation identity UT oracle to the equivalent-key transition, and scopes the BVT catalog queries to its database with an exit drop-database teardown (golden file regenerated). Issue matrixorigin#30342.
…action

Review 5691776262: DROP PRIMARY KEY resolves its child rebinding only after the COPY's final key set is assembled, so a same-statement ADD UNIQUE covers the transition on both clause orders. Rebinding updates each referencing child's stored ForeignKeyDef via UpdateConstraint inside the same DDL transaction as the mo_foreign_keys row - self-references through the COPY definition and INPLACE alters through the relation itself - while a stale name recorded before re-materialization heals to the covering survivor instead of failing the recreation. Adds planner regressions plus a persistent self-referencing BVT case (fk_rebind_truncate) covering rebind, TRUNCATE, recreation, and last-key 1553 / orphan 1452 enforcement. Issue matrixorigin#30342.
…paths

Close review 5695003826: map the INPLACE zero self-reference sentinel to the
altered table's real id so syncDurableForeignKeyIndexBindings repairs its own
stored ForeignKeyDef; run the COPY final restore and the same-transaction
durable alignment of the published relation through one production boundary,
finalizeAlterCopyForeignKeyState. Capture actual UpdateConstraint bytes in
caller-level tests, round-trip them through the production codec, and add
the fk_self_rebind_durable regression (INPLACE + COPY equivalent-key drops,
old-name recreation, last-key and 1452/1553 controls).
@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 726255bc8dcaa14b9169e9046051dc4b725f0eb0

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: 726255bc8dcaa14b9169e9046051dc4b725f0eb0

Assessment: approve

Earlier FK-rebinding findings, including the compound ALTER durable-binding mismatch, are resolved. Complete delta, affected owners and discussion reviewed; no actionable findings remain. Source is unchanged.

Model: gpt-6-astra / xhigh

Session: 01a1869d-999c-7481-b340-ae4a63e8cee4 · slot 1 · generation 2

Validation:

  • Static audit passed: 17 changed files, nine formatted Go files, 144 SQL/result statement pairs and all 13 discussion keys. Receipt: checks/1793295845069737041-2.json; log: static-review.stdout.log.

  • Initial audit failed only because the supplied patch omitted its final newline; corrected comparison passed. Both receipts and logs are retained.

  • Frozen-head evidence reports successful build, UT, SCA, coverage and active multi-CN BVT. Author-reported planner, persistence and SQL checks were assessed alongside source tracing.

  • Saved review-plan.md, discussion-assessment.json, source-review.md and validation-reconciliation.json.

Limitations:

  • No new Go or SQL runtime tests were executed locally; raw author and CI logs were unavailable.

  • End-to-end injected transaction rollback, crash recovery and SQL-to-stored-constraint verification were not independently executed.

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

mergify Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

12 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Thu 29 Oct, 17:46 · rule main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue 17:58 · 4a1681f

Reason

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

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

  • Requeue this pull request

Times in UTC · dashboard · how the merge queue works

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

dequeued kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Compatibility]: FK blocks replacing its bound parent key despite an equivalent UNIQUE

4 participants