Skip to content

fix: support aggregation with non-equality conditions in scalar subqueries - #24034

Merged
mergify[bot] merged 4 commits into
matrixorigin:mainfrom
ck89119:fix-23942
Apr 1, 2026
Merged

mergify[bot] merged 4 commits into
matrixorigin:mainfrom
ck89119:fix-23942

Conversation

@ck89119

@ck89119 ck89119 commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Bug fix

Which issue(s) does this PR fix or relate to?

Fixes #23942

What this PR does / why we need it:

When a scalar subquery contains an aggregate function with non-equality correlated predicates (e.g. <, >=), the planner incorrectly rejects it with a NYI error.

However, pullupCorrelatedPredicates already handles this correctly — pullupThroughAgg adds the outer columns to GROUP BY, so the aggregation result is properly grouped per outer row combination. The SINGLE JOIN semantics remain correct since each outer row matches at most one aggregated row.

This PR removes the unnecessary NYI restriction and the now-unused findNonEqPred method.

What does this PR do?

  • Remove the NYI check for aggregation with non-equal predicates in scalar subqueries (flatten_subquery.go)
  • Remove unused findNonEqPred method
  • Update unit test to reflect the fix
  • Add BVT test cases covering the reported scenario

@qodo-code-review

Copy link
Copy Markdown

Review Summary by Qodo

Support aggregation with non-equality conditions in scalar subqueries

🐞 Bug fix

Grey Divider

Walkthroughs

Description
• Remove NYI restriction blocking aggregation with non-equality correlated predicates in scalar
  subqueries
• Delete unused findNonEqPred method that was checking for non-equality predicates
• Add comprehensive BVT test cases covering scalar subqueries with aggregation and non-equal
  predicates
• Update unit test to reflect the fix by moving previously failing case to passing tests
Diagram
flowchart LR
  A["Scalar Subquery<br/>with Aggregation"] -->|Remove NYI Check| B["Allow Non-Equal<br/>Predicates"]
  B -->|pullupCorrelatedPredicates| C["Outer Columns<br/>Added to GROUP BY"]
  C -->|Correct Semantics| D["Single Row<br/>Per Outer Row"]
  E["Delete findNonEqPred<br/>Method"] -.->|Cleanup| B
  F["Add BVT Tests"] -.->|Validate| D
Loading

Grey Divider

File Changes

1. pkg/sql/plan/flatten_subquery.go 🐞 Bug fix +0/-15

Remove NYI restriction and unused predicate check

• Remove the NYI check that rejected aggregation with non-equal predicates in scalar subqueries
• Delete the unused findNonEqPred method that was checking for non-equality operators
• Simplify the subquery flattening logic by removing the unnecessary restriction

pkg/sql/plan/flatten_subquery.go


2. pkg/sql/plan/build_test.go 🧪 Tests +6/-1

Update unit tests for non-equal predicate support

• Add new test case for scalar subquery with aggregation and non-equal predicate
• Move previously failing test case from error tests to passing tests
• Verify that `SELECT * FROM NATION where N_REGIONKEY > (select max(R_REGIONKEY) from REGION where
 R_REGIONKEY < N_REGIONKEY)` now passes

pkg/sql/plan/build_test.go


3. test/distributed/cases/subquery/scalar-subquery.sql 🧪 Tests +38/-0

Add BVT test cases for aggregation with non-equal predicates

• Add BVT test case with complex scalar subquery using aggregation and multiple non-equal correlated
 predicates
• Include test with date comparison functions and interval operations
• Add simpler test case with less-than predicate and average aggregation
• Cover real-world scenario from issue #23942

test/distributed/cases/subquery/scalar-subquery.sql


View more (1)
4. test/distributed/cases/subquery/scalar-subquery.result 🧪 Tests +38/-0

Expected results for new BVT test cases

• Expected output for BVT test cases showing correct query execution
• Verify that complex scalar subqueries with aggregation and non-equal predicates return correct
 results
• Demonstrate proper handling of NULL values and grouped aggregation results

test/distributed/cases/subquery/scalar-subquery.result


Grey Divider

Qodo Logo

@qodo-code-review

