Skip to content

fix(plan): reject FK ON DELETE/UPDATE SET NULL over NOT NULL child columns (#30282) - #30925

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
daviszhen:fix-30282-fk-setnull-notnull
Oct 24, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
daviszhen:fix-30282-fk-setnull-notnull

Conversation

@daviszhen

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 #30282

What this PR does / why we need it:

Rejects at DDL time a foreign key declared ON DELETE SET NULL or ON UPDATE SET NULL over a NOT NULL child column — MySQL error 1830
(ER_FK_COLUMN_NOT_NULL, "Column 'x' cannot be NOT NULL: needed in a foreign
key constraint 'fk' SET NULL"
). Such an action could never write NULL at
runtime; MatrixOne accepted the definition, and the observed consequences
were:

  • ON DELETE SET NULL: deleting the parent "succeeded" but kept the child
    row unchanged → silent orphan
  • ON UPDATE SET NULL: the parent update failed at runtime with error 3819,
    far away from the DDL that created the trap
  • the invalid definition could also enter through ALTER TABLE ADD CONSTRAINT (issue comments)

Changes

  • pkg/common/moerr/error.go: new internal error ErrFkColumnNotNull
    (20483) mapped to ER_FK_COLUMN_NOT_NULL (MySQL 1830) with MySQL's exact
    message text; constructor NewErrFkColumnNotNull.
  • pkg/sql/plan/build_ddl.go:
    • shared validator checkFkSetNullColumnsRequireNullable — consulted by
      both CREATE TABLE (after the primary-key pass, so PK-implied NOT NULL
      is caught) and INPLACE ALTER ... ADD CONSTRAINT
    • reads nullability from Default.NullAbility (authoritative), with
      NotNull / Typ.NotNullable fallbacks for catalog-loaded definitions
    • recovery replay (replay != nil) skips the check so layouts accepted on
      older versions stay buildable during restore
  • pkg/sql/plan/build_alter_table.go: same validation in the COPY-ALTER
    add-FK path, against the final schema view (a NOT NULL column
    introduced by an earlier action of the same ALTER is caught)
  • tests: pkg/sql/plan/issue_30282_test.go (SQL-driven planner tests for
    delete/update/PK-implied/self-reference + direct helper coverage) and BVT
    test/distributed/cases/foreign_key/fk_issue_30282.sql/.result (covers
    CREATE TABLE, ALTER ADD CONSTRAINT, COPY-mode ALTER, plus nullable
    positive controls)

Verification

  • new planner tests pass; go test ./pkg/sql/plan FK/DDL suite green;
    pkg/common/moerr green
  • live verification against a local build of this branch: every statement of
    the issue reproduction (and both comment variants, incl.
    ALTER TABLE / COPY ALTER / self-reference) now fails with
    ERROR 1830 (HY000): Column 'parent_id' cannot be NOT NULL: needed in a foreign key constraint 'fk_...' SET NULL, byte-identical to the checked-in
    golden; nullable positive controls still succeed and install the constraint

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

@daviszhen

Copy link
Copy Markdown
Contributor Author

All CI legs are green at head 91c33b62ca (including the compose PROXY/PESSIMISTIC BVT runs that caught the golden-format issue earlier, now fixed in 91c33b6). Ready for review.

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 91c33b62cad097cd1e1c2bb8da294802fb3c2260

"interrupted"

…lumns (matrixorigin#30282)

MySQL error 1830 (ER_FK_COLUMN_NOT_NULL): a foreign key declared with an
ON DELETE or ON UPDATE SET NULL action must not name a NOT NULL child
column, because the action could never write NULL at runtime. MatrixOne
accepted the definition at CREATE TABLE and ALTER TABLE ADD CONSTRAINT
time; the DELETE action then silently kept the old child value (leaving
an orphan) and the UPDATE action failed only at first parent update.

- new moerr.ErrFkColumnNotNull (20483) mapped to ER_FK_COLUMN_NOT_NULL
  with MySQL's exact message text
- shared checkFkSetNullColumnsRequireNullable validator consulted by
  CREATE TABLE, INPLACE ALTER ... ADD CONSTRAINT, and COPY ALTER
  ... ADD CONSTRAINT; primary-key implied NOT NULL columns are covered
- recovery replay keeps historical layouts buildable (replay guard)
- planner tests + BVT fk_issue_30282.sql/.result

Co-authored-by: daviszhen <[email protected]>
…xorigin#30282)

mo-tester renders errors carrying a mapped MySQL code without the
"internal error:" prefix; the CI compose+proxy run expects the bare
message.
@daviszhen
daviszhen force-pushed the fix-30282-fk-setnull-notnull branch from 91c33b6 to e3cdf29 Compare October 24, 2026 03:03
@daviszhen

Copy link
Copy Markdown
Contributor Author

Rebased onto d60a98aeb6 (main had merged #31010 whose ErrDependentByCheckConstraint took internal code 20483, causing the DIRTY merge state). Resolution: this branch's ErrFkColumnNotNull moved to 20484; no functional change. pkg/sql/plan builds and the issue-focused suites re-passed in-container at head e3cdf29c73.

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 91f26777ee71efa73c86ccd23e2be49739488b9d

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: 91f26777ee71efa73c86ccd23e2be49739488b9d

Assessment: request_changes

Reviewed the complete six-file delta and affected callers. Shared DDL validation is the appropriate design, and the earlier forward-binding and simple ALTER cases now pass. However, name-based comparison of old nullability permits an ALTER bypass that still produces silent orphans.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P1 pkg/sql/plan/build_ddl.go:8187: Create child(pid INT, other INT NOT NULL) with a SET NULL foreign key on pid, then execute ALTER TABLE child DROP COLUMN other, CHANGE pid other INT NOT NULL.
    Impact: The ALTER succeeds and installs an impossible SET NULL constraint. A subsequent parent DELETE succeeds, removes the parent, and leaves the child referencing its deleted value.
    Evidence: oldNotNull is keyed by name, so the renamed FK column incorrectly inherits the exemption belonging to the removed column. CHANGE preserves ColId; compare old and final nullability using that identity. Current-head SQL probes reproduced both DROP-plus-rename and rename-away-plus-rename variants: SHOW CREATE retained NOT NULL with ON DELETE SET NULL; parent count became 0 while child other remained 1. tests.log lines 1715–1735 and 1842–1861 retain the results. Add regression coverage for name reuse.

Validation:

  • Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/741bb347650b2d5ab23413b2/attempt-1; review-evidence.json and final-audit-index.json correlate commands, source fingerprints, receipts and log hashes.

  • Isolation preflight passed. All 192 native inputs matched; repository provenance verification passed after restoring the retained compiler profile. The initial profile mismatch is retained separately.

  • run-tests.sh used the supplied test-exec and a test-only overlay. All six PR planner tests and seven SQL control groups passed; two name-reuse cases failed with demonstrated orphans. Receipt 1792836464526862427-4.json records exit 1.

  • Supplied exact-head CI reports successful build, UT, SCA and PROXY/PESSIMISTIC BVT checks.

  • Final evidence audit passed: clean frozen source, complete patch match, unique error code and reconciled results; receipt 1792836564434959760-4.json.

Limitations:

  • No separate linked-issue body or raw CI case logs were supplied.

  • Historical restore compatibility and performance were assessed from source, without local restore or benchmark runs. Added work is bounded DDL-only map construction; SELECT/DML execution paths are unchanged.

…matrixorigin#30282)

Review round 3: CHANGE/RENAME preserve a column's ColId, while its name can
be reused by a different physical column inside one ALTER
(DROP COLUMN other, CHANGE pid other ... NOT NULL, or renaming the old
column away first). A name-keyed comparison inherited the dropped column's
NOT NULL exemption and reinstalled an impossible SET NULL constraint,
orphaning child rows on the next parent DELETE. The surviving-constraint
guard now compares pre- and post-ALTER nullability by ColId.

UT: helper-level name-reuse scenarios plus end-to-end mock ALTER coverage
for both review variants; BVT records both 1830 rejections and the legal
rename-and-tighten once the constraint is dropped.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Review round-3 finding addressed at head 1d3e13e8ea63765981e04bbc517cacf484a210e0 (commit 1d3e13e8ea).

Root cause confirmed. The surviving-constraint guard keyed the pre-ALTER NOT NULL set by column name, so a column renamed onto the name of a column dropped (or renamed away) by the same ALTER inherited the dropped column's exemption and reinstalled an impossible SET NULL constraint.

Fix. checkAlterSurvivingFkSetNull now compares pre- and post-ALTER nullability by ColId identity — CHANGE/RENAME preserve the column's ColId, so name reuse cannot inherit an exemption (pkg/sql/plan/build_ddl.go). Missing/unknown identity is treated as "NOT NULL attributable to this ALTER" (no exemption).

Tests

  • TestCheckAlterSurvivingFkSetNull: added both name-reuse variants (DROP-plus-rename, rename-away-plus-rename) → 1830; controls: same name reuse staying NULLABLE is legal, and renaming the pre-existing NOT NULL column itself keeps its exemption via identity.
  • New TestIssue30282AlterNameReuseCannotBypassSetNullGuard: end-to-end mock ALTER coverage for the exact review probes — both now error 1830 naming fk_nr_setnull; same rename-and-tighten passes once the constraint is dropped.
  • Full pkg/sql/plan suite green at this head.
  • BVT test/distributed/cases/foreign_key/fk_issue_30282.{sql,result}: both variants recorded as native 1830 messages, plus the post-DROP FOREIGN KEY legal control (nr_non_null_other=1, nr_fk_count=0). The previously committed golden replays byte-identical against a build of this head, confirming no behavior drift for unchanged statements.

Live verification on a single-node instance running a binary built at this head (sha256 25db09b73c04ebe39d2a8cff63da3404ac96fd7a9c47670c958307d3b794df8b):

alter table nr_child drop column other, change pid other int not null;
ERROR 1830 (HY000): Column 'other' cannot be NOT NULL: needed in a foreign key constraint 'fk_nr_setnull' SET NULL
alter table nr_child change other tmp int null, change pid other int not null;
ERROR 1830 (HY000): Column 'other' cannot be NOT NULL: needed in a foreign key constraint 'fk_nr_setnull' SET NULL

SHOW CREATE TABLE after both rejections shows the table untouched (pid still nullable, fk_nr_setnull intact). After alter table nr_child drop foreign key fk_nr_setnull;, the identical rename-away-plus-rename statement succeeds — final shape other NOT NULL (formerly pid), tmp nullable, index follows the rename — and a parent delete with the constraint removed leaves the child row intact, as expected with no SET NULL action present.

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 1d3e13e8ea63765981e04bbc517cacf484a210e0

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: 1d3e13e8ea63765981e04bbc517cacf484a210e0

Assessment: request_changes

Reviewed the complete six-file delta and affected callers. Shared nullability validation and identity-based ALTER comparison are sound, and the earlier bypasses are addressed. However, the new CREATE validation breaks maintenance of legacy layouts that the PR explicitly preserves.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/sql/plan/build_ddl.go:4598: An existing or restored table has a NOT NULL child column with an historically accepted SET NULL foreign key. Execute TRUNCATE TABLE child or an unfiltered DELETE FROM child.
    Impact: Both operations now fail with error 1830. Scope.TruncateTable recreates the unchanged table through internal CREATE without this replay marker, so the new guard treats physical reconstruction as new constraint admission. Extend the trusted reconstruction contract to these paths while retaining validation for newly authored constraints and nullability tightening.
    Evidence: TestReviewLegacyRecreate seeds the legacy layout through the existing replay owner, then uses ordinary frontend SQL. At HEAD, COPY ADD COLUMN succeeds, but TRUNCATE and unfiltered DELETE fail with 1830 (legacy-head.log, lines 1283 and 1308; receipt 1792843139854506560-4.json, exit 1). The identical test passes with all three changed production files replaced by their exact merge-base blobs (legacy-base.log; receipt 1792843167801026006-3.json, exit 0). Add regression coverage for these unchanged-schema reconstruction paths.

Validation:

  • Evidence is retained under /home/xupeng/.local/state/mo-bot/jobs/c206b86b994bd6f96bf977ad/attempt-1. review-evidence.json and final-audit-index.json correlate commands, source fingerprints, receipts, logs and artifact hashes.

  • Isolation preflight and repository native-provenance verification passed; all 192 native inputs matched the frozen source. Tests used the supplied test-exec.

  • Production SQL probes confirmed rejection after fresh FK installation, including within one transaction, and successful nullable SET NULL actions and unrelated composite-primary-key changes.

  • Combined INPLACE ADD FK/MODIFY probes failed on both HEAD and merge-base; the preexisting duplicate-constraint failure was excluded from findings. Explicit COPY controls passed.

  • Supplied exact-head CI reports successful build, UT, SCA and BVT checks. Final audit passed with clean source, matching complete patch and reconciled terminal receipts: 1792843245799614473-4.json.

Limitations:

  • No separate linked-issue body or raw CI case logs were supplied.

  • Legacy metadata was seeded through the existing replay context; this was not a full upgrade or snapshot-restore run.

  • Performance was assessed from source without benchmarks: added work is bounded DDL metadata processing, with no new per-row SELECT/DML work.

…ble (matrixorigin#30282)

Review round 4: TRUNCATE and the truncate-optimized unfiltered DELETE
physically reconstruct the table through the internal executor, which
re-plans SHOW CREATE output as an ordinary CREATE TABLE. The 1830 guard
for newly authored SET NULL constraints fired on that trusted
reconstruction, so a pre-validation layout (NOT NULL child column with a
historically accepted SET NULL foreign key) could no longer be truncated
or bulk-deleted.

Extend the trusted-reconstruction contract: StatementOption gains
WithTrustedForeignKeyLayout, bridged through defines.TrustedForeignKeyLayout
by the internal SQL executor, and the CREATE-side 1830 gate skips only
when that marker is present. TRUNCATE/unfiltered-DELETE recreate sets it,
mirroring the sibling ALTER ... COPY replica. User-authored CREATE TABLE
keeps failing with 1830.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Round-4 P2 addressed at head 4af80f2dc500e3b7e353ded6e0f6c1ffe9367f9b (commit 4af80f2dc5).

Root cause confirmed. TRUNCATE and the truncate-optimized unfiltered DELETE recreate the table via the internal SQL executor, which re-plans SHOW CREATE TABLE output as ordinary CREATE TABLE — so the 1830 gate for newly authored constraints fired on trusted physical reconstruction of a pre-validation layout.

Fix. The trusted-reconstruction contract now covers these paths end to end:

  • StatementOption.WithTrustedForeignKeyLayout() (mirroring WithTrustedCheckConstraintNames) → bridged by the internal executor into defines.TrustedForeignKeyLayout{} ctx (pkg/util/executor/options.go, pkg/sql/compile/sql_executor.go).
  • Scope.TruncateTable's recreate opts set it alongside the existing keep-relkind/trusted-check-name flags (pkg/sql/compile/ddl.go) — single code path serves both TRUNCATE and the truncate-optimized unfiltered DELETE.
  • The CREATE-side gate skips 1830 only while that marker is present (pkg/sql/plan/build_ddl.go); replay-restore and user paths are unchanged.

Tests

  • New TestIssue30282TrustedForeignKeyLayoutRebuild: identical CREATE fails with 1830 as user-authored DDL and plans cleanly under the trusted-rebuild ctx marker.
  • Full pkg/sql/plan, pkg/sql/compile, pkg/util/executor, pkg/defines suites green at this head.
  • BVT golden for fk_issue_30282 replays byte-identical against the verification build (no drift in any previously covered statement).

Live verification (single-node instance): the legacy layout was seeded by the pristine pre-validation binary into a persistent volume — an exact old-version-upgrade scenario — then the instance was restarted on a binary built at this head (sha256 7face9af0713459b9a842fe894c64c9076c219bb67988ff821e2d2b60085aff7):

show create table lchild;   -- pid int NOT NULL + CONSTRAINT fk_legacy ... ON DELETE SET NULL
truncate table lchild;      -- SUCCESS (pre-fix: ERROR 1830)
delete from lchild;         -- SUCCESS (truncate-optimized unfiltered delete; pre-fix: ERROR 1830)
-- FK survives both rebuilds: delete from lparent where id=1 leaves the classic
-- legacy orphan, identical to merge-base behavior for this impossible constraint
create table newauth (... same layout ...);  -- still ERROR 1830 (new constraints stay rejected)

No new BVT case: the legacy layout cannot be authored at this head by user SQL (that is the point of 1830), so coverage lives in the planner UT plus this live two-version verification.

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 4af80f2dc500e3b7e353ded6e0f6c1ffe9367f9b

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: 4af80f2dc500e3b7e353ded6e0f6c1ffe9367f9b

Assessment: approve

Reviewed the complete 11-file delta, affected callers and prior review concerns. Shared schema validation, column-identity comparison and statement-scoped reconstruction trust form a coherent fix. Earlier findings are addressed; no actionable defects remain. Added work is bounded DDL metadata processing.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Reused supplied exact-head successful build, UT, SCA and PROXY/PESSIMISTIC BVT results.

  • Isolation preflight and repository native-provenance verification passed; all 192 native inputs matched the frozen source.

  • Six focused probe groups passed using test-exec: legacy child/parent COPY ALTER, TRUNCATE, unfiltered DELETE with affected-row checks, subsequent ordinary CREATE rejection, self-reference reconstruction and internal-executor trust isolation. Receipt: 1792873070082719664-4.json; log: legacy-current.log.

  • Final audit verified clean source, complete patch correspondence, formatting, unique error code and command/source/exit/log consistency. Receipt: 1792873176941549856-5.json.

  • Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/9233fac4cd9e1c95a00de601/attempt-1 in review-evidence.json and final-audit-index.json.

Limitations:

  • No separate linked-issue body or raw CI case logs were supplied.

  • Local legacy layouts were seeded through the existing replay owner; no full upgrade or snapshot-restore run was performed.

  • Performance was assessed from source without benchmarks; no new per-row SELECT/DML work was identified.

@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-24 20:20 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-24 20:24 UTC · at b42d59e01601b02715c0109252e8b1fc5be91161

This pull request spent 4 minutes 6 seconds in the queue, with no time running CI.

Reason

Pull request #30925 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

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