Skip to content

fix(plan): make overlapping ON DELETE CASCADE and SET NULL order-independent (#30246) - #31015

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
daviszhen:fix-30246-fk-overlap-actions
Oct 25, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
daviszhen:fix-30246-fk-overlap-actions

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

What this PR does / why we need it:

A plain parent DELETE on a child table that declares both ON DELETE CASCADE and ON DELETE SET NULL references to the same parent produced
answers that depended on the constraints' declaration order:

  • CASCADE declared first: the delete silently left an orphan — the
    SET NULL stream re-inserted the cascade-deleted row with its old FK
    value (cascade_pid pointing at a deleted parent);
  • SET NULL declared first: the same delete panicked
    (index out of range [5] with length 5, ColumnExpressionExecutor.Eval).

MySQL 8.0.45 applies both actions consistently regardless of order: the
doubly-owned row is deleted by CASCADE, the set-null-only row is nulled.

Root causes (two, both tied to sibling actions writing into one

shared delete-ownership stream)

  1. The overlap-resolving appendExcludeCascadeOwnedRows ANTI join (added
    earlier for REPLACE/self-refer flows) was a no-op for direct parent
    DELETEs
    (gated on skipTargetDelete), so the SET NULL stream always
    resurrected the cascade-owned row by replacing it on the same rowid.
  2. When SET NULL is the first action registered for a child table, its
    delete source is wider than the union's base layout (it carries the
    action-local update image). The ownership-union merging rewired all
    sink scans of that step to the union step — delete halves kept reading
    past the union width (panic), while the action's INSERT half lost the
    temporary column it legitimately needs.

Changes (pkg/sql/plan/build_dml_util.go)

  • Build the exclusion ANTI join also for direct DELETE
    (candidateTag == 0, the local positional JOIN ABI left=0/right=1),
    so cascade-owned rows never enter the SET NULL stream; the tagged path
    used by REPLACE flows is untouched.
  • When merging sibling delete sources, rewire only scans that belong to
    registered DELETE nodes' subgraphs
    of the same table, and truncate
    rewired scan projections to the union width; no other consumer of the
    widened action stream is touched.