qodo-code-review Bot commented Apr 1, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Scalar agg non-equi wrong ☑ 🐞 Bug ≡ Correctness
Description
Removing the NYI guard allows flattenSubquery to decorrelate scalar aggregate subqueries with
non-equality predicates, but pullupThroughAgg preserves predicates by adding the *inner* predicate
operands to GROUP BY, which changes the aggregation semantics for range predicates (e.g. =).
Since aggregate scalar subqueries are compiled as LEFT joins (via hasSingleRow) and LEFT join
does not enforce “at most 1 match”, an outer row can match multiple aggregated rows, duplicating
output rows and producing incorrect scalar results.
Code

pkg/sql/plan/flatten_subquery.go[R129-134]

  	return 0, nil, err
  }

-	if subquery.Typ == plan.SubqueryRef_SCALAR && len(subCtx.aggregates) > 0 && builder.findNonEqPred(preds) {
-		return 0, nil, moerr.NewNYIf(builder.GetContext(), "aggregation with non equal predicate in %s subquery  will be supported in future version", subquery.Typ.String())
-	}
-
  filterPreds, joinPreds := decreaseDepthAndDispatch(preds)

  if len(filterPreds) > 0 && subquery.Typ >= plan.SubqueryRef_SCALAR {
Evidence
The removed check previously blocked scalar subqueries with aggregates + non-equality correlated
predicates. After removal, correlated predicates are still pulled up and rewritten through
aggregation by adding any non-correlated column/function subexpression to node.GroupBy (i.e.,
inner-side operands), which is only semantics-preserving when the join predicate is equality on
those grouped keys. For non-equality, this can yield multiple groups that satisfy the join predicate
per outer row. Additionally, for aggregate subqueries without explicit GROUP BY, the builder sets
hasSingleRow=true, causing flattenSubquery to choose a LEFT join, and the executor only throws
“scalar subquery returns more than 1 row” for Node_SINGLE (not Node_LEFT), so multi-match cases
will duplicate rows rather than error.

pkg/sql/plan/flatten_subquery.go[127-157]
pkg/sql/plan/flatten_subquery.go[430-481]
pkg/sql/plan/flatten_subquery.go[483-521]
pkg/sql/plan/query_builder.go[3126-3129]
pkg/sql/colexec/loopjoin/join.go[205-236]
pkg/sql/colexec/loopjoin/join.go[281-316]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Scalar correlated subqueries with aggregates and non-equality correlated predicates are no longer rejected, but the current decorrelation strategy (`pullupThroughAgg` + join) is not semantics-preserving for non-equality predicates and can produce multiple matches per outer row.
### Issue Context
- `pullupThroughAgg` rewrites pulled-up predicates by pushing non-correlated operands into `GROUP BY` so the predicate can be evaluated above the aggregate.
- This works for equality joins (one group per key), but for range predicates it can create many groups that satisfy the join for a single outer row.
- Aggregate scalar subqueries without explicit GROUP BY are treated as `hasSingleRow` and flattened using `LEFT` join, which does not enforce scalar uniqueness at execution time.
### Fix Focus Areas
- pkg/sql/plan/flatten_subquery.go[127-157]
- pkg/sql/plan/flatten_subquery.go[430-521]
- pkg/sql/plan/query_builder.go[3126-3129]
- pkg/sql/colexec/loopjoin/join.go[205-236]
### What to change
Implement a semantics-preserving plan for this pattern, e.g.:
1) **Preferred:** represent such correlated scalar aggregate subqueries using a correlated execution operator (e.g., `Node_APPLY`/lateral evaluation) so the non-equality predicate stays *below* the aggregate; OR
2) **Interim safe fix:** reintroduce a guard that rejects (or does not flatten) scalar aggregate subqueries where pulled-up correlated predicates include non-equality comparisons, until a correct APPLY-based rewrite is implemented.
Also add/extend tests so at least one outer row matches **multiple** inner rows for the same correlation key, ensuring the plan returns a single scalar value (not duplicated rows).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Scalar-subquery BVT nondeterministic ☑ 🐞 Bug ☼ Reliability
Description
The new BVT case asserts a fixed output order for a query without ORDER BY, which can make the
test flaky. Additionally, the date-range dataset inserts only one timestamp per SISTKC, so the
non-equality predicates never match and the test doesn’t validate correct aggregate behavior on
non-empty matches.
Code

test/distributed/cases/subquery/scalar-subquery.sql[R18-27]

