Skip to content

fix(sql): remap reused CTE readers after projection pruning - #30145

Merged
XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/30141-reused-aggregate-cte-pruning
Oct 14, 2026
Merged

XuPeng-SH merged 2 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/30141-reused-aggregate-cte-pruning

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:

The issue remains open after merge for verification by the reporter.

What this PR does / why we need it:

A reused four-column CTE can materialize only columns 0, 1 and 3 after pruning an unused intermediate column. Its readers retain original input ordinal 3 while the producer emits three vectors, causing a projection panic. This affects ordinary filtered CTEs as well as aggregate CTEs and grouping extensions.

Register shared CTE readers for the existing final positional remap, so their input positions follow the producer's compacted layout while each reader keeps its own pruned output. Count-only readers retain the existing fallback projection and now publish those retained column demands before producer pruning, ensuring every emitted read has a materialized slot. Storage admission estimates that full fallback schema, including variable-width columns.

Planning adds work proportional to shared-reader projection columns; there is no added per-row execution work. The count-only fallback can retain a wider materialized row to satisfy its existing projection. Runtime storage quotas and CTE reuse/fallibility guards remain in effect.

Validation on macOS arm64, Go 1.27.1:

  • Confirmed the unfixed planner mismatch and public SQL projection panic; the full-projection control returned the expected row.
  • Ten focused column-mapping scenarios, three variable-width admission controls and the entire pkg/sql/plan package pass, including existing DML, fallibility and storage-admission controls.
  • The new cte/projection_pruning.sql BVT passes normal mo-tester comparison twice on the same isolated 1 CN + 1 TN + 1 LogService instance: 36/36 statements each run, with explicit database teardown verification. Results cover ordinary/aggregate CTEs, asymmetric readers, leading/middle-column pruning, count-only fallback, HAVING/LIMIT, UNION, nested declarations, ROLLUP/CUBE/GROUPING SETS, NULL/empty input, repeated prepared execution and INSERT SELECT with a sentinel.
  • Incremental go vet, configured golangci-lint and formatting checks pass.

Design and final overall review use gpt-6-astra, reasoning effort medium. Upstream CI is pending; local execution validation used a single CN because this change affects sequential planner column mapping without changing transport or operator ownership.

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

Copy link
Copy Markdown
Contributor

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

Commit: 77156ad68d7556abef38b46273abcf8c9df84ec3

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: 77156ad68d7556abef38b46273abcf8c9df84ec3

Assessment: approve

Reviewed the complete five-file delta and affected planner/compiler callers. Registering shared CTE readers with the existing positional remapper restores producer/reader column alignment without duplicating ownership. Count-only fallback demand and storage admission consistently retain the full schema. Existing fallibility and resource guards remain intact. No actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-8e48-7622-ad17-b605f08450ce · slot 1 · generation 0

Validation:

  • Verified the clean frozen HEAD, supplied patch and all five changed files. Reviewed asymmetric and in-range stale ordinals, count-only readers, admission guards, existing DML remapping and compiler projection consumption.

  • git diff --check passed; receipt checks/1791969580129248036-2.json matches diff-check.log and the frozen source fingerprint.

  • Static evidence/fixture audit passed; receipt checks/1791969669794880049-2.json matches evidence-audit.log. All 36 SQL statements match the result fixture in order; this was not SQL execution.

  • Reused successful current-head Ubuntu UT, Linux SCA, coverage and complementary multi-CN BVT results from the frozen evidence. The author additionally reports focused planner checks, full planner tests and two executions of the new SQL case.

  • Detailed evidence and design assessment retained at /home/xupeng/.local/state/mo-bot/jobs/5f7ecb337050f22c4898e63b/attempt-1/review-evidence-audit.json.

Limitations:

  • No local Go/native or SQL runtime tests were executed. Raw CI logs and author execution receipts were not supplied; author-reported checks are distinguished from independently verified local checks.

  • Linked issue #30141's full text was not bundled; review covered the concrete projection-pruning failure described in the frozen PR.

  • No performance measurements were supplied. Added work is confined to planning; count-only fallback can retain wider rows or decline reuse, an accepted correctness tradeoff protected by existing admission and runtime quotas.

@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 09:25 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 09:57 UTC · at 5e6e33f011505db45afc157d22eba4b782ee9d8a

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

Reason

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

@mergify mergify Bot added dequeued and removed queued labels Oct 14, 2026
XuPeng-SH pushed a commit that referenced this pull request Oct 20, 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:

- #30141

The issue remains open after merge for verification by the reporter.

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

A shared aggregate CTE over `(g,h,v)=(1,7,10)` can return `(1,10,10)`
instead of `(1,7,7)` when readers select `MAX(h)` and omit the preceding
`SUM(v)`.

This follows
[#30145](#30145). Readers
use the compacted logical SINK schema, but the producer can retain extra
computations to preserve their error semantics. Publishing that wider
child batch makes a reader fetch SUM at the ordinal intended for MAX.

At the planner's column-remapping boundary, add an explicit PROJECT
before a shared CTE SINK when its publication schema differs from the
evaluated child. Track the actual shared CTE sinks created by CTE reuse
so this projection is paired with positional remapping of all readers.
Other sources also use CTESinkOption, including foreign-key maintenance
row images; their established layouts must remain intact. The compiler
consumes the explicit plan and does not interpret SINK metadata as
another executable projection.

Validation on macOS arm64, Go 1.27.1 with the repository CGo test
wrapper:

- Reproduced both failed CI UTs on the original PR head:
self-referencing functional-index cascade and repeated-alias cascade/SET
NULL updates. All their subcases pass after the fix.
- A new planner regression fails before the correction on the wider
child/compacted SINK mismatch. Planner tests verify published width,
identity ordinals and types; compiler tests verify actual values,
reordered/narrowed outputs, streaming fallback, child errors, orphan
cleanup and non-executable SINK metadata.
- Complete `pkg/sql/plan` and `pkg/sql/compile` packages, focused public
SQL integration tests, incremental `go vet`, configured golangci-lint
and formatting checks pass.
- Normal mo-tester comparison passes twice on the same isolated 1 CN + 1
TN + 1 LogService instance for `cte/projection_pruning.sql` and all
three failed CI SQL files: `update_multi_target_modern.sql`,
`fk_issue_26831.sql` and `update_modern_fk.sql`. Database teardown is
checked between rounds. CTE cases include distinct SUM/MAX values,
asymmetric readers, NULL/empty/multiple groups, prepared reuse, INSERT
SELECT and ROLLUP.

Identity layouts need no additional operator. Nonidentity shared CTE
layouts reuse the existing projection executor with bounded per-batch
column work. No wire or storage format changes. Linux/x64 multi-CN CI
will run on the updated head.

---------

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was previously deployed

1 inactive deployment
ci — 5e6e33f0 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 size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants