comphead commented on code in PR #21075: URL: https://github.com/apache/datafusion/pull/21075#discussion_r3131901542
########## datafusion/optimizer/src/unions_to_filter.rs: ########## @@ -0,0 +1,652 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Rewrites `UNION DISTINCT` branches that differ only by filter predicates +//! into a single filtered branch plus `DISTINCT`. + +use crate::{OptimizerConfig, OptimizerRule}; +use datafusion_common::Result; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRewriter}; +use datafusion_expr::expr_rewriter::coerce_plan_expr_for_schema; +use datafusion_expr::logical_plan::builder::LogicalPlanBuilder; +use datafusion_expr::utils::disjunction; +use datafusion_expr::{ + Distinct, Expr, Filter, LogicalPlan, Projection, SubqueryAlias, Union, +}; +use log::debug; +use std::collections::HashMap; +use std::sync::Arc; + +#[derive(Default, Debug)] +pub struct UnionsToFilter; + +impl UnionsToFilter { + #[expect(missing_docs)] + pub fn new() -> Self { + Self + } +} + +impl OptimizerRule for UnionsToFilter { + fn name(&self) -> &str { + "unions_to_filter" + } + + fn supports_rewrite(&self) -> bool { + true + } + + fn rewrite( + &self, + plan: LogicalPlan, + config: &dyn OptimizerConfig, + ) -> Result<Transformed<LogicalPlan>> { + if !config.options().optimizer.enable_unions_to_filter { + return Ok(Transformed::no(plan)); + } + + // Fast pre-check: if the plan tree has no Distinct::All node at all we can + // skip the expensive bottom-up rewrite_with_subqueries traversal entirely. + // This matters for large UNION ALL plans (e.g. TPC-DS Q4) where the rule + // can never fire and the traversal overhead is otherwise measurable. + if !plan.exists(|p| Ok(matches!(p, LogicalPlan::Distinct(Distinct::All(_)))))? { + return Ok(Transformed::no(plan)); + } + + plan.rewrite_with_subqueries(&mut UnionsToFilterRewriter) + } +} + +struct UnionsToFilterRewriter; + +impl TreeNodeRewriter for UnionsToFilterRewriter { + type Node = LogicalPlan; + + fn f_up(&mut self, plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> { + match plan { + LogicalPlan::Distinct(Distinct::All(input)) => { + let inner = Arc::unwrap_or_clone(input); + match try_rewrite_distinct_union(inner.clone())? { + Some(rewritten) => Ok(Transformed::yes(rewritten)), + None => Ok(Transformed::no(LogicalPlan::Distinct(Distinct::All( + Arc::new(inner), + )))), + } + } + _ => Ok(Transformed::no(plan)), + } + } +} + +fn try_rewrite_distinct_union(plan: LogicalPlan) -> Result<Option<LogicalPlan>> { + let LogicalPlan::Union(Union { inputs, schema }) = plan else { + debug!("unions_to_filter skipped: input is not a UNION"); + return Ok(None); + }; + + if inputs.len() < 2 { + debug!( + "unions_to_filter skipped: UNION has {} input(s), need at least 2", + inputs.len() + ); + return Ok(None); + } + + let mut grouped: HashMap<GroupKey, Vec<Expr>> = HashMap::new(); + let mut input_order: Vec<GroupKey> = Vec::new(); + let mut transformed = false; + + for input in inputs { + let Some(branch) = extract_branch(Arc::unwrap_or_clone(input))? else { + return Ok(None); + }; + + let key = GroupKey { + source: branch.source, + wrappers: branch.wrappers, + }; + if let Some(conds) = grouped.get_mut(&key) { + conds.push(branch.predicate); + transformed = true; + } else { + input_order.push(key.clone()); + grouped.insert(key, vec![branch.predicate]); + } + } + + if !transformed { + debug!("unions_to_filter skipped: no branch groups could be merged"); + return Ok(None); + } + + let mut builder: Option<LogicalPlanBuilder> = None; + for key in input_order { + let predicates = grouped + .remove(&key) + .expect("grouped predicates should exist for every source"); + let combined = + disjunction(predicates).expect("union branches always provide predicates"); + let branch = LogicalPlanBuilder::from(key.source) + .filter(combined)? + .build()?; + let branch = wrap_branch(branch, &key.wrappers)?; + let branch = coerce_plan_expr_for_schema(branch, &schema)?; + let branch = align_plan_to_schema(branch, Arc::clone(&schema))?; + builder = Some(match builder { + None => LogicalPlanBuilder::from(branch), + Some(builder) => builder.union(branch)?, + }); + } + + let union = builder + .expect("at least one branch after rewrite") + .build()?; + Ok(Some(LogicalPlan::Distinct(Distinct::All(Arc::new(union))))) +} + +struct UnionBranch { + source: LogicalPlan, + predicate: Expr, + wrappers: Vec<Wrapper>, +} + +fn extract_branch(plan: LogicalPlan) -> Result<Option<UnionBranch>> { + let (wrappers, plan) = peel_wrappers(plan); + + // Volatile or subquery expressions in the projection must not be merged: + // they are evaluated once per branch in the original plan but would be + // evaluated once per combined row after the rewrite, which can change the + // output row set. + if !wrapper_projections_are_safe(&wrappers) { + debug!( + "unions_to_filter skipped: projection wrapper contains volatile expression or subquery" + ); + return Ok(None); + } + + match plan { + LogicalPlan::Filter(Filter { + predicate, input, .. + }) => { + if !is_mergeable_predicate(&predicate) { + debug!( + "unions_to_filter skipped: branch predicate contains volatility or a subquery" + ); + return Ok(None); + } + Ok(Some(UnionBranch { + source: strip_passthrough_nodes(Arc::unwrap_or_clone(input)), + predicate, + wrappers, + })) + } + // A Limit or Sort node changes the row-set semantics of the branch. + // Merging two such branches into one would silently drop the per-branch + // row restriction (LIMIT) or rely on an order guarantee that UNION does + // not preserve (ORDER BY). Bail out to leave the UNION unchanged. + LogicalPlan::Limit(_) => { + debug!("unions_to_filter skipped: branch contains LIMIT"); + Ok(None) + } + LogicalPlan::Sort(_) => { + debug!("unions_to_filter skipped: branch contains ORDER BY / SORT"); + Ok(None) + } + other => Ok(Some(UnionBranch { + source: strip_passthrough_nodes(other.clone()), Review Comment: this might be expensive and redundant clone -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
