Skip to content

fix: EXISTS/IN subqueries hit the count bug for groupless aggregates - #25008

Closed
mohammadnaqvi04 wants to merge 5 commits into
apache:mainfrom
mohammadnaqvi04:exists-in-count-bug
Closed

mohammadnaqvi04 wants to merge 5 commits into
apache:mainfrom
mohammadnaqvi04:exists-in-count-bug

Conversation

@mohammadnaqvi04

@mohammadnaqvi04 mohammadnaqvi04 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

Rationale for this change

See #24960.

What changes are included in this PR?

Correlated EXISTS/NOT EXISTS/IN/NOT IN subqueries had count-bug compensation available but never turned it on.

  • Turn on count-bug compensation for correlated EXISTS/NOT EXISTS/IN/NOT IN subqueries.
  • When compensation is needed, decorrelate into a LEFT JOIN and substitute the correct value instead of dropping the row.
  • Fix a related bug in the IN case, where the comparison value could wrongly affect which rows the join matched, corrupting results for rows with a real correlated match.
  • Make unsupported join shapes fail loudly instead of silently falling back to incorrect behavior.

What is the testing strategy for this PR?

Added eighteen sqllogictest cases in subquery.slt and one unit test.

They cover EXISTS, NOT EXISTS, IN, and NOT IN. Each is tested standalone and embedded in an OR. Each is also tested against an aggregate with a zero default and one with a NULL default.

Ran the full datafusion, datafusion-cli, and datafusion-sqllogictest suites, and ./dev/rust_lint.sh.

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.

@github-actions github-actions Bot added optimizer Optimizer rules sqllogictest SQL Logic Tests (.slt) labels Sep 7, 2026
@codecov-commenter

codecov-commenter commented Sep 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.56410% with 35 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.90%. Comparing base (e4c4fa4) to head (a8b0fb4).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
...on/optimizer/src/decorrelate_predicate_subquery.rs 77.56% 6 Missing and 29 partials ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main   #25008    +/-   ##
========================================
  Coverage   81.89%   81.90%            
========================================
  Files        1133     1133            
  Lines      424660   425129   +469     
  Branches   424660   425129   +469     
========================================
+ Hits       347765   348183   +418     
- Misses      56283    56288     +5     
- Partials    20612    20658    +46     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

I think there are still bugs here, see comments. I've compared the results against DuckDB.

Comment on lines +1210 to +1211
SELECT t1_id, t1_int FROM t1 WHERE 0 NOT IN (SELECT count(*) FROM t2 WHERE t1.t1_id = t2.t2_id HAVING count(*) = 0)
----

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.

This is still buggy, it should return:

11 1
22 2
44 4

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.

Oof, two things here:

  1. The join mishandled NULL negation for NOT IN
  2. This test's expected value was wrong too, they just happened to match each other.

Fixed both in the follow-up commit.

Comment on lines +1501 to +1504
select t1_id from t1
where t1_id > 40 or 0 not in (select count(*) from t2 where t1.t1_id = t2.t2_id having count(*) = 0)
----
44

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.

This result is also wrong, it should return:

11 1
22 2
44 4

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.

Fixed both in followup.

> SELECT t1_id, t1_int FROM t1 WHERE 0 NOT IN (SELECT count(*) FROM t2 WHERE t1.t1_id = t2.t2_id HAVING count(*) = 0);

+-------+--------+
| t1_id | t1_int |
+-------+--------+
| 11    | 1      |
| 22    | 2      |
| 44    | 4      |
+-------+--------+
3 row(s) fetched.
Elapsed 0.018 seconds.

> select t1_id from t1 where t1_id > 40 or 0 not in (select count(*) from t2 where t1.t1_id = t2.t2_id having count(*) = 0);

+-------+
| t1_id |
+-------+
| 11    |
| 22    |
| 44    |
+-------+
3 row(s) fetched.
Elapsed 0.011 seconds.

@mohammadnaqvi04

Copy link
Copy Markdown
Contributor Author

@AdamGS Thanks for the review! It seems like there was a trickier bug hiding under the one I initially wanted to fix. HAVING-failed rows were compensated with NULL, and negating NULL for NOT IN caused rows to be dropped rather than included. Fixed now.

@AdamGS

AdamGS commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

I did a pass with claude, and it spit out the following tests that all pass on main and in DuckDB, but fail on this branch:

statement ok
CREATE TABLE outer_rows(k INT);

statement ok
INSERT INTO outer_rows VALUES (1);

statement ok
CREATE TABLE inner_rows(k INT, v INT);

statement ok
INSERT INTO inner_rows VALUES (1, NULL);

statement ok
CREATE TABLE text_keys(k VARCHAR);

statement ok
INSERT INTO text_keys VALUES ('1'), ('01');

# HAVING evaluates to NULL for the matching group and must discard its row.
query I
SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k
  HAVING count(*) = 0 OR sum(i.v) > 0
);
----

