Skip to content

fix(plan): parameterize local CTE outer references - #29372

Merged
XuPeng-SH merged 59 commits into
matrixorigin:mainfrom
ck89119:issue-29145-main
Oct 8, 2026
Merged

XuPeng-SH merged 59 commits into
matrixorigin:mainfrom
ck89119:issue-29145-main

Conversation

@ck89119

@ck89119 ck89119 commented Sep 24, 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 #29145

What this PR does / why we need it:

Local CTEs can bind outer references but leave Corr expressions in projections or independent recursive producer steps, which the executor cannot evaluate.

This change parameterizes eligible CTE producers with a replay-safe outer domain carrying a stable row identity and referenced values. Hidden columns flow through recursive scans and sinks; the consumer rejoins by row identity using the existing scalar/aggregate/existence decorrelation paths. This preserves NULL seeds, duplicate parameter values, empty-input COUNT, per-row DISTINCT, and scalar cardinality errors without introducing a new executor protocol.

Admission is read-only across all producers before publishing any rewrite. Unsafe producer shapes and outer domains fail at planning time instead of leaking unsupported references to execution.

Scope and design

Review findings addressed for the bounded v1 domain: A parameterized CTE's consumer window now partitions by the hidden outer-row identity in both its logical window spec and physical PARTITION input; scalar single-COUNT HAVING runs after the per-row empty-group fallback, preserving both filtered-result NULL and genuinely empty-input zero; and UNION ALL with two matching correlated branches exports a consistent hidden identity slot through both branch schemas and the set-operation output. Unsupported HAVING and non-UNION-ALL set-operation shapes, or a UNION ALL branch without matching identity, fail safely at planning time. Following correctness review, COUNT HAVING across LIMIT/OFFSET or UNION/JOIN branches, a parameterized CTE beneath a consumer outer join, and a non-COUNT scalar projection with COUNT HAVING also fail explicitly before unsafe rewrites. The third review identified five further unsafe consumers: non-equality filtering before an aggregate with HAVING, empty-input ungrouped aggregates consumed by EXISTS/IN/branches/nested aggregates, filtering before a window, pagination of COUNT even without HAVING, and window projections on COUNT. Each now fails at admission before any HAVING removal or predicate pull-up. The next review found COUNT compensation incorrectly applied to explicit GROUP BY: this is corrected for empty input (NULL), OFFSET (NULL), and nonempty duplicate outer parameters (1,1). A later review found the compensation too narrow for ordinary correlated and local CTE COUNT under ORDER BY/DISTINCT: transparent projections now retain COUNT's zero; COUNT expressions are evaluated after restoring the raw COUNT above the join; scalar LIMIT 0/positive OFFSET does not fabricate a row, and safe COUNT HAVING is evaluated after restoration. Follow-up review found that LIMIT 1 without ORDER BY still skipped expression reconstruction and that COUNT+1 HAVING compared the final projection instead of the raw COUNT. This revision reconstructs expressions through the per-key LIMIT 1 window, retains all aggregate slots through ordering wrappers, compares HAVING against the restored original COUNT, keeps explicitly grouped HAVING on its prior path, and permits parameterized HAVING casts during PREPARE and re-execution. A further review found OFFSET 1 incorrectly reconstructed BIT_OR/BIT_AND despite removal of the aggregate result row; pagination now suppresses post-join reconstruction for every aggregate, and known-deleted COUNT HAVING results return NULL without an erroneous NYI. Aggregated window consumers with or without explicit GROUP BY, and consumer JOIN ON predicates that still contain outer references, now fail at planning time rather than panic or leak Corr into the executor. The explicitly rejected SQL shapes are not claimed as supported; complete support requires preserving their independent per-outer-row semantics. This is still a draft PR pending maintainer review.

Approved v1 design.

This is deliberately bounded: the outer input must preserve a single base-table row identity. It does not introduce general LATERAL/APPLY, arbitrary outer joins/aggregates, producer pagination/ordering/aggregation/windowing, explicit VALUES producers, or volatile producer expressions. The issue's three reported queries are covered.

