Skip to content

Fix correlated scalar CTE aggregates across equality and range - #29413

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29412-cte-aggregate-empty
Sep 28, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29412-cte-aggregate-empty

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG
  • Improvement

Which issue(s) this PR fixes:

Fixes #29129. Fixes #29412. Integrates the work from #29305 into this PR while retaining its author's commits.

What this PR does / why we need it:

Correlation pullup crosses an implicit scalar aggregate by grouping it on the inner key. That has two different failure modes: a non-equality predicate can turn one scalar result into several per-key rows; an equality predicate can erase the aggregate's mandatory empty-input row, changing COUNT(*)=0, computed values, and nested singleton aggregates.

This integration makes the aggregate boundary and predicate shape decide the rewrite:

  • A proven equality partition either preserves the existing plan when the complete consumer chain is empty-row-equivalent, or restores the lowest aggregate's empty result after the join and folds safe upper singleton aggregates into post-join expressions.
  • A supported non-equality scalar aggregate joins the raw inner rows and reaggregates once per original outer row; it does not aggregate per inner key first. Aliases and outer row identity survive previous scalar expressions, filter consumers and subsequent range aggregates.
  • Unproven grouped/nested/nontransparent shapes and deep non-equality shapes fail closed. An independent aggregate that correlation does not cross retains main's behavior. In particular, a deep range predicate under EXISTS must not expose a per-key aggregate.

The follow-up repair covers lower GROUP BY, rejecting HAVING/filters and LIMIT 0 followed by upper COUNT: the original empty-input result is compared with the actual missing-group finalizer, including COUNT's zero fallback and computed NULLIF results. An unresolved filter whose evaluation might be skipped cannot be newly admitted merely because both resulting scalar values agree; invalid-CAST probes before/after upper COUNT and after computed NULL all fail closed.

The integration shares the aggregate-spine analysis rather than maintaining separate projection tracers, empty-row suppression checks or a duplicate range COUNT fallback. It adds no executor operator or persistent query state beyond the existing join/aggregate plan.

Validation

  • Full pkg/sql/plan CGo test package, go vet, golangci-lint (0 issues), build, and diff checks: pass on the integrated source.
  • Exact rebuilt service: normal mo-tester result comparison passed 28/28 range/equality cases and 115/115 empty-row cases; no ignored, failed or abnormal cases.
  • Replayed 48 independent public-SQL/SQLite comparison probes on the final binary. All 13 cases that worked on the common main base but were rejected by the prior PR head—lower grouping, rejecting HAVING/filter or zero/one limit followed by upper COUNT—now match both base and SQLite. Existing unsupported or base-incorrect shapes remain outside this repair. The six previously reported Fix correlated scalar aggregates through local CTEs #29305 regressions remain fixed.
  • Three prepared invalid-CAST unhappy-path probes are explicitly rejected at PREPARE rather than silently returning 0/NULL. Positive scalar and computed cases retain expected values; independent post-aggregate filtering remains supported.
  • Adversarial SQL: independent COUNT and grouped MAX filtered by outer values return correct rows; empty independent COUNT and computed COUNT keep correct values; deep equality under EXISTS remains supported. Deep range MAX/SUM, OR and mixed predicates under EXISTS return NYI instead of the previously reproduced wrong result.
  • Prior integrated-source local 1000×1000 direct-versus-CTE COUNT comparisons produced identical result digests and close timings across range/no-match/selective predicates; this follow-up changes planner admission, not the range executor. This is not a production-scale bound.
  • Exact final-source bounded in-process planning probe: 16 range-scalar siblings used 26,300 versus 26,283 allocations and 1.778 versus 1.775 ms median before this follow-up; depth-8 equality spine used 6,128 versus 6,001 allocations and 0.326 versus 0.319 ms. Alias entries remain 120 at 16 siblings. This quantifies a known sibling cost without a new growth trend; small local timings are not a production bound.
  • Independent GPT-6 Astra medium design review and final overall review: PASS. CI for the new revision is pending; no CI result is claimed.

Known limitation outside this follow-up: an older direct nullable-MAX path with an unresolved parameter-dependent filter can still skip a runtime error on an absent equality key. The new proof does not expand that path; preserving its synthetic-row filter evaluation requires separate work.

The PR retains #29305's commits/author attribution in the merge history. #29305 remains open for the author to coordinate closure after this integrated PR lands.

@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 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review decision: REQUEST_CHANGES recommendation for cc3fba621edc7297d317b5f62de5b7d758ffbbb7 against a99db843c7b4630a86883addc9424433d93fc2d2. Submitted as COMMENT because this account is the PR author; this is not an independent GitHub approval.

P1: preserve already-correct grouped/HAVING/zero-row CTE scalar queries

At pkg/sql/plan/flatten_subquery.go:508-511, every aggregateSpineCandidate with a nil spine returns NYI. However, traceCorrelatedAggregateSpine also produces that state for an ordinary grouped aggregate, a null-rejecting HAVING, or LIMIT 0. Those queries do not need the new empty-row restoration and already work on the base.

Executed with o(id,k) = (1,0),(2,1),(3,2),(4,1),(5,NULL) and i(k,v) = (1,10),(1,20),(2,NULL):

select o.id, (with x as (
  select count(*) c from i where i.k=o.k group by i.k
) select c from x) from o order by id;

select o.id, (with x as (
  select max(i.v) m from i where i.k=o.k having max(i.v)>0
) select m from x) from o order by id;

select o.id, (with x as (
  select max(i.v) m from i where i.k=o.k
) select m from x limit 0) from o order by id;

The exact base returns respectively NULL,2,1,2,NULL, NULL,20,NULL,20,NULL, and five NULL scalar values. The PR head rejects all three with ERROR 20102 (correlated aggregate spine cannot preserve empty-input rows). These were public SQL executions against the same test-owned service configuration, using head and base binaries with identical remaining production source/native inputs.

The algebraic fix is reasonable, but its eligibility contract must distinguish safe/not applicable, supported restoration, and unsafe empty-row loss. A failed singleton-spine proof does not justify rejecting an already-correct scalar query. Preserve the former paths and add these compatibility controls; retain rejection for the genuinely unsafe nested grouped/HAVING shapes. Coordinate this classification with #29305, which explicitly preserves the grouped/HAVING cases.

Other review results

  • Intended COUNT+1 repair, tuple comparison, decimal SUM, and NULL-filter consumers passed the additional public SQL probes. The previously identified OR/LIKE partition hole is fixed.
  • For a nested MAX over a point-filtered outer row, both versions return the same result; head reduces two aggregates plus an extra SEMI join/outer scan to one aggregate and the scalar LEFT join. No large-scale throughput claim is made.
  • Exact-head planner tests, vet, and two 97/97 normal BVT runs are valid evidence for their selected cases; they miss the compatibility controls above.
  • Nonblocking: consider sharing the typed singleton aggregate construction with singleRowAggregateExpr in opt_misc.go, while keeping each caller's evaluation/truncation safety policy separate. The current helper duplicates these laws; no new framework is needed.
  • There were no existing human review comments or code-review threads to resolve; the sole issue comment was a Qodo subscription notice. No subagents were used for this review.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

The P1 compatibility finding in the prior review is addressed in b5d55bbba2. The planner now preserves the existing path for a lone grouped aggregate, a final LIMIT 0, and a single implicit aggregate whose canonical empty row is provably rejected by HAVING/filter. Empty-row-retaining or nested unsafe forms still return explicit NYI.

I rechecked the original issue queries and base-correct compatibility controls on a rebuilt task-owned MatrixOne instance. Grouped multi-row scalar cardinality still errors as expected; HAVING COUNT(*) >= 0 and HAVING MAX(...) IS NULL remain rejected. Full planner CGo tests, vet, lint, and two consecutive BVT runs (99/99 each) passed. Independent GPT-6 Astra medium final review found no remaining blocker. CI is not awaited.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review decision: REQUEST_CHANGES recommendation for b5d55bbba2175295d4fc8a6ecf3c65153b5103ac against base a99db843c7b4630a86883addc9424433d93fc2d2. This is recorded as COMMENT because the GitHub account owns the PR. No subagents were used.

P1 — compatibility classification still rejects correct legacy queries

At flatten_subquery.go:1627-1638, the preserve exceptions cover a single GROUP BY and an empty-row-rejecting filter, but other valid shapes still become candidate=true, spine=nil and fail at lines 509-512. The eligibility contract must consider the complete observable scalar result: an empty-input row whose final value is NULL is equivalent to a missing scalar row. It need not be suppressed by HAVING to be safe. Separately, a valid nested aggregate is forced into the new rewrite even if its singleton helper does not support that aggregate, causing another compatibility rejection at line 1967.

