Skip to content

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

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

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

Conversation

@tlfua

@tlfua tlfua commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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. 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.
  • An aggregate without GROUP BY gives one row for every outer row. When the pull up adds a correlated column to its GROUP BY, an outer row without a match gets no row. A new regrouped_scalar_agg flag records this, and the Join/AsOfJoin arm then keeps the subquery correlated. So an EXISTS, NOT EXISTS or IN subquery 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. Unnest is not changed: the aggregate is still pulled up through it, as on main.

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):

  • Scalar (both join orders), EXISTS, NOT EXISTS and IN subqueries, including a row with no match (the count bug result 0), an aggregate without GROUP BY that reads no outer column, and the non-equality query from the issue. They fail on main with the schema error.
  • EXISTS, NOT EXISTS, IN and a projected EXISTS over an aggregate without GROUP BY below a join. They expect the not-implemented error, where main gives the schema error. Removing the Join/AsOfJoin arm check makes these 4 tests fail.
  • Two queries with an aggregate below an Unnest. They return the same rows as on main, and fail if the check also stops the pull up through an Unnest.
  • A correlated filter below the side an outer join fills with NULLs, and a correlated column name that repeats through the join. These give the same error on main and 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 on main fails or gives different rows on this PR, and this PR gives no wrong rows that main does not also give.

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 affects the Join/AsOfJoin path 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. 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.

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
Contributor 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@tlfua

tlfua commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@jayzhan211 thanks for the review! Opened #27800 for the LATERAL extra row; it reproduces on main too.

Separately, #27801: an outer column in a JOIN ... ON inside the subquery fails on main even without a derived table, so I left it out of this PR.

@tlfua

tlfua commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Fork CI for fac0f00 passed: Rust, Dev, Dependencies and extended tests.

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

Comment thread datafusion/optimizer/src/decorrelate.rs Outdated
// `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

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

Checking 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
+2

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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:

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 4a35c0e2-98fe-41b8-b3ac-fba2cecb888c
@tlfua

tlfua commented Nov 29, 2026

Copy link
Copy Markdown
Contributor Author

Fork CI for 3605ae0 passed: Rust, Dev, Dependencies and extended tests.

@tlfua

tlfua commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor Author

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:

Shape Both correct Error on main, correct on PR
3 to 5 wrappers (projection, filter, alias, sort, distinct, window, limit, join) between the correlated aggregate and the subquery 291 1122
2 or 3 stacked joins in that chain 0 834
3 or 4 levels of nested subqueries, each level correlated only to its direct outer query 180 0
Two correlated subqueries of these shapes in one query 15 66
  • No query that is correct on main fails or gives different rows on this PR.

  • This PR gives no wrong rows, and no query gives different results across runs.

  • The 2022 fixed cases all fail on main with the same No field named ... error as this issue. For example:

    SELECT t.a FROM t WHERE EXISTS (SELECT 1 FROM (
      SELECT w2.v FROM (SELECT w1.v FROM (SELECT w0.v FROM (
        SELECT i.b AS v FROM i WHERE i.a = t.a) w0) w1 CROSS JOIN u u1) w2
      LEFT JOIN u u2 ON u2.c > w2.v) s);

    Main fails with Schema error: No field named w1.a. This PR returns the same rows as DuckDB.

The tests in subquery.slt cover one join and two stacked wrappers, but not two stacked joins, which is the shape of 834 of the fixed cases. Should I add a case like this one to subquery.slt? It fails on main with No field named e.a, and this PR returns the same rows as DuckDB:

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

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