Skip to content

Fix correlated scalar aggregates through local CTEs - #29305

Closed
iamlinjunhong wants to merge 3 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29129-cte-correlated-aggregate
Closed

iamlinjunhong wants to merge 3 commits into
matrixorigin:mainfrom
iamlinjunhong:fix/29129-cte-correlated-aggregate

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Fixes #29129. The related computed/nested empty-row boundary is tracked in #29412.

What this PR does / why we need it:

A scalar aggregate inside a local CTE owns a separate binding context. Correlation pullup adds an inner key to its GROUP BY; a non-equality predicate can then produce multiple rows for one outer row. The PR preserves the selected aggregate and outer row identity, joins raw inner rows once, and reaggregates per outer row.

This update closes three independent review counterexamples on the existing PR head:

  • Equality-correlated HAVING and GROUP BY wrappers that were correct on main again retain their scalar semantics; the empty-row guard remains for cases whose result cannot be reconstructed.
  • A preceding raw scalar output keeps its scan identity through projection cleanup, so changing SELECT-list order no longer causes column remapping failure.
  • Earlier scalar values used by later WHERE OR/EXISTS filters are normalized to the synthetic aggregate's group outputs before filter pushdown and HAVING remapping.

Equality row comparisons now restore the empty-input result for every selected aggregate, including both COUNT(*) and COUNT(col). A nested equality aggregate that loses a lower global aggregate's mandatory row returns an explicit NYI instead of an incorrect zero. Existing explicit NYI guards for non-equality nested aggregates, JOIN-hidden aggregates, and computed CTE aggregate outputs remain.

Validation

  • Reproduced all three review failures on exact PR head and compared equality controls with main; all three now return expected public SQL results on the candidate.
  • Full pkg/sql/plan test package: pass. Focused planner tests: pass. go vet ./pkg/sql/plan: pass. Incremental golangci-lint v2.6.2 on pkg/sql/plan: pass, 0 issues.
  • Scalar CTE BVT, including new equality, ordering, disjunction, tuple, and NYI cases: 24/24 in four normal comparison runs on a task-owned service. No golden assertions were relaxed.
  • Independent GPT-6 Sol xhigh QA: 27/28 public SQL cases matched an independent SQLite oracle. The one mismatch is the already documented COUNT(*)+1 NYI, tracked in [Bug]: correlated local CTE computed and nested aggregates lose empty-input row #29412; additional row-tuple and mixed-aggregate challenges found no wrong result. The service remained healthy after the rejected statements and QA databases were removed.
  • Range COUNT on 1000 outer × 1000 inner rows exactly matched the direct-correlated query for all 1000 output rows. Three local runs yielded median 0.131 s (CTE) and 0.132 s (direct). EXPLAIN retained the original PR's join and aggregate shape; this small local test is not a large-scale performance bound.
  • Focused pkg/sql/plan tests under -race: pass (1.238 s test execution after first-build linking).

Only the pkg/sql/plan Go package changed, so this is the incremental SCA scope. Rebased onto main a99db843c7 at commit 3aacfc5145. On this rebased head, focused CTE aggregate planner tests, the full pkg/sql/plan package, go build, go vet, and git diff --check passed. The BVT, independent SQL-oracle QA, performance measurements, and lint results above were obtained before this rebase and have not been repeated on the rebased head. No new-head CI result is claimed.

The non-equality range plan still performs a LEFT range join and groups by outer row identity. The unsupported computed/nested contracts are described in #29412. Rolling back this update is a revert of the follow-up commit on this PR branch.

@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

Choose a reason for hiding this comment

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

REQUEST_CHANGES — one P1 query-result correctness bug. The admitted nested-aggregate shape can return cumulative values instead of the scalar result for each outer row. See the inline counterexample and add a regression that asserts exact results.

if builder.scalarReaggAliases == nil {
builder.scalarReaggAliases = make(map[int32][]scalarReaggAlias)
}
builder.scalarReaggAliases[nodeID] = passthrough

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.

