Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions datafusion/optimizer/src/decorrelate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,12 +573,6 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
self.can_pull_up = false;
return Ok(Transformed::new(plan, false, TreeNodeRecursion::Stop));
}
// If the aggregation is from a distinct it will not change the result for
// exists/in subqueries so we can still pull up all predicates.
let is_distinct = aggregate.aggr_expr.is_empty();
if !is_distinct {
self.can_pull_up = self.can_pull_up && self.can_pull_over_aggregation;
}
let mut local_correlated_cols = BTreeSet::new();
collect_local_correlated_cols(
&plan,
Expand Down Expand Up @@ -644,6 +638,31 @@ impl TreeNodeRewriter for PullUpCorrelatedExpr {
aggregate.input.schema(),
)?
};
// A DISTINCT may skip this check under EXISTS/IN, or when the pull
// up adds no group key that splits a group. An added key only adds
// duplicate rows, which EXISTS/IN ignore; elsewhere, e.g. LATERAL,
// they reach the result (#25808). A key that a correlated equality
// pins to one value per outer row splits no group.
let is_distinct = aggregate.aggr_expr.is_empty();
let is_exists_or_in =
self.exists_sub_query || self.in_predicate_opt.is_some();
let pinned_cols: Vec<&Expr> = self
.join_filters
.iter()
.filter(|f| is_partitionable_equality(f, aggregate.input.schema()))
.filter_map(|f| split_column_equality(f).map(|(col, _)| col))
.map(|col| match col {
Expr::Cast(Cast { expr, .. }) => expr.as_ref(),
_ => col,
})
.collect();
let adds_group_keys = missing_exprs.iter().any(|expr| {
!aggregate.group_expr.contains(expr) && !pinned_cols.contains(&expr)
});
let can_skip_check = is_distinct && (is_exists_or_in || !adds_group_keys);
if !can_skip_check {
self.can_pull_up = self.can_pull_up && self.can_pull_over_aggregation;
}

// if the original group expressions are empty, need to handle the Count bug
let mut expr_result_map_for_count_bug = HashMap::new();
Expand Down
67 changes: 67 additions & 0 deletions datafusion/sqllogictest/test_files/lateral_join.slt
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,73 @@ ORDER BY t1.id, sub.id;
1 20 2 1
2 30 1 1

# --- Non-equality correlated filter below a DISTINCT ---
# https://github.com/apache/datafusion/issues/25808
# The pull up adds `t2.id` to the DISTINCT keys, so the t2 rows 10 and 20,
# which both have t1_id = 1, are no longer merged.
# Expected result once supported: sub.t1_id = 1 and 2 once each, for every
# t1 row (6 rows).
statement error OuterReferenceColumn

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.

Optional: two more shapes returned duplicates on main and now error, GROUP BY without aggregates and LEFT JOIN LATERAL. A statement error for each would pin them:

statement error OuterReferenceColumn
SELECT t1.id, sub.t1_id
FROM t1, LATERAL (SELECT t2.t1_id FROM t2 WHERE t2.id > t1.id GROUP BY t2.t1_id) AS sub;

statement error OuterReferenceColumn
SELECT t1.id, sub.t1_id
FROM t1 LEFT JOIN LATERAL (SELECT DISTINCT t2.t1_id FROM t2 WHERE t2.id > t1.id) AS sub ON true;

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 5eed032.

SELECT t1.id, sub.t1_id
FROM t1, LATERAL (SELECT DISTINCT t2.t1_id FROM t2 WHERE t2.id > t1.id) AS sub
ORDER BY t1.id, sub.t1_id;

# The same with a GROUP BY that has no aggregates, which is planned as a
# DISTINCT.
statement error OuterReferenceColumn
SELECT t1.id, sub.t1_id
FROM t1, LATERAL (SELECT t2.t1_id FROM t2 WHERE t2.id > t1.id GROUP BY t2.t1_id) AS sub;

# The same with LEFT JOIN LATERAL.
statement error OuterReferenceColumn
SELECT t1.id, sub.t1_id
FROM t1 LEFT JOIN LATERAL (SELECT DISTINCT t2.t1_id FROM t2 WHERE t2.id > t1.id) AS sub ON true;