+-- @case
+-- @desc:test scalar subquery with aggregation and non-equality correlated predicates
+SELECT s.SISTKC,
+  (SELECT AVG(s2.SIVOL)
+   FROM ms_t_stk_sis s2
+   WHERE s2.SISTKC = s.SISTKC
+     AND STR_TO_DATE(s2.SITXDT, '%d%b%Y:%H:%i:%s') < STR_TO_DATE(s.SITXDT, '%d%b%Y:%H:%i:%s')
+     AND STR_TO_DATE(s2.SITXDT, '%d%b%Y:%H:%i:%s') >= STR_TO_DATE(s.SITXDT, '%d%b%Y:%H:%i:%s') - INTERVAL 30 DAY
+  ) AS avg_30d_vol
+FROM ms_t_stk_sis s;
Evidence
scalar-subquery.sql runs SELECT ... FROM ms_t_stk_sis s; without ordering, while
scalar-subquery.result expects rows in a specific order. Also, all inserted rows share the same
SITXDT value, making the = ... - INTERVAL 30 DAY predicates unsatisfiable, so AVG is always
NULL and the planner/runtime path for non-empty matches isn’t exercised.

test/distributed/cases/subquery/scalar-subquery.sql[13-28]
test/distributed/cases/subquery/scalar-subquery.result[15-26]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new distributed test can be flaky due to missing `ORDER BY` and currently does not exercise non-empty matches for the non-equality correlated aggregate.
### Issue Context
- Without `ORDER BY`, result row order is not guaranteed.
- With only one `SITXDT` per `SISTKC`, the subquery’s date predicates cannot match, so `AVG(...)` is always NULL.
### Fix Focus Areas
- test/distributed/cases/subquery/scalar-subquery.sql[13-35]
- test/distributed/cases/subquery/scalar-subquery.result[15-36]
### What to change
1) Add an `ORDER BY` (e.g. `ORDER BY s.SISTKC`) to the first query.
2) Insert additional rows per `SISTKC` with earlier `SITXDT` values so at least one outer row matches **multiple** inner rows within the date range, and update expected results accordingly.
3) (Optional) Extend the second case’s data so for some `a` there are at least two `b` values `< t1.b` to validate aggregation over multiple matches (e.g., add `(1, 5)` and validate `avg_less` becomes `7.5` for the `(1,40)` row).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

@ck89119

ck89119 commented Apr 1, 2026

Copy link
Copy Markdown
Contributor Author

@mergify refresh

@mergify

mergify Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

refresh

✅ Pull request refreshed

@mergify mergify Bot added the queued label Apr 1, 2026
@mergify

mergify Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-04-01 13:45 UTC · Rule: main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-04-01 14:42 UTC · at 03f3819d47e90555f73e0228c7ab1d13fe13f761

This pull request spent 57 minutes 9 seconds in the queue, including 56 minutes 49 seconds running CI.

Required conditions to merge
  • #approved-reviews-by >= 1 [🛡 GitHub branch protection]
  • #changes-requested-reviews-by = 0 [🛡 GitHub branch protection]
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • branch-protection-review-decision = APPROVED [🛡 GitHub branch protection]
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Ubuntu/x86
    • check-neutral = Matrixone CI / SCA Test on Ubuntu/x86
    • check-skipped = Matrixone CI / SCA Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(Optimistic/PUSH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH,Optimistic)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-neutral = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
    • check-skipped = Matrixone Upgrade CI / Compatibility Test With Target on Linux/x64(LAUNCH)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage

@mergify
mergify Bot merged commit 79cca06 into matrixorigin:main Apr 1, 2026
24 of 25 checks passed
@mergify mergify Bot removed the queued label Apr 1, 2026
@ck89119
ck89119 deleted the fix-23942 branch April 1, 2026 15:12
fengttt pushed a commit to fengttt/matrixone that referenced this pull request May 7, 2026
…eries (matrixorigin#24034)

When a scalar subquery contains an aggregate function with non-equality correlated predicates (e.g. `<`, `>=`), the planner incorrectly rejects it with a NYI error.

However, `pullupCorrelatedPredicates` already handles this correctly — `pullupThroughAgg` adds the outer columns to GROUP BY, so the aggregation result is properly grouped per outer row combination. The SINGLE JOIN semantics remain correct since each outer row matches at most one aggregated row.

This PR removes the unnecessary NYI restriction and the now-unused `findNonEqPred` method.

Approved by: @ouyuanning, @heni02

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/XS Denotes a PR that changes [1, 9] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: mo does not support aggregation with non-equality conditions in subqueries with predicates.

4 participants