Validation

Merged current mo/main before the follow-up fix. Final Go 1.26.4 CGo planner-package tests, go vet, incremental lint, and service build pass. The expanded local_outer_reference.sql generated result and normal mo-tester comparison passed 87/87, including explicit grouped COUNT empty/nonempty cases and ordinary/local-CTE correlated COUNT through ORDER BY, DISTINCT (including duplicate outer parameters), COUNT arithmetic and multiple COUNTs, LIMIT 1/zero/OFFSET, HAVING, parameterized PREPARE/re-execution, and WHERE (=0) filtering. These cases distinguish valid empty-input COUNT zero from a deleted scalar result row (NULL). Existing window and UNION ALL coverage remains. Full planner-package UT, vet, incremental lint and service build pass at the tested source revision. Full planner-package UT, vet, incremental lint and service build pass after merging current mo/main.

  • Go 1.26.4, Darwin/arm64, repository CGo wrapper and verified native artifacts.
  • Full ./pkg/sql/plan tests: PASS; package statement coverage 81.9%.
  • New implementation statement coverage: 88.9%; changed-block coverage exceeded the 75% gate.
  • go vet ./pkg/sql/plan and incremental golangci-lint v2.6.2 built with Go 1.26.4: PASS.
  • Final service build: PASS.
  • local_outer_reference.sql: mo-tester normal comparison 87/87 PASS, including result metadata; earlier version of the suite passed 31/31 twice, including teardown checks.
  • Coverage includes the three reported results, NULL/empty seeds, repeated parameters, recursive-member references, DISTINCT, multiple consumers, scalar multi-row errors, recursion limits, memory-quota failure followed by recovery, and prepared reexecution.
  • Before the upstream merge, the same BVT also passed twice in a two-CN topology; existing mergecte lifecycle/memory/schema tests passed. The final merged head was revalidated on an isolated single-CN instance.

No TODO files, local logs, test-instance configuration, or native build artifacts are included.

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

Decision: APPROVE

Reviewed the complete 11-file diff at e7847adb03e80b437bf239d7a72f60dda4c59708 against base/merge-base 9e50a0f2c925c512fe13f54611630aa615ac93db, including the final design, all historical technical comments and their adjacent failure paths. No subagents or production edits. No remaining demonstrated blocker in the documented bounded v1.

Design and ownership

Stable base-row identity plus outer-value payload is a reasonable bounded relational rewrite. Repeated/NULL values do not become row identity, recursive members inherit their own partition, and execution still uses the existing recursive/relational operators and quota/reset/free owners. No second executor protocol, persistent store, global cache or worker lifecycle is introduced.

The latest repair closes the important operator-level gap: guarded recursion is rejected before publishing the rewrite; safe outer-only demand predicates constrain the replay before starting producer work. Mixed CTE/outer predicates stay at their original consumer position, with payload propagation across the admitted DISTINCT/window/pagination wrappers. COUNT empty-input zero remains distinct from an aggregate row removed by HAVING/OFFSET. These are necessary semantic boundaries, not merely new exceptions to suppress failing tests.

Historical-comment closure

  • 4115138078 / 4115867246: ordinary COUNT HAVING conjunction/IN/outer references are preserved; literal/parameter/list/variable handling and post-join reconstruction are covered.
  • 4115138084 / 4115867250: inactive CASE with throwing CAST/ABS now fails safely at planning admission. Safe filtered-demand cases execute, while genuinely demanded errors remain errors. This is bounded rejection, not a claim of general guarded APPLY support.
  • 4121177423: the inactive recursive partition witness now fails during admission instead of consuming depth/resources; filtered/demanded terminating partitions succeed, active nontermination still hits the cap and subsequent queries recover.
  • Two older GitHub threads (4115138084 and 4115867250) are still marked unresolved in the UI; their technical findings are addressed by this head. That UI state is not additional unreviewed code.

