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
| // `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
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. It 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.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 with a schema error. 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.What is the testing strategy for this PR?
New
sqllogictestcases at the end ofsubquery.slt(t27691tables) cover scalar (both join orders),EXISTS,NOT EXISTSandINsubqueries, including a row with no match (the count bug result0), and the non-equality query from the issue. All of them fail onmainwith the schema error.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 adds one arm forJoin/AsOfJoininpull_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. No public API changes.