I executed the following against both the base and head with:

create table o(id int primary key, k int);
create table i(k int, v int);
insert into o values (1,0),(2,1),(3,2),(4,1),(5,null);
insert into i values (1,10),(1,20),(2,null);
-- Correct at base: five NULL results. Head: ERROR 20102.
select o.id, (with x as (
  select max(i.v) m from i where i.k=o.k having max(i.v) is null
) select m from x) from o order by id;

-- Correct at base: NULL,20,NULL,20,NULL. Head: ERROR 20102.
select o.id, (with x as (
  select max(i.v) m from i where i.k=o.k
) select m from x limit 1) from o order by id;

-- Correct at base: NULL,20.0000,NULL,20.0000,NULL.
-- Head: ERROR 20102, unsupported singleton aggregate.
select o.id, (with a as (
  select max(i.v) m from i where i.k=o.k
) select avg(m) from a) from o order by id;

Two additional base-correct controls regress in the same way: the MAX CTE with ORDER BY m, and a lower grouped MAX (GROUP BY i.k) followed by upper MAX. SQLite independently agrees with the HAVING/LIMIT/AVG/grouped-MAX base results. The direct HAVING control also succeeds on head.

Please close the eligibility contract around preserve / restore / reject using final result, row removal and cardinality semantics, rather than adding only these SQL spellings to the exceptions. Keep the genuinely unsafe COUNT/non-equality/OR guards. Include paired NULL-on-empty versus non-NULL-on-empty controls, and preserve correct legacy behavior when the optional singleton fold is unsupported.

Design, performance, tests and prior comments

  • The core normalization direction is reasonable: fold proven upper singleton aggregates, restore the lowest aggregate after the join, and retain strict equality-partition proof. It introduces no new executor mechanism or per-outer query execution. The blocker is its overly broad admission/rejection policy.
  • The prior review's three exact examples are fixed (single grouped COUNT, rejecting HAVING MAX, LIMIT 0), but the general P1 compatibility concern remains unresolved. In particular, the follow-up comment treating HAVING MAX(...) IS NULL rejection as positive evidence was incorrect. There are no code-review threads; the remaining automated comment is a Qodo subscription notice. The singleton-helper sharing suggestion remains nonblocking.
  • Reused valid current-code evidence: full planner CGo tests, vet, lint, and two 99/99 normal BVT runs. Additional public probes pass for multiple correlation keys, NULL-safe equality, outer-only correlation, and prepared parameters changed from 15 to 25. The new negative tests are valid for their selected COUNT cases but do not establish that every retained empty row is unsafe.
  • A larger-input probe used 100,000 inner rows and 20,000 groups with one selected outer key. Head removes the upper aggregate, extra SEMI join and extra outer scan. Both base and head still aggregate all 100,000 rows at the lowest layer (1.19 MiB reported memory; local aggregate time 13/14 ms versus 14/12 ms). This demonstrates reduced operator overhead, not a significant scan/latency improvement. The direct scalar MAX control aggregates only five rows using existing key-domain pushdown. Reusing that optimization after normalization is a worthwhile nonblocking follow-up.

No source changes were made during this review. CI was not awaited. The earlier PASS is superseded by the reproduced compatibility regression above.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

整体 deep review(gpt-6-astra high),针对 66987f7:代码与设计未发现新的已证实 blocker。已覆盖 equality/range 相关聚合、空输入及嵌套 COUNT、mixed-depth correlation admission、外层行身份与 alias 消费、错误路径、性能增长和 UT/BVT 质量;复核了 48 个 SQL 对照及 28/28、115/115 的正常 BVT 证据。已知边界:多 sibling alias 的 query-local 二次增长,以及旧 direct-MAX/unknown-filter 错误行为限制;本次没有证据表明它们是新回归。CI run 36355798713 的 coverage 重跑(attempt 2)仍在进行,不能宣称 CI 已通过;attempt 1 的失败位于未改动的并发建索引用例,归因仍需重跑终态,不能称为已证明的 base flaky。这是 self-authored COMMENT review,不是 GitHub APPROVE。

@XuPeng-SH
XuPeng-SH merged commit 0782faf into matrixorigin:main Sep 28, 2026
1 of 4 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/issue-29412-cte-aggregate-empty branch September 28, 2026 01:08

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 kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

3 participants