# The same NULL-valued HAVING makes the subquery empty, so NOT IN is true.
query I
SELECT o.k
FROM outer_rows o
WHERE 1 NOT IN (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k
  HAVING count(*) = 0 OR sum(i.v) > 0
);
----
1

# LIMIT 0 removes the aggregate row, so EXISTS is false.
query I
SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k LIMIT 0
);
----

# Both text keys cast to 1, but EXISTS must return the outer row only once.
query I
SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM text_keys i WHERE CAST(i.k AS INT) = o.k
);
----
1

I didn't have the time to try and dive into the individual causes here, but might be worth it to try and split this PR into smaller ones that are more specific (and potentially stacked) as each one seems to be pretty hard to review

@mohammadnaqvi04

Copy link
Copy Markdown
Contributor Author

@AdamGS Thanks for the second pass. I worked through the faulty queries and am re-scoping what this PR is and isn't claiming to fix.

# HAVING evaluates to NULL for the matching group and must discard its row.
query I
SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k
  HAVING count(*) = 0 OR sum(i.v) > 0
);
----

# The same NULL-valued HAVING makes the subquery empty, so NOT IN is true.
query I
SELECT o.k
FROM outer_rows o
WHERE 1 NOT IN (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k
  HAVING count(*) = 0 OR sum(i.v) > 0
);
----
1

These two cover the same three-valued bug where a HAVING predicate can itself be NULL. Both are now fixed.

The LIMIT 0 case and the CAST-based duplicate-match case are gaps in what count-bug compensation is capable of tracking. LIMIT-truncated rows aren't tracked the way HAVING-failed rows are, and the compensation join can fan out multiple rows per outer row under a non-injective (one-to-many from outer row to inner) correlation key. I gave this some thought, and think both are big enough that they don't belong in this PR.

I've decided to narrow this PR's scope to EXISTS/NOT EXISTS/IN/NOT IN over groupless aggregates with HAVING, including NULL-valued and compound HAVING predicates. I'll open LIMIT-truncation and join fan-out as separate follow-ups.

Also, in the process of more adversarial review targeting the HAVING mechanics here, I discovered three more. I've included fixes and test cases for all three:

  1. A second filter stacked on an already-compensated aggregate fell back to silently dropping the HAVING clause.
  2. The unmatched-row default for that stacked-filter case skipped the combined predicate on the IN/NOT IN side.
  3. The unmatched-row default for that stacked-filter case skipped the combined predicate on the EXISTS side.

I've also just now run and compared every new query I added in subquery.slt from my branch against latest DuckDB and DataFusion main builds.

@AdamGS

AdamGS commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

Seems like you ran into some conflicts.

But as you mentioned, seems like the last two queries from above still show a regression, I'm not sure how I feel about knowingly introducing correctness regressions. I'll try and do a deeper pass over the PR sometime this week as I think about that, maybe someone else will also weigh in.

@mohammadnaqvi04

Copy link
Copy Markdown
Contributor Author

I took a look at potentially splitting this PR into two more contained ones between EXISTS/NOT EXISTS, and then a stacked IN/NOT IN on top, to reduce some of the surface area here.

The reason I'm holding off on doing so, for now at least, is because the non-injective correlation bug, from your last failing example query, appears in both of the aforementioned shape categories. I'm going to stress test a bit more, and I can refactor for better composability afterward.

On a secondary note, to make this a bit more robust, I'm working on extending our fuzz test setup to generate random query shapes for groupless aggregates. I'll cross-verify against other engines to see where this breaks, and hopefully iterate from there.

@mohammadnaqvi04

Copy link
Copy Markdown
Contributor Author

@AdamGS Circling back on the LIMIT 0 and fan-out cases from your last comment, both are fixed now. I changed how the subquery's aggregate is grouped so that two raw values that equal eachother post-cast don't fan-out anymore.

> SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM inner_rows i WHERE i.k = o.k LIMIT 0
);
+---+
| k |
+---+
+---+
0 row(s) fetched.
Elapsed 0.005 seconds.

> SELECT o.k
FROM outer_rows o
WHERE EXISTS (
  SELECT count(*) FROM text_keys i WHERE CAST(i.k AS INT) = o.k
);
+---+
| k |
+---+
| 1 |
+---+
1 row(s) fetched.
Elapsed 0.006 seconds.

I'm going to split this into two smaller PRs for reviewability: one for EXISTS/NOT EXISTS, then IN/NOT IN afterward once that one's merged. I'll close this PR once the first one is up.

@mohammadnaqvi04

Copy link
Copy Markdown
Contributor Author

Closing in favor of #25391.

joroKr21 pushed a commit to coralogix/arrow-datafusion that referenced this pull request Oct 21, 2026
…oupless 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._
lukekim pushed a commit to spiceai/datafusion that referenced this pull request Nov 22, 2026
…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>
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.

Wrong results: correlated EXISTS/IN subqueries over a groupless aggregate get the wrong outer rows

3 participants