Skip to content

fix(plan): handle empty indexed FK cascades and cover self-FK ALTER - #29994

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
aptend:fix/indexed-fk-cascade-empty
Oct 14, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
aptend:fix/indexed-fk-cascade-empty

Conversation

@aptend

@aptend aptend commented Oct 12, 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 #29954

Related to #29910: the production fix is already on main in #27799; this PR adds regression coverage.

What this PR does / why we need it:

Deleting a parent with no matching children can panic when an indexed CASCADE child table contains unrelated rows. Direct DELETE appends these recursive branches after planner tag remapping. Use a matched-only index lookup and local input positions throughout untagged recursive deletes, and keep runtime filters disabled to avoid a feedback wait cycle. Carry the tagged self-referencing CASCADE source into its recursive context before createQuery, so indexed REPLACE keeps the planner tags needed by index scans, locks, and DELETE. Positional direct-DELETE actions still use the matched-only local layout.

Add planner assertions and SQL regressions for empty and matching cascades, single/composite/unique indexes, NULL keys, prepared deletes, rollback, unrelated-row preservation, and RESTRICT controls. Cover indexed self-referencing REPLACE with secondary/unique indexes, recursive descendants, empty actions, forced-index reads, key reuse, and subsequent direct DELETE. Extend the existing ALTER regression to cover populated self references during VARCHAR resizing, including dropping and re-adding the foreign key (#29910).

Validation:

  • Review follow-up: the indexed self-referencing REPLACE planner regression reproduces a panic at the previous PR head. After propagating the descendant source tag, focused regressions and full pkg/sql/plan tests pass (9.479s); package vet and configured incremental golangci-lint pass.
  • Updated indexed-cascade SQL regression passes normal mo-tester comparison twice (128/128 each), with database teardown independently checked before/between/after runs. Secondary-index EXPLAIN confirms that the forced-index control uses an Index Table Scan.
  • Rebased onto main 7af631bdf7; full pkg/sql/plan tests pass with repository CGo setup, Go 1.27.1, GOAMD64=v3, GOEXPERIMENT=simd.
  • gofmt, diff checks, package vet, and configured incremental golangci-lint pass.
  • Before rebase, normal mo-tester comparisons passed: ALTER-integrity 81/81 statements; indexed cascade 102/102 twice; six related FK cases 681/681. The main update does not change the FK planner/ALTER paths; its result-metadata evidence hook is opt-in and disabled in these tests.
  • Actual COM_STMT_EXECUTE checks passed for single/composite indexes, empty and matching deletes, rollback, and second-session isolation.
  • On the clean pre-fix baseline, the original SQL reproduces the panic and both new planner subtests fail.

This PR targets main; it does not include a v4.2.5 backport.

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

Copy link
Copy Markdown
Contributor

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

Commit: 4a19f94b73c0913a9208622a624da8ecf8234ffd

Assessment: request_changes

Reviewed the complete six-file delta. The direct DELETE fix introduces a planning regression for indexed self-referencing CASCADE under REPLACE.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

  • P2 pkg/sql/plan/build_dml_util.go:6561: REPLACE on a table with an ON DELETE CASCADE self-reference and a regular secondary or unique index. Example: create table sr(id int primary key, parent_id int, key idx_parent(parent_id), foreign key(parent_id) references sr(id) on delete cascade); insert into sr values (1,null),(2,1); replace into sr values (1,null);
    Impact: The new predicate incorrectly selects the positional DELETE path before createQuery, producing an untagged hidden-index scan that causes planning to fail.
    Evidence: Modern REPLACE builds its cascade graph before createQuery (build.go:250–270). The self-cascade context at build_dml_util.go:1821–1827 leaves sourceTag and updateColLength zero, making localCascadeDelete true. Lines 6609–6611 disable projection preservation, so appendDeleteIndexTablePlan omits scan BindingTags at 4492–4494. Subsequent TABLE_SCAN remapping unconditionally reads BindingTags[0] (query_builder.go:1314). Previously this branch retained a binding tag. Distinguish the actual construction phase or propagate the self-cascade tag, and add an indexed self-referencing REPLACE regression.

Validation:

  • Traced direct DELETE, ordinary tagged cascades, self-referencing REPLACE, index lookup, deletion and optimizer consumers.

  • Reviewed all added planner tests and SQL/result regressions; none covers indexed self-referencing REPLACE.

  • Frozen exact-head CI reports successful UT, SCA, coverage, proxy BVT, pessimistic multi-CN BVT and required checks.

  • gofmt and git diff --check passed; assigned HEAD and unchanged source verified.

  • Saved the source-trace audit and diagnostic SQL under the current attempt directory.

Limitations:

  • Finding established by source tracing; the SQL trigger was not executed locally. Available native artifacts failed the repository owner's input-equivalence requirement.

  • Author-reported pre-rebase runtime checks were treated as supplementary evidence.

  • Full linked-issue bodies were absent. No independent performance measurements were made.

@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: 4a19f94b73c0913a9208622a624da8ecf8234ffd

Assessment: request_changes

Reviewed the complete six-file delta. The direct DELETE fix introduces a planning regression for indexed self-referencing CASCADE under REPLACE.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

  • P2 pkg/sql/plan/build_dml_util.go:6561: REPLACE on a table with an ON DELETE CASCADE self-reference and a regular secondary or unique index. Example: create table sr(id int primary key, parent_id int, key idx_parent(parent_id), foreign key(parent_id) references sr(id) on delete cascade); insert into sr values (1,null),(2,1); replace into sr values (1,null);
    Impact: The new predicate incorrectly selects the positional DELETE path before createQuery, producing an untagged hidden-index scan that causes planning to fail.
    Evidence: Modern REPLACE builds its cascade graph before createQuery (build.go:250–270). The self-cascade context at build_dml_util.go:1821–1827 leaves sourceTag and updateColLength zero, making localCascadeDelete true. Lines 6609–6611 disable projection preservation, so appendDeleteIndexTablePlan omits scan BindingTags at 4492–4494. Subsequent TABLE_SCAN remapping unconditionally reads BindingTags[0] (query_builder.go:1314). Previously this branch retained a binding tag. Distinguish the actual construction phase or propagate the self-cascade tag, and add an indexed self-referencing REPLACE regression.

Validation:

  • Traced direct DELETE, ordinary tagged cascades, self-referencing REPLACE, index lookup, deletion and optimizer consumers.

  • Reviewed all added planner tests and SQL/result regressions; none covers indexed self-referencing REPLACE.

  • Frozen exact-head CI reports successful UT, SCA, coverage, proxy BVT, pessimistic multi-CN BVT and required checks.

  • gofmt and git diff --check passed; assigned HEAD and unchanged source verified.

  • Saved the source-trace audit and diagnostic SQL under the current attempt directory.

Limitations:

  • Finding established by source tracing; the SQL trigger was not executed locally. Available native artifacts failed the repository owner's input-equivalence requirement.

  • Author-reported pre-rebase runtime checks were treated as supplementary evidence.

  • Full linked-issue bodies were absent. No independent performance measurements were made.

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 4268bd4c66980482adb46038aaad67ae9e27b130

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: 4268bd4c66980482adb46038aaad67ae9e27b130

Assessment: approve

Reviewed the complete six-file delta and frozen discussion. The fix coherently reuses existing index maintenance, preserves positional DELETE and tagged REPLACE contracts, and addresses the prior self-cascade finding. No actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

Validation:

  • Traced cascade sources through index joins, locks, DELETE, and planner remapping; reviewed all planner and SQL/result changes, including empty actions, rollback, NULL keys, RESTRICT, and self-referencing REPLACE.

  • Reused frozen exact-head CI results: successful build, Ubuntu UT, SCA, coverage, proxy BVT, and pessimistic multi-CN BVT.

  • HEAD/base, unchanged source, patch contents, diff whitespace, and Go formatting passed. Receipt: attempt-1/checks/1791950704935376966-4.json; log: attempt-1/review_static_check.log.

  • Detailed scope, evidence reconciliation, and performance analysis retained in attempt-1/review-record.json. Runtime-filter suppression was already present; ordinary SQL paths retain their previous behavior.

Limitations:

  • No local Go/SQL execution or performance benchmarks were repeated. Author-reported checks lack retained logs and were treated as supplementary evidence; raw CI logs were not supplied.

  • Full linked-issue bodies were absent; their behavioral contracts were assessed from the frozen PR description and regression cases.

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

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 04:07 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 04:43 UTC · at 02938cffbf86386c482982f7ec383889b08167fb

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

Reason

Pull request #29994 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 was previously deployed

1 inactive deployment
ci — 02938cff Deployed Oct 14, 2026 by mergify[bot]
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 kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: indexed ON DELETE CASCADE panics when target has no children but unrelated child rows exist

3 participants