Independent exact-head evidence

  • Full ./pkg/sql/plan: PASS, 6.496s.
  • Changed TestTPCHNumericEligibilityInventory: PASS, 1.805s; nullable correlated SUM/AVG results have justified metadata.
  • Reviewer real-MySQL-protocol QA: PASS, 14.752s overall; 15 named counterexample/control cases run in each of two rounds, plus hierarchy/depth exact results, quota failure/recovery, prepared demand values 2/NULL/1(error)/2, and DROP followed by independent catalog-absence checks between rounds. Covered old guarded recursion/ABS witnesses, active errors, duplicate outer values, DISTINCT/window identity, LIMIT-before-filter, mixed predicates, ordinary HAVING and aggregate OFFSET.
  • All implementation/test/design hunks and SQL/result expectations were reviewed; git diff --check passed. Exact-head required CI, UT/SCA and executable multi-CN BVT jobs are green. I did not rerun the entire mo-tester suite locally or wait for CI.

Engineering/performance limits

Implementation (+1662 lines), tests/expected results (+2230) and design (+100) were assessed separately. The substantial complexity is in admission and existing scalar-aggregate reconstruction, not a new execution subsystem. The scalar-value/row-comparison reconstruction helpers must continue to share the existing empty-result/type owners rather than grow independent semantics. Current tests have real result/error controls in addition to no-Corr planner checks.

Replay still adds base scans and hidden payload proportional to recursive rows and parameter width; demand filtering removes provably unnecessary partitions, but this is not a throughput or lower-peak-memory claim. No production-scale benchmark or exhaustive cancellation stress is claimed. General LATERAL, arbitrary outer relations and the explicitly rejected producer/consumer shapes remain outside scope.

Non-blocking cleanup: the PR body still says draft and retains old 87-statement validation/review chronology. Update it to the final supported/rejected contract and current evidence; avoid presenting bounded rejection as full MySQL correlated-CTE support.

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

REQUEST_CHANGES. Deep re-review of all 11 PR files at exact head de3973b0db2a6dbf3c13b09013eb521f0907176e, base/merge-base e5f70bedc47d84866359f903afed1da0f6562602, including all historical reviews, inline comments and resolved/unresolved threads; compared the prior aptend review and the later approved revision with the current full diff.

The old ordinary COUNT HAVING outer-reference/conjunction/IN witnesses now pass independently. Guarded ABS and recursive producers fail safely during planning, while filtered terminating recursion and the new single-empty-seed variable case return the expected rows. Two old threads remain unresolved in the UI, but their original witnesses are addressed. The attached finding is a remaining nested-producer variable evaluation-domain hole; no claim that it was introduced only by the latest commit.

Reviewed the versioned design, identity/payload propagation, scalar aggregate/HAVING/pagination reconstruction, consumer guards and variable barriers. Existing recursive batch accounting includes the hidden payload and retains its quota/rollback/reset/free owners; no new executor, wire, catalog or global state is added.

Evidence: exact-head CI run 36588700275 completed successfully, including owning-package UT and executable multi-CN BVT; its normal-comparison report selected local_outer_reference.sql with 232/232 successful statements. Independent CGo real-client probes verified the six historical/current positive or rejection controls, the nested failing witness and its valid-variable/no-demand/ordinary correlated controls, plus query recovery and successful database teardown. The failing witness was also checked on prior approved head e7847ad. Temporary probes were removed; no production code changed.

Comment thread pkg/sql/plan/cte_outer_reference.go Resolved

@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 cef710d2b6ee177247206024f1028886d8d086cf and the runtime-demand repairs after the last blocking review. The dependent-producer witness is now rejected during read-only admission: seed barriers are selected from the actual producer rather than every transitive SINK, and SourceStep dependencies without a demand proof fail admission. Parameters and variables stay behind row-deleting consumer boundaries; barriers are inserted after child rewrites and survive runtime-only filters.

