From 39a49abc44b969578a9fbff40bd35dbb4bf2c2d1 Mon Sep 17 00:00:00 2001 From: faizaan Date: Sun, 29 Nov 2026 19:58:58 +0530 Subject: [PATCH] fix: handle count bug through Unnest in correlated predicate subqueries --- datafusion/optimizer/src/decorrelate.rs | 237 +++++++++++++++++- .../src/decorrelate_predicate_subquery.rs | 60 ++++- .../sqllogictest/test_files/subquery.slt | 96 +++++++ 3 files changed, 380 insertions(+), 13 deletions(-) diff --git a/datafusion/optimizer/src/decorrelate.rs b/datafusion/optimizer/src/decorrelate.rs index efbfa00776743..113f09794f323 100644 --- a/datafusion/optimizer/src/decorrelate.rs +++ b/datafusion/optimizer/src/decorrelate.rs @@ -11,6 +11,8 @@ use crate::push_down_filter::lr_is_preserved; use crate::simplify_expressions::ExprSimplifier; use crate::utils::{aggregate_emits_on_empty_input, replace_qualified_name}; +use arrow::array::Array; +use arrow::datatypes::DataType; use datafusion_common::nested_struct::is_injective_cast; use datafusion_common::tree_node::{ Transformed, TransformedResult, TreeNode, TreeNodeRecursion, TreeNodeRewriter, @@ -23,7 +25,7 @@ use datafusion_common::{ use datafusion_expr::expr::{Alias, GroupingSet}; use datafusion_expr::expr_rewriter::strip_outer_reference; use datafusion_expr::logical_plan::builder::unique_field_aliases; -use datafusion_expr::logical_plan::{Join, JoinType}; +use datafusion_expr::logical_plan::{Join, JoinType, Unnest}; use datafusion_expr::simplify::SimplifyContext; use datafusion_expr::utils::{collect_subquery_cols, conjunction, split_conjunction}; use datafusion_expr::{ @@ -87,6 +89,10 @@ pub struct PullUpCorrelatedExpr { /// 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, + /// Whether an `Unnest` above a regrouped scalar aggregate may emit more + /// than one row per input group, which would duplicate outer rows in a + /// `LEFT JOIN` used for count-bug compensation. + pub(crate) unnest_may_multiply_rows: bool, /// Every correlated conjunct that a `Filter` of the subquery applies, /// before `remove_duplicated_filter` drops the ones that the `IN` /// predicate already covers. The outer references are kept, so that a @@ -155,6 +161,7 @@ impl PullUpCorrelatedExpr { having_like_join_filters: Vec::new(), pulled_up_scalar_agg: false, regrouped_scalar_agg: false, + unnest_may_multiply_rows: false, correlated_filters: Vec::new(), column_refs_above: Vec::new(), depends_only_on_input_having_rows_above: Vec::new(), @@ -842,7 +849,7 @@ impl PullUpCorrelatedExpr { } // `f_down` checked that the pulled up filters do not read an // unnested column. - LogicalPlan::Unnest(_) => self.pass_through_pulled_up_cols(plan), + LogicalPlan::Unnest(_) => self.pull_up_unnest(plan), 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 @@ -887,6 +894,61 @@ impl PullUpCorrelatedExpr { Ok(Transformed::yes(plan.recompute_schema()?)) } + fn pull_up_unnest(&mut self, plan: LogicalPlan) -> Result> { + if !self.regrouped_scalar_agg { + return self.pass_through_pulled_up_cols(plan); + } + if !self.need_handle_count_bug { + // `EXISTS` retries without count-bug handling when compensation + // fails; do not let that retry drop unmatched outer rows. `IN` + // runs a second pass with count-bug handling on to validate. + if self.exists_sub_query { + self.can_pull_up = false; + } + return self.pass_through_pulled_up_cols(plan); + } + let LogicalPlan::Unnest(unnest) = &plan else { + return self.pass_through_pulled_up_cols(plan); + }; + let Some(input_map) = self.collected_count_expr_map.get(&*unnest.input).cloned() + else { + return self.pass_through_pulled_up_cols(plan); + }; + // Scalar subqueries and LATERAL joins depend on exact row multiplicity, + // so only predicate subqueries propagate uniform unnest outputs. + if !self.exists_sub_query && self.in_predicate_opt.is_none() { + return self.pass_through_pulled_up_cols(plan); + } + + let outcome = evaluate_unnest_on_empty_batch(unnest, &input_map)?; + let new_plan = plan.recompute_schema()?; + match outcome { + UnnestEmptyBatchResult::Empty => Ok(Transformed::yes(new_plan)), + UnnestEmptyBatchResult::UniformRows { + expr_map, + never_drops_matched_rows, + single_row_per_input, + } => { + // `build_join_with_count_bug` uses `UN_MATCHED_ROW_INDICATOR IS NULL` + // on a `LEFT JOIN`, which cannot distinguish an unmatched outer row + // from a matched group that `Unnest` turned into 0 rows. + if self.exists_sub_query && !never_drops_matched_rows { + self.can_pull_up = false; + } + if !single_row_per_input { + self.unnest_may_multiply_rows = true; + } + self.collected_count_expr_map + .insert(new_plan.clone(), expr_map); + Ok(Transformed::yes(new_plan)) + } + UnnestEmptyBatchResult::Unknown => { + self.can_pull_up = false; + Ok(Transformed::yes(new_plan)) + } + } + } + /// Whether the pull up can add its columns to a grouping set `Aggregate`, /// and whether it needs to. /// @@ -1526,6 +1588,177 @@ fn filter_exprs_evaluation_result_on_empty_batch( Ok(pull_up_expr) } +enum UnnestEmptyBatchResult { + /// On empty input to the aggregate, `Unnest` produces 0 rows. + Empty, + /// On empty input to the aggregate, `Unnest` produces one or more identical + /// rows whose output column values are stored in `expr_map`. + UniformRows { + expr_map: ExprResultMap, + never_drops_matched_rows: bool, + single_row_per_input: bool, + }, + /// Cannot statically determine uniform empty-input output. + Unknown, +} + +fn strip_aliases(mut expr: &Expr) -> &Expr { + while let Expr::Alias(alias) = expr { + expr = &alias.expr; + } + expr +} + +fn evaluate_unnest_on_empty_batch( + unnest: &Unnest, + input_map: &ExprResultMap, +) -> Result { + if !unnest.struct_type_columns.is_empty() || unnest.list_type_columns.len() != 1 { + return Ok(UnnestEmptyBatchResult::Unknown); + } + let (input_idx, col_unnest) = &unnest.list_type_columns[0]; + if col_unnest.depth != 1 { + return Ok(UnnestEmptyBatchResult::Unknown); + } + + let input_col_name = unnest.input.schema().field(*input_idx).name(); + let Some(Expr::Literal(scalar, _)) = input_map.get(input_col_name).map(strip_aliases) + else { + return Ok(UnnestEmptyBatchResult::Unknown); + }; + + let output_field = unnest + .schema + .field_with_unqualified_name(&col_unnest.output_column.name)?; + let typed_null = + || ScalarValue::try_from(output_field.data_type()).unwrap_or(ScalarValue::Null); + + let outcome = match scalar { + ScalarValue::Null => { + if unnest.options.preserve_nulls() { + ListElementOutcome::Uniform(typed_null()) + } else { + ListElementOutcome::Empty + } + } + ScalarValue::List(arr) => { + list_element_outcome(arr.is_null(0), || arr.value(0), unnest, &typed_null)? + } + ScalarValue::LargeList(arr) => { + list_element_outcome(arr.is_null(0), || arr.value(0), unnest, &typed_null)? + } + ScalarValue::FixedSizeList(arr) => { + list_element_outcome(arr.is_null(0), || arr.value(0), unnest, &typed_null)? + } + _ => return Ok(UnnestEmptyBatchResult::Unknown), + }; + + let elem = match outcome { + ListElementOutcome::Empty => return Ok(UnnestEmptyBatchResult::Empty), + ListElementOutcome::Uniform(elem) => elem, + ListElementOutcome::Mixed => return Ok(UnnestEmptyBatchResult::Unknown), + }; + + let mut expr_map = HashMap::new(); + for field in unnest.schema.fields() { + let name = field.name(); + if name == &col_unnest.output_column.name { + expr_map.insert(name.clone(), Expr::Literal(elem.clone(), None)); + } else if let Some(val) = input_map.get(name) { + expr_map.insert(name.clone(), val.clone()); + } + } + + let (never_drops_matched_rows, single_row_per_input) = + unnest_row_cardinality_bounds(unnest, *input_idx); + + Ok(UnnestEmptyBatchResult::UniformRows { + expr_map, + never_drops_matched_rows, + single_row_per_input, + }) +} + +enum ListElementOutcome { + Empty, + Uniform(ScalarValue), + Mixed, +} + +fn list_element_outcome( + is_null: bool, + values: impl FnOnce() -> arrow::array::ArrayRef, + unnest: &Unnest, + typed_null: &impl Fn() -> ScalarValue, +) -> Result { + if is_null { + return Ok(if unnest.options.preserve_nulls() { + ListElementOutcome::Uniform(typed_null()) + } else { + ListElementOutcome::Empty + }); + } + let values = values(); + if values.is_empty() { + return Ok(if unnest.options.expand_empty_as_null() { + ListElementOutcome::Uniform(typed_null()) + } else { + ListElementOutcome::Empty + }); + } + let first = ScalarValue::try_from_array(&values, 0)?; + for i in 1..values.len() { + if ScalarValue::try_from_array(&values, i)? != first { + return Ok(ListElementOutcome::Mixed); + } + } + Ok(ListElementOutcome::Uniform(first)) +} + +/// Returns `(never_drops_matched_rows, single_row_per_input)` for a single +/// depth-1 list column unnest. +fn unnest_row_cardinality_bounds(unnest: &Unnest, input_idx: usize) -> (bool, bool) { + let options_never_drop = + unnest.options.preserve_nulls() && unnest.options.expand_empty_as_null(); + let input_field = unnest.input.schema().field(input_idx); + if let DataType::FixedSizeList(_, size) = input_field.data_type() { + let never_drops = options_never_drop + || (*size > 0 + && (!input_field.is_nullable() || unnest.options.preserve_nulls())); + let single_row = *size <= 1; + return (never_drops, single_row); + } + + if let LogicalPlan::Projection(proj) = unnest.input.as_ref() + && let Some(expr) = proj.expr.get(input_idx) + { + match strip_aliases(expr) { + Expr::ScalarFunction(func) if func.func.name() == "make_array" => { + let len = func.args.len(); + return (options_never_drop || len >= 1, len <= 1); + } + Expr::Literal(scalar, _) => { + let len = match scalar { + ScalarValue::List(arr) if !arr.is_null(0) => Some(arr.value(0).len()), + ScalarValue::LargeList(arr) if !arr.is_null(0) => { + Some(arr.value(0).len()) + } + ScalarValue::FixedSizeList(arr) if !arr.is_null(0) => { + Some(arr.value(0).len()) + } + _ => None, + }; + if let Some(len) = len { + return (options_never_drop || len >= 1, len <= 1); + } + } + _ => {} + } + } + + (options_never_drop, false) +} + #[cfg(test)] mod tests { use super::*; diff --git a/datafusion/optimizer/src/decorrelate_predicate_subquery.rs b/datafusion/optimizer/src/decorrelate_predicate_subquery.rs index f920ba1233667..b575e81b84122 100644 --- a/datafusion/optimizer/src/decorrelate_predicate_subquery.rs +++ b/datafusion/optimizer/src/decorrelate_predicate_subquery.rs @@ -909,8 +909,12 @@ fn build_join( let keys_are_bare = count_bug_compensation.is_none() || subquery_operands_are_bare_columns(&pull_up.join_filters, &subquery_cols); // Fall back to the uncompensated rewrite whenever compensation can't safely apply, so a HAVING never gets silently dropped. + let unnest_multiplies_with_filter = pull_up.unnest_may_multiply_rows + && (pull_up.pull_up_having_expr.is_some() + || !pull_up.having_like_join_filters.is_empty()); let compensable = pull_up.can_pull_up && !reads_agg_output + && !unnest_multiplies_with_filter && keys_are_bare && (count_bug_compensation.is_some() || pull_up.pull_up_having_expr.is_none()); if exists_sub_query && !compensable { @@ -930,7 +934,7 @@ fn build_join( _ => false, }; let count_bug_is_harmless = match rewrite(true) { - Ok((plan, pull_up)) => pull_up + Ok((plan, pull_up)) if pull_up.can_pull_up => pull_up .collected_count_expr_map .get(&plan) .filter(|m| !m.is_empty()) @@ -938,12 +942,15 @@ fn build_join( null_reads_as_false && empty_input_values .get(subquery.schema().field(0).name()) - .is_some_and(|value| { + .is_some_and(|mut value| { + while let Expr::Alias(alias) = value { + value = &alias.expr; + } matches!(value, Expr::Literal(v, _) if v.is_null()) }) }), - // Count-bug handling errors on some shapes it cannot compensate. - Err(_) => false, + // Count-bug handling errors or cannot pull up on some shapes. + Ok(_) | Err(_) => false, }; if !count_bug_is_harmless { return Ok(None); @@ -971,6 +978,7 @@ fn build_join( alias, &expr_map, pull_up.pull_up_having_expr, + pull_up.unnest_may_multiply_rows, ) .map(|plan| { Some(BuiltJoin { @@ -1289,6 +1297,7 @@ fn build_join( /// Builds the join for a correlated `EXISTS` subquery whose groupless /// aggregate requires count-bug compensation. +#[expect(clippy::too_many_arguments)] fn build_join_with_count_bug( left: &LogicalPlan, sub_query_alias: LogicalPlan, @@ -1297,7 +1306,43 @@ fn build_join_with_count_bug( alias: &str, expr_map: &crate::decorrelate::ExprResultMap, pull_up_having_expr: Option, + unnest_may_multiply_rows: bool, ) -> Result { + let left_projection: Vec = left + .schema() + .columns() + .into_iter() + .map(Expr::from) + .collect(); + + // When `Unnest` may emit multiple rows per matched group and there is no + // HAVING or outer filter above the aggregate, every outer row is guaranteed + // to produce at least one row. Skip the LEFT JOIN so matched outer rows are + // not duplicated. + if unnest_may_multiply_rows && pull_up_having_expr.is_none() { + let new_plan = match join_type { + JoinType::LeftMark | JoinType::RightMark => { + let mut proj_exprs = left_projection; + proj_exprs.push(lit(true).alias_qualified(Some(alias), "mark")); + LogicalPlanBuilder::from(left.clone()) + .project(proj_exprs)? + .build()? + } + JoinType::LeftAnti => LogicalPlanBuilder::from(left.clone()) + .filter(lit(false))? + .project(left_projection)? + .build()?, + JoinType::LeftSemi => LogicalPlanBuilder::from(left.clone()) + .filter(lit(true))? + .project(left_projection)? + .build()?, + _ => { + return internal_err!("unsupported join type {join_type:?}"); + } + }; + return Ok(new_plan); + } + let pull_up_having_expr = pull_up_having_expr .map(|f| { f.transform_up(|e| match e { @@ -1315,13 +1360,6 @@ fn build_join_with_count_bug( .join_on(sub_query_alias, JoinType::Left, join_filter_opt)? .build()?; - let left_projection: Vec = left - .schema() - .columns() - .into_iter() - .map(Expr::from) - .collect(); - let mut expr_rewrite = TypeCoercionRewriter::new(joined.schema()); // EXISTS is true by default (the groupless aggregate always diff --git a/datafusion/sqllogictest/test_files/subquery.slt b/datafusion/sqllogictest/test_files/subquery.slt index 336acb886d525..ca71b48934bbd 100644 --- a/datafusion/sqllogictest/test_files/subquery.slt +++ b/datafusion/sqllogictest/test_files/subquery.slt @@ -5300,6 +5300,102 @@ SELECT ( SELECT count(*) FROM (SELECT a AS x FROM t27691_i) e, t27691_u u WHERE e.x < o.a ) FROM t27691 o; +# EXISTS over unnest of a correlated count(*) without GROUP BY must keep outer +# rows with no match (count(*) = 0 still produces unnested rows). +# See https://github.com/apache/datafusion/issues/27829 +query I +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; +---- +1 +2 +4 + +query I +SELECT o.a FROM t27691 o WHERE NOT EXISTS ( + SELECT unnest(make_array(c, c)) + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; +---- + +query IB +SELECT o.a, EXISTS ( + SELECT unnest(make_array(c, c)) + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) FROM t27691 o ORDER BY o.a; +---- +1 true +2 true +4 true + +# Single-element unnest with a filter that the empty-input row satisfies. +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; +---- +4 + +# Multi-element unnest with a filter above stays correlated rather than +# duplicating outer rows in a LEFT JOIN. Expected: 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 1 FROM ( + SELECT unnest(make_array(c, c)) v + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e + ) y WHERE v = 0 +) ORDER BY o.a; + +# Multi-element unnest with distinct elements stays correlated. 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 + 1)) + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; + +# Unnest that can drop a matched group (empty array when c > 0) stays +# correlated so matched rows are not mistaken for unmatched rows. Expected: 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(CASE WHEN c = 0 THEN make_array(1) ELSE make_array() END) + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; + +# Unnest of an always-empty array produces 0 rows for every outer row. +query I +SELECT o.a FROM t27691 o WHERE EXISTS ( + SELECT unnest(make_array()) + FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; +---- + +# Outer-only filter above the unnest stays correlated. Expected: 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 + WHERE o.a > 1 +) ORDER BY o.a; + +# NOT IN over unnest of max(a) (NULL on empty input) and IN over unnest of +# count(*) (0 on empty input) stay correlated instead of returning wrong rows. +# Expected: no rows. +query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression InSubquery +SELECT o.a FROM t27691 o WHERE o.a NOT IN ( + SELECT unnest(make_array(m)) FROM (SELECT max(a) m FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; + +# Expected: 4. +query error DataFusion error: This feature is not implemented: Physical plan does not support logical expression InSubquery +SELECT o.a FROM t27691 o WHERE o.a - 4 IN ( + SELECT unnest(make_array(c)) FROM (SELECT count(*) c FROM t27691_i WHERE a = o.a) e +) ORDER BY o.a; + statement ok DROP TABLE t27691;