From 3eb7cf77f1cd10fc60800c63f41a5369cfe02e1f Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Wed, 23 Sep 2026 20:22:44 -0500 Subject: [PATCH 1/2] perf: collapse partitioned hash join InList dynamic filters into one IN list In partitioned mode the hash join pushes a routed filter: CASE hash_repartition % N WHEN i THEN bounds_i AND key IN (list_i) ... END When every non-empty build partition pushes an InList and no partition is canceled, the routing is redundant. Routing is a deterministic function of the join keys, so a build row with key K is in the partition that a probe row with key K routes to. A test of K against the union of all lists therefore accepts the same rows as the routed CASE. The per-partition bounds reject no additional rows either, because every key in a list is inside the bounds of its partition. The filter is now `key IN (union)`. This removes the per-row routing hash from the probe side, and the pruning code can use an InList (up to `max_in_list_size`), which it cannot do with a CASE. The union is capped at 1 MiB. Each partition's list is limited independently by `hash_join_inlist_pushdown_max_size`, so the union grows with the partition count; past the cap the routed CASE, where a probe row checks only one list, stays in use. Partitions that push a hash table, and builds with a canceled partition, also keep the CASE. Co-Authored-By: Claude Opus 5.5 --- .../physical_optimizer/filter_pushdown.rs | 11 +- .../physical-plan/src/joins/hash_join/exec.rs | 6 + .../src/joins/hash_join/shared_bounds.rs | 192 +++++++++++++++++- .../test_files/range_partitioning.slt | 8 +- 4 files changed, 209 insertions(+), 8 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs index ddd4bb4d271aa..a4090eeb15b87 100644 --- a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs @@ -1010,7 +1010,7 @@ async fn optimize_and_collect_pushdown_plan( // Not portable to sqllogictest: this test pins `PartitionMode::Partitioned` // by hand-wiring `RepartitionExec(Hash, 12)` on both join sides. A SQL // INNER JOIN over small parquet inputs plans as `CollectLeft`, so the -// per-partition CASE filter this test exercises is not reachable via SQL. +// partitioned filter this test exercises is not reachable via SQL. #[tokio::test] async fn test_hashjoin_dynamic_filter_pushdown_partitioned() { // Rough sketch of the MRE we're trying to recreate: @@ -1165,7 +1165,7 @@ async fn test_hashjoin_dynamic_filter_pushdown_partitioned() { - RepartitionExec: partitioning=Hash([a@0, b@1], 12), input_partitions=1 - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true - RepartitionExec: partitioning=Hash([a@0, b@1], 12), input_partitions=1 - - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ CASE hash_repartition % 12 WHEN 5 THEN a@0 >= ab AND a@0 <= ab AND b@1 >= bb AND b@1 <= bb AND struct(a@0, b@1) IN (SET) ([{c0:ab,c1:bb}]) WHEN 8 THEN a@0 >= aa AND a@0 <= aa AND b@1 >= ba AND b@1 <= ba AND struct(a@0, b@1) IN (SET) ([{c0:aa,c1:ba}]) ELSE false END ] + - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ struct(a@0, b@1) IN (SET) ([{c0:ab,c1:bb}, {c0:aa,c1:ba}]) ] " ); @@ -1369,6 +1369,11 @@ async fn test_hashjoin_dynamic_filter_pushdown_range_partitioned() { config.execution.parquet.pushdown_filters = true; config.optimizer.enable_dynamic_filter_pushdown = true; config.optimizer.preserve_file_partitions = 1; + // Push hash table lookups instead of `InList`s so the filter keeps the + // `range_partition` routing: an all-`InList` build collapses into one `InList`. + config + .optimizer + .hash_join_inlist_pushdown_max_distinct_values = 0; let (plan, batches) = optimize_and_collect_pushdown_plan(plan, config).await; // Now check what our filter looks like @@ -1381,7 +1386,7 @@ async fn test_hashjoin_dynamic_filter_pushdown_range_partitioned() { - RepartitionExec: partitioning=Range([a@0 ASC, b@1 ASC], [(aa, bb)], 2), input_partitions=1 - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true - RepartitionExec: partitioning=Range([a@0 ASC, b@1 ASC], [(aa, bb)], 2), input_partitions=1 - - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ CASE range_partition WHEN 0 THEN a@0 >= aa AND a@0 <= aa AND b@1 >= ba AND b@1 <= ba AND struct(a@0, b@1) IN (SET) ([{c0:aa,c1:ba}]) WHEN 1 THEN a@0 >= ab AND a@0 <= ab AND b@1 >= bb AND b@1 <= bb AND struct(a@0, b@1) IN (SET) ([{c0:ab,c1:bb}]) ELSE false END ] + - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ CASE range_partition WHEN 0 THEN a@0 >= aa AND a@0 <= aa AND b@1 >= ba AND b@1 <= ba AND hash_lookup WHEN 1 THEN a@0 >= ab AND a@0 <= ab AND b@1 >= bb AND b@1 <= bb AND hash_lookup ELSE false END ] " ); diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index d2fcf5191d160..a83b36e959dec 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -8641,6 +8641,12 @@ mod tests { .options_mut() .optimizer .enable_dynamic_filter_pushdown = true; + // Push hash table lookups instead of `InList`s: when every partition pushes + // an `InList`, the routed `CASE` collapses into a single `InList`. + session_config + .options_mut() + .optimizer + .hash_join_inlist_pushdown_max_distinct_values = 0; let task_ctx = Arc::new(TaskContext::default().with_session_config(session_config)); diff --git a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs index 62087c14c5179..eca7bc4f6d2bc 100644 --- a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs +++ b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs @@ -33,6 +33,7 @@ use crate::joins::hash_join::partitioned_hash_eval::{ }; use crate::repartition::RangeExpr; use arrow::array::ArrayRef; +use arrow::compute::concat; use arrow::datatypes::{DataType, Field, Schema}; use datafusion_common::config::ConfigOptions; use datafusion_common::{ @@ -272,6 +273,15 @@ pub(crate) struct SharedBuildAccumulator { null_aware: bool, } +/// Ceiling on the combined size of the per-partition `InList` arrays that +/// [`SharedBuildAccumulator::union_inlist_filter`] will concatenate. +/// +/// Each partition's list is independently capped by +/// `hash_join_inlist_pushdown_max_size`, so without a combined cap the union +/// grows with the partition count. Past this size, keeping the routed `CASE` +/// (where each probe row only probes one list) is the cheaper shape. +const MAX_UNIONED_INLIST_BYTES: usize = 1024 * 1024; + /// Strategy for filter pushdown (decided at collection time) #[derive(Clone)] pub(crate) enum PushdownStrategy { @@ -657,7 +667,19 @@ impl SharedBuildAccumulator { /// Builds one routed probe-side filter from finalized partitioned build data. /// Empty partitions reject their routed rows, while canceled partitions stay /// permissive because their build contents are unknown. + /// + /// When every non-empty partition pushes an `InList`, the routed `CASE` is + /// replaced by one `InList` over the union of the lists. See + /// [`Self::union_inlist_filter`]. fn build_partitioned_filter(&self, partitions: Vec) -> Result<()> { + if let Some((filter_expr, keys_have_null)) = + self.union_inlist_filter(&partitions)? + { + return self + .dynamic_filter + .update(self.preserve_probe_nulls(filter_expr, keys_have_null)?); + } + let mut partition_filters = Vec::with_capacity(partitions.len()); let mut real_partition_ids = Vec::new(); let mut empty_partition_ids = Vec::new(); @@ -798,6 +820,73 @@ impl SharedBuildAccumulator { .update(self.preserve_probe_nulls(filter_expr, keys_have_null)?) } + /// Collapses an all-`InList` partitioned build into one `InList` over the + /// union of the per-partition lists, instead of a `CASE` that routes each + /// probe row to the list of its partition. + /// + /// This is exact, not a relaxation: routing is a deterministic function of + /// the key columns, so every build row with key `K` is in the partition that + /// a probe row with key `K` routes to. A test of `K` against the union thus + /// accepts the same rows as the routed `CASE`. The result does not compute + /// the routing hash for each probe row, and unlike a `CASE`, pruning can use + /// an `InList`. + /// + /// The per-partition bounds are dropped: every key in a partition's list is + /// inside that partition's bounds, so the bounds reject no additional rows. + /// + /// Returns the filter and whether any build key is NULL, or `None` when the + /// collapse does not apply: fewer than two partitions have rows, a partition + /// is canceled or pushes a hash table, the lists have different types, or + /// the union is larger than [`MAX_UNIONED_INLIST_BYTES`]. + fn union_inlist_filter( + &self, + partitions: &[PartitionStatus], + ) -> Result, bool)>> { + let mut arrays: Vec<&ArrayRef> = Vec::with_capacity(partitions.len()); + let mut total_bytes = 0; + let mut keys_have_null = false; + for partition in partitions { + let PartitionStatus::Reported(PartitionData { + pushdown, + keys_have_null: partition_keys_have_null, + .. + }) = partition + else { + return Ok(None); + }; + let values = match pushdown { + PushdownStrategy::InList(values) => values, + PushdownStrategy::Empty => continue, + PushdownStrategy::Map(_) => return Ok(None), + }; + total_bytes += values.get_array_memory_size(); + if total_bytes > MAX_UNIONED_INLIST_BYTES + || arrays + .first() + .is_some_and(|first| first.data_type() != values.data_type()) + { + return Ok(None); + } + keys_have_null |= partition_keys_have_null; + arrays.push(values); + } + + // With zero or one non-empty partition, `build_partitioned_filter` + // already skips the `CASE`. + if arrays.len() < 2 { + return Ok(None); + } + + let union = concat(&arrays.iter().map(|a| a.as_ref()).collect::>())?; + let filter_expr = create_membership_predicate( + &self.on_right, + PushdownStrategy::InList(union), + &HASH_JOIN_SEED, + self.probe_schema.as_ref(), + )?; + Ok(filter_expr.map(|expr| (expr, keys_have_null))) + } + /// Keeps probe rows with a NULL key when the join semantics need them. /// /// The build-side predicate drops probe rows whose key is NULL. A null-aware join @@ -910,6 +999,7 @@ pub(super) fn completed_partitions_for_test(acc: &SharedBuildAccumulator) -> usi mod tests { use super::*; + use crate::joins::join_hash_map::JoinHashMapU32; use arrow::array::{ArrayRef, BooleanArray, Float64Array, Int32Array}; use arrow::compute::SortOptions; use arrow::record_batch::RecordBatch; @@ -985,6 +1075,12 @@ mod tests { PushdownStrategy::InList(Arc::new(Int32Array::from(values.to_vec())) as ArrayRef) } + fn map_pushdown() -> PushdownStrategy { + PushdownStrategy::Map(Arc::new(Map::HashMap(Box::new( + JoinHashMapU32::with_capacity(1), + )))) + } + fn bounds(min: i32, max: i32) -> PartitionBounds { PartitionBounds::new(vec![ColumnBounds::new( ScalarValue::Int32(Some(min)), @@ -1142,6 +1238,77 @@ mod tests { assert!(expr.downcast_ref::().is_none()); } + #[test] + fn partitioned_all_inlist_collapses_to_a_single_union_inlist() { + let acc = make_partitioned_expr_accumulator_for_test(3); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[1, 4]), bounds(1, 4)), + reported(in_list(&[2, 5]), bounds(2, 5)), + reported(PushdownStrategy::Empty, no_bounds()), + ])) + .unwrap(); + + // Routing is a function of the key, so a probe key can only match the + // list of the partition it routes to: the union is exact, and neither the + // `CASE` nor the per-partition bounds are necessary. + let expr = current_expr(&acc); + assert_in_list_column_values(&expr, "probe_key", 0, &[1, 4, 2, 5]); + } + + #[test] + fn partitioned_mixed_strategies_keep_the_routing_case() { + let acc = make_partitioned_expr_accumulator_for_test(2); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[1, 2]), bounds(1, 2)), + reported(map_pushdown(), bounds(3, 4)), + ])) + .unwrap(); + + // One partition needs a hash table lookup, so routing is necessary. + let expr = current_expr(&acc); + assert_eq!(case_expr(&expr).when_then_expr().len(), 2); + } + + #[test] + fn partitioned_canceled_partition_keeps_the_routing_case() { + let acc = make_partitioned_expr_accumulator_for_test(3); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[1]), no_bounds()), + reported(in_list(&[2]), no_bounds()), + PartitionStatus::CanceledUnknown, + ])) + .unwrap(); + + // The canceled partition's keys are unknown, so the union is incomplete + // and the rows routed to that partition must stay permissive. + let expr = current_expr(&acc); + let case = case_expr(&expr); + assert_eq!(case.when_then_expr().len(), 2); + assert_literal_bool( + case.else_expr().expect("expected permissive fallback"), + true, + ); + } + + #[test] + fn partitioned_oversized_inlist_union_keeps_the_routing_case() { + let acc = make_partitioned_expr_accumulator_for_test(2); + let half = MAX_UNIONED_INLIST_BYTES / size_of::() / 2 + 1; + let values = (0..half as i32).collect::>(); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&values), no_bounds()), + reported(in_list(&values), no_bounds()), + ])) + .unwrap(); + + let expr = current_expr(&acc); + assert_eq!(case_expr(&expr).when_then_expr().len(), 2); + } + #[test] fn partitioned_canceled_unknown_partitions_keep_unknown_routes_permissive() { let acc = make_partitioned_expr_accumulator_for_test(2); @@ -1497,8 +1664,9 @@ mod tests { fn partitioned_null_keys_in_one_partition_widen_whole_routed_filter() { let acc = null_equal_partitioned_accumulator(2); + // One partition pushes a hash table, so the filter keeps the routed `CASE`. acc.build_filter(FinalizeInput::Partitioned(vec![ - reported(in_list(&[1]), no_bounds()), + reported(map_pushdown(), no_bounds()), reported_with_null_keys(in_list(&[2]), no_bounds()), ])) .unwrap(); @@ -1518,6 +1686,28 @@ mod tests { ); } + /// The collapsed `InList` must be widened by the NULL flag of every partition, + /// not only of the first one. + #[test] + fn partitioned_null_keys_in_one_partition_widen_union_inlist() { + let acc = null_equal_partitioned_accumulator(2); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[1]), no_bounds()), + reported_with_null_keys(in_list(&[2]), no_bounds()), + ])) + .unwrap(); + + let expr = current_expr(&acc); + assert_top_binary_op(&expr, Operator::Or); + let widened = binary_expr(&expr); + assert!( + widened.left().downcast_ref::().is_some(), + "expected the IS NULL disjunct first, got: {expr}" + ); + assert_in_list_column_values(widened.right(), "probe_key", 0, &[1, 2]); + } + /// A canceled partition's build content is unknown, so it may hold a NULL key: /// the aggregated flag must be permissive even when no partition reported one. #[test] diff --git a/datafusion/sqllogictest/test_files/range_partitioning.slt b/datafusion/sqllogictest/test_files/range_partitioning.slt index ec374b3d62a28..cedeb475da47b 100644 --- a/datafusion/sqllogictest/test_files/range_partitioning.slt +++ b/datafusion/sqllogictest/test_files/range_partitioning.slt @@ -1834,10 +1834,10 @@ SELECT range_key, SUM(value) FROM ( ########## # TEST 48: Hash Join Dynamic Filter Pushdown on Compatible Range Inputs -# The Parquet-backed probe accepts the partition-routed dynamic filter. Matching +# The Parquet-backed probe accepts the partitioned dynamic filter. Matching # Range split points keep build filter i aligned with probe partition i. The -# build has rows only in partitions 0 and 2, so the sparse runtime CASE includes -# only those branches and lets empty partitions fall through to false. +# build has rows only in partitions 0 and 2, and both push an IN list, so the +# routed CASE collapses into one IN list over the union of their keys. ########## statement ok @@ -1878,7 +1878,7 @@ JOIN range_partitioned p ON b.range_key = p.range_key; Plan with Metrics 01)HashJoinExec: mode=Partitionedmetrics=[output_rows=2,] 02)--DataSourceExec: file_type=parquet, predicate=range_key@0 = 5 OR range_key@0 = 20metrics=[output_rows=2,] -03)--DataSourceExec: file_type=parquet, predicate=DynamicFilter [ CASE range_partition WHEN 0 THEN range_key@0 >= 5 AND range_key@0 <= 5 AND range_key@0 IN (SET) ([5]) WHEN 2 THEN range_key@0 >= 20 AND range_key@0 <= 20 AND range_key@0 IN (SET) ([20]) ELSE false END ]metrics=[output_rows=2,] +03)--DataSourceExec: file_type=parquet, predicate=DynamicFilter [ range_key@0 IN (SET) ([5, 20]) ]metrics=[output_rows=2,] query III SELECT b.range_key, b.value, p.value From 635757407bfd722048f5f2034be504bc7c57d7d5 Mon Sep 17 00:00:00 2001 From: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com> Date: Thu, 24 Sep 2026 01:14:23 -0500 Subject: [PATCH 2/2] perf: dedupe collapsed hash join IN lists and add combined bounds The per-partition InList arrays hold one entry per build row, and the collapsed union concatenated them. On TPC-DS SF1 with 12 partitions, Q65 pushed 54,000 entries for 6 distinct keys, and Q18 pushed 10,848 entries for 1,178 distinct keys. The pruning code uses an IN list only up to `max_in_list_size` (20) entries, so these filters gave no pruning term, and the long lists made the statistics evaluation for each file range slow. The union is now deduplicated and sorted with the arrow row format before the IN list is built. This works for single and struct (multi-column) keys and dictionaries, keeps one NULL, and makes the list order deterministic. The 1 MiB cap now applies to the deduplicated union. The collapsed filter also gets one range per key column, `col >= min AND col <= max`, from the combined bounds of all non-empty partitions, before the IN list. Every key in the union is inside this range, so the filter stays exact, and the pruning code can use the range when the list has more than `max_in_list_size` entries. Co-Authored-By: Claude Opus 5.5 --- .../physical_optimizer/filter_pushdown.rs | 2 +- .../src/joins/hash_join/inlist_builder.rs | 68 +++- .../src/joins/hash_join/shared_bounds.rs | 303 ++++++++++++++++-- .../test_files/range_partitioning.slt | 5 +- 4 files changed, 349 insertions(+), 29 deletions(-) diff --git a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs index a4090eeb15b87..7c84feae249ff 100644 --- a/datafusion/core/tests/physical_optimizer/filter_pushdown.rs +++ b/datafusion/core/tests/physical_optimizer/filter_pushdown.rs @@ -1165,7 +1165,7 @@ async fn test_hashjoin_dynamic_filter_pushdown_partitioned() { - RepartitionExec: partitioning=Hash([a@0, b@1], 12), input_partitions=1 - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, c], file_type=test, pushdown_supported=true - RepartitionExec: partitioning=Hash([a@0, b@1], 12), input_partitions=1 - - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ struct(a@0, b@1) IN (SET) ([{c0:ab,c1:bb}, {c0:aa,c1:ba}]) ] + - DataSourceExec: file_groups={1 group: [[test.parquet]]}, projection=[a, b, e], file_type=test, pushdown_supported=true, predicate=DynamicFilter [ a@0 >= aa AND a@0 <= ab AND b@1 >= ba AND b@1 <= bb AND struct(a@0, b@1) IN (SET) ([{c0:aa,c1:ba}, {c0:ab,c1:bb}]) ] " ); diff --git a/datafusion/physical-plan/src/joins/hash_join/inlist_builder.rs b/datafusion/physical-plan/src/joins/hash_join/inlist_builder.rs index 2fc3201c6363f..83a4a32c73ae4 100644 --- a/datafusion/physical-plan/src/joins/hash_join/inlist_builder.rs +++ b/datafusion/physical-plan/src/joins/hash_join/inlist_builder.rs @@ -17,10 +17,13 @@ //! Utilities for building InList expressions from hash join build side data +use std::collections::HashSet; use std::sync::Arc; -use arrow::array::{ArrayRef, StructArray}; +use arrow::array::{ArrayRef, StructArray, UInt64Array}; +use arrow::compute::take; use arrow::datatypes::{Field, FieldRef, Fields}; +use arrow::row::{Row, RowConverter, SortField}; use arrow_schema::DataType; use datafusion_common::Result; @@ -77,6 +80,48 @@ pub(super) fn build_struct_inlist_values( Ok(Some(source_array)) } +/// Removes duplicate entries from an `IN` list value array and sorts the +/// remaining entries. +/// +/// Equality and order are those of the arrow row format produced by +/// [`RowConverter`] with default [`SortField`] options (ascending, NULLs +/// first). This works for single values, for the struct values of +/// multi-column keys and for dictionaries. NULLs compare equal to each other, +/// so many NULLs collapse into one NULL. That does not change the result of +/// `IN`: one NULL in the list gives the same three-valued result as many. +/// +/// Sorting makes the list independent of the order in which build rows +/// arrive, so the displayed filter is deterministic. +/// +/// Returns the input unchanged when it has fewer than two entries, or when +/// its type cannot be row-encoded (deduplication is an optimization, not a +/// requirement). +pub(super) fn sorted_distinct_inlist_values(values: ArrayRef) -> Result { + if values.len() < 2 { + return Ok(values); + } + + let sort_field = SortField::new(values.data_type().clone()); + if !RowConverter::supports_fields(std::slice::from_ref(&sort_field)) { + return Ok(values); + } + + let converter = RowConverter::new(vec![sort_field])?; + let rows = converter.convert_columns(std::slice::from_ref(&values))?; + + // Select the first entry of each distinct value by index. The entries are + // taken from the input instead of decoded from the rows, so that the type + // of the input (for example a dictionary) is kept. + let mut seen: HashSet = HashSet::with_capacity(values.len()); + let mut indices: Vec = (0..rows.num_rows()) + .filter(|&idx| seen.insert(rows.row(idx))) + .collect(); + indices.sort_unstable_by(|&a, &b| rows.row(a).cmp(&rows.row(b))); + + let indices = UInt64Array::from_iter_values(indices.into_iter().map(|i| i as u64)); + Ok(take(values.as_ref(), &indices, None)?) +} + #[cfg(test)] mod tests { use super::*; @@ -155,4 +200,25 @@ mod tests { assert_eq!(result.len(), 3); assert_eq!(result.data_type(), dict_array.data_type()); } + + #[test] + fn test_sorted_distinct_inlist_values_keeps_dictionary_type() { + let keys = Int8Array::from(vec![1i8, 0, 1, 1, 0]); + let values = Arc::new(StringArray::from(vec!["foo", "bar"])); + let dict_array = Arc::new(DictionaryArray::new(keys, values)) as ArrayRef; + + let result = sorted_distinct_inlist_values(Arc::clone(&dict_array)).unwrap(); + + assert_eq!(result.data_type(), dict_array.data_type()); + assert_eq!(result.len(), 2); + // "bar" sorts before "foo". + assert_eq!( + arrow::util::display::array_value_to_string(&result, 0).unwrap(), + "bar" + ); + assert_eq!( + arrow::util::display::array_value_to_string(&result, 1).unwrap(), + "foo" + ); + } } diff --git a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs index eca7bc4f6d2bc..53ba9cdb7a2e7 100644 --- a/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs +++ b/datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs @@ -18,6 +18,7 @@ //! Utilities for shared build-side information. Used in dynamic filter pushdown in Hash Joins. // TODO: include the link to the Dynamic Filter blog post. +use std::cmp::Ordering; use std::fmt; use std::sync::Arc; @@ -27,7 +28,9 @@ use crate::Partitioning; use crate::joins::Map; use crate::joins::PartitionMode; use crate::joins::hash_join::exec::HASH_JOIN_SEED; -use crate::joins::hash_join::inlist_builder::build_struct_fields; +use crate::joins::hash_join::inlist_builder::{ + build_struct_fields, sorted_distinct_inlist_values, +}; use crate::joins::hash_join::partitioned_hash_eval::{ HashExpr, HashTableLookupExpr, SeededRandomState, }; @@ -155,11 +158,26 @@ fn create_membership_predicate( fn create_bounds_predicate( on_right: &[PhysicalExprRef], bounds: &PartitionBounds, +) -> Option> { + create_column_bounds_predicate( + on_right, + (0..on_right.len()).map(|col_idx| bounds.get_column_bounds(col_idx)), + ) +} + +/// Creates a predicate `col >= min AND col <= max` for each key column that has +/// bounds, combined with `AND`. Item `i` of `column_bounds` holds the bounds of +/// `on_right[i]`, or `None` when that column has no bounds. +/// +/// Returns `None` if no column has bounds. +fn create_column_bounds_predicate<'a>( + on_right: &[PhysicalExprRef], + column_bounds: impl IntoIterator>, ) -> Option> { let mut column_predicates = Vec::new(); - for (col_idx, right_expr) in on_right.iter().enumerate() { - if let Some(column_bounds) = bounds.get_column_bounds(col_idx) { + for (right_expr, column_bounds) in on_right.iter().zip(column_bounds) { + if let Some(column_bounds) = column_bounds { // Create predicate: col >= min AND col <= max let min_expr = Arc::new(BinaryExpr::new( Arc::clone(right_expr), @@ -192,6 +210,47 @@ fn create_bounds_predicate( } } +/// Combines the bounds of the given partitions into, for each of the +/// `num_columns` key columns, one range that contains the bounds of every +/// partition. +/// +/// A column gets `None` when a partition has no bounds for it or when two +/// bounds cannot be compared. NULL bounds are skipped: they occur only when +/// every key of the column in that partition is NULL, and a NULL key cannot +/// satisfy a range check in any case. If every bound of a column is NULL, the +/// column gets `None`. +fn combined_column_bounds( + num_columns: usize, + partition_bounds: &[&PartitionBounds], +) -> Vec> { + (0..num_columns) + .map(|col_idx| { + let mut combined: Option = None; + for bounds in partition_bounds { + let column_bounds = bounds.get_column_bounds(col_idx)?; + if column_bounds.min.is_null() || column_bounds.max.is_null() { + continue; + } + combined = Some(match combined { + None => column_bounds.clone(), + Some(ColumnBounds { min, max }) => { + let min = match column_bounds.min.partial_cmp(&min)? { + Ordering::Less => column_bounds.min.clone(), + _ => min, + }; + let max = match column_bounds.max.partial_cmp(&max)? { + Ordering::Greater => column_bounds.max.clone(), + _ => max, + }; + ColumnBounds::new(min, max) + } + }); + } + combined + }) + .collect() +} + /// Combines a membership predicate and a bounds predicate with logical AND. /// /// Returns `None` when neither is available; callers decide the fallback (e.g. @@ -273,8 +332,8 @@ pub(crate) struct SharedBuildAccumulator { null_aware: bool, } -/// Ceiling on the combined size of the per-partition `InList` arrays that -/// [`SharedBuildAccumulator::union_inlist_filter`] will concatenate. +/// Ceiling on the size of the deduplicated union `InList` array that +/// [`SharedBuildAccumulator::union_inlist_filter`] will push. /// /// Each partition's list is independently capped by /// `hash_join_inlist_pushdown_max_size`, so without a combined cap the union @@ -831,25 +890,34 @@ impl SharedBuildAccumulator { /// the routing hash for each probe row, and unlike a `CASE`, pruning can use /// an `InList`. /// - /// The per-partition bounds are dropped: every key in a partition's list is - /// inside that partition's bounds, so the bounds reject no additional rows. + /// The union is deduplicated and sorted (see + /// [`sorted_distinct_inlist_values`]). The per-partition lists hold one + /// entry per build row, not per distinct key, and the pruning code uses an + /// `InList` only up to `max_in_list_size` entries. + /// + /// The per-partition bounds are replaced by one range per key column that + /// contains the bounds of all partitions: `col >= min AND col <= max AND + /// col IN (...)`. Every key in the union is inside this range, so the range + /// rejects no additional rows, but the pruning code can use it when the + /// list has more than `max_in_list_size` entries. /// /// Returns the filter and whether any build key is NULL, or `None` when the /// collapse does not apply: fewer than two partitions have rows, a partition /// is canceled or pushes a hash table, the lists have different types, or - /// the union is larger than [`MAX_UNIONED_INLIST_BYTES`]. + /// the deduplicated union is larger than [`MAX_UNIONED_INLIST_BYTES`]. fn union_inlist_filter( &self, partitions: &[PartitionStatus], ) -> Result, bool)>> { let mut arrays: Vec<&ArrayRef> = Vec::with_capacity(partitions.len()); - let mut total_bytes = 0; + let mut partition_bounds: Vec<&PartitionBounds> = + Vec::with_capacity(partitions.len()); let mut keys_have_null = false; for partition in partitions { let PartitionStatus::Reported(PartitionData { + bounds, pushdown, keys_have_null: partition_keys_have_null, - .. }) = partition else { return Ok(None); @@ -859,16 +927,15 @@ impl SharedBuildAccumulator { PushdownStrategy::Empty => continue, PushdownStrategy::Map(_) => return Ok(None), }; - total_bytes += values.get_array_memory_size(); - if total_bytes > MAX_UNIONED_INLIST_BYTES - || arrays - .first() - .is_some_and(|first| first.data_type() != values.data_type()) + if arrays + .first() + .is_some_and(|first| first.data_type() != values.data_type()) { return Ok(None); } keys_have_null |= partition_keys_have_null; arrays.push(values); + partition_bounds.push(bounds); } // With zero or one non-empty partition, `build_partitioned_filter` @@ -877,14 +944,28 @@ impl SharedBuildAccumulator { return Ok(None); } + // Each partition's list is at most `hash_join_inlist_pushdown_max_size`, + // so the concatenation is at most the partition count times that size. let union = concat(&arrays.iter().map(|a| a.as_ref()).collect::>())?; - let filter_expr = create_membership_predicate( + let union = sorted_distinct_inlist_values(union)?; + if union.get_array_memory_size() > MAX_UNIONED_INLIST_BYTES { + return Ok(None); + } + + let membership_expr = create_membership_predicate( &self.on_right, PushdownStrategy::InList(union), &HASH_JOIN_SEED, self.probe_schema.as_ref(), )?; - Ok(filter_expr.map(|expr| (expr, keys_have_null))) + let combined_bounds = + combined_column_bounds(self.on_right.len(), &partition_bounds); + let bounds_expr = create_column_bounds_predicate( + &self.on_right, + combined_bounds.iter().map(Option::as_ref), + ); + Ok(combine_membership_and_bounds(membership_expr, bounds_expr) + .map(|expr| (expr, keys_have_null))) } /// Keeps probe rows with a NULL key when the join semantics need them. @@ -999,8 +1080,9 @@ pub(super) fn completed_partitions_for_test(acc: &SharedBuildAccumulator) -> usi mod tests { use super::*; + use crate::joins::hash_join::inlist_builder::build_struct_inlist_values; use crate::joins::join_hash_map::JoinHashMapU32; - use arrow::array::{ArrayRef, BooleanArray, Float64Array, Int32Array}; + use arrow::array::{ArrayRef, BooleanArray, Float64Array, Int32Array, StringArray}; use arrow::compute::SortOptions; use arrow::record_batch::RecordBatch; use datafusion_common::SplitPoint; @@ -1250,10 +1332,161 @@ mod tests { .unwrap(); // Routing is a function of the key, so a probe key can only match the - // list of the partition it routes to: the union is exact, and neither the - // `CASE` nor the per-partition bounds are necessary. + // list of the partition it routes to: the union is exact, and the `CASE` + // is not necessary. The per-partition bounds are replaced by one range + // that contains all of them. + let expr = current_expr(&acc); + assert_eq!( + expr.to_string(), + "probe_key@0 >= 1 AND probe_key@0 <= 5 AND probe_key@0 IN (SET) ([1, 2, 4, 5])" + ); + let union = binary_expr(&expr).right(); + assert_in_list_column_values(union, "probe_key", 0, &[1, 2, 4, 5]); + } + + #[test] + fn partitioned_union_inlist_drops_duplicates_within_and_across_partitions() { + let acc = make_partitioned_expr_accumulator_for_test(3); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[7, 3, 7, 7, 3]), no_bounds()), + reported(in_list(&[5, 5, 3]), no_bounds()), + reported(in_list(&[9, 9]), no_bounds()), + ])) + .unwrap(); + + // The per-partition lists hold one entry per build row. The union holds + // each distinct key once, in sorted order. let expr = current_expr(&acc); - assert_in_list_column_values(&expr, "probe_key", 0, &[1, 4, 2, 5]); + assert_in_list_column_values(&expr, "probe_key", 0, &[3, 5, 7, 9]); + } + + #[test] + fn partitioned_union_inlist_keeps_one_null_key() { + let acc = null_equal_partitioned_accumulator(2); + let with_nulls = |values: Vec>| { + PushdownStrategy::InList(Arc::new(Int32Array::from(values)) as ArrayRef) + }; + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported_with_null_keys( + with_nulls(vec![Some(2), None, Some(2), None]), + bounds(2, 2), + ), + reported_with_null_keys(with_nulls(vec![None, Some(1)]), bounds(1, 1)), + ])) + .unwrap(); + + // The NULL keys collapse into one NULL, and the filter still keeps the + // probe NULLs that a null-equal join can match. + let expr = current_expr(&acc); + assert_eq!( + expr.to_string(), + "probe_key@0 IS NULL OR probe_key@0 >= 1 AND probe_key@0 <= 2 AND probe_key@0 IN (SET) ([NULL, 1, 2])" + ); + } + + #[test] + fn partitioned_union_inlist_bounds_skip_all_null_partitions() { + let acc = null_equal_partitioned_accumulator(2); + let null_bounds = PartitionBounds::new(vec![ColumnBounds::new( + ScalarValue::Int32(None), + ScalarValue::Int32(None), + )]); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[4, 6]), bounds(4, 6)), + reported_with_null_keys( + PushdownStrategy::InList( + Arc::new(Int32Array::from(vec![None, None])) as ArrayRef + ), + null_bounds, + ), + ])) + .unwrap(); + + // A partition with only NULL keys has NULL bounds. It adds nothing to + // the range, because a NULL key cannot pass a range check. + let expr = current_expr(&acc); + assert_eq!( + expr.to_string(), + "probe_key@0 IS NULL OR probe_key@0 >= 4 AND probe_key@0 <= 6 AND probe_key@0 IN (SET) ([NULL, 4, 6])" + ); + } + + #[test] + fn partitioned_union_inlist_without_bounds_in_one_partition_has_no_range() { + let acc = make_partitioned_expr_accumulator_for_test(2); + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&[1, 2]), bounds(1, 2)), + reported(in_list(&[3]), no_bounds()), + ])) + .unwrap(); + + // The bounds of the second partition are unknown, so no range covers + // all partitions. + let expr = current_expr(&acc); + assert_in_list_column_values(&expr, "probe_key", 0, &[1, 2, 3]); + } + + #[test] + fn partitioned_multi_column_union_inlist_is_deduplicated_with_bounds() { + let probe_schema = Arc::new(Schema::new(vec![ + Field::new("a", DataType::Int32, false), + Field::new("b", DataType::Utf8, false), + ])); + let on_right: Vec = + vec![Arc::new(Column::new("a", 0)), Arc::new(Column::new("b", 1))]; + let mut acc = make_accumulator_for_test( + AccumulatedBuildData::Partitioned { + partitions: vec![PartitionStatus::Pending; 2], + completed_partitions: 0, + }, + on_right, + ); + acc.probe_schema = probe_schema; + + let struct_list = |a: Vec, b: Vec<&str>| { + PushdownStrategy::InList( + build_struct_inlist_values(&[ + Arc::new(Int32Array::from(a)) as ArrayRef, + Arc::new(StringArray::from(b)) as ArrayRef, + ]) + .unwrap() + .unwrap(), + ) + }; + let two_column_bounds = |a: (i32, i32), b: (&str, &str)| { + PartitionBounds::new(vec![ + ColumnBounds::new( + ScalarValue::Int32(Some(a.0)), + ScalarValue::Int32(Some(a.1)), + ), + ColumnBounds::new(ScalarValue::from(b.0), ScalarValue::from(b.1)), + ]) + }; + + acc.build_filter(FinalizeInput::Partitioned(vec![ + // `(2, x)` is present twice; `(1, x)` and `(1, y)` differ only in `b`. + reported( + struct_list(vec![2, 1, 2, 1], vec!["x", "y", "x", "x"]), + two_column_bounds((1, 2), ("x", "y")), + ), + reported( + struct_list(vec![3, 3], vec!["w", "w"]), + two_column_bounds((3, 3), ("w", "w")), + ), + ])) + .unwrap(); + + // Deduplication is on the whole tuple, and each column gets its own + // range. + let expr = current_expr(&acc); + assert_eq!( + expr.to_string(), + "a@0 >= 1 AND a@0 <= 3 AND b@1 >= w AND b@1 <= y AND struct(a@0, b@1) IN (SET) ([{c0:1,c1:x}, {c0:1,c1:y}, {c0:2,c1:x}, {c0:3,c1:w}])" + ); } #[test] @@ -1296,12 +1529,13 @@ mod tests { #[test] fn partitioned_oversized_inlist_union_keeps_the_routing_case() { let acc = make_partitioned_expr_accumulator_for_test(2); - let half = MAX_UNIONED_INLIST_BYTES / size_of::() / 2 + 1; - let values = (0..half as i32).collect::>(); + let half = (MAX_UNIONED_INLIST_BYTES / size_of::() / 2 + 1) as i32; + let low = (0..half).collect::>(); + let high = (half..2 * half).collect::>(); acc.build_filter(FinalizeInput::Partitioned(vec![ - reported(in_list(&values), no_bounds()), - reported(in_list(&values), no_bounds()), + reported(in_list(&low), no_bounds()), + reported(in_list(&high), no_bounds()), ])) .unwrap(); @@ -1309,6 +1543,25 @@ mod tests { assert_eq!(case_expr(&expr).when_then_expr().len(), 2); } + #[test] + fn partitioned_inlist_union_cap_applies_after_deduplication() { + let acc = make_partitioned_expr_accumulator_for_test(2); + // Before deduplication the two lists are larger than the cap, but they + // hold only two distinct keys. + let half = MAX_UNIONED_INLIST_BYTES / size_of::() / 2 + 1; + let ones = vec![1; half]; + let twos = vec![2; half]; + + acc.build_filter(FinalizeInput::Partitioned(vec![ + reported(in_list(&ones), no_bounds()), + reported(in_list(&twos), no_bounds()), + ])) + .unwrap(); + + let expr = current_expr(&acc); + assert_in_list_column_values(&expr, "probe_key", 0, &[1, 2]); + } + #[test] fn partitioned_canceled_unknown_partitions_keep_unknown_routes_permissive() { let acc = make_partitioned_expr_accumulator_for_test(2); diff --git a/datafusion/sqllogictest/test_files/range_partitioning.slt b/datafusion/sqllogictest/test_files/range_partitioning.slt index cedeb475da47b..07ec911344456 100644 --- a/datafusion/sqllogictest/test_files/range_partitioning.slt +++ b/datafusion/sqllogictest/test_files/range_partitioning.slt @@ -1837,7 +1837,8 @@ SELECT range_key, SUM(value) FROM ( # The Parquet-backed probe accepts the partitioned dynamic filter. Matching # Range split points keep build filter i aligned with probe partition i. The # build has rows only in partitions 0 and 2, and both push an IN list, so the -# routed CASE collapses into one IN list over the union of their keys. +# routed CASE collapses into one IN list over the union of their keys, after +# one range that contains the bounds of both partitions. ########## statement ok @@ -1878,7 +1879,7 @@ JOIN range_partitioned p ON b.range_key = p.range_key; Plan with Metrics 01)HashJoinExec: mode=Partitionedmetrics=[output_rows=2,] 02)--DataSourceExec: file_type=parquet, predicate=range_key@0 = 5 OR range_key@0 = 20metrics=[output_rows=2,] -03)--DataSourceExec: file_type=parquet, predicate=DynamicFilter [ range_key@0 IN (SET) ([5, 20]) ]metrics=[output_rows=2,] +03)--DataSourceExec: file_type=parquet, predicate=DynamicFilter [ range_key@0 >= 5 AND range_key@0 <= 20 AND range_key@0 IN (SET) ([5, 20]) ]metrics=[output_rows=2,] query III SELECT b.range_key, b.value, p.value