This rewrite adds a reaggregation layer for the traced wrapped aggregate, but the accepted path does not preserve a lower aggregate when the local CTE chain contains nested aggregates. For t(n) = (1),(2),(3), this reachable query:
SELECT o.n, (WITH a AS (SELECT MAX(i.n) AS m FROM t i WHERE i.n <= o.n), x AS (SELECT SUM(m) AS s FROM a) SELECT s FROM x) AS s FROM t o ORDER BY o.n
must return (1,1),(2,2),(3,3). Correlation pullup groups the inner MAX by i.n; repairing only the outer SUM then yields (1,1),(2,3),(3,6). Please preserve the inner aggregate's per-outer-row semantics or reject this shape explicitly, and add this public SQL regression with exact row assertions. This counterexample is source-derived and has not been runtime reproduced.

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.

Resolved in 947c504. The raw-row rewrite now rejects a second aggregate reachable below the selected aggregate before bypassing the selected AGG. Your MAX→SUM counterexample has a planner regression and a public SQL BVT asserting the explicit NYI; the BVT also covers an aggregate hidden behind a JOIN. Supported single-layer CTE cases passed 18/18 twice on a local service. I chose the explicit rejection boundary you suggested because preserving the nested intermediate aggregate would require a separate per-outer-row rewrite.

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

REQUEST_CHANGES on 947c504b5dc1883b997d8f6525bf99e525f45f2c, against base/merge-base 5be6cd90b501da225be591ffffe6000bf01f515e.

Three verified P2 blockers are attached inline: supported equality aggregate wrappers now fail with NYI; a preceding scalar column is lost by range reaggregation; and disjunctions consuming two scalar results fail during HAVING column pruning. All three were reproduced through public SQL on a binary built from this exact, clean head. The equality regression was also executed successfully on the exact base. Independent GPT-6 Sol xhigh review confirmed the equality regression and the missing scan-column alias.

Shared minimal setup for the inline reproducers:

CREATE TABLE o(n INT);
CREATE TABLE i(n INT PRIMARY KEY, v INT);
INSERT INTO o VALUES (0),(1),(2);
INSERT INTO i VALUES (1,10),(2,20);

The earlier MAX-to-SUM non-equality nested-aggregate review comment is resolved within its explicitly accepted rejection boundary: public SQL now returns the intended NYI, and the regression is committed. This does not mean every nested/empty-input case is solved. Two additional equality-path correctness gaps remain, and base/head execution establishes that they predate this PR:

-- For o.n=0: actual NULL, expected TRUE. Same wrong result on base.
SELECT o.n, (0,0) =
  (WITH x AS (SELECT COUNT(*) c, COUNT(v) d FROM i WHERE i.n=o.n)
   SELECT c,d FROM x) AS actual FROM o;

-- For o.n=0: head returns 0, base returned NULL; expected 1.
-- The inner ungrouped MAX still produces one row on empty input.
SELECT o.n,
  (WITH a AS (SELECT MAX(i.n) m FROM i WHERE i.n=o.n),
        x AS (SELECT COUNT(*) c FROM a)
   SELECT c FROM x) AS actual FROM o;

These two are recorded as existing gaps, not new regressions. The body’s unqualified claim that nested aggregates fail explicitly should be narrowed to the non-equality path.

Validation/evaluation: reused completed exact-head CI UT, SCA, and multi-CN BVT evidence; added public-SQL base/head comparisons and independent planner probes for the uncovered combinations. Reversing the scalar projection order works; moving the failing OR from WHERE to SELECT works; AND also works. Failed statements left the service usable; the test databases were removed and the owned services stopped. The PR worktree was not modified. No CI waiting was needed.

The single raw-inner scan plus per-outer-row aggregation is a reasonable repair for the admitted simple shape. I found no additional demonstrated performance or concurrency regression; the existing 1,000-row comparison is limited evidence, not a large-scale performance guarantee. Engineering concern is completeness of the new alias contract across projection removal and filter consumers. Fix those shared boundaries and retain compact result-based regression pairs rather than adding SQL-shape exceptions. Existing tests cover useful empty/NULL/duplicate/sibling cases, but miss these consumer and order variations.

Comment thread pkg/sql/plan/flatten_subquery.go Outdated
Comment on lines +540 to +542
if len(preds) > 0 && wrappedAggCandidate && wrappedAgg == nil {
return 0, nil, moerr.NewNYI(builder.GetContext(),
"correlated scalar HAVING with non-equality input predicates cannot be safely decorrelated")
"non-transparent correlated aggregate projection cannot preserve empty-input result")

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.

[P2] Preserve the already-correct equality aggregate wrappers

This guard rejects every aggregate that the transparent projection tracer cannot recognize, including valid equality-correlated MAX with HAVING or GROUP BY. With the review's o/i setup, this query returns (0,NULL),(1,10),(2,20) on base 5be6cd90b5, but exact head returns NYI:

SELECT o.n,
 (WITH x AS (SELECT MAX(i.v) m FROM i WHERE i.n=o.n HAVING MAX(i.v)>0)
  SELECT m FROM x) m
FROM o ORDER BY o.n;

Replacing HAVING with GROUP BY i.n has the same regression. A filtered-out or absent MAX group already has the correct scalar NULL result; it does not need COUNT-style empty-row reconstruction. Scope the rejection to the unproven semantic cases while preserving these existing supported equality shapes, and retain both positive controls alongside the computed-COUNT negative test.

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.

Addressed in abb4a2f8cf: the equality path now retains grouped aggregates and null-rejecting HAVING cases that already worked on main, while rejecting only unproven empty-row shapes. The exact public SQL HAVING/GROUP BY controls return (0,NULL),(1,10),(2,20); added planner UT and result-based BVT coverage. The completed BVT was 24/24 on the final commit.

Comment on lines +2360 to +2361
default:
return aliases

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.

[P2] Retain the forwarded table-scan column alias

A preceding scalar subquery can expose a raw scan column through its PROJECT. This walker records PROJECT/AGG aliases but stops at TABLE_SCAN without recording that column. The new reaggregation consequently retains only the project-tag identity, while the outer result still needs the scan-tag identity. Public SQL on exact head fails with Column remapping failed, missing i.v:

SELECT o.n,
 (SELECT i.v FROM i WHERE i.n=o.n) v,
 (WITH x AS (SELECT MAX(i.n) m FROM i WHERE i.n<=o.n) SELECT m FROM x) m
FROM o ORDER BY o.n;

Swapping the two scalar expressions returns the correct three rows. An independent planner probe with an external overlay retaining just this TABLE_SCAN alias makes the failing order plan successfully. Preserve the forwarded scan identity through the same alias mechanism and add a result-based order-pair regression; otherwise the newly repaired CTE path depends on SELECT-list order.

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.

Addressed in abb4a2f8cf: pure forwarded column aliases now continue through transparent FILTER/SORT to the terminal TABLE_SCAN/MATERIAL_SCAN identity, with tag and column-position checks. The public SQL reproducer and reversed SELECT-list control both return the exact expected rows; the new result-based BVT retains that order-pair regression.

