Repository navigation
Conversation
PullUpCorrelatedExpr lets a correlated filter move above a Join or an AsOfJoin, but f_up kept the join's original schema. When a Projection or SubqueryAlias below the join added the pulled up column, the node above the join could not find it and planning failed with a schema error. Pass the pulled up columns through the join with pass_through_pulled_up_cols, as for Window and Unnest. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4a35c0e2-98fe-41b8-b3ac-fba2cecb888c
|
This PR is ready for review. The fork CI run passed ( Since this is my first contribution here, the workflows on this PR are waiting for approval. Could a maintainer please approve them when you have a chance? Thank you! |
jayzhan211
left a comment
There was a problem hiding this comment.
@tlfua thanks for picking this up! A LATERAL join over the same shape now returns an extra row where main returned a schema error. SELECT t.a, s.y, s.c FROM t, LATERAL (SELECT * FROM (SELECT a*10 AS y FROM i WHERE a = t.a), (SELECT count(*) c FROM u) z) s returns (4, NULL, NULL) on top of the expected rows. Main already returns that row when the derived table keeps the name (SELECT a FROM i WHERE a = t.a): the uncorrelated count(*) sets pulled_up_scalar_agg, and decorrelate_lateral_join then turns the inner lateral join into a left join. It's fine to handle this in a follow-up; could you open an issue for it?
| // `f_down` checked that the pulled up filters do not read an | ||
| // unnested column. | ||
| LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan), | ||
| LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_) => { |
There was a problem hiding this comment.
@tlfua thanks for the fix! With this arm, an EXISTS, NOT EXISTS or IN subquery whose derived table is an aggregate without GROUP BY now returns wrong rows where main returned the schema error. For EXISTS, build_join retries the pull up with count bug handling off, so the collected_count_expr_map check in pass_through_pulled_up_cols never fires, and the regrouped aggregate gives no row for an outer row without a match:
SELECT o.a FROM t o WHERE EXISTS (
SELECT 1 FROM (SELECT count(*) c FROM i WHERE a = o.a) e, u
) ORDER BY o.a;
-- t = 1, 2, 4; i = 1, 2, 2, 3; u = 10, 20
-- expected 1, 2, 4; this PR: 1, 2NOT EXISTS returns 4 (expected none), and o.a - 4 IN (SELECT e.c ...) returns nothing (expected 4). Checking pulled_up_scalar_agg instead is too broad: an uncorrelated (SELECT count(*) c FROM u) z in the other join input sets it too, and that would stop a query that works today. A flag that is set only when the pull up adds a correlated column to an empty GROUP BY, checked in the shared helper, keeps these correlated (it also fixes the same bug for an Unnest, which main already has):
@@ pub struct PullUpCorrelatedExpr {
pub pulled_up_scalar_agg: bool,
+ /// Whether the pull up added a correlated column to the `GROUP BY` of an
+ /// aggregate that had none. Unlike [`Self::pulled_up_scalar_agg`], an
+ /// uncorrelated aggregate visited after a correlated filter leaves it unset.
+ regrouped_scalar_agg: bool,
@@ pub fn new() -> Self {
pulled_up_scalar_agg: false,
+ regrouped_scalar_agg: false,
@@ LogicalPlan::Aggregate(aggregate)
if aggregate.group_expr.is_empty() {
self.pulled_up_scalar_agg = true;
+ self.regrouped_scalar_agg |= !local_correlated_cols.is_empty();
}
@@ fn pass_through_pulled_up_cols(
- if plan
- .inputs()
- .iter()
- .any(|input| self.collected_count_expr_map.contains_key(*input))
+ // `EXISTS` retries the pull up without count bug handling, so
+ // `collected_count_expr_map` can be empty while such an aggregate is
+ // below `plan`.
+ if self.regrouped_scalar_agg
+ || plan
+ .inputs()
+ .iter()
+ .any(|input| self.collected_count_expr_map.contains_key(*input))
{With this, cargo test -p datafusion-optimizer and the full sqllogictest suite pass. Removing either new condition fails one of the tests below.
Tests for subquery.slt (after the IN case), with the expected results in comments
# An aggregate without GROUP BY below the join returns a row for every outer
# row, so the subquery stays correlated. Expected: 1, 2, 4.
query error
SELECT o.a FROM t27691 o WHERE EXISTS (
SELECT 1 FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e, t27691_u u
) ORDER BY o.a;
----
DataFusion error: This feature is not implemented: Physical plan does not support logical expression Exists(Exists { subquery: <subquery>, negated: false })
# Expected: 4 (its count is 0).
query error
SELECT o.a FROM t27691 o WHERE o.a - 4 IN (
SELECT e.c FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e, t27691_u u
) ORDER BY o.a;
----
DataFusion error: This feature is not implemented: Physical plan does not support logical expression InSubquery(InSubquery { expr: BinaryExpr(BinaryExpr { left: Cast(Cast { expr: Column(Column { relation: Some(Bare { table: "t27691" }), name: "a" }), field: Field { name: "", data_type: Int64, nullable: true } }), op: Minus, right: Literal(Int64(4), None) }), subquery: <subquery>, negated: false })
# The same holds for an Unnest. Expected: 1, 2, 4.
query error
SELECT o.a FROM t27691 o WHERE EXISTS (
SELECT unnest(make_array(c, c))
FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e
) ORDER BY o.a;
----
DataFusion error: This feature is not implemented: Physical plan does not support logical expression Exists(Exists { subquery: <subquery>, negated: false })
# An aggregate without GROUP BY that reads no outer column does not.
query I
SELECT o.a FROM t27691 o WHERE EXISTS (
SELECT 1 FROM (SELECT a AS x FROM t27691_i WHERE a = o.a) e,
(SELECT count(*) c FROM t27691_u) z
) ORDER BY o.a;
----
1
2
There was a problem hiding this comment.
Thanks, applied in fac0f00 along with your tests (error messages filled in). I also added NOT EXISTS and an EXISTS in the projection (mark join) over sum. These now keep the subquery correlated and fail with the not-implemented error instead of returning wrong rows. Removing the regrouped_scalar_agg check fails five of the new tests.
I also ran a 1152-query matrix (kind of derived table × join form × kind of subquery) against DuckDB. Before the flag, all 64 wrong results had an aggregate without GROUP BY under EXISTS, NOT EXISTS, NOT IN, or a mark join. With the flag there are none. (IN happened to give correct rows with my data; your o.a - 4 case covers it.)
| // `f_down` checked that the pulled up filters do not read an | ||
| // unnested column. | ||
| LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan), | ||
| LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_) => { |
There was a problem hiding this comment.
Nothing tests the AsOfJoin part of this arm: removing it keeps every test passing, and its schema is rebuilt through AsOfJoin::try_new rather than the Join path. This query fails with the schema error on main and returns the rows below with this PR. Could you add it next to the other cases?
query II
SELECT o.a, (
SELECT count(*) FROM (SELECT a AS x FROM t27691_i WHERE a = o.a) e
ASOF JOIN t27691_u u MATCH_CONDITION (e.x * 10 >= u.b)
) FROM t27691 o ORDER BY o.a;
----
1 1
2 2
4 0
There was a problem hiding this comment.
Added in fac0f00. Removing AsOfJoin from the arm now fails it.
…below a join The `EXISTS` retry runs the pull up without count bug handling, so `collected_count_expr_map` is empty and a groupless aggregate that the pull up regroups by a correlated column could pass through a join, window or unnest and lose the row of an outer row without a match. Track that case with `regrouped_scalar_agg` and stop the pull up there. Also test the `AsOfJoin` arm, a filter above the join, a nested join, the null-supplying side of an outer join and a repeated correlated column name. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4a35c0e2-98fe-41b8-b3ac-fba2cecb888c
|
@jayzhan211 thanks for the review! Opened #27800 for the Separately, #27801: an outer column in a |
|
Fork CI for fac0f00 passed: Rust, Dev, Dependencies and extended tests. |
jayzhan211
left a comment
There was a problem hiding this comment.
@tlfua thanks for the update! Optional cleanup: the PR description could use an update after the second commit. "What changes" could add that an EXISTS, NOT EXISTS or IN subquery over an aggregate without GROUP BY below the join now stays correlated (a not-implemented error) instead of returning wrong rows. The testing section says all new tests fail on main with the schema error, which no longer fits the new query error cases.
| // `EXISTS` retries the pull up without count bug handling, so | ||
| // `collected_count_expr_map` can be empty while such an aggregate is | ||
| // below `plan`. | ||
| if self.regrouped_scalar_agg |
There was a problem hiding this comment.
@tlfua thanks for applying this! My earlier suggestion put the check in the shared helper, which was too broad. It also stops the pull up through an Unnest, so two queries that return correct rows on 56.0.0 now fail with the not-implemented error:
SELECT o.a FROM t27691 o WHERE o.a IN (
SELECT unnest(make_array(m)) FROM (SELECT max(a) m FROM t27691_i WHERE a = o.a) e
) ORDER BY o.a;
-- 56.0.0: 1, 2; this PR: This feature is not implemented ... InSubqueryChecking the flag only in the Join/AsOfJoin arm keeps every join case in this PR correlated (all of them were schema errors on 56.0.0) and leaves Unnest as it is in 56.0.0. With that change the Unnest test returns 1, 2 (wrong, the same as 56.0.0), so it should become its own issue rather than a test here. Could you open one?
LogicalPlan::Join(_) | LogicalPlan::AsOfJoin(_) => {
+ // A regrouped aggregate below gives no row for an outer row
+ // without a match, where the aggregate gave one. `IN` and the
+ // `EXISTS` retry run without count bug handling, so
+ // `collected_count_expr_map` can be empty here.
+ if self.regrouped_scalar_agg {
+ self.can_pull_up = false;
+ }
self.pass_through_pulled_up_cols(plan)
}
@@
- /// hold once a Window or an Unnest runs over the aggregate, so the pull up
- /// stops in that case.
+ /// hold once a Window, an Unnest or a Join runs over the aggregate, so the
+ /// pull up stops in that case.
fn pass_through_pulled_up_cols(
&mut self,
plan: LogicalPlan,
) -> Result<Transformed<LogicalPlan>> {
- // `EXISTS` retries the pull up without count bug handling, so
- // `collected_count_expr_map` can be empty while such an aggregate is
- // below `plan`.
- if self.regrouped_scalar_agg
- || plan
- .inputs()
- .iter()
- .any(|input| self.collected_count_expr_map.contains_key(*input))
+ if plan
+ .inputs()
+ .iter()
+ .any(|input| self.collected_count_expr_map.contains_key(*input))
{subquery.slt: replace the Unnest error test with the two queries that work on 56.0.0
-# The same holds for an Unnest. Expected: 1, 2, 4.
-query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression Exists
-SELECT o.a FROM t27691 o WHERE EXISTS (
- SELECT unnest(make_array(c, c))
- FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e
-) ORDER BY o.a;
+# Below an Unnest, the aggregate is still pulled up. These queries give no
+# row for an outer row without a match either way.
+query I
+SELECT o.a FROM t27691 o WHERE o.a IN (
+ SELECT unnest(make_array(m)) FROM (SELECT max(a) m FROM t27691_i WHERE a = o.a) e
+) ORDER BY o.a;
+----
+1
+2
+
+query I
+SELECT o.a FROM t27691 o WHERE EXISTS (
+ SELECT 1 FROM (
+ SELECT unnest(make_array(c)) v
+ FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e
+ ) y WHERE v > 0
+) ORDER BY o.a;
+----
+1
+2With this change the full sqllogictest suite, cargo test -p datafusion-optimizer and clippy pass. Removing the Join-arm check fails 4 tests, and moving it back into the helper fails the 2 new Unnest tests.
There was a problem hiding this comment.
@jayzhan211 thanks, applied in 3605ae0: the check is now only in the Join/AsOfJoin arm, and the Unnest error test is replaced with your two queries (both return 1, 2, as on main). Removing the Join-arm check fails 4 tests, and moving it back into the helper fails the 2 Unnest tests.
Opened #27829 for the make_array(c, c) case.
I also compared main, this PR and DuckDB 2.0.1 on about 15k generated subqueries (EXISTS/NOT EXISTS/IN/scalar/LATERAL, with joins, ASOF, windows, unnest and filters over aggregates, on 3 datasets, two of them with an empty table), 5 runs each, plus about 60 hand-written join shapes:
- No query that is correct on main fails or gives different rows on this PR.
- This PR gives no wrong rows that main does not also give.
- 3192 cases in this set go from an error on main to the correct rows.
Two things that are not new, for the record:
-
With a
LATERALsubquery that joins a correlated derived table with an uncorrelatedcount(*), some queries change from main's schema error to an internal error from the schema check afterdecorrelate_lateral_join. For example:SELECT o.a, s.v FROM t o, LATERAL ( SELECT e.v FROM (SELECT i.a AS w FROM i WHERE i.a = o.a) q, (SELECT count(*) AS v FROM i) e ) s;
This looks related to Wrong results: LATERAL over a correlated derived table and an uncorrelated aggregate without GROUP BY returns an extra NULL row #27800 : the uncorrelated
count(*)setspulled_up_scalar_agg, and the new schema has an extras.afield and a nullablev. In the cases I tested, both main and this PR give an error, never rows. -
An
EXISTSover two nested filters on a correlatedcount(*)fails with a schema error in about half of the runs (10 of 20 on main and on this PR). The query has no join: Correlated EXISTS over nested filters on count(*) fails with "No field named" in some runs only #27830 .
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4a35c0e2-98fe-41b8-b3ac-fba2cecb888c
|
Fork CI for 3605ae0 passed: Rust, Dev, Dependencies and extended tests. |
|
To check queries deeper than two levels, I ran a three-way comparison in CI between main (053386b), this PR (3605ae0) and DuckDB 2.0.1: https://github.com/tlfua/datafusion/actions/runs/46217032638 The generator, runner and workflow are on https://github.com/tlfua/datafusion/tree/ci/27691-deep-sweep . The cases were generated and run with AI assistance. The generator produced 7294 queries. I kept the 836 that return rows on main or on this PR for at least one dataset. The other queries give an error on both, mostly "Physical plan does not support logical expression". Each kept query ran on 3 datasets (two with an empty table), 5 times on each binary:
The tests in query II
SELECT o.a, (
SELECT count(*) FROM (
SELECT e1.x FROM (SELECT e.x FROM (SELECT a AS x FROM t27691_i WHERE a = o.a) e, t27691_u u1) e1,
t27691_u u2
) e2
) FROM t27691 o ORDER BY o.a;
----
1 4
2 8
4 0 |
Important
Fork CI setup: For pull requests from a fork to
main, enable workflows in your fork's Actions tab before you push.See the fork CI setup guide.
Which issue does this PR close?
Rationale for this change
A correlated subquery fails to plan with a schema error when its correlated filter sits inside a derived table that renames a column, and that derived table is joined with another relation inside the subquery. It affects scalar,
EXISTS,NOT EXISTSandINsubqueries:When
PullUpCorrelatedExprmoves the correlated filter up, theProjectionand theSubqueryAliasbelow the join add the column the filter reads (e.a). AJoinfalls into the_arm ofPullUpCorrelatedExpr::pull_upand keeps the schema it was built with. The node above it then looks upe.ain the join schema and fails.f_downalready lets a correlated filter move above aJoinor anAsOfJoin(when the join preserves the rows of the correlated side). Only the schema update on the way up is missing, the same as forUnnestbefore #25838.What changes are included in this PR?
PullUpCorrelatedExpr::pull_uppasses the pulled up columns through aJoinand anAsOfJoinwithpass_through_pulled_up_cols, as it already does forWindowandUnnest. This recomputes the join schema. The helper also keeps the subquery correlated when a join input carries count bug handling, which only holds when nothing runs between the aggregate and the node that reads it.GROUP BYgives one row for every outer row. When the pull up adds a correlated column to itsGROUP BY, an outer row without a match gets no row. A newregrouped_scalar_aggflag records this, and theJoin/AsOfJoinarm then keeps the subquery correlated. So anEXISTS,NOT EXISTSorINsubquery over such an aggregate below a join now fails with a not-implemented error instead of the schema error, and does not return wrong rows.Unnestis not changed: the aggregate is still pulled up through it, as onmain.The query in #27691 uses a non-equality correlated predicate (
e.x < o.a), which is not decorrelated (see#non_equal_correlated_scalar_subqueryinsubquery.slt). With this PR it now gets the sameThis feature is not implemented: Physical plan does not support logical expression ScalarSubqueryerror as the variants without the join or without the rename, instead of the schema error. Onmain, those variants also fail with this error, so the query cannot return0until non-equality correlated scalar subqueries are supported.Not changed by this PR:
Unsupported correlated subquery: correlated column ... has the same name as an earlier column of the subquery output(fix: error on correlated subqueries with ambiguous duplicate columns across relations #27244).LATERALsubquery still fails. This is LATERAL subquery fails with a schema error when a derived table alias differs from the table name #25837, which also happens without a join. For someLATERALsubqueries that also join an uncorrelatedcount(*), the error changes from the schema error to an internal error from the schema check afterdecorrelate_lateral_join(see Wrong results: LATERAL over a correlated derived table and an uncorrelated aggregate without GROUP BY returns an extra NULL row #27800). It is an error onmainand on this PR.What is the testing strategy for this PR?
New
sqllogictestcases at the end ofsubquery.slt(t27691tables):EXISTS,NOT EXISTSandINsubqueries, including a row with no match (the count bug result0), an aggregate withoutGROUP BYthat reads no outer column, and the non-equality query from the issue. They fail onmainwith the schema error.EXISTS,NOT EXISTS,INand a projectedEXISTSover an aggregate withoutGROUP BYbelow a join. They expect the not-implemented error, wheremaingives the schema error. Removing theJoin/AsOfJoinarm check makes these 4 tests fail.Unnest. They return the same rows as onmain, and fail if the check also stops the pull up through anUnnest.mainand on this PR, and check that the pull up through a join does not change them.I also compared
main, this PR and DuckDB 2.0.1 on about 15k generated subqueries over 3 datasets (two of them with an empty table), plus about 60 hand-written join shapes. No query that is correct onmainfails or gives different rows on this PR, and this PR gives no wrong rows thatmaindoes not also give.Commands run locally:
cargo test -p datafusion-sqllogictest --test sqllogictests: passedcargo test -p datafusion-optimizer --lib --tests: passedcargo fmt --all -- --check: passedcargo clippy -p datafusion-optimizer --all-targets --all-features -- -D warnings: passedThe full lint suite and the extended tests run in fork CI. I did not run the
sql_plannerbenchmarks: the change only affects theJoin/AsOfJoinpath inpull_up, which recomputes the schema of joins that are on the path of a pulled up correlated filter.Are there any user-facing changes?
The queries above now return results instead of a schema error. Some other queries that failed with a schema error now fail with a not-implemented error or an internal error instead. No public API changes.