Skip to content

fix(plan): support self-referencing cascade actions - #26936

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:m-26831
Aug 11, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
iamlinjunhong:m-26831

Conversation

@iamlinjunhong

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

What this PR does / why we need it:

fix(plan): support self-referencing cascade actions

@iamlinjunhong
iamlinjunhong requested a review from a user August 10, 2026 13:16
@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 →

@matrix-meow matrix-meow added the size/L Denotes a PR that changes [500,999] lines label Aug 10, 2026

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

Reviewed exact head 651a033 with all 26 checks terminal and passing.

[P1] Compute self-referencing DELETE CASCADE closure across every cascade edge, not independently per foreign key.

appendSelfReferCascadeSource recursively follows only the one ForeignKeyDef passed to it, while buildDeletePlans skips every self-referencing CASCADE once isFkRecursionCall is set. With two valid self foreign keys, descendants reached by alternating edges are therefore missed. Example: t(id primary key, p1 references t(id) on delete cascade, p2 references t(id) on delete cascade) with rows (1,NULL,NULL), (2,1,NULL), (3,NULL,2). DELETE id=1 finds row 2 through p1, but the p1-only recursive CTE does not find row 3 and the recursive child plan skips p2; row 3 remains referencing deleted row 2. Build one fixpoint over the union of all applicable self-cascade edges, or otherwise allow newly discovered rows to expand through the other edges. Add this alternating-edge regression and a converging-path control.

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

Deep-reviewed exact head 651a0339a2a077cae016845e173a535f76f4cb3b. The single-edge DELETE/UPDATE cases added here pass, but the cascade closure is still incomplete in two data-preserving cases. I reproduced both against an embedded real cluster built from this exact head.

[P1] DELETE recursion stops when a cascade path switches between two self-referencing FKs.

CREATE TABLE tree (
  id INT PRIMARY KEY, parent_a INT, parent_b INT,
  FOREIGN KEY (parent_a) REFERENCES tree(id) ON DELETE CASCADE,
  FOREIGN KEY (parent_b) REFERENCES tree(id) ON DELETE CASCADE
);
INSERT INTO tree VALUES (1,NULL,NULL),(2,1,NULL),(3,NULL,2);
DELETE FROM tree WHERE id=1;
SELECT COUNT(*) FROM tree;

The count is 1 on this head (row 3 is orphaned); the DELETE also hit the 30-second pipeline cleanup warning. appendSelfReferCascadeSource computes descendants for only the current FK, while buildDeletePlans immediately skips every self-referencing CASCADE once isFkRecursionCall is set. Thus FK1 reaches row 2, but the recursive delete can never follow FK2 from row 2 to row 3. Please compute the fixed point across all applicable self-referencing cascade edges (with rowid-based cycle/dedup handling), and add this cross-FK regression.

[P1] ON UPDATE CASCADE does not handle two statement roots where one references the other.

CREATE TABLE tree (
  id INT PRIMARY KEY, parent_id INT,
  FOREIGN KEY (parent_id) REFERENCES tree(id) ON UPDATE CASCADE
);
INSERT INTO tree VALUES (1,NULL),(2,1);
UPDATE tree SET id=id+10 WHERE id IN (1,2);

Expected (11,NULL),(12,11), but this head returns error 1452 and rolls back. The separate cascade branch excludes only parentRowID == childRowID; it does not exclude all rows owned by the statement update. Meanwhile rewriteSelfReferOnUpdateCascadeProjection rewrites only a literal self-loop (childOld == parentOld), so row 2 is simultaneously owned by the main update and the cascade update without combining id=12 and parent_id=11. Please make root ownership disjoint and fold/apply cascades for references between distinct roots; add a multi-root regression.

Validation of the intended paths: the new single-chain DELETE/UPDATE tests, existing REPLACE/SET NULL self-reference tests, the complete pkg/sql/plan test package, and build/vet all pass on this exact head. The failures above are independent counterexamples removed after reproduction.

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

Deep-reviewed exact head 9727c0cf7c76659526004c84ed10360bb22aa8c9.

Both prior P1 counterexamples are closed. DELETE now computes one recursive UNION DISTINCT fixpoint over the OR of every applicable self-cascade edge, so alternating edges, cycles, and converging paths share one rowid-bearing closure. UPDATE materializes the immutable statement-root set, folds root-to-root cascades into the primary writer, and anti-joins those roots from the separate cascade action, yielding disjoint ownership.