Comment on lines +1952 to +1956
if aliases := builder.scalarReaggAliases[nodeID]; len(aliases) > 0 {
aliasesByGroup = make(map[int32][][2]int32, len(aliases))
for _, alias := range aliases {
aliasesByGroup[alias.groupPos] = append(aliasesByGroup[alias.groupPos], alias.ref)
}

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.

[P2] Apply the reaggregation alias contract to filter consumers

These aliases are handled for the output projection, but not for node.FilterList, whose remapHavingClause call just above accepts only this AGG's group/aggregate tags. pushdownFilters retains a disjunction referring to the current aggregate on that AGG; its earlier scalar reference still has the previous tag. Exact-head public SQL therefore errors with invalid relation tag ... in HAVING during column pruning:

SELECT o.n FROM o
WHERE (WITH x AS (SELECT MAX(i.n) m FROM i WHERE i.n<=o.n) SELECT m FROM x)>0
   OR (WITH x AS (SELECT SUM(i.n) s FROM i WHERE i.n<o.n) SELECT s FROM x)>0
ORDER BY o.n;

Expected rows are 1,2. The same OR in SELECT works, and WHERE with AND works. EXISTS followed by a range scalar under OR also fails. Normalize preserved aliases for aggregate-local filter consumers and account for their demand, not only final projections; add the WHERE/SELECT control pair to prove this consumer boundary.

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.

Addressed in abb4a2f8cf: registered synthetic reaggregation aliases are normalized to this AGG's group tag before filter classification and HAVING remapping, and HAVING consumers are counted before alias demand is snapshotted. The exact WHERE OR reproducer now returns 1,2; SELECT, AND, EXISTS/OR, NOT EXISTS, and three-scalar controls passed independent public SQL comparison. Planner UT and result-based BVT cover the filter boundary.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Sep 27, 2026

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

Re-reviewed exact commit abb4a2f8cf after the three P2 counterexamples on 947c504b5d were repaired. Equality HAVING/GROUP BY behavior, the preceding scalar scan alias, and the WHERE OR filter consumer now have result-based public SQL regressions. The equality COUNT tuple reconstructs all selected empty-input outputs; nested equality that cannot preserve a lower global aggregate row now fails explicitly and is tracked with computed CTE outputs in #29412.

Local evidence: full planner package pass; focused planner race pass; go vet pass; incremental golangci-lint 0 issues; final-commit scalar CTE BVT 24/24 (with four normal comparison runs total); independent GPT-6 Sol xhigh QA 27/28 SQLite-differential cases, with the one mismatch being the documented COUNT+1 NYI. A 1000x1000 row CTE/direct COUNT comparison matched all rows, with local medians 0.131 s vs 0.132 s. No new-head CI outcome is claimed. No remaining blocker for the stated #29129 scope.

@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: REQUEST_CHANGES

Reviewed head 3aacfc51458c768bd6f444b221821845c7cfe603 against base/merge-base a99db843c7b4630a86883addc9424433d93fc2d2. All eight changed files were read. No subagents were used; no PR source was edited.

The raw-inner-row LEFT JOIN followed by aggregation on a preserved outer-row identity is a sound direction for #29129. Keeping planner-only alias metadata instead of changing the executable plan format is reasonable. However, the admission/rejection contract is still too broad: three distinct compatibility regressions are reproduced on independently built, clean base and head. See inline comments. These are not requests to implement the known COUNT+1 / nested-global-aggregate gaps in #29412.

Shared fixture for inline reproductions

CREATE TABLE o(id INT PRIMARY KEY,n INT);
CREATE TABLE i(n INT,v INT);
INSERT INTO o VALUES (1,0),(2,1),(3,2),(4,2),(5,3),(6,NULL);
INSERT INTO i VALUES (1,10),(2,20),(2,NULL),(3,30);

Design / fix direction

Preserve the pre-pullup aggregate owner and correlate the safety proof with the predicates that actually cross that aggregate. “An AGG exists somewhere in this subtree” does not establish that this scalar result needs aggregate-empty-row reconstruction. Delay correlation-specific row-output rejection until correlation is established. For equality wrappers, distinguish: (a) an empty aggregate row suppressed by HAVING, (b) an output that already propagates NULL correctly, and (c) a genuinely non-NULL empty result requiring reconstruction. Reuse these semantic facts across consumers rather than adding SQL-shape exceptions or broad NYI branches.

This is a bug-fix extension of existing decorrelation, not a new executor/protocol feature; lack of a standalone design document is not a blocker. The blocker is the demonstrated mismatch between the safety contract and actual accepted SQL.

Previous comments

  • Nested non-equality MAX→SUM counterexample: explicit rejection retained, with UT/BVT; acceptable within the recorded scope.
  • Equality MAX/HAVING and GROUP BY exact examples: covered and fixed, but the broader compatibility requirement remains incomplete (third finding).
  • Forwarded scan identity and old scalar aliases in WHERE OR: fixes are present; exact-head BVT covers the original examples, and new consumer-control probes passed.
  • All four GitHub review threads still have isResolved=false; one is outdated. Thread status is separate from technical disposition. No threads were changed.

Evidence / QA

  • Current-head CI run 36333182404 is green for UT, SCA, coverage and both selected multi-CN BVT jobs. The PROXY log explicitly shows scalar_cte_non_equality_aggregate.sql: 24 total / 24 success / 0 ignored / 0 failed; this file really executed.
  • Locally built both exact revisions using Go 1.26.4 darwin/arm64 with identical, provenance-verified native dependencies. Focused planner UT TestCorrelatedLocalCTE|TestCorrelatedAggregatePreservesExistential passed, exit 0. git diff --check passed.
  • 36 public-SQL probes on both revisions, with SQLite result oracles for portable semantics. New checks cover duplicate outer keys, NULL/empty inputs, DISTINCT aggregates, AVG, CTE output permutation, CASE, two/three scalar OR, EXISTS/NOT EXISTS/IN, ordering and derived consumers. Six failing head statements that succeed on base form the three inline findings. AVG's text formatting difference is not a failure; outer-composition/grouped/window probes already return wrong results or an execution error on base, so their explicit NYI on head is not reported as a new correctness regression.
  • A multiple-row preceding scalar still returns error 1242 rather than being silently collapsed by the reaggregation. Ordinary queries continue to work after rejected SQL.
  • Exact-head 1,000 outer × 1,000 inner rows: direct vs CTE COUNT results have identical hashes for range, no-match, and narrow-range predicates. Five measured executions after warm-up: median direct/CTE 82.50/82.00 ms, 55.55/54.90 ms, 56.34/55.70 ms (client startup included). No measured incremental overhead here; not a production-scale performance guarantee. The range join can still require O(outer × inner) work. Multiple siblings and wide passthrough grouping deserve bounded scale coverage; no unproven performance blocker is asserted.
  • Q1/Q2/Q3: added maps/slices are owned by a single QueryBuilder and terminate with planning; no new locks, goroutines, RPC waits or pooled resources. No demonstrated leak/hang or cross-request retained-state failure. Reaggregation still uses existing join/aggregate runtime operators. Wire/disk/catalog migration, privilege and platform contracts are unchanged by this diff.
  • UT and public-result BVT are complementary. The missing orthogonal dimensions are correlation absent/present, aggregate ownership versus unrelated descendant AGG, and correct equality empty-row semantics—not more repetitions of the original happy path.

The previous approval does not cover these newly demonstrated regressions; fix the three boundaries before merge. Both local services have been stopped.

wrappedAggRowOutputs = make([]*scalarAggregateProjectionPath, len(subCtx.results))
for i := range wrappedAggRowOutputs {
path := builder.traceScalarAggregateProjectionAt(subID, int32(i))
if path == nil || path.aggNode != wrappedAgg.aggNode {

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.

[P2] Do not reject uncorrelated row comparisons before checking correlation

The row-output validation runs before pullupCorrelatedPredicates, and rejects a computed/constant second output even when there is no correlated reference anywhere. Using the shared fixture:

SELECT (4,5) =
  (WITH x AS (SELECT COUNT(*) c FROM i)
   SELECT c,c+1 FROM x);

Clean base returns 1; exact head returns row comparison with a non-transparent correlated aggregate is not yet implemented. Replacing c+1 with constant 1 (and comparing with (4,1)) fails too. Reversing the projection to c+1,c with (5,4) succeeds on both revisions, exposing the first-output-dependent admission rule.

Record the pre-pullup paths if needed, but only require the correlation-specific reconstruction proof after establishing that correlation requires it. Retain uncorrelated computed/constant tuple controls as well as the correlated COUNT tuple regression.

"correlated scalar HAVING with non-equality input predicates cannot be safely decorrelated")
"nested correlated aggregate cannot preserve empty-input rows")
}
if len(preds) > 0 && wrappedAggCandidate && wrappedAgg == nil && !wrappedAggEmptyRowSuppressed {

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.

[P2] Do not classify an unrelated descendant aggregate as this scalar's aggregate

wrappedAggCandidate is set by a scan of every descendant, including a separate scalar aggregate used only in an inner filter. The new fallback then rejects a normal correlated scalar that has no aggregate output to reconstruct:

SELECT o.id,
 (SELECT i.v FROM i
  WHERE i.n=o.n AND i.v=(SELECT MAX(v) FROM i))
FROM o ORDER BY o.id;

With the shared fixture, clean base correctly returns (1,NULL),(2,NULL),(3,NULL),(4,NULL),(5,30),(6,NULL); exact head returns non-transparent correlated aggregate projection cannot preserve empty-input result. Replacing the independent MAX subquery with its value 30 succeeds on head. An uncorrelated aggregate in a CROSS JOIN branch triggers the same regression.

The MAX has no correlation pulled through its own AGG, and the surrounding scalar's no-match NULL is already correct. Tie candidate/safety classification to the aggregate owning the selected result and actually crossed by correlation; an arbitrary AGG anywhere below the root is not sufficient. Keep the nested-correlated rejection control so narrowing this check does not reopen the previous wrong-result bug.

if len(node.GroupBy) > 0 {
return true
}
if len(node.BindingTags) < 2 || !allAggregatesReturnNullOnEmpty(node.AggList) {

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.

[P2] Preserve already-correct equality wrappers, not just NULL-returning aggregates

The empty-row suppression proof requires allAggregatesReturnNullOnEmpty, so it cannot recognize COUNT with a HAVING predicate that rejects COUNT's real empty value:

SELECT o.id,
 (WITH x AS
    (SELECT COUNT(*) m FROM i
     WHERE i.n=o.n HAVING COUNT(*)>0)
  SELECT m FROM x)
FROM o ORDER BY o.id;

Clean base returns (1,NULL),(2,1),(3,2),(4,2),(5,1),(6,NULL); exact head rejects it with the non-transparent-projection NYI. The missing-key row is deliberately removed by HAVING, so scalar NULL is correct and no zero reconstruction is needed. The nearby MAX/HAVING case works on both.

The same incomplete equality proof rejects another base-correct case: SELECT o.id,(WITH x AS (SELECT MAX(i.v) m FROM i WHERE i.n=o.n) SELECT m+1 FROM x) FROM o ORDER BY o.id. Base returns NULL,11,21,21,31,NULL; head errors. This strict NULL-propagating expression is distinct from the recorded COUNT+1 / COALESCE gaps.

Use the actual aggregate-empty-result contract plus the wrapper's consumer semantics: preserve cases whose row is suppressed or whose output already becomes NULL correctly. Add both controls, retaining rejection for genuinely unproven non-NULL empty results. The earlier equality-wrapper compatibility comment is therefore only partially closed beyond its exact MAX/GROUP BY examples.

@XuPeng-SH

Copy link
Copy Markdown
Contributor

The #29129 non-equality fix is now integrated with the overlapping #29412 empty-row fix in #29413. The integration retains this PR's commits and author attribution, shares the aggregate-ownership analysis, and keeps the raw-row range reaggregation rather than duplicating the equality reconstruction path.

The integrated revision passed full planner CGo tests, vet, lint, and normal result comparison for the range/equality BVT (28/28) and original empty-row BVT (114/114). It also closes the compatibility issues raised in this PR's review (uncorrelated tuples, unrelated aggregates, equality HAVING/COUNT/MAX wrappers, forwarded aliases, and WHERE OR/EXISTS consumers). Adversarial deep range/mixed-depth predicates fail closed; a mixed-depth equality control remains supported. Small 1000×1000 direct/wrapped COUNT comparisons produced identical result digests.

Please coordinate closure of this PR after #29413 lands so the same planner changes are not merged twice. I am leaving this PR open for its author rather than closing it unilaterally.

@XuPeng-SH XuPeng-SH closed this Sep 27, 2026
XuPeng-SH added a commit that referenced this pull request Sep 28, 2026
## What type of PR is this?

- [x] BUG
- [x] 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 #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.

---------

Co-authored-by: iamlinjunhong <[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

kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: non-equality correlated aggregate inside a local CTE expands scalar results into duplicate rows

3 participants