I also checked identity/payload propagation through recursive scans and sinks, read-only admission before mutation, consumer window/set-operation handling, and scalar aggregate/HAVING/pagination restoration. The added planner and SQL regressions cover empty versus live input, OFFSET/filter boundaries, invalid conversions and prepared reuse. Valid owning-package/BVT execution evidence is reused for the corresponding unchanged paths. Current CI is green. No remaining concrete blocker found within the documented single-base-row-identity scope.

@aptend aptend 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 re-review of exact head cef710d2b6ee177247206024f1028886d8d086cf (base/merge-base 0d3687004d712e0878d63f2e848f69c5df5d1c0f), including the increment since my previous reviewed head de3973b0db2a6dbf3c13b09013eb521f0907176e and the complete 11-file PR diff. I read all historical reviews, all six inline threads and their resolution state, and the PR discussion.

No blocking issue found in the current head.

The previous blocker is closed by the implementation, not merely by thread resolution: admitVariableDemand now selects the actual recursive anchor owner and rejects dependent source-step inputs without a valid demand proof. I independently reran the nested r -> q, empty-q, @demand='bad' counterexample from my previous review. It now rejects at planning with “variable demand needs a total seed input before projection”, rather than evaluating the bad conversion at an unrelated producer. This is consistent with the documented bounded v1 support.

I also checked the complete rewrite closure: physical row identity versus NULL/repeated parameters; payload propagation through recursive scans/sinks, DISTINCT, windows and UNION ALL; scalar cardinality; raw aggregate/COUNT empty-input restoration versus HAVING/pagination-deleted rows; and totality/error-demand boundaries. The older ordinary COUNT HAVING regressions, inactive CAST/ABS branches and unused nonterminating recursive partition witnesses are corrected or explicitly rejected as documented. The versioned v1 design and its recorded approval/scope are preserved; arbitrary outer relations/general APPLY are not silently admitted. Recursive payload bytes remain charged by the existing batch accountant, with existing reset/free/error ownership.

Validation on this exact detached head, with locally built native artifacts and CGO enabled:

  • Full ./pkg/sql/plan and ./pkg/sql/plan/substrait: passed. A separate planner coverage run passed at 82.0%; the two new CTE production files have 86.3% statement coverage.
  • Full ./pkg/sql/colexec/mergecte and ./pkg/sql/colexec/cteaccount: passed, including quota admission/rollback, failed-execution retry, reset/layout changes and recursive-depth accounting.
  • Temporary public-SQL probe using an owned two-CN embedded cluster: passed in 12.57s. All 268 checked-in BVT statements were replayed twice in the same SQL session with exact row, visible-column-count and expected-error assertions, including quota/depth errors followed by recovery and teardown.
  • Additional independently specified witnesses passed: the previous nested-producer blocker, ordinary correlated COUNT HAVING, NULL/repeated identity, bad runtime conversion behind empty derived/filter/OFFSET input (including explicit parameter casts), and binary-protocol PREPARE/EXECUTE across valid, NULL, demanded overflow and subsequent recovery.
  • Exact-head CI Required, Linux UT/coverage, SCA and compose/proxy checks are successful: https://github.com/matrixorigin/matrixone/actions/runs/36746614344 . Skipped checks are not counted as validation.

Temporary probes were review-only; no production source was changed.

@mergify

mergify Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-08 03:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-10-08 04:23 UTC · at c8eb418c2db5109d35946dd9b6649f1a13df7243

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

Reason

The merge conditions cannot be satisfied due to failing checks

  • Mergify Merge Protections
  • CI Required

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, 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

Requeued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-08 09:13 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-08 10:23 UTC · at 26925a07b2fc66b6650e8f7de319355819bd76bb

This pull request spent 1 hour 9 minutes 41 seconds in the queue, with no time running CI.

Reason

Pull request #29372 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 — 26925a07 Deployed Oct 8, 2026 by mergify[bot]
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 kind/documentation Improvements or additions to documentation kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Compatibility]: CTE outer references supported by MySQL are rejected by the executor

6 participants