# With an equality filter, every row of a group has the same `t2.t1_id`,
# so adding it to the DISTINCT keys splits nothing.
query II
SELECT t1.id, sub.t1_id
FROM t1, LATERAL (SELECT DISTINCT t2.t1_id FROM t2 WHERE t2.t1_id = t1.id) AS sub
ORDER BY t1.id, sub.t1_id;
----
1 1
2 2

# A non-equality filter on a column that is already a DISTINCT key adds no
# key, so the pull up acts as a HAVING and stays decorrelated.
query II
SELECT t1.id, sub.id
FROM t1, LATERAL (SELECT DISTINCT t2.id FROM t2 WHERE t2.id > t1.id * 10) AS sub
ORDER BY t1.id, sub.id;
----
1 20
1 30
2 30

# The added key `t2.t1_id` is pinned by the equality, so it splits no group.
query II
SELECT t1.id, sub.id
FROM t1, LATERAL (SELECT DISTINCT t2.id FROM t2 WHERE t2.t1_id = t1.id AND t2.id > t1.id * 10 + 5) AS sub
ORDER BY t1.id, sub.id;
----
1 20
2 30

# The same through an injective cast.
query II
SELECT t1.id, sub.id
FROM t1, LATERAL (SELECT DISTINCT t2.id FROM t2 WHERE CAST(t2.t1_id AS BIGINT) = t1.id AND t2.id > t1.id * 10 + 5) AS sub
ORDER BY t1.id, sub.id;
----
1 20
2 30

# A lossy cast does not pin `d`: 1.2 and 1.4 both cast to 1, so v = 7 would
# appear twice. Expected result once supported: (1, 7) once.
statement error OuterReferenceColumn
SELECT t1.id, sub.v
FROM t1, LATERAL (SELECT DISTINCT td.v FROM (VALUES (1.2, 7), (1.4, 7)) AS td(d, v) WHERE CAST(td.d AS INT) = t1.id AND td.v > t1.id) AS sub;

# --- Implicit LATERAL (comma without LATERAL keyword) ---
# DuckDB auto-detects lateral correlation; DataFusion requires
# the explicit LATERAL keyword.
Expand Down
25 changes: 25 additions & 0 deletions datafusion/sqllogictest/test_files/subquery.slt
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,31 @@ SELECT t1_id FROM t1 WHERE EXISTS (SELECT DISTINCT s.t2_id FROM (SELECT t2_id FR
22
44

#exists_subquery_with_non_equality_filter_below_distinct
#de-correlated, the pulled up `t2_id` becomes an extra DISTINCT key, which only
#adds duplicate rows, and EXISTS ignores duplicates. See #25808.
query I rowsort
SELECT t1_id FROM t1 WHERE EXISTS (SELECT DISTINCT t2_int FROM t2 WHERE t2_id < t1_id)
----
22
33
44

#in_subquery_with_non_equality_filter_below_distinct
#de-correlated, IN ignores duplicates as well. For t1_id = 33, both
#(44, 3) and (55, 3) match, yet 33 is returned once.
query I rowsort
SELECT t1_id FROM t1 WHERE t1_int IN (SELECT DISTINCT t2_int FROM t2 WHERE t2_id > t1_id)
----
11
33

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.

Optional: no test covers the is_distinct part of the gate. Without it, this query returns 11 instead of 11, 22. A statement error would pin it:

Suggested change
33
33
#in_subquery_with_non_equality_filter_below_group_by
#not de-correlated: the pulled up `t2_id` would become an extra group key and
#change the counts. Expected result once supported: 11, 22.
statement error InSubquery
SELECT t1_id FROM t1 WHERE t1_int IN (SELECT count(*) FROM t2 WHERE t2_id > t1_id GROUP BY t2_int)


#in_subquery_with_non_equality_filter_below_group_by
#not de-correlated: an extra group key would change the counts.
#Expected result once supported: 11, 22.
statement error InSubquery
SELECT t1_id FROM t1 WHERE t1_int IN (SELECT count(*) FROM t2 WHERE t2_id > t1_id GROUP BY t2_int)

#exists_subquery_with_limit_below_group_by
#de-correlated, a grouping has rows exactly when its input has rows
query I rowsort
Expand Down
Loading