Skip to content

fix: update join schema when pulling up correlated columns - #27783

Open
tlfua wants to merge 1 commit into
apache:mainfrom
tlfua:tlfua/fix/27691-correlated-subquery-schema-error
Open

tlfua wants to merge 1 commit into
apache:mainfrom
tlfua:tlfua/fix/27691-correlated-subquery-schema-error

Conversation

@tlfua

@tlfua tlfua commented Nov 27, 2026

Copy link
Copy Markdown

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 EXISTS and IN subqueries:

CREATE TABLE t(a INT) AS VALUES (1), (2), (4);
CREATE TABLE i(a INT) AS VALUES (1), (2), (2), (3);
CREATE TABLE u(b INT) AS VALUES (10), (20);

SELECT o.a, (
  SELECT count(*) FROM (SELECT a AS x FROM i WHERE a = o.a) e, u
) FROM t o;
-- main: Optimizer rule 'scalar_subquery_to_join' failed
--       Schema error: No field named e.a. Did you mean 'e.x'?
-- this PR: (1, 2), (2, 4), (4, 0)

When PullUpCorrelatedExpr moves the correlated filter up, the Projection and the SubqueryAlias below the join add the column the filter reads (e.a). A Join falls into the _ arm of PullUpCorrelatedExpr::pull_up and keeps the schema it was built with. The node above it then looks up e.a in the join schema and fails.

f_down already lets a correlated filter move above a Join or an AsOfJoin (when the join preserves the rows of the correlated side). Only the schema update on the way up is missing, the same as for Unnest before #25838.

What changes are included in this PR?

  • PullUpCorrelatedExpr::pull_up passes the pulled up columns through a Join and an AsOfJoin with pass_through_pulled_up_cols, as it already does for Window and Unnest. 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_subquery in subquery.slt). With this PR it now gets the same This feature is not implemented: Physical plan does not support logical expression ScalarSubquery error as the variants without the join or without the rename, instead of the schema error. On main, those variants also fail with this error, so the query cannot return 0 until non-equality correlated scalar subqueries are supported.

Not changed by this PR:

What is the testing strategy for this PR?

New sqllogictest cases at the end of subquery.slt (t27691 tables) cover scalar (both join orders), EXISTS, NOT EXISTS and IN subqueries, including a row with no match (the count bug result 0), and the non-equality query from the issue. All of them fail on main with the schema error.

Commands run locally:

  • cargo test -p datafusion-sqllogictest --test sqllogictests: passed
  • cargo test -p datafusion-optimizer --lib --tests: passed
  • cargo fmt --all -- --check: passed
  • cargo clippy -p datafusion-optimizer --all-targets --all-features -- -D warnings: passed

The full lint suite and the extended tests run in fork CI. I did not run the sql_planner benchmarks: the change only adds one arm for Join/AsOfJoin in pull_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.

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
@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Nov 27, 2026
@tlfua
tlfua marked this pull request as ready for review November 27, 2026 03:27
@tlfua

tlfua commented Nov 27, 2026

Copy link
Copy Markdown
Author

This PR is ready for review. The fork CI run passed (Rust, Dev and Dependencies), and I also ran the extended tests on my fork: https://github.com/tlfua/datafusion/actions/runs/45928527943

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

@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(_) => {

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.

@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, 2

NOT 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(_) => {

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.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Correlated scalar subquery with a non-equality predicate fails with a schema error over a renamed column

2 participants