I also audited the new materialized sink reader lifecycle across Call/Reset/Free and repeated execution: returned batches have an idempotent cleanup backstop, reader ownership is released once, and the source generation cannot be reused before all owners release. The exact alternating-edge and multi-root planner regressions pass, as do all focused materialized merge tests (independent readers, reset cleanup, concurrent production, producer error, and spill ownership). All live CI checks are terminal and green.

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

Re-reviewed exact head 9727c0c with all checks terminal and green. DELETE now computes one UNION DISTINCT fixpoint across all self-cascade edges, and UPDATE folds root-to-root cascades into the primary writer while anti-joining the complete root set from the separate writer. The alternating-edge, converging-path, multi-root, cycle, and materialized-reader ownership paths are covered. LGTM.

@mergify mergify Bot added the queued label Aug 11, 2026
@mergify

mergify Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-11 11:13 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-08-11 11:39 UTC · at b945e2d1b4079ab8cc6a8ecff034800baf4c82c7

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

Reason

The pull request can't be updated

This pull request seems to come 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, or update the branch manually.

Hint

You should update or rebase your pull request manually. If you do, this pull request will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue, 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

@XuPeng-SH
XuPeng-SH merged commit 690fed8 into matrixorigin:main Aug 11, 2026
25 of 26 checks passed
@mergify mergify Bot added dequeued and removed queued labels Aug 11, 2026
@iamlinjunhong
iamlinjunhong deleted the m-26831 branch August 23, 2026 17:13
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#26831

## What this PR does / why we need it:

fix(plan): support self-referencing cascade actions

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#26831

## What this PR does / why we need it:

fix(plan): support self-referencing cascade actions

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#26831

## What this PR does / why we need it:

fix(plan): support self-referencing cascade actions

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
XuPeng-SH added a commit that referenced this pull request Oct 22, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #30790

## What this PR does / why we need it:

Adapt the materialized-reader ownership fix from main #26936
(`690fed8e1f03fa716494b5f2dbc2304d040c0b98`) to `4.2-dev`, without
backporting
its unrelated foreign-key changes.

`materialized.Source.Next` returns an independent caller-owned batch.
Ordinary
4.2 Merge readers did not retain this copy for cleanup. A pass-through
Projection
borrows its vectors, so neither downstream teardown nor Source cleanup
reclaims
the returned copy. Q15 can therefore succeed while leaking off-heap
memory.
Native profile deltas and a real operator reproduction both confirmed
4,000,256 bytes / 52 allocations left for the observed two-consumer
input.

### Changes and release-branch compatibility

- Retain one current materialized batch and reclaim it before the next
ordinary
  reader Call, as well as on Prepare, Reset and Free.
- Make Free release the source reader when Reset has not run; preserve
  idempotent teardown.
- Preserve the 4.2-only `MaterializedSingleBatch` contract: scalar
vector-query
TVFs may still borrow their first batch after EOF, until Reset/Free.
Keep the
  existing rejection of a second scalar batch. This is why an unmodified
  cherry-pick of main's unconditional per-Call cleanup is inappropriate.
- Keep non-materialized Merge, planner decisions, allocation algorithms,
transport and persistent formats unchanged. No additional batch copies,
  goroutines, locks, or I/O are introduced.

### Validation

Base: `26d3a200cb13f4be3b5f64d489bac75d8dcc5814`.
Local validation used the repository CGo wrapper on macOS arm64 / Go
1.26.4.

- Before the production change, the new borrowing and terminal-cleanup
tests
  fail on the unmodified base with unclaimed batches.
- Real `Source -> Merge -> Projection` diagnostic: the 100k-group input
changes
  from 4,000,256 outstanding bytes / 52 allocations to zero. This larger
  diagnostic is not added to CI; permanent tests use only tiny batches.
- Full owning `merge` package passes, including scalar EOF lifetime,
rejection
  of multiple scalar batches, concurrent readers and MergeOrder spill.
- `materialized`, `projection`, and `mergeorder` package tests pass.
- Full `merge` package passes under `-race`; the borrowing, terminal
cleanup,
concurrent-reader and scalar-lifetime tests each pass 100 focused race
runs.
- Existing frontend integration test
`TestIssue26131Q15SharedCTEExecutesBothConsumers` passes (16.18 s),
including
the two-Sink-Scan plan assertion and expected SQL result. No new large
BVT or
  embedded cluster fixture is added.
- Changed-code golangci-lint reports 0 issues; `git diff --check`
passes.

The incident reproduction and local checks do not replace release CI or
a
post-upgrade stability observation. No production cluster was modified.

Co-authored-by: XuPeng-SH <[email protected]>

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

size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants