Repository navigation
fix: keep a subquery correlated when an aggregate sits above a pulled up scalar aggregate - #26544
Conversation
… up scalar aggregate
There was a problem hiding this comment.
Thanks @comphead
nit: In decorrelate.rs around line 511, putting a filter between the two aggregates gives a confusing error instead of the not-implemented one:
SELECT o.k, (SELECT count(*) FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k) WHERE n >= 0)
FROM nested_agg_outer AS o ORDER BY o.k;
-- Schema error: Schema contains duplicate unqualified field name "count(Int64(1))"The first optimizer pass now leaves the subquery correlated, and the second pass rewrites a reshaped plan that fails with a schema error. With datafusion.optimizer.max_passes = 1 it gives the expected Physical plan does not support logical expression ScalarSubquery. It's still an error (main returned (2, 0) here, which was wrong), so it would be nice to add it as a test case even if the message stays as is.
| // A pulled up scalar aggregate below gives no row for unmatched | ||
| // outer rows, so this aggregate would see an empty input. | ||
| // See https://github.com/apache/datafusion/issues/26508 | ||
| if self.pulled_up_scalar_agg { |
There was a problem hiding this comment.
This also blocks some shapes that were correct before and now fail to plan. For example, max over max, sum over sum and count(m) over max all returned the right rows on main, and now hit Physical plan does not support logical expression ScalarSubquery:
SELECT o.k, (SELECT max(m) FROM (SELECT max(i.v) AS m FROM nested_agg_inner AS i WHERE i.id = o.k))
FROM nested_agg_outer AS o ORDER BY o.k;
-- main: (1, 10), (2, NULL) this PR: errorBlocking makes sense to me, since a precise rule would have to evaluate the outer aggregate on the inner aggregate's empty-input row. Could you mention this in the PR description and add a test that pins the new error, so it's clear this is an intended trade-off?
There was a problem hiding this comment.
Added the max over max case as a pinned error, with a comment saying it returned the right rows before and why it is blocked too. The PR description now lists this trade-off under user-facing changes.
| statement error DataFusion error: This feature is not implemented: Physical plan does not support logical expression ScalarSubquery | ||
| SELECT o.k, (SELECT max(n) FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k)) FROM nested_agg_outer AS o ORDER BY o.k; | ||
|
|
||
| # IN and LATERAL. Expected `2` and `(1, 1), (2, 0)`. |
There was a problem hiding this comment.
nit: Two more shapes that returned wrong rows on main are now blocked too: EXISTS, and a projection between the two aggregates. It would be good to cover them here:
+# EXISTS. Expected `1, 2`.
+statement error DataFusion error: This feature is not implemented: Physical plan does not support logical expression Exists
+SELECT o.k FROM nested_agg_outer AS o WHERE EXISTS (SELECT max(n) FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k)) ORDER BY o.k;
+
+# A projection between the aggregates. Expected `(1, 2), (2, 1)`.
+statement error DataFusion error: This feature is not implemented: Physical plan does not support logical expression ScalarSubquery
+SELECT o.k, (SELECT max(n2) FROM (SELECT n + 1 AS n2 FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k))) FROM nested_agg_outer AS o ORDER BY o.k;| // A pulled up scalar aggregate below gives no row for unmatched | ||
| // outer rows, so this aggregate would see an empty input. | ||
| // See https://github.com/apache/datafusion/issues/26508 | ||
| if self.pulled_up_scalar_agg { | ||
| self.can_pull_up = false; | ||
| } |
There was a problem hiding this comment.
nit: Two statements now update can_pull_up for the same "can we pull past this aggregate" rule. You could fold this into the line above:
self.can_pull_up = self.can_pull_up
&& self.can_pull_over_aggregation
&& !self.pulled_up_scalar_agg;(this changes nothing for the distinct case, because the new check is outside the if !is_distinct block and must stay there.)
Also, pulled_up_scalar_agg now controls this decision, and the check works only because the child's f_up sets the flag first. A short doc comment on the field would make both points clear.
There was a problem hiding this comment.
The check moved to the top of the Aggregate branch. It now sets can_pull_up = false and returns early with TreeNodeRecursion::Stop, which fixes the schema error jayzhan211 found (details in the top-level comment). That leaves no second update of can_pull_up to fold. The check is still outside the is_distinct block. I also added the doc comment on pulled_up_scalar_agg.
| CREATE TABLE nested_agg_inner(id INT, v INT) AS VALUES (1, 10); | ||
|
|
||
| # Expected `(1, 1), (2, 1)` and `(1, 1), (2, 0)`. | ||
| statement error DataFusion error: This feature is not implemented: Physical plan does not support logical expression ScalarSubquery |
There was a problem hiding this comment.
The same file has a precedent for this kind of test (around lines 692-716): it uses query error, matches only part of the message, and has a comment saying it "errors rather than returning wrong rows". Can these tests (and the extra cases suggested in the other review) do the same? For example:
# Errors rather than returning wrong rows. Expected `(1, 1), (2, 1)`.
query error Physical plan does not support logical expression ScalarSubquery
If the DataFusion error: This feature is not implemented: prefix changes, the full-message match breaks. The comment also tells readers that the error is a stop-gap.
There was a problem hiding this comment.
Switched all the new cases to query error with a partial message match and an "Errors rather than returning wrong rows" comment.
| statement ok | ||
| CREATE TABLE nested_agg_inner(id INT, v INT) AS VALUES (1, 10); | ||
|
|
||
| # Expected `(1, 1), (2, 1)` and `(1, 1), (2, 0)`. |
There was a problem hiding this comment.
nit: This one comment gives the expected results for the two queries below. Please put one comment above each query, so readers can see which result goes with which query.
There was a problem hiding this comment.
Done. Each query now has its own comment with its expected result.
| SELECT o.k, (SELECT max(c) FROM (SELECT i.id, count(*) AS c FROM nested_agg_inner AS i WHERE i.id = o.k GROUP BY i.id)) FROM nested_agg_outer AS o ORDER BY o.k; | ||
| ---- | ||
| 1 1 | ||
| 2 NULL |
There was a problem hiding this comment.
The guard also stops two more shapes that have no test: a GROUP BY-only aggregate (the is_distinct path) over the scalar aggregate, and an aggregate with GROUP BY over the scalar aggregate. Both lose the row for unmatched outer rows in the same way, so blocking them is correct. I ran both on this branch and they give the error below. Tests would keep that behaviour in place:
| 2 NULL | |
| 2 NULL | |
| # A GROUP BY-only aggregate over the scalar aggregate. | |
| # Errors rather than returning wrong rows. Expected `(1, 1), (2, 1)`. | |
| query error Physical plan does not support logical expression ScalarSubquery | |
| SELECT o.k, (SELECT count(*) FROM (SELECT n FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k) GROUP BY n)) FROM nested_agg_outer AS o ORDER BY o.k; | |
| # A grouped aggregate over the scalar aggregate. | |
| # Errors rather than returning wrong rows. Expected `(1, 1), (2, 1)`. | |
| query error Physical plan does not support logical expression ScalarSubquery | |
| SELECT o.k, (SELECT max(c) FROM (SELECT n, count(*) AS c FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k) GROUP BY n)) FROM nested_agg_outer AS o ORDER BY o.k; |
There was a problem hiding this comment.
Added both, thanks for running them.
|
Thanks @jayzhan211 and @adriangb. @jayzhan211 the schema error with a filter between the aggregates is not new. Main hits the same error on the SELECT o.k, (SELECT count(*) FROM (SELECT count(*) AS n FROM nested_agg_inner AS i WHERE i.id = o.k HAVING count(*) >= 0))
FROM nested_agg_outer AS o ORDER BY o.k;
-- Schema error: Schema contains duplicate unqualified field name "count(Int64(1))"The |
|
Thanks @jayzhan211 and @adriangb for reviewing this, btw this is a second item for today which makes me think our test coverage is less than we would expect |
|
@adriangb @jayzhan211 please have another look |
|
@jayzhan211 PTAL if you dont mind |
…s whose result is NULL on empty input (apache#26942) ## Which issue does this PR close? - Closes apache#26505. ## Rationale for this change A correlated scalar subquery without `GROUP BY` ignores its `HAVING` when the `HAVING` is true for an empty input and the subquery returns an aggregate that is NULL for an empty input (`sum`, `max`, `min`): ```sql SELECT x.a, (SELECT sum(y.b) FROM (VALUES (1, 10)) AS y(a, b) WHERE y.a = x.a HAVING sum(y.b) IS NULL) AS v FROM (VALUES (1), (2)) AS x(a) -- main: (1, 10), (2, NULL) -- PostgreSQL: (1, NULL), (2, NULL) ``` `PullUpCorrelatedExpr` pulls such a `HAVING` out of the subquery, and `ScalarSubqueryToJoin` only applies it again through the count bug compensation `CASE`. That `CASE` is not built for expressions that are NULL on empty input, so the `HAVING` is dropped. Following apache#5492 (comment), this makes the query error instead of trying to return the right rows. ## What changes are included in this PR? `build_join` keeps the subquery correlated when a `HAVING` was pulled up and the subquery's output is NULL on empty input. The query then fails with `Physical plan does not support logical expression ScalarSubquery`, the same way apache#26544 does. Only the output column is checked. A `count(*)` subquery whose `HAVING` reads `sum` or `max` still gets the `HAVING` from the compensation and keeps working. ## What is the testing strategy for this PR? New cases in `subquery.slt`: the query from the issue, `max`, and `sum` with `HAVING count(*) = 0` now error. A `count(*)` subquery with a `HAVING` on `count(*)` or on `sum`, and a `HAVING` that is false on empty input, still return the same rows as before. All `sqllogictest` files, the `datafusion-optimizer` unit tests and the `core_integration` `sql::` tests pass locally. ## Are there any user-facing changes? These queries now return a "not implemented" error instead of wrong results. No API changes. --------- Co-authored-by: Alejandro Borrego <210245044+abp002@users.noreply.github.com>
…s without GROUP BY (#311) * fix: correlated exists/not exists subqueries hit the count bug for groupless aggregates (apache#25391) ## Which issue does this PR close? - Part of apache#24960. ## Rationale for this change See apache#24960. This is a split of apache#25008, which originally covered `EXISTS`/`NOT EXISTS`/`IN`/`NOT IN` together. That PR has been split into two smaller PRs between this one for `EXISTS`/`NOT EXISTS` and a (to come) follow-up stacked on top of it for `IN`/`NOT IN`. ## What changes are included in this PR? Correlated `EXISTS`/`NOT EXISTS` subqueries had count-bug compensation available but never turned it on. * Turn on count-bug compensation for correlated `EXISTS`/`NOT EXISTS` subqueries. * When compensation is needed, decorrelate into a `LEFT JOIN` and substitute the correct value instead of dropping the row. * Make unsupported join shapes fail loudly instead of silently falling back to incorrect behavior. `IN`/`NOT IN` compensation is out of scope for this PR and returns an explicit "not implemented" error. This will be covered by the follow-up PR. ## What is the testing strategy for this PR? Added twenty sqllogictest cases in `subquery.slt`. Ran all `datafusion`, `datafusion-cli`, and `datafusion-sqllogictest` suites, and `./dev/rust_lint.sh`. Also differentially fuzz-tested against DuckDB with a standalone harness, and did several adversarial review passes with Claude to look for gaps beyond the fuzzer's generated shapes. ## Are there any user-facing changes? None, except in the sense that this fixes a user-visible bug. ## AI Usage _AI was used during development of this PR, primarily to help review the test suite and verify test cases against the implemented fix._ * fix: keep a subquery correlated when an aggregate sits above a pulled up scalar aggregate (apache#26544) ## Which issue does this PR close? - Part of apache#26508. ## Rationale for this change An aggregate without `GROUP BY` returns one row even when its input is empty. When such an aggregate is in a correlated subquery and another aggregate sits above it, DataFusion returns wrong results for outer rows that match no inner rows: ```sql SELECT x.a, (SELECT count(*) FROM (SELECT max(y.b) FROM (VALUES (1, 10)) AS y(a, b) WHERE y.a = x.a)) AS v1, (SELECT max(n) FROM (SELECT count(*) AS n FROM (VALUES (1, 10)) AS y(a, b) WHERE y.a = x.a)) AS v2 FROM (VALUES (1), (2)) AS x(a) ``` For `a = 2` this returns `v1 = 0, v2 = NULL` instead of `v1 = 1, v2 = 0`, which DuckDB, SQLite and PostgreSQL return. The same shape gives wrong results under `IN` and `LEFT JOIN LATERAL` too. When the correlated filter is pulled up, the inner scalar aggregate becomes a grouped aggregate, which returns no row for the outer rows it does not match. The aggregate above then runs over an empty input. The count bug handling only fixes the aggregate the join reads, which here is the outer one, so the inner row is never restored. The existing `TODO` next to `pulled_up_scalar_agg` described this case. ## What changes are included in this PR? `PullUpCorrelatedExpr` stops the pull up when it reaches an `Aggregate` after a scalar aggregate has already been pulled up. The subquery stays correlated, the same way a window over an aggregate with count bug handling does today. The rewrite stops at that `Aggregate`, so the nodes above it are not rebuilt over the pulled up plan. Before, the rebuild could fail with a schema error. Such a query now fails with `Physical plan does not support logical expression ScalarSubquery` instead of returning wrong rows. A projection over the scalar aggregate (`SELECT n + 1 FROM (SELECT count(*) AS n ...)`) and an aggregate over a grouped aggregate are still pulled up. ## What is the testing strategy for this PR? New `sqllogictest` cases at the end of `subquery.slt` cover the two queries from the issue, the `IN`, `LATERAL` and `EXISTS` forms, a projection, a filter, a `GROUP BY`-only aggregate and a grouped aggregate between the aggregates, a `max` over `max` query that is now blocked, and the two shapes that must still be pulled up. All `sqllogictest` files, the `datafusion-optimizer` unit tests and the `core_integration` `sql::` tests (which include the TPC-DS planning tests) pass locally. ## Are there any user-facing changes? Queries with this shape now return a "not implemented" error instead of wrong results. Some queries of this shape returned correct rows before and now fail too, for example `max` over `max`. Telling them apart needs the outer aggregate evaluated on the inner one's empty-input row. No API changes. --------- Co-authored-by: Jay Zhan <jayzhan211@gmail.com> * fix: reject correlated IN/NOT IN over a groupless aggregate (apache#26677) ## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> Part of apache#24960. This PR adds a safe rejection until `IN`/`NOT IN` count-bug compensation is implemented. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. Please explain the problem you are trying to solve in terms of the user-visible behavior, rather than the implementation. For example, "The code in `foo.rs` doesn't handle nulls" is a symptom of the implementation. "COUNT(DISTINCT) returns wrong results when the column contains nulls" is the user-visible problem. --> A correlated `IN`/`NOT IN` over an aggregate without `GROUP BY` returns wrong rows when an outer row has no match (see apache#24960 (comment)). apache#25391 fixed `EXISTS`/`NOT EXISTS`. `IN`/`NOT IN` will be covered in a follow-up, so until then these queries should error instead of returning wrong results. ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here, but it is sometimes worth providing a summary of the individual changes in this PR. --> `build_join` in `decorrelate_predicate_subquery.rs` now keeps these subqueries correlated, so they fail to plan with a not-implemented error. The exception is an `IN` in a `WHERE` over an aggregate that is NULL on empty input (e.g. `max`, `sum`), which the current rewrite already answers correctly. ## What is the testing strategy for this PR? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code Briefly describe how this PR is tested, and point to the specific tests you added. For example: 'This new feature is covered by the `sqllogictest` cases added in `foo.slt`'. If this PR does not add tests, explain why. For example, if the change is already covered by existing tests, please mention it. You should also check the `codecov` bot reply on this PR to confirm the changed code is exercised. --> - The existing IN over max test still passes unchanged. - The existing NOT IN over count test now expects the error. - New tests expect the error for IN over count in a filter and in a projection, NOT IN over max, and IN over max in a projection. ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. If there are any breaking changes to public APIs, please add the `api change` label. --> These queries now return a not-implemented error instead of wrong results. * test: expect the count-bug backport's plans and errors on spiceai-55; add ANY/ALL cases over a groupless aggregate (two are guards that pass without the change) * fix(optimizer): compensate the count bug only for plain correlation keys and rows a LIMIT keeps * test: spiceai-55 fails IN over a groupless max inside OR with a duplicate projection name * fix(optimizer): read a NULL IN result as false only in a positive position; stop only above a grouped scalar aggregate * fix(optimizer): keep a correlated EXISTS with an OFFSET correlated --------- Co-authored-by: Mohammad Naqvi <81446894+mohammadnaqvi04@users.noreply.github.com> Co-authored-by: Oleks V <comphead@users.noreply.github.com> Co-authored-by: Jay Zhan <jayzhan211@gmail.com>
Which issue does this PR close?
Rationale for this change
An aggregate without
GROUP BYreturns one row even when its input is empty. When such an aggregate is in a correlated subquery and another aggregate sits above it, DataFusion returns wrong results for outer rows that match no inner rows:For
a = 2this returnsv1 = 0, v2 = NULLinstead ofv1 = 1, v2 = 0, which DuckDB, SQLite and PostgreSQL return. The same shape gives wrong results underINandLEFT JOIN LATERALtoo.When the correlated filter is pulled up, the inner scalar aggregate becomes a grouped aggregate, which returns no row for the outer rows it does not match. The aggregate above then runs over an empty input. The count bug handling only fixes the aggregate the join reads, which here is the outer one, so the inner row is never restored. The existing
TODOnext topulled_up_scalar_aggdescribed this case.What changes are included in this PR?
PullUpCorrelatedExprstops the pull up when it reaches anAggregateafter a scalar aggregate has already been pulled up. The subquery stays correlated, the same way a window over an aggregate with count bug handling does today. The rewrite stops at thatAggregate, so the nodes above it are not rebuilt over the pulled up plan. Before, the rebuild could fail with a schema error. Such a query now fails withPhysical plan does not support logical expression ScalarSubqueryinstead of returning wrong rows.A projection over the scalar aggregate (
SELECT n + 1 FROM (SELECT count(*) AS n ...)) and an aggregate over a grouped aggregate are still pulled up.What is the testing strategy for this PR?
New
sqllogictestcases at the end ofsubquery.sltcover the two queries from the issue, theIN,LATERALandEXISTSforms, a projection, a filter, aGROUP BY-only aggregate and a grouped aggregate between the aggregates, amaxovermaxquery that is now blocked, and the two shapes that must still be pulled up. Allsqllogictestfiles, thedatafusion-optimizerunit tests and thecore_integrationsql::tests (which include the TPC-DS planning tests) pass locally.Are there any user-facing changes?
Queries with this shape now return a "not implemented" error instead of wrong results. Some queries of this shape returned correct rows before and now fail too, for example
maxovermax. Telling them apart needs the outer aggregate evaluated on the inner one's empty-input row. No API changes.