Verification

  • planner unit test TestIssue30246OverlappingCascadeAndSetNullOrderInvariant
    (mock emp/dept wired with both actions; both declaration orders must plan
    with an exclusion anti-join and the same child-side action repertoire)
  • full pkg/sql/plan FK/Delete/Update/Replace/Cascade/SelfRefer suites and
    pkg/sql/compile delete-scope tests green
  • live verification on a build of this branch — the issue's exact fixture:
    scenario pristine main this branch
    order 1 (CASCADE first) orphan ((10,1,NULL) kept) (12,2,NULL),(13,2,3) ✓ MySQL
    order 2 (SET NULL first) panic 20101 [5]/5 (12,2,NULL),(13,2,3) ✓ MySQL
    3-way overlap (CASCADE + 2 SET NULL) — (12,2,NULL,3),(13,2,3,3) ✓
  • behavior regression replay: all 29 existing
    test/distributed/cases/foreign_key/*.sql replayed on pristine main
    (a648b13… binary built from upstream 2b388dd) and this branch; every
    statement's outcome compared — zero differences
  • BVT pair fk_issue_30246.sql/.result generated from the verified live
    end states

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

Copy link
Copy Markdown
Contributor

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

Commit: fed1df5773baaab90ae38a8893de609a19e0fd30

Review completed. Read the assessment.

@daviszhen

Copy link
Copy Markdown
Contributor Author

All CI legs are green at head fed1df5773 (Mergify rebase of verified head 6b770c3b1b; fix scope pkg/sql/plan/build_dml_util.go is byte-identical across the rebase, so the live evidence above stands). Ready for review.

@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: fed1df5773baaab90ae38a8893de609a19e0fd30

Assessment: request_changes

Reviewed the complete four-file delta and affected callers. Extending cascade exclusion in the existing planner is appropriate, but the new DELETE filter excludes required index maintenance and descendant FK consumers from merged cascade sources.

Model: gpt-6-astra / xhigh

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

  • P1 pkg/sql/plan/build_dml_util.go:1091: A child has two ON DELETE CASCADE FKs to one parent, plus a secondary/UNIQUE index or a referencing grandchild. Delete a parent matched only by the second FK—for example, parents 1 and 2, child (id=10,a=2,b=1,u=100), and a grandchild referencing child 10.
    Impact: The child DELETE consumes the union, but index deletion and descendant actions still consume the first cascade source. This leaves stale index entries and can leave orphaned grandchildren. Preserve all deletion-dependent consumers while keeping UPDATE insertion images separate, and add regression coverage.
    Evidence: The same-TblId predicate excludes hidden-table DELETE nodes and separate descendant-action branches. buildDeleteRegularIndex creates its own source scan; repeated buildDeletePlans returns at line 1116 before rebuilding maintenance. An extracted-loop probe passes for the base but fails for the candidate: index and grandchild consumers retain the old source step. See review-rewire.log and checks/1792810558098042107-3.json (exit 1). The proposed SQL reproduction is retained but was not executed.

Validation:

  • Frozen evidence reports successful exact-head build, UT, SCA, coverage and BVT checks; local_validation is empty. Author-reported live results have no retained execution artifacts.

  • Isolation preflight passed: checks/1792810406272226881-5.json and review-preflight.log.

  • Standalone Go probe ran through the supplied test-exec with assigned caches: base subtest passed; candidate failed both maintenance-consumer assertions.

  • Audit passed: checks/1792810659845587457-5.json and review-source-audit.json verify clean frozen HEAD, the four-file delta, extracted snippet identity, receipts and logs.

  • Reviewed positional/tagged projections, insertion ownership, index maintenance, descendant actions, sink folding and all added tests. The new SQL cases omit the failing consumers.

  • Assessment, review notes, logs and proposed reproduction are retained under /home/xupeng/.local/state/mo-bot/jobs/894a6451e5e78402d9a2250d/attempt-1.

Limitations:

  • No native planner suite or live SQL reproduction ran locally. The finding combines reachable source paths with an extracted-loop counterexample.

  • Performance assessment was static: applicable DELETEs add an anti-join and parent-source read; repeated-source merges add graph traversal and a visited map. No performance measurements were made.

  • The linked issue's full discussion was unavailable; its contract was assessed from the frozen PR description and regression fixtures.

…pendent (matrixorigin#30246)

A child row matched by both an ON DELETE CASCADE and an ON DELETE SET NULL
constraint to the same parent was handled differently depending on FK
declaration order:

- one order resurrected the cascade-deleted row: the SET NULL stream
  re-inserted its old foreign key value, leaving an orphan row whose FK
  points at a deleted parent
- the other order panicked at runtime with 'index out of range' when the
  shared delete-ownership union rewired a wide action stream into the
  narrower base-column layout

Two planner invariants now hold for direct parent DELETEs with mixed
actions:

- cascade-owned rows are excluded from the SET NULL stream (the existing
  appendExcludeCascadeOwnedRows semantics, added for REPLACE flows, now
  also built with the local positional pointcut ABI of a direct DELETE:
  ANTI join against the statement's parent key values)
- the delete-ownership union of sibling actions rewires only the delete
  halves of earlier actions, and rewired sink scans are truncated to the
  union width; the INSERT side of an UPDATE-driven action keeps the
  action's own widened stream

Verified live on both declaration orders and on a three-way overlap
(CASCADE + two SET NULL), all matching MySQL 8.0.45 end state, plus a
zero-diff behavior replay of the whole existing foreign_key BVT family
against pristine main.

Co-authored-by: daviszhen <[email protected]>
…rixorigin#30246)

Review follow-up for matrixorigin#31015: the repeated-source merge previously only
moved scans inside same-TblId delete branches to the union step. Two
consumer classes kept consuming the superseded first stream:

- index-maintenance deletes, whose hidden index tables carry their own
  TblId, leaving stale index entries after a parent delete matched only
  by the second of two cascades;
- descendant referential-action branches, whose grandchild tables again
  carry their own TblIds and whose positional cascade pieces are not
  even wired under a DELETE node yet when the merge runs, leaving
  orphaned grandchildren.

Invert the gate: every consumer of the previous ownership stream follows
the merge, except the INSERT-side images of update-driven actions. Those
are fenced off by reachability from INSERT/PRE_INSERT(+UK/SK)/
MULTI_UPDATE roots and by the newSourceDependencies guard, so their
widened action-local layout (base row plus temporary update columns) is
never re-pointed at the union's flat base-row layout.

Regression coverage replays the reviewer scenario in the plan builder —
two cascades to one parent on a child with secondary/unique indexes and
a cascade grandchild must leave every deletion-side consumer of the emp
family reading the single final merged stream — and extends the BVT case
with the live end-to-end variant (second-cascade-only delete: grandchild
survival check, stale unique-index detection via re-insert, first-
cascade recheck after re-insert).
@daviszhen

Copy link
Copy Markdown
Contributor Author

Review follow-up addressed at 90f4fe88fc06244c530d60c2a99e9c3c29af02e7 (rebased onto upstream/main 3878a13ef0; the branch's previous Mergify main-merge is folded away).

The P1 gate is inverted. The probe was right: the same-TblId reachability predicate could never see the two missing consumer classes — hidden index-maintenance tables carry their own TblId by construction, and the descendant cascade branches are not even wired under a DELETE node when the merge runs for a direct DELETE (the positional two-input ABI pieces are appended before their join/DELETE parents, so subtree reachability from DELETE roots structurally misses them — confirmed by tracing delete-root idx=44 children=[43] at merge time while the stale scan sat at node 39, unwired).

The new predicate removes identity-based inclusion entirely: every SINK_SCAN consuming the superseded step follows the union, and the only exclusion is the INSERT side of an update-driven action, now fenced off positively by reachability from INSERT / PRE_INSERT / PRE_INSERT_UK / PRE_INSERT_SK / MULTI_UPDATE roots (plus the pre-existing newSourceDependencies guard for the merged-in action's own inputs). INSERT-side images were never structurally pinned before; they are now excluded by construction rather than by absence from a delete closure. The widened-image projection guard and the union-width slice for legacy wide scans are unchanged.

Regression coverage at both layers, mirroring the reviewer scenario (p4/c4 with cascades on a and b, c4.u unique, g4 grandchild on c4.id):

  • Plan-builder UT TestIssue30246MergedCascadeRewiresAllDeleteConsumers: every deletion-side consumer of the emp family (child delete, both hidden index deletes, grandchild cascade) must converge on the single stream the child's own delete reads — previously the index and grandchild branches retained the first action's step (the probe found {4, 10}; now exactly one). The pre-existing order-invariance test for CASCADE+SET NULL still passes, confirming the INSERT image stays put.
  • BVT test/distributed/cases/foreign_key/fk_issue_30246.{sql,result} extended with the live variant: a parent delete matched only through the second cascade must retire the grandchild rows (g4_rows = 0) and the hidden unique entries (re-inserting u=100 afterwards must succeed — on the old head this correctly reproduces your finding: orphan g4 row plus ERROR 1062 Duplicate entry '100' for key 'u'). The existing CASCADE+SET NULL sections are byte-identical in the regenerated golden — both declaration orders keep producing the same rows, so the INSERT-side exclusion is behaviorally intact. The golden was regenerated by live replay against an instance running this exact head; the full pkg/sql/plan suite is green.

…atrixorigin#30246)

The coverage gate measured 71.88% (below the 75% requirement) on the
changed lines of build_dml_util.go: the INSERT-side reachability fence
of the repeated-source merge only runs while INSERT-family nodes exist
(a REPLACE statement plans delete and insert in one query), and the
tagged recursion of the cascade-owner exclusion needed a grandchild
whose own actions overlap. Add plan tests for both shapes in both
declaration orders; changed-block coverage rises from 72.7% to 87.9%.
@daviszhen

Copy link
Copy Markdown
Contributor Author

Coverage gate remediation @ 590e4786ec

The changed-code coverage gate (75% threshold) correctly rejected the previous head at 71.88%. Root cause: three behaviors in pkg/sql/plan/build_dml_util.go were only reachable through shapes the existing unit tests never built:

  1. INSERT-side reachability fence of the repeated-source merge (markInsertDownstream, build_dml_util.go:1084-1104) — the fence only executes while INSERT-family nodes exist in the query graph at merge time. A plain DELETE never produces them; a REPLACE statement plans its delete and insert in one query, so the overlap merge runs with INSERT nodes present.
  2. Tagged cascade-owner exclusion (appendExcludeCascadeOwnedRows early returns) — the bind-tagged branch needs a recursive build, i.e. a grandchild whose own foreign-key actions overlap.

New tests in pkg/sql/plan/issue_30246_coverage_test.go, in both declaration orders:

  • TestIssue30246ReplaceOverlapFencesInsertImage — REPLACE INTO dept ... with the overlapping SET NULL/CASCADE children plus the cascade grandchild: verifies the plan stays acyclic, the replacement-row insert side exists, and the cascade deletes of emp/empgc are planned.
  • TestIssue30246TaggedGrandchildOverlapDelete — DELETE FROM dept where a grandchild empgcsc declares overlapping SET NULL/CASCADE to emp: verifies the recursive plan stays acyclic and the grandchild physical delete exists.

(An ON UPDATE variant was considered first; the update planner route explicitly rejects multiple parent foreign key actions targeting the same child table, so REPLACE is the supported statement shape that drives this merge with an insert image present.)

Verification at 590e4786ec:

  • Changed-block coverage of the PR diff measured locally with go test ./pkg/sql/plan/ -coverpkg=./pkg/sql/plan/ -coverprofile: 87.9% (was 72.7% at dd27cc3b; the same measure predicted the gate's 71.88% before, so the delta is directly comparable). The remaining uncovered blocks are defensive guards (ProjectList width slice for the width-mismatch scenario and two single-case early returns) on shapes the planner currently accepts only partially.
  • Full ./pkg/sql/plan/ test suite green (10.0s); gofmt clean.
  • New ALL-CI run 40129024550 in flight.

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 590e4786ecb9a77b326c1b5055c760fe279f1747

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: 590e4786ecb9a77b326c1b5055c760fe279f1747

Assessment: approve

Reviewed the complete six-file delta and affected callers. The fix belongs in the existing DML planner: it excludes cascade-owned rows from SET NULL images, preserves INSERT projections, and retains index and descendant maintenance. Both earlier review findings are addressed. No introduced actionable blocker remains.

Model: gpt-6-astra / xhigh

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

Validation:

  • Verified frozen HEAD, merge-base, clean source and supplied patch identity. Reviewed all added tests, SQL expectations and supplied review concerns.

  • Reused CI run 40129024550 after verifying exact-head checkout/build provenance and downloaded artifact SHA-256 digests. All eight planner race-test shards and their aggregate stage exited 0.

  • Exact-head Compose/PROXY BVT executed fk_issue_30246.sql: 75/75 statements passed, with zero failures, ignored statements or abnormal results. The cases verify declaration orders, unique-key reuse and descendant deletion.

  • Retained CI logs show SCA completed with 0 issues and the changed-block coverage gate passed at 87.5%. Coverage was not treated as a semantic oracle.

  • Evidence audit passed: checks/1792876876329768851-3.json. git diff --check passed: checks/1792876876217397299-3.json. Commands, source fingerprints, exit statuses and retained logs were reconciled. Reports and CI archives reside under /home/xupeng/.local/state/mo-bot/jobs/c4c0d5039bf49c35419554f1/attempt-1.

  • Performance review was static: overlapping actions add an anti-join and parent-source read; repeated-source merges add traversal and temporary state bounded by plan size. Ordinary SELECT and unrelated DDL paths are unaffected.

Limitations:

  • No local Go/native tests or benchmarks were repeated; traceable exact-head CI execution was reused.

  • The separately reported CASCADE-first grandchild over-deletion was classified as pre-existing in the supplied baseline comparison; this approval does not claim that separate issue is fixed.

  • The linked issue's full discussion was unavailable; its contract was assessed through the frozen PR evidence and regression fixtures.

@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-24 21:22 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-25 00:43 UTC · at b264f5df894c9e5aba5e852e73f6a5acd80e3614 · squash

This pull request spent 3 hours 20 minutes 58 seconds in the queue, including 54 minutes 9 seconds running CI.

Required conditions to merge

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

kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants