From 6f6f37db00023be6fcf4c6bf29568d27ca9a2fc3 Mon Sep 17 00:00:00 2001 From: linfeng Date: Tue, 15 Sep 2026 22:36:46 +0800 Subject: [PATCH 1/3] perf: add an adaptive integer prefilter for hash joins --- datafusion/common/src/config.rs | 22 + datafusion/physical-plan/Cargo.toml | 5 + .../physical-plan/benches/hash_join_probe.rs | 321 +++++++++++ .../physical-plan/src/joins/hash_join/exec.rs | 496 ++++++++++++++++- .../src/joins/hash_join/stream.rs | 63 ++- .../src/joins/integer_prefilter.rs | 518 ++++++++++++++++++ datafusion/physical-plan/src/joins/mod.rs | 1 + .../hash_join_integer_prefilter.slt | 230 ++++++++ docs/source/user-guide/configs.md | 4 + 9 files changed, 1654 insertions(+), 6 deletions(-) create mode 100644 datafusion/physical-plan/benches/hash_join_probe.rs create mode 100644 datafusion/physical-plan/src/joins/integer_prefilter.rs create mode 100644 datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 360586b0e9bae..9b9db7bfeda41 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -922,6 +922,28 @@ config_namespace! { /// Support for build_side.num_rows() >= u32::MAX will be added in the future. pub perfect_hash_join_min_key_density: f64, default = 0.15 + /// Enable an exact integer membership prefilter for hash joins with a single + /// integer key when the build side uses a hash table. It skips lookups for + /// absent keys while retaining probe rows for unmatched join output. + pub enable_join_integer_prefilter: bool, default = false + + /// Maximum number of integer values covered by the join prefilter bitmap + /// (`max_key - min_key + 1`). Must be greater than zero when enabled. + /// Larger ranges fall back to normal hash table lookups. + pub join_integer_prefilter_max_key_range: usize, default = 262144 + + /// Minimum fraction of otherwise eligible hash lookups the integer prefilter + /// must eliminate to keep filtering. Must be finite and in [0, 1]. + /// Unprofitable samples pause filtering, then periodically retry. + pub join_integer_prefilter_min_pruning_ratio: f64, default = 0.5 + + /// Minimum input probe rows in each integer prefilter sampling window, + /// including NULLs. Pruning ratios only count otherwise eligible lookups. + /// Must be greater than zero when enabled. Windows end at batch boundaries; + /// unprofitable windows pause filtering for eight times this many input rows + /// before retrying at the next batch boundary. + pub join_integer_prefilter_sample_rows: usize, default = 12288 + /// When set to true, record batches will be examined between each operator and /// small batches will be coalesced into larger batches. This is helpful when there /// are highly selective filters or joins that could produce tiny output batches. The diff --git a/datafusion/physical-plan/Cargo.toml b/datafusion/physical-plan/Cargo.toml index 534cea8ea9cbb..8af9b59fd7cc4 100644 --- a/datafusion/physical-plan/Cargo.toml +++ b/datafusion/physical-plan/Cargo.toml @@ -148,6 +148,11 @@ name = "compute_statistics" harness = false name = "dictionary_group_values" +[[bench]] +harness = false +name = "hash_join_probe" +required-features = ["test_utils"] + [[bench]] harness = false name = "hash_join_semi_anti" diff --git a/datafusion/physical-plan/benches/hash_join_probe.rs b/datafusion/physical-plan/benches/hash_join_probe.rs new file mode 100644 index 0000000000000..eb6a6fa4e6b7e --- /dev/null +++ b/datafusion/physical-plan/benches/hash_join_probe.rs @@ -0,0 +1,321 @@ +// 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. + +//! Full in-memory HashJoin execution, including build, with fixed Int32 workloads. +//! Covers inner, semi, and anti joins with key-only and payload-bearing inputs. +//! Session settings use the standard DataFusion environment configuration. + +use std::hint::black_box; +use std::sync::Arc; + +use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use arrow::record_batch::RecordBatch; +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; +use datafusion_common::{JoinType, NullEquality}; +use datafusion_execution::TaskContext; +use datafusion_execution::config::SessionConfig; +use datafusion_physical_expr::expressions::col; +use datafusion_physical_plan::ExecutionPlan; +use datafusion_physical_plan::joins::{HashJoinExec, PartitionMode}; +use datafusion_physical_plan::test::TestMemoryExec; +use futures::StreamExt; +use tokio::runtime::Runtime; + +const BUILD_ROWS: usize = 8_192; +const PROBE_ROWS: usize = 1_048_576; +const BATCH_SIZE: usize = 8_192; +const SHORT_PROBE_ROWS: usize = 4_096; +const PHASE_ROWS: usize = PROBE_ROWS / 2; +const HIT_EVERY: usize = 16; +const SPARSE_KEY_STEP: i32 = 16; +const DENSE_KEY_STEP: i32 = 1; +const WIDE_KEY_STEP: i32 = 64; +const NON_NULL_EVERY: usize = 1_024; +const PAYLOAD_BYTES: usize = 64; + +#[derive(Clone, Copy)] +enum Pattern { + AllHit, + InRange, + OutOfRange, + HighToLow, + LowToHigh, + ShortProbe, + NullHeavyHits, + NullHeavyMisses, +} + +fn make_batches( + rows: usize, + key_step: i32, + pattern: Pattern, + schema: &SchemaRef, +) -> Vec { + (0..rows) + .step_by(BATCH_SIZE) + .map(|start| { + let end = (start + BATCH_SIZE).min(rows); + let keys = Int32Array::from_iter((start..end).map(|row| { + if matches!(pattern, Pattern::NullHeavyHits | Pattern::NullHeavyMisses) { + return (row % NON_NULL_EVERY == 0).then(|| { + (row % (BUILD_ROWS - 1)) as i32 * key_step + + i32::from(matches!(pattern, Pattern::NullHeavyMisses)) + }); + } + let high_hit = match pattern { + Pattern::AllHit => true, + Pattern::HighToLow => row < PHASE_ROWS, + Pattern::LowToHigh => row >= PHASE_ROWS, + _ => false, + }; + Some(if high_hit || row % HIT_EVERY == 0 { + (row % BUILD_ROWS) as i32 * key_step + } else if matches!(pattern, Pattern::OutOfRange) { + (BUILD_ROWS + row % BUILD_ROWS) as i32 * key_step + } else { + // Every hole stays strictly between the build min and max. + (row % (BUILD_ROWS - 1)) as i32 * key_step + 1 + }) + })); + let mut columns: Vec = vec![Arc::new(keys)]; + if schema.fields().len() > 1 { + columns.push(Arc::new(Int64Array::from_iter_values( + (start..end).map(|row| row as i64), + ))); + columns.push(Arc::new(StringArray::from_iter_values( + (start..end).map(|row| format!("{row:0PAYLOAD_BYTES$}")), + ))); + } + RecordBatch::try_new(Arc::clone(schema), columns).unwrap() + }) + .collect() +} + +fn make_join( + build: &Arc, + probe: &Arc, + join_type: JoinType, +) -> HashJoinExec { + HashJoinExec::try_new( + Arc::clone(build), + Arc::clone(probe), + vec![( + col("key", &build.schema()).unwrap(), + col("key", &probe.schema()).unwrap(), + )], + None, + &join_type, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, + ) + .unwrap() +} + +fn bench_hash_join_probe(c: &mut Criterion) { + let rt = Runtime::new().unwrap(); + let config = SessionConfig::from_env() + .unwrap() + .with_batch_size(BATCH_SIZE); + let context = Arc::new(TaskContext::default().with_session_config(config)); + let mut group = c.benchmark_group("hash_join_probe"); + // Default PHJ settings select ArrayMap only for the dense case. Sparse keys + // span 131,057 values; wide keys span 524,225. + for (name, pattern, key_step, join_type, with_payload) in [ + ( + "low_hit_in_range", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "low_hit_out_of_range", + Pattern::OutOfRange, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "high_to_low", + Pattern::HighToLow, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "low_to_high", + Pattern::LowToHigh, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "all_hit", + Pattern::AllHit, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "short_probe", + Pattern::ShortProbe, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "dense", + Pattern::OutOfRange, + DENSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "wide_range", + Pattern::InRange, + WIDE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "right_semi_low_hit", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::RightSemi, + false, + ), + ( + "right_anti_low_hit", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::RightAnti, + false, + ), + ( + "inner_low_hit_payload", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::Inner, + true, + ), + ( + "right_semi_low_hit_payload", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::RightSemi, + true, + ), + ( + "right_anti_low_hit_payload", + Pattern::InRange, + SPARSE_KEY_STEP, + JoinType::RightAnti, + true, + ), + ( + "null_heavy_hits", + Pattern::NullHeavyHits, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ( + "null_heavy_misses", + Pattern::NullHeavyMisses, + SPARSE_KEY_STEP, + JoinType::Inner, + false, + ), + ] { + let nullable = + matches!(pattern, Pattern::NullHeavyHits | Pattern::NullHeavyMisses); + let mut fields = vec![Field::new("key", DataType::Int32, nullable)]; + if with_payload { + fields.push(Field::new("row_id", DataType::Int64, false)); + fields.push(Field::new("payload", DataType::Utf8, false)); + } + let schema = Arc::new(Schema::new(fields)); + let rows = if matches!(pattern, Pattern::ShortProbe) { + SHORT_PROBE_ROWS + } else { + PROBE_ROWS + }; + let hits = match pattern { + Pattern::AllHit => rows, + Pattern::HighToLow | Pattern::LowToHigh => { + PHASE_ROWS + PHASE_ROWS / HIT_EVERY + } + Pattern::NullHeavyHits => rows / NON_NULL_EVERY, + Pattern::NullHeavyMisses => 0, + _ => rows / HIT_EVERY, + }; + let expected = if join_type == JoinType::RightAnti { + rows - hits + } else { + hits + }; + let expected_columns = + schema.fields().len() * if join_type == JoinType::Inner { 2 } else { 1 }; + let build: Arc = TestMemoryExec::try_new_exec( + &[make_batches(BUILD_ROWS, key_step, Pattern::AllHit, &schema)], + Arc::clone(&schema), + None, + ) + .unwrap(); + let probe: Arc = TestMemoryExec::try_new_exec( + &[make_batches(rows, key_step, pattern, &schema)], + Arc::clone(&schema), + None, + ) + .unwrap(); + + let diagnostic = make_join(&build, &probe, join_type); + let output_rows = rt.block_on(async { + let mut stream = diagnostic.execute(0, Arc::clone(&context)).unwrap(); + let mut output_rows = 0; + while let Some(batch) = stream.next().await { + let batch = batch.unwrap(); + assert_eq!(batch.num_columns(), expected_columns, "{name}"); + output_rows += batch.num_rows(); + } + output_rows + }); + assert_eq!(output_rows, expected, "{name}"); + + group.bench_function(name, |b| { + b.iter_batched( + || make_join(&build, &probe, join_type), + |join| { + rt.block_on(async { + let mut stream = join.execute(0, Arc::clone(&context)).unwrap(); + while let Some(batch) = stream.next().await { + black_box(batch.unwrap()); + } + }) + }, + BatchSize::LargeInput, + ); + }); + } + group.finish(); +} + +criterion_group!(benches, bench_hash_join_probe); +criterion_main!(benches); diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index 5f2274166234b..4b9b6ecf3bdca 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -39,6 +39,7 @@ use crate::joins::hash_join::shared_bounds::{ use crate::joins::hash_join::stream::{ BuildSide, BuildSideInitialState, HashJoinStream, HashJoinStreamState, }; +use crate::joins::integer_prefilter::{IntegerPrefilter, PrefilterState}; use crate::joins::join_hash_map::{JoinHashMapU32, JoinHashMapU64}; use crate::joins::utils::{ OnceAsync, OnceFut, asymmetric_join_output_partitioning, emits_unmatched_left_rows, @@ -274,6 +275,8 @@ pub(super) struct JoinLeftData { /// The hash table with indices into `batch` /// Arc is used to allow sharing with SharedBuildAccumulator for hash map pushdown pub(super) map: Arc, + /// Optional exact integer membership bitmap shared by probe streams. + pub(super) integer_prefilter: Option, /// Hash table over correlated scope keys for scalar null-aware mark joins. /// /// For null-aware `LeftMark`, key 0 is the scalar `NOT IN` value key and @@ -1569,6 +1572,28 @@ impl ExecutionPlan for HashJoinExec { .allow_join_dynamic_filter_pushdown(context.session_config().options()) && self.dynamic_filter.is_some(); + let integer_prefilter_state = PrefilterState::try_from_config( + &context.session_config().options().execution, + )? + .map(|state| { + let reservation = MemoryConsumer::new("HashJoinIntegerPrefilter") + .register(context.memory_pool()); + (state, reservation) + }); + let (integer_prefilter_pruned_rows, integer_prefilter_created_count) = + if integer_prefilter_state.is_some() { + ( + MetricBuilder::new(&self.metrics) + .with_category(MetricCategory::Rows) + .counter("integer_prefilter_pruned_rows", partition), + MetricBuilder::new(&self.metrics) + .counter("integer_prefilter_created_count", partition), + ) + } else { + // Keep the default metrics unchanged when the prefilter is disabled. + (Count::new(), Count::new()) + }; + let join_metrics = BuildProbeJoinMetrics::new(partition, &self.metrics); let array_map_created_count = MetricBuilder::new(&self.metrics) @@ -1626,6 +1651,7 @@ impl ExecutionPlan for HashJoinExec { self.null_equality, null_aware, array_map_created_count, + integer_prefilter_created_count, )) })?, PartitionMode::Partitioned => { @@ -1647,6 +1673,7 @@ impl ExecutionPlan for HashJoinExec { self.null_equality, null_aware, array_map_created_count, + integer_prefilter_created_count, )) } PartitionMode::Auto => { @@ -1698,6 +1725,8 @@ impl ExecutionPlan for HashJoinExec { self.mode, null_aware, self.fetch, + integer_prefilter_state, + integer_prefilter_pruned_rows, ))) } @@ -2722,6 +2751,7 @@ async fn collect_left_input( null_equality: NullEquality, null_aware: Option, array_map_created_count: Count, + integer_prefilter_created_count: Count, ) -> Result { let schema = left_stream.schema(); @@ -2964,15 +2994,42 @@ async fn collect_left_input( } }; - if is_phj_candidate && !should_compute_dynamic_filters { - bounds = None; - } - let build_has_null = null_aware == Some(NullAwareMode::RightAnti) && !left_values.is_empty() && left_values[0].logical_null_count() > 0; + // Reserve optional memory only after all mandatory join state has been + // allocated. Reuse the bounds already computed for perfect hash join. + let integer_prefilter = if config.execution.enable_join_integer_prefilter + && matches!(map.as_ref(), Map::HashMap(_)) + && left_values.len() == 1 + { + bounds + .as_ref() + .and_then(|bounds| bounds.get_column_bounds(0)) + .and_then(|bounds| { + IntegerPrefilter::try_new( + left_values[0].as_ref(), + (&bounds.min, &bounds.max), + config.execution.join_integer_prefilter_max_key_range, + null_equality, + &reservation, + ) + }) + } else { + None + }; + if let Some(filter) = &integer_prefilter { + metrics.build_mem_used.add(filter.size()); + integer_prefilter_created_count.add(1); + } + + if is_phj_candidate && !should_compute_dynamic_filters { + bounds = None; + } + let data = JoinLeftData { + integer_prefilter, map, null_aware_mark_scope_map, null_value_scope_map, @@ -2996,6 +3053,435 @@ async fn collect_left_input( mod tests { use super::*; + #[tokio::test] + async fn test_integer_prefilter_prunes_lookup_rows() -> Result<()> { + let left = build_table_two_cols( + ("a", &vec![Some(0), Some(2048)]), + ("b", &vec![Some(1), Some(2)]), + ); + let right = build_table_two_cols( + ("a", &vec![Some(0), Some(1), Some(2049), None]), + ("b", &vec![Some(1); 4]), + ); + let on = vec![(col("a", &left.schema())?, col("a", &right.schema())?)]; + let join = Arc::new(HashJoinExec::try_new( + left, + right, + on, + None, + &JoinType::Inner, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, + )?); + let mut config = SessionConfig::default(); + config.options_mut().execution.enable_join_integer_prefilter = true; + let context = Arc::new(TaskContext::default().with_session_config(config)); + let batches = crate::collect(Arc::clone(&join) as _, context).await?; + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); + assert_eq!( + join.metrics() + .unwrap() + .sum_by_name("integer_prefilter_pruned_rows") + .map(|value| value.as_usize()) + .unwrap_or(0), + 2 + ); + Ok(()) + } + + /// Duplicate keys cross output chunks; input batches also cross sampling windows. + fn integer_prefilter_join( + build: ArrayRef, + probe: ArrayRef, + join_type: JoinType, + null_equality: NullEquality, + null_aware: bool, + mode: PartitionMode, + with_filter: bool, + ) -> Result> { + let table = |keys: ArrayRef| -> Result> { + let schema = Arc::new(Schema::new(vec![Field::new( + "key", + keys.data_type().clone(), + true, + )])); + let batches = (0..keys.len()) + .step_by(3) + .map(|offset| { + RecordBatch::try_new( + Arc::clone(&schema), + vec![keys.slice(offset, 3.min(keys.len() - offset))], + ) + }) + .collect::, _>>()?; + Ok(TestMemoryExec::try_new_exec(&[batches], schema, None)?) + }; + let left = table(build)?; + let right = table(probe)?; + let filter = with_filter.then(|| { + JoinFilter::new( + Arc::new(BinaryExpr::new( + Arc::new(Column::new("key", 0)), + Operator::Gt, + lit(0_i32), + )), + vec![ColumnIndex { + index: 0, + side: JoinSide::Left, + }], + left.schema(), + ) + }); + let on = vec![(col("key", &left.schema())?, col("key", &right.schema())?)]; + Ok(Arc::new(HashJoinExec::try_new( + left, + right, + on, + filter, + &join_type, + None, + mode, + null_equality, + null_aware, + )?)) + } + + fn integer_prefilter_context(enabled: bool) -> Arc { + let mut config = SessionConfig::default().with_batch_size(2); + config.options_mut().execution.enable_join_integer_prefilter = enabled; + config + .options_mut() + .execution + .join_integer_prefilter_sample_rows = 3; + Arc::new(TaskContext::default().with_session_config(config)) + } + + #[tokio::test] + async fn test_integer_prefilter_join_types() -> Result<()> { + for join_type in [ + JoinType::Inner, + JoinType::Left, + JoinType::Right, + JoinType::Full, + JoinType::LeftSemi, + JoinType::RightSemi, + JoinType::LeftAnti, + JoinType::RightAnti, + JoinType::LeftMark, + JoinType::RightMark, + ] { + for null_equality in [ + NullEquality::NullEqualsNothing, + NullEquality::NullEqualsNull, + ] { + let mut expected = None; + for enabled in [false, true] { + let join = integer_prefilter_join( + Arc::new(Int32Array::from(vec![ + None, + Some(0), + Some(0), + Some(0), + Some(2048), + ])), + Arc::new(Int32Array::from(vec![ + Some(-1), + None, + Some(0), + Some(2048), + Some(3000), + Some(1), + ])), + join_type, + null_equality, + false, + PartitionMode::CollectLeft, + false, + )?; + let batches = crate::collect( + Arc::clone(&join) as _, + integer_prefilter_context(enabled), + ) + .await?; + let output = batches_to_sort_string(&batches); + if enabled { + assert_eq!( + &output, + expected.as_ref().unwrap(), + "{join_type:?} {null_equality:?}" + ); + assert_eq!( + join.metrics() + .unwrap() + .sum_by_name("integer_prefilter_created_count") + .unwrap() + .as_usize(), + 1 + ); + assert!( + join.metrics() + .unwrap() + .sum_by_name("integer_prefilter_pruned_rows") + .unwrap() + .as_usize() + > 0 + ); + } else { + expected = Some(output); + } + } + } + } + Ok(()) + } + + #[tokio::test] + async fn test_integer_prefilter_null_aware_and_filter() -> Result<()> { + // Preserve NULL/non-empty state even for probe rows excluded from lookup. + for (join_type, null_aware, mode, with_filter) in [ + (JoinType::LeftAnti, true, PartitionMode::CollectLeft, false), + (JoinType::RightAnti, true, PartitionMode::CollectLeft, false), + (JoinType::LeftMark, true, PartitionMode::CollectLeft, false), + (JoinType::Full, false, PartitionMode::Partitioned, true), + ] { + for (build, probe) in [ + ( + vec![Some(0), Some(0), Some(2048)], + vec![Some(1), Some(0), Some(3000), None], + ), + ( + vec![None, Some(0), Some(2048)], + vec![Some(1), Some(0), Some(3000)], + ), + (vec![None], vec![None, Some(1)]), + (vec![], vec![None, Some(1)]), + (vec![None, Some(0)], vec![]), + ] { + let mut expected = None; + for enabled in [false, true] { + let join = integer_prefilter_join( + Arc::new(Int32Array::from(build.clone())), + Arc::new(Int32Array::from(probe.clone())), + join_type, + NullEquality::NullEqualsNothing, + null_aware, + mode, + with_filter, + )?; + let batches = + crate::collect(join, integer_prefilter_context(enabled)).await?; + let output = batches_to_sort_string(&batches); + if enabled { + assert_eq!( + &output, + expected.as_ref().unwrap(), + "{join_type:?}, build={build:?}, probe={probe:?}" + ); + } else { + expected = Some(output); + } + } + } + } + Ok(()) + } + + #[tokio::test] + async fn test_integer_prefilter_fallbacks() -> Result<()> { + let cases: Vec<(ArrayRef, ArrayRef, bool)> = vec![ + ( + Arc::new(Int32Array::from(vec![0, 1])), + Arc::new(Int32Array::from(vec![0, 2])), + true, + ), + ( + Arc::new(Int32Array::from(vec![0, 262144])), + Arc::new(Int32Array::from(vec![0, 2])), + false, + ), + ( + Arc::new(arrow::array::StringArray::from(vec!["a", "c"])), + Arc::new(arrow::array::StringArray::from(vec!["a", "b"])), + false, + ), + ( + Arc::new(Int32Array::from(vec![None, None])), + Arc::new(Int32Array::from(vec![None, Some(2)])), + false, + ), + ]; + for (build, probe, phj) in cases { + let join = integer_prefilter_join( + build, + probe, + JoinType::Full, + NullEquality::NullEqualsNothing, + false, + PartitionMode::CollectLeft, + false, + )?; + crate::collect(Arc::clone(&join) as _, integer_prefilter_context(true)) + .await?; + let metrics = join.metrics().unwrap(); + assert_phj_used(&metrics, phj); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_created_count") + .unwrap() + .as_usize(), + 0 + ); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_pruned_rows") + .unwrap() + .as_usize(), + 0 + ); + } + Ok(()) + } + + #[tokio::test] + async fn test_integer_prefilter_memory_fallback_preserves_join() -> Result<()> { + use datafusion_execution::memory_pool::GreedyMemoryPool; + let make_join = || { + integer_prefilter_join( + Arc::new(Int32Array::from(vec![0, 2048])), + Arc::new(Int32Array::from(vec![0, 1, 2049])), + JoinType::Full, + NullEquality::NullEqualsNothing, + false, + PartitionMode::CollectLeft, + false, + ) + }; + // Measure mandatory build reservations, including the visited bitmap. + let baseline = make_join()?; + let expected = + crate::collect(Arc::clone(&baseline) as _, integer_prefilter_context(false)) + .await?; + let bytes = baseline + .metrics() + .unwrap() + .sum_by_name("build_mem_used") + .unwrap() + .as_usize(); + // Either only mandatory state fits, or the build bitmap fits but the + // additional probe masks do not. Both must preserve normal join output. + for bitmap_bytes in [0, 2049_usize.div_ceil(8)] { + let pool = Arc::new(GreedyMemoryPool::new(bytes + bitmap_bytes)); + let runtime = RuntimeEnvBuilder::new() + .with_memory_pool(Arc::clone(&pool) as _) + .build_arc()?; + let context = integer_prefilter_context(true); + let context = Arc::new( + TaskContext::default() + .with_session_config(context.session_config().clone()) + .with_runtime(runtime), + ); + let join = make_join()?; + let result = crate::collect(Arc::clone(&join) as _, context).await?; + assert_eq!( + batches_to_sort_string(&result), + batches_to_sort_string(&expected) + ); + let metrics = join.metrics().unwrap(); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_created_count") + .unwrap() + .as_usize(), + usize::from(bitmap_bytes > 0) + ); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_pruned_rows") + .unwrap() + .as_usize(), + 0 + ); + assert_eq!( + metrics.sum_by_name("build_mem_used").unwrap().as_usize(), + bytes + bitmap_bytes + ); + drop(join); + use datafusion_execution::memory_pool::MemoryPool; + assert_eq!(pool.reserved(), 0); + } + Ok(()) + } + + #[tokio::test] + async fn test_integer_prefilter_shared_build() -> Result<()> { + let schema = + Arc::new(Schema::new(vec![Field::new("key", DataType::Int32, false)])); + let hits = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from(vec![0; 12]))], + )?; + let misses = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from(vec![1; 12]))], + )?; + let mut expected = None; + for enabled in [false, true] { + let build = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from(vec![0, 2048]))], + )?; + let left = + TestMemoryExec::try_new_exec(&[vec![build]], Arc::clone(&schema), None)?; + // Partition 0 pauses on hits; partition 1 must independently prune. + let right = TestMemoryExec::try_new_exec( + &[vec![hits.clone()], vec![misses.clone()]], + Arc::clone(&schema), + None, + )?; + let on = vec![(col("key", &schema)?, col("key", &schema)?)]; + let join = Arc::new(HashJoinExec::try_new( + left, + right, + on, + None, + &JoinType::Full, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, + )?); + let result = crate::collect( + Arc::clone(&join) as _, + integer_prefilter_context(enabled), + ) + .await?; + let output = batches_to_sort_string(&result); + if enabled { + assert_eq!(&output, expected.as_ref().unwrap()); + let metrics = join.metrics().unwrap(); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_created_count") + .unwrap() + .as_usize(), + 1 + ); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_pruned_rows") + .unwrap() + .as_usize(), + 12 + ); + } else { + expected = Some(output); + } + } + Ok(()) + } + fn assert_phj_used(metrics: &MetricsSet, use_phj: bool) { if use_phj { assert!( @@ -3058,7 +3544,7 @@ mod tests { use datafusion_execution::config::SessionConfig; use datafusion_execution::runtime_env::RuntimeEnvBuilder; use datafusion_expr::Operator; - use datafusion_physical_expr::expressions::{BinaryExpr, Literal}; + use datafusion_physical_expr::expressions::{BinaryExpr, Literal, col}; use datafusion_physical_expr::{ EquivalenceProperties, PhysicalSortExpr, RangePartitioning, SplitPoint, }; diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index 2c1ad94460540..7590209ab0b54 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -32,7 +32,9 @@ use crate::joins::hash_join::exec::{JoinLeftData, NullAwareMode}; use crate::joins::hash_join::shared_bounds::{ PartitionBounds, PartitionBuildData, SharedBuildAccumulator, }; +use crate::joins::integer_prefilter::PrefilterState; use crate::joins::utils::{OnceFut, equal_rows_arr, matchable_join_keys}; +use crate::metrics::Count; use crate::stream::EmptyRecordBatchStream; use crate::{ RecordBatchStream, SendableRecordBatchStream, handle_state, @@ -53,6 +55,7 @@ use arrow::record_batch::RecordBatch; use datafusion_common::{ JoinSide, JoinType, NullEquality, Result, internal_datafusion_err, internal_err, }; +use datafusion_execution::memory_pool::MemoryReservation; use datafusion_physical_expr::PhysicalExprRef; use datafusion_common::hash_utils::RandomState; @@ -184,6 +187,8 @@ pub(super) struct ProcessProbeBatchState { /// exist and cannot match (`NullEquality::NullEqualsNothing`); NULL rows /// are skipped during JoinHashMap lookups valid_keys: Option, + /// Original validity combined with integer membership, for lookup only. + lookup_keys: Option, /// Starting offset for JoinHashMap lookups offset: MapOffset, /// Max joined probe-side index from current batch @@ -345,6 +350,8 @@ pub(super) struct HashJoinStream { random_state: RandomState, /// Metrics join_metrics: BuildProbeJoinMetrics, + integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, + integer_prefilter_pruned_rows: Count, /// Information of index and left / right placement of columns column_indices: Vec, /// Defines the null equality for the join. @@ -533,6 +540,8 @@ impl HashJoinStream { mode: PartitionMode, null_aware: Option, fetch: Option, + integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, + integer_prefilter_pruned_rows: Count, ) -> Self { // Create output buffer with coalescing and optional fetch limit. let output_buffer = @@ -547,6 +556,8 @@ impl HashJoinStream { right, random_state, join_metrics, + integer_prefilter_state, + integer_prefilter_pruned_rows, column_indices, null_equality, state, @@ -744,6 +755,10 @@ impl HashJoinStream { &mut self, cx: &mut std::task::Context<'_>, ) -> Poll>>> { + // The previous batch's lookup mask has been released with its state. + if let Some((_, reservation)) = &self.integer_prefilter_state { + reservation.free(); + } match ready!(self.right.poll_next_unpin(cx)) { None => { // Release the probe-side input pipeline's resources. The schema @@ -772,6 +787,51 @@ impl HashJoinStream { None }; + let lookup_keys = if let (Some((state, reservation)), Some(filter)) = ( + self.integer_prefilter_state.as_mut(), + self.build_side + .try_as_ready()? + .left_data + .integer_prefilter + .as_ref(), + ) { + let timer = self.join_metrics.join_time.timer(); + let bytes = PrefilterState::mask_memory_size( + batch.num_rows(), + valid_keys.is_some(), + ); + let lookup_keys = if bytes + .is_some_and(|bytes| reservation.try_resize(bytes).is_ok()) + { + let (mask, pruned) = state.filter( + filter, + keys_values[0].as_ref(), + valid_keys.as_ref(), + ); + self.integer_prefilter_pruned_rows.add(pruned); + if mask.is_some() { + let lookup = + NullBuffer::union(valid_keys.as_ref(), mask.as_ref()); + drop(mask); + reservation.resize( + lookup + .as_ref() + .map_or(0, |mask| mask.inner().inner().capacity()), + ); + lookup + } else { + reservation.free(); + valid_keys.clone() + } + } else { + valid_keys.clone() + }; + timer.done(); + lookup_keys + } else { + valid_keys.clone() + }; + self.join_metrics.input_batches.add(1); self.join_metrics.input_rows.add(batch.num_rows()); @@ -780,6 +840,7 @@ impl HashJoinStream { batch, values: keys_values, valid_keys, + lookup_keys, offset: (0, None), joined_probe_idx: None, }); @@ -864,7 +925,7 @@ impl HashJoinStream { &state.values, self.null_equality, &self.hashes_buffer, - state.valid_keys.as_ref(), + state.lookup_keys.as_ref(), self.batch_size, state.offset, &mut self.probe_indices_buffer, diff --git a/datafusion/physical-plan/src/joins/integer_prefilter.rs b/datafusion/physical-plan/src/joins/integer_prefilter.rs new file mode 100644 index 0000000000000..c69aab69f304a --- /dev/null +++ b/datafusion/physical-plan/src/joins/integer_prefilter.rs @@ -0,0 +1,518 @@ +// 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. + +//! Exact membership filtering for a single integer hash join key. +//! +//! This only avoids hash table lookups. Probe rows remain in their original +//! batch so outer, anti and mark joins can still produce unmatched results. + +use arrow::array::Array; +use arrow::array::downcast_integer_array; +use arrow::buffer::{BooleanBuffer, NullBuffer}; +use datafusion_common::config::ExecutionOptions; +use datafusion_common::{NullEquality, Result, ScalarValue, config_err}; +use datafusion_execution::memory_pool::MemoryReservation; + +/// One bit per integer in the build key range, shared by all probe streams. +#[derive(Debug)] +pub(super) struct IntegerPrefilter { + bits: Vec, + min: u64, + range: usize, + null_matches: bool, +} + +impl IntegerPrefilter { + /// Uses already computed build bounds. Failure to reserve this optional + /// allocation leaves the normal hash join available. + pub(super) fn try_new( + values: &dyn Array, + bounds: (&ScalarValue, &ScalarValue), + max_key_range: usize, + null_equality: NullEquality, + reservation: &MemoryReservation, + ) -> Option { + if !values.data_type().is_integer() { + return None; + } + let min = integer_value(bounds.0)?; + let max = integer_value(bounds.1)?; + let range = usize::try_from(max - min).ok()?.checked_add(1)?; + if range > max_key_range { + return None; + } + let bytes = range.div_ceil(8); + reservation.try_grow(bytes).ok()?; + let mut bits = Vec::new(); + if bits.try_reserve_exact(bytes).is_err() { + reservation.shrink(bytes); + return None; + } + let extra = bits.capacity() - bytes; + if reservation.try_grow(extra).is_err() { + reservation.shrink(bytes); + return None; + } + bits.resize(bytes, 0); + downcast_integer_array!(values => { + for value in values.iter().flatten() { + let offset = (i128::from(value) - min) as usize; + bits[offset / 8] |= 1 << (offset % 8); + } + } + _ => unreachable!("integer type checked above")); + Some(Self { + bits, + min: min as u64, + range, + null_matches: null_equality == NullEquality::NullEqualsNull + && values.null_count() > 0, + }) + } + + pub(super) fn size(&self) -> usize { + self.bits.capacity() + } + + #[inline] + fn contains(&self, value: u64) -> bool { + // Build range validation uses i128. Here, same-type integer keys can + // use wrapping offsets: values below min wrap beyond the valid range, + // including signed keys whose range crosses zero. + let offset = value.wrapping_sub(self.min); + offset < self.range as u64 + && self.bits[offset as usize / 8] & (1 << (offset as usize % 8)) != 0 + } +} + +fn integer_value(value: &ScalarValue) -> Option { + match value { + ScalarValue::Int8(v) => v.map(i128::from), + ScalarValue::Int16(v) => v.map(i128::from), + ScalarValue::Int32(v) => v.map(i128::from), + ScalarValue::Int64(v) => v.map(i128::from), + ScalarValue::UInt8(v) => v.map(i128::from), + ScalarValue::UInt16(v) => v.map(i128::from), + ScalarValue::UInt32(v) => v.map(i128::from), + ScalarValue::UInt64(v) => v.map(i128::from), + _ => None, + } +} + +/// Each probe stream independently measures additional skipped lookups. +/// Windows end at batch boundaries after at least `sample_rows` input rows, +/// including already invalid keys. Savings only count eligible lookups. +/// Unprofitable windows pause filtering for eight windows of input rows, +/// then retry to accommodate changing probe distributions. +#[derive(Debug)] +pub(super) struct PrefilterState { + sample_rows: usize, + min_pruning_ratio: f64, + scanned_rows: usize, + eligible_rows: usize, + pruned_rows: usize, + skip_rows: usize, +} + +impl PrefilterState { + fn new(sample_rows: usize, min_pruning_ratio: f64) -> Self { + Self { + sample_rows, + min_pruning_ratio, + scanned_rows: 0, + eligible_rows: 0, + pruned_rows: 0, + skip_rows: 0, + } + } + + pub(super) fn try_from_config(config: &ExecutionOptions) -> Result> { + if !config.enable_join_integer_prefilter { + return Ok(None); + } + if config.join_integer_prefilter_max_key_range == 0 { + return config_err!( + "join_integer_prefilter_max_key_range must be greater than zero" + ); + } + if config.join_integer_prefilter_sample_rows == 0 { + return config_err!( + "join_integer_prefilter_sample_rows must be greater than zero" + ); + } + let ratio = config.join_integer_prefilter_min_pruning_ratio; + if !(0.0..=1.0).contains(&ratio) { + return config_err!( + "join_integer_prefilter_min_pruning_ratio must be finite and in [0, 1]" + ); + } + Ok(Some(Self::new( + config.join_integer_prefilter_sample_rows, + ratio, + ))) + } + + /// Upper bound for simultaneously live membership and combined masks. + /// A bitmap union with differing bit offsets may double its allocation + /// when appending a partial word. No union allocation is needed without NULLs. + pub(super) fn mask_memory_size(rows: usize, has_validity: bool) -> Option { + rows.div_ceil(8) + .checked_next_multiple_of(64)? + .checked_mul(if has_validity { 3 } else { 1 }) + } + + /// Returns the additional lookup mask and number of newly excluded rows. + /// Already invalid keys stay set here: the caller combines this mask with + /// the original validity without counting those keys as prefilter savings. + pub(super) fn filter( + &mut self, + filter: &IntegerPrefilter, + values: &dyn Array, + valid_keys: Option<&NullBuffer>, + ) -> (Option, usize) { + if self.skip_rows > 0 { + self.skip_rows = self.skip_rows.saturating_sub(values.len()); + return (None, 0); + } + let eligible_rows = values.len() - valid_keys.map_or(0, NullBuffer::null_count); + if eligible_rows == 0 { + self.record_sample(values.len(), 0, 0); + return (None, 0); + } + let mask = downcast_integer_array!(values => { + if values.null_count() == 0 && valid_keys.is_none() { + let values = values.values(); + BooleanBuffer::collect_bool(values.len(), |i| { + filter.contains(values[i] as u64) + }) + } else { + BooleanBuffer::collect_bool(values.len(), |i| { + if valid_keys.is_some_and(|valid| valid.is_null(i)) { + return true; + } + if values.is_null(i) { + filter.null_matches + } else { + filter.contains(values.value(i) as u64) + } + }) + } + } + _ => return (None, 0)); + let mask = NullBuffer::new(mask); + let pruned = mask.null_count(); + self.record_sample(values.len(), eligible_rows, pruned); + ((pruned > 0).then_some(mask), pruned) + } + + fn record_sample( + &mut self, + scanned_rows: usize, + eligible_rows: usize, + pruned: usize, + ) { + self.scanned_rows = self.scanned_rows.saturating_add(scanned_rows); + self.eligible_rows = self.eligible_rows.saturating_add(eligible_rows); + self.pruned_rows = self.pruned_rows.saturating_add(pruned); + if self.scanned_rows >= self.sample_rows { + if self.eligible_rows == 0 + || (self.pruned_rows as f64) + < self.min_pruning_ratio * self.eligible_rows as f64 + { + self.skip_rows = self.sample_rows.saturating_mul(8); + } + self.scanned_rows = 0; + self.eligible_rows = 0; + self.pruned_rows = 0; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use arrow::array::{ + Int8Array, Int16Array, Int32Array, Int64Array, UInt8Array, UInt16Array, + UInt32Array, UInt64Array, + }; + use datafusion_execution::memory_pool::{ + GreedyMemoryPool, MemoryConsumer, MemoryPool, + }; + use std::sync::Arc; + + fn reservation(limit: usize) -> MemoryReservation { + let pool: Arc = Arc::new(GreedyMemoryPool::new(limit)); + MemoryConsumer::new("integer prefilter test").register(&pool) + } + + #[test] + fn membership_and_integer_boundaries() { + macro_rules! check { + ($array:ty, $scalar:ident, $min:expr) => {{ + let min = $min; + let build = + <$array>::from(vec![Some(min), Some(min + 2), Some(min), None]); + let memory = reservation(1); + let filter = IntegerPrefilter::try_new( + &build, + ( + &ScalarValue::$scalar(Some(min)), + &ScalarValue::$scalar(Some(min + 2)), + ), + 3, + NullEquality::NullEqualsNothing, + &memory, + ) + .unwrap(); + assert_eq!(memory.size(), 1); + assert!(!filter.contains((min as u64).wrapping_sub(1))); + let probe = <$array>::from(vec![ + None, + Some(min), + Some(min + 1), + Some(min + 2), + Some(min + 3), + ]); + let valid = probe.nulls(); + let (mask, pruned) = + PrefilterState::new(10, 0.5).filter(&filter, &probe, valid); + assert_eq!(pruned, 2); + let mask = NullBuffer::union(valid, mask.as_ref()).unwrap(); + assert_eq!( + mask.iter().collect::>(), + vec![false, true, false, true, false] + ); + }}; + } + check!(Int8Array, Int8, i8::MIN); + check!(Int16Array, Int16, i16::MIN); + check!(Int32Array, Int32, -1_i32); + check!(Int64Array, Int64, i64::MIN); + check!(Int64Array, Int64, i64::MAX - 3); + check!(UInt8Array, UInt8, 0_u8); + check!(UInt16Array, UInt16, 0_u16); + check!(UInt32Array, UInt32, 0_u32); + check!(UInt64Array, UInt64, u64::MAX - 3); + } + + #[test] + fn null_equals_null() { + for has_null in [false, true] { + let build = if has_null { + Int32Array::from(vec![Some(1), None]) + } else { + Int32Array::from(vec![1]) + }; + let memory = reservation(1); + let filter = IntegerPrefilter::try_new( + &build, + (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), + 1, + NullEquality::NullEqualsNull, + &memory, + ) + .unwrap(); + let probe = Int32Array::from(vec![None, Some(1), Some(2)]); + let (mask, count) = + PrefilterState::new(10, 0.5).filter(&filter, &probe, None); + assert_eq!(count, if has_null { 1 } else { 2 }); + assert_eq!( + mask.unwrap().iter().collect::>(), + vec![has_null, true, false] + ); + } + } + + #[test] + fn range_and_memory_fallback() { + let build = Int64Array::from(vec![i64::MIN, i64::MAX]); + let memory = reservation(1024); + assert!( + IntegerPrefilter::try_new( + &build, + ( + &ScalarValue::Int64(Some(i64::MIN)), + &ScalarValue::Int64(Some(i64::MAX)) + ), + usize::MAX, + NullEquality::NullEqualsNothing, + &memory + ) + .is_none() + ); + assert_eq!(memory.size(), 0); + let build = UInt64Array::from(vec![0, u64::MAX]); + assert!( + IntegerPrefilter::try_new( + &build, + ( + &ScalarValue::UInt64(Some(0)), + &ScalarValue::UInt64(Some(u64::MAX)) + ), + usize::MAX, + NullEquality::NullEqualsNothing, + &memory + ) + .is_none() + ); + let build = Int32Array::from(vec![0, 8]); + let bounds = (ScalarValue::Int32(Some(0)), ScalarValue::Int32(Some(8))); + assert!( + IntegerPrefilter::try_new( + &build, + (&bounds.0, &bounds.1), + 8, + NullEquality::NullEqualsNothing, + &memory + ) + .is_none() + ); + let memory = reservation(1); + memory.try_grow(1).unwrap(); + assert!( + IntegerPrefilter::try_new( + &build, + (&bounds.0, &bounds.1), + 9, + NullEquality::NullEqualsNothing, + &memory + ) + .is_none() + ); + assert_eq!(memory.size(), 1, "existing reservations must be preserved"); + } + + #[test] + fn sampling_pauses_retries_and_ignores_invalid_keys() { + let memory = reservation(1); + let filter = IntegerPrefilter::try_new( + &Int32Array::from(vec![1]), + (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), + 1, + NullEquality::NullEqualsNothing, + &memory, + ) + .unwrap(); + let mut state = PrefilterState::new(8, 0.5); + let hits = Int32Array::from(vec![Some(1), None, None, None]); + // Both batches consume the scan budget even though only two keys are + // eligible for lookup. NULLs must not prolong an unprofitable sample. + assert_eq!(state.filter(&filter, &hits, hits.nulls()).1, 0); + assert_eq!(state.skip_rows, 0); + state.filter(&filter, &hits, hits.nulls()); + assert_eq!(state.skip_rows, 64); + let misses = Int32Array::from(vec![2; 4]); + for _ in 0..16 { + assert_eq!(state.filter(&filter, &misses, None).1, 0); + } + // Savings use eligible lookups, not scanned rows: eliminating both + // eligible keys is profitable even with six NULLs in the window. + let sparse_misses = Int32Array::from(vec![Some(2), None, None, None]); + for _ in 0..2 { + let (mask, pruned) = + state.filter(&filter, &sparse_misses, sparse_misses.nulls()); + assert_eq!(pruned, 1); + assert_eq!( + mask.unwrap().iter().collect::>(), + vec![false, true, true, true] + ); + } + assert_eq!(state.skip_rows, 0); + // Re-evaluate even after a profitable window. + assert!( + state + .filter(&filter, &Int32Array::from(vec![1; 8]), None) + .0 + .is_none() + ); + assert_eq!(state.skip_rows, 64); + } + + #[test] + fn sampling_without_eligible_keys_pauses() { + let memory = reservation(1); + let filter = IntegerPrefilter::try_new( + &Int32Array::from(vec![1]), + (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), + 1, + NullEquality::NullEqualsNothing, + &memory, + ) + .unwrap(); + let mut state = PrefilterState::new(4, 0.5); + let empty = Int32Array::from(Vec::::new()); + assert_eq!(state.filter(&filter, &empty, None), (None, 0)); + assert_eq!(state.skip_rows, 0); + let nulls = Int32Array::from(vec![None; 4]); + assert_eq!(state.filter(&filter, &nulls, nulls.nulls()), (None, 0)); + assert_eq!(state.skip_rows, 32); + } + + #[test] + fn sliced_validity_mask_memory() { + // A trailing partial word forces Arrow's differently aligned bitmap + // union to grow. Account for both allocations while they coexist. + let rows = 8193; + let values = Int32Array::from_iter( + (0..=rows).map(|i| (i % 3 != 0).then_some((i % 2) as i32)), + ) + .slice(1, rows); + let memory = reservation(1); + let filter = IntegerPrefilter::try_new( + &Int32Array::from(vec![0]), + (&ScalarValue::Int32(Some(0)), &ScalarValue::Int32(Some(0))), + 1, + NullEquality::NullEqualsNothing, + &memory, + ) + .unwrap(); + let (mask, pruned) = + PrefilterState::new(rows, 0.5).filter(&filter, &values, values.nulls()); + let mask = mask.unwrap(); + let lookup = NullBuffer::union(values.nulls(), Some(&mask)).unwrap(); + let peak = mask.inner().inner().capacity() + lookup.inner().inner().capacity(); + assert!(peak <= PrefilterState::mask_memory_size(rows, true).unwrap()); + assert_eq!(pruned, values.iter().filter(|v| *v == Some(1)).count()); + assert_eq!( + lookup.iter().collect::>(), + values.iter().map(|v| v == Some(0)).collect::>() + ); + } + + #[test] + fn validates_configuration_only_when_enabled() { + let mut config = ExecutionOptions { + join_integer_prefilter_sample_rows: 0, + ..Default::default() + }; + assert!(PrefilterState::try_from_config(&config).unwrap().is_none()); + config.enable_join_integer_prefilter = true; + assert!(PrefilterState::try_from_config(&config).is_err()); + config.join_integer_prefilter_sample_rows = 1; + config.join_integer_prefilter_max_key_range = 0; + assert!(PrefilterState::try_from_config(&config).is_err()); + config.join_integer_prefilter_max_key_range = 1; + for ratio in [f64::NAN, f64::INFINITY, -0.1, 1.1] { + config.join_integer_prefilter_min_pruning_ratio = ratio; + assert!(PrefilterState::try_from_config(&config).is_err()); + } + for ratio in [0.0, 0.5, 1.0] { + config.join_integer_prefilter_min_pruning_ratio = ratio; + assert!(PrefilterState::try_from_config(&config).unwrap().is_some()); + } + } +} diff --git a/datafusion/physical-plan/src/joins/mod.rs b/datafusion/physical-plan/src/joins/mod.rs index 84de98902d2bf..bb64db77f9616 100644 --- a/datafusion/physical-plan/src/joins/mod.rs +++ b/datafusion/physical-plan/src/joins/mod.rs @@ -37,6 +37,7 @@ mod asof_join; pub mod chain; mod cross_join; mod hash_join; +mod integer_prefilter; mod nested_loop_join; mod piecewise_merge_join; #[cfg(feature = "proto")] diff --git a/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt b/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt new file mode 100644 index 0000000000000..b98c16062994d --- /dev/null +++ b/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt @@ -0,0 +1,230 @@ +# 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. + +# Exercise the integer prefilter inside HashJoin, including probe rows that +# skip lookup but must still contribute to outer, anti, and mark join output. +# Sparse keys avoid the existing ArrayMap path. Keep the SQL build/probe order +# and prevent dynamic filters from removing probe rows before HashJoin sees them. +statement ok +SET datafusion.execution.target_partitions = 1; + +statement ok +SET datafusion.optimizer.join_reordering = false; + +statement ok +SET datafusion.optimizer.enable_join_dynamic_filter_pushdown = false; + +statement ok +SET datafusion.explain.analyze_categories = 'rows,uncategorized'; + +statement ok +SET datafusion.catalog.information_schema = true; + +query TT rowsort +SELECT name, value FROM information_schema.df_settings +WHERE name LIKE 'datafusion.execution.%join_integer_prefilter%'; +---- +datafusion.execution.enable_join_integer_prefilter false +datafusion.execution.join_integer_prefilter_max_key_range 262144 +datafusion.execution.join_integer_prefilter_min_pruning_ratio 0.5 +datafusion.execution.join_integer_prefilter_sample_rows 12288 + +statement ok +CREATE TABLE build(k INT, label VARCHAR) AS VALUES + (NULL, 'build_null'), (0, 'zero_a'), (0, 'zero_b'), (2048, 'build_only'); + +statement ok +CREATE TABLE probe(k INT, label VARCHAR) AS VALUES + (NULL, 'probe_null'), (-1, 'below'), (0, 'hit_a'), + (1, 'gap'), (3000, 'above'), (0, 'hit_b'); + +# Baseline: duplicate matches and unmatched rows on both sides. +query TT rowsort +SELECT b.label, p.label FROM build b FULL JOIN probe p ON b.k = p.k; +---- +NULL above +NULL below +NULL gap +NULL probe_null +build_null NULL +build_only NULL +zero_a hit_a +zero_a hit_b +zero_b hit_a +zero_b hit_b + +statement ok +SET datafusion.execution.enable_join_integer_prefilter = true; + +# The bitmap is created and rejects below-range, in-range-gap, and above-range +# keys. The NULL probe key is already invalid for equality and is not counted. +# These three rejected rows must remain in the full join's output. +query TT +EXPLAIN ANALYZE SELECT * FROM build b FULL JOIN probe p ON b.k = p.k; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=1, integer_prefilter_pruned_rows=3, ] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] + +query TT rowsort +SELECT b.label, p.label FROM build b FULL JOIN probe p ON b.k = p.k; +---- +NULL above +NULL below +NULL gap +NULL probe_null +build_null NULL +build_only NULL +zero_a hit_a +zero_a hit_b +zero_b hit_a +zero_b hit_b + +query TT rowsort +SELECT b.label, p.label FROM build b JOIN probe p ON b.k = p.k; +---- +zero_a hit_a +zero_a hit_b +zero_b hit_a +zero_b hit_b + +# NULL equality must still look up the build-side NULL. +query TT rowsort +SELECT b.label, p.label FROM build b JOIN probe p +ON b.k IS NOT DISTINCT FROM p.k; +---- +build_null probe_null +zero_a hit_a +zero_a hit_b +zero_b hit_a +zero_b hit_b + +# Anti joins retain rejected probe rows and unmatched build rows respectively. +query T rowsort +SELECT p.label FROM build b RIGHT ANTI JOIN probe p ON b.k = p.k; +---- +above +below +gap +probe_null + +query T rowsort +SELECT b.label FROM build b LEFT ANTI JOIN probe p ON b.k = p.k; +---- +build_null +build_only + +query T rowsort +SELECT p.label FROM build b RIGHT SEMI JOIN probe p ON b.k = p.k; +---- +hit_a +hit_b + +# IS NULL around IN requires a null-aware mark join. The rejected 2048 key on +# its probe side must not change SQL's three-valued result. +query TT +EXPLAIN ANALYZE SELECT p.label FROM probe p +WHERE (p.k IN (SELECT k FROM build)) IS NULL; +---- +Plan with Metrics +HashJoinExec: mode=CollectLeft, join_type=LeftMark, on=[(k@0, k@0)], null_aware, metrics=[output_rows=6, array_map_created_count=0, integer_prefilter_created_count=1, integer_prefilter_pruned_rows=1, ] + + +query T rowsort +SELECT p.label FROM probe p WHERE (p.k IN (SELECT k FROM build)) IS NULL; +---- +above +below +gap +probe_null + +query T rowsort +SELECT p.label FROM probe p +WHERE (p.k IN (SELECT k FROM build WHERE k IS NOT NULL)) IS NULL; +---- +probe_null + +query T rowsort +SELECT p.label FROM probe p +WHERE (p.k IN (SELECT k FROM build WHERE k IS NOT NULL)) IS FALSE; +---- +above +below +gap + +# NOT IN must not emit the misses when its subquery contains NULL. +query T rowsort +SELECT p.label FROM probe p WHERE p.k NOT IN (SELECT k FROM build); +---- + +query T rowsort +SELECT p.label FROM probe p +WHERE p.k NOT IN (SELECT k FROM build WHERE k IS NOT NULL); +---- +above +below +gap + +# max_key_range counts max - min + 1: 0..=2048 needs 2049 bits. A smaller +# configured limit falls back to the normal hash lookup with identical output. +statement ok +SET datafusion.execution.join_integer_prefilter_max_key_range = 2048; + +query TT +EXPLAIN ANALYZE SELECT * FROM build b FULL JOIN probe p ON b.k = p.k; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=0, integer_prefilter_pruned_rows=0, ] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] + +query TT rowsort +SELECT b.label, p.label FROM build b FULL JOIN probe p ON b.k = p.k; +---- +NULL above +NULL below +NULL gap +NULL probe_null +build_null NULL +build_only NULL +zero_a hit_a +zero_a hit_b +zero_b hit_a +zero_b hit_b + +statement ok +RESET datafusion.execution.enable_join_integer_prefilter; + +statement ok +RESET datafusion.execution.join_integer_prefilter_max_key_range; + +# The SLT runner starts with four partitions, rather than the CPU-count default. +statement ok +SET datafusion.execution.target_partitions = 4; + +statement ok +RESET datafusion.optimizer.join_reordering; + +statement ok +RESET datafusion.optimizer.enable_join_dynamic_filter_pushdown; + +statement ok +RESET datafusion.explain.analyze_categories; + +statement ok +RESET datafusion.catalog.information_schema; diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 16750d79d750d..259e9c6054d39 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -76,6 +76,10 @@ The following configuration settings are available: | datafusion.execution.batch_size | 8192 | Default batch size while creating new batches, it's especially useful for buffer-in-memory batches since creating tiny batches would result in too much metadata memory consumption | | datafusion.execution.perfect_hash_join_small_build_threshold | 1024 | A perfect hash join (see `HashJoinExec` for more details) will be considered if the range of keys (max - min) on the build side is < this threshold. This provides a fast path for joins with very small key ranges, bypassing the density check. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. | | datafusion.execution.perfect_hash_join_min_key_density | 0.15 | The minimum required density of join keys on the build side to consider a perfect hash join (see `HashJoinExec` for more details). Density is calculated as: `(number of rows) / (max_key - min_key + 1)`. A perfect hash join may be used if the actual key density > this value. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. | +| datafusion.execution.enable_join_integer_prefilter | false | Enable an exact integer membership prefilter for hash joins with a single integer key when the build side uses a hash table. It skips lookups for absent keys while retaining probe rows for unmatched join output. | +| datafusion.execution.join_integer_prefilter_max_key_range | 262144 | Maximum number of integer values covered by the join prefilter bitmap (`max_key - min_key + 1`). Must be greater than zero when enabled. Larger ranges fall back to normal hash table lookups. | +| datafusion.execution.join_integer_prefilter_min_pruning_ratio | 0.5 | Minimum fraction of otherwise eligible hash lookups the integer prefilter must eliminate to keep filtering. Must be finite and in [0, 1]. Unprofitable samples pause filtering, then periodically retry. | +| datafusion.execution.join_integer_prefilter_sample_rows | 12288 | Minimum input probe rows in each integer prefilter sampling window, including NULLs. Pruning ratios only count otherwise eligible lookups. Must be greater than zero when enabled. Windows end at batch boundaries; unprofitable windows pause filtering for eight times this many input rows before retrying at the next batch boundary. | | datafusion.execution.coalesce_batches | true | When set to true, record batches will be examined between each operator and small batches will be coalesced into larger batches. This is helpful when there are highly selective filters or joins that could produce tiny output batches. The target batch size is determined by the configuration setting | | datafusion.execution.collect_statistics | true | Should DataFusion collect statistics when first creating a table. Has no effect after the table is created. Defaults to true. | | datafusion.execution.target_partitions | 0 | Number of partitions for query execution. Increasing partitions can increase concurrency. Defaults to the number of CPU cores on the system | From afde22bc2a3ba8a32252eba0aeb84a54531d801e Mon Sep 17 00:00:00 2001 From: linfeng Date: Tue, 15 Sep 2026 23:24:04 +0800 Subject: [PATCH 2/3] perf: align hash join integer prefilter and benchmarks Use a shared word bitmap that retains NULL keys and applies membership only to hash lookups. Count all observed rows when deciding whether to pause, with bounded exponential backoff. Align configuration types and metrics while preserving optional memory accounting and fallback. Standardize the 13 payload-bearing benchmark workloads and extend join, projection, fetch, and SQL regression coverage. --- datafusion/common/src/config.rs | 25 +- .../physical-plan/benches/hash_join_probe.rs | 343 ++++++-------- .../physical-plan/src/joins/hash_join/exec.rs | 237 +--------- .../src/joins/hash_join/stream.rs | 23 +- .../src/joins/integer_prefilter.rs | 433 ++++++++---------- .../hash_join_integer_prefilter.slt | 22 +- docs/source/user-guide/configs.md | 8 +- 7 files changed, 399 insertions(+), 692 deletions(-) diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 9b9db7bfeda41..5607e1dd5744a 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -923,26 +923,27 @@ config_namespace! { pub perfect_hash_join_min_key_density: f64, default = 0.15 /// Enable an exact integer membership prefilter for hash joins with a single - /// integer key when the build side uses a hash table. It skips lookups for - /// absent keys while retaining probe rows for unmatched join output. + /// integer key when the build side uses a hash table and the join is not + /// null-aware. It skips lookups for absent keys while retaining NULLs and + /// probe rows for the original join logic. pub enable_join_integer_prefilter: bool, default = false /// Maximum number of integer values covered by the join prefilter bitmap - /// (`max_key - min_key + 1`). Must be greater than zero when enabled. + /// (`max_key - min_key + 1`). Zero disables bitmap construction. /// Larger ranges fall back to normal hash table lookups. - pub join_integer_prefilter_max_key_range: usize, default = 262144 + pub join_integer_prefilter_max_key_range: u64, default = 262144 - /// Minimum fraction of otherwise eligible hash lookups the integer prefilter - /// must eliminate to keep filtering. Must be finite and in [0, 1]. - /// Unprofitable samples pause filtering, then periodically retry. + /// The integer prefilter must prune more than this fraction of all sampled + /// probe rows, including NULLs, to keep filtering. Must be finite and in + /// [0, 1], validated when executing the join. pub join_integer_prefilter_min_pruning_ratio: f64, default = 0.5 /// Minimum input probe rows in each integer prefilter sampling window, - /// including NULLs. Pruning ratios only count otherwise eligible lookups. - /// Must be greater than zero when enabled. Windows end at batch boundaries; - /// unprofitable windows pause filtering for eight times this many input rows - /// before retrying at the next batch boundary. - pub join_integer_prefilter_sample_rows: usize, default = 12288 + /// including NULLs. Must be greater than zero. Windows end at batch boundaries. + /// Unprofitable samples initially pause for 10 times this many input rows; + /// consecutive failures double the pause up to 128 times. A profitable + /// sample resets the pause to 10 times this many rows. + pub join_integer_prefilter_sample_rows: ConfigNonZeroUsize, default = non_zero_usize_default(12288) /// When set to true, record batches will be examined between each operator and /// small batches will be coalesced into larger batches. This is helpful when there diff --git a/datafusion/physical-plan/benches/hash_join_probe.rs b/datafusion/physical-plan/benches/hash_join_probe.rs index eb6a6fa4e6b7e..ddd853c1df463 100644 --- a/datafusion/physical-plan/benches/hash_join_probe.rs +++ b/datafusion/physical-plan/benches/hash_join_probe.rs @@ -16,116 +16,115 @@ // under the License. //! Full in-memory HashJoin execution, including build, with fixed Int32 workloads. -//! Covers inner, semi, and anti joins with key-only and payload-bearing inputs. +//! All inputs carry an Int32 data column and a Utf8 payload column. //! Session settings use the standard DataFusion environment configuration. use std::hint::black_box; use std::sync::Arc; -use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray}; +use arrow::array::{ArrayRef, Int32Array, StringArray}; use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; use arrow::record_batch::RecordBatch; -use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; +use criterion::{Criterion, criterion_group, criterion_main}; use datafusion_common::{JoinType, NullEquality}; use datafusion_execution::TaskContext; use datafusion_execution::config::SessionConfig; use datafusion_physical_expr::expressions::col; -use datafusion_physical_plan::ExecutionPlan; use datafusion_physical_plan::joins::{HashJoinExec, PartitionMode}; use datafusion_physical_plan::test::TestMemoryExec; -use futures::StreamExt; +use datafusion_physical_plan::{ExecutionPlan, collect}; use tokio::runtime::Runtime; -const BUILD_ROWS: usize = 8_192; -const PROBE_ROWS: usize = 1_048_576; const BATCH_SIZE: usize = 8_192; -const SHORT_PROBE_ROWS: usize = 4_096; -const PHASE_ROWS: usize = PROBE_ROWS / 2; -const HIT_EVERY: usize = 16; -const SPARSE_KEY_STEP: i32 = 16; +const BUILD_ROWS: usize = 20_000; +const PROBE_ROWS: usize = 1_000_000; +const LARGE_BUILD_ROWS: usize = 100_000; +const SPARSE_KEY_STEP: i32 = 10; const DENSE_KEY_STEP: i32 = 1; -const WIDE_KEY_STEP: i32 = 64; -const NON_NULL_EVERY: usize = 1_024; -const PAYLOAD_BYTES: usize = 64; +const HIT_EVERY: usize = 10; #[derive(Clone, Copy)] enum Pattern { AllHit, - InRange, - OutOfRange, + InterleavedLowHit, + ClusteredLowHit, HighToLow, - LowToHigh, - ShortProbe, - NullHeavyHits, - NullHeavyMisses, } fn make_batches( rows: usize, + build_rows: usize, key_step: i32, pattern: Pattern, schema: &SchemaRef, ) -> Vec { + let mut hits = 0; (0..rows) .step_by(BATCH_SIZE) .map(|start| { let end = (start + BATCH_SIZE).min(rows); - let keys = Int32Array::from_iter((start..end).map(|row| { - if matches!(pattern, Pattern::NullHeavyHits | Pattern::NullHeavyMisses) { - return (row % NON_NULL_EVERY == 0).then(|| { - (row % (BUILD_ROWS - 1)) as i32 * key_step - + i32::from(matches!(pattern, Pattern::NullHeavyMisses)) - }); - } - let high_hit = match pattern { + let keys = Int32Array::from_iter_values((start..end).map(|row| { + let hit = match pattern { Pattern::AllHit => true, - Pattern::HighToLow => row < PHASE_ROWS, - Pattern::LowToHigh => row >= PHASE_ROWS, - _ => false, + Pattern::InterleavedLowHit => row % HIT_EVERY == 0, + Pattern::ClusteredLowHit => row < rows / HIT_EVERY, + Pattern::HighToLow => row < rows / 2 || row % HIT_EVERY == 0, }; - Some(if high_hit || row % HIT_EVERY == 0 { - (row % BUILD_ROWS) as i32 * key_step - } else if matches!(pattern, Pattern::OutOfRange) { - (BUILD_ROWS + row % BUILD_ROWS) as i32 * key_step + if hit { + let key = (hits % build_rows) as i32 * key_step; + hits += 1; + key } else { // Every hole stays strictly between the build min and max. - (row % (BUILD_ROWS - 1)) as i32 * key_step + 1 - }) + (row % (build_rows - 1)) as i32 * key_step + 1 + } })); - let mut columns: Vec = vec![Arc::new(keys)]; - if schema.fields().len() > 1 { - columns.push(Arc::new(Int64Array::from_iter_values( - (start..end).map(|row| row as i64), - ))); - columns.push(Arc::new(StringArray::from_iter_values( - (start..end).map(|row| format!("{row:0PAYLOAD_BYTES$}")), - ))); - } + let columns: Vec = vec![ + Arc::new(keys), + Arc::new(Int32Array::from_iter_values( + (start..end).map(|row| row as i32), + )), + Arc::new(StringArray::from_iter_values( + (start..end).map(|row| format!("{row}")), + )), + ]; RecordBatch::try_new(Arc::clone(schema), columns).unwrap() }) .collect() } fn make_join( - build: &Arc, - probe: &Arc, + build_batches: &[RecordBatch], + probe_batches: &[RecordBatch], join_type: JoinType, -) -> HashJoinExec { - HashJoinExec::try_new( - Arc::clone(build), - Arc::clone(probe), - vec![( - col("key", &build.schema()).unwrap(), - col("key", &probe.schema()).unwrap(), - )], +) -> Arc { + let schema = build_batches[0].schema(); + let build = TestMemoryExec::try_new_exec( + &[build_batches.to_vec()], + Arc::clone(&schema), None, - &join_type, + ) + .unwrap(); + let probe = TestMemoryExec::try_new_exec( + &[probe_batches.to_vec()], + Arc::clone(&schema), None, - PartitionMode::CollectLeft, - NullEquality::NullEqualsNothing, - false, ) - .unwrap() + .unwrap(); + Arc::new( + HashJoinExec::try_new( + build, + probe, + vec![(col("key", &schema).unwrap(), col("key", &schema).unwrap())], + None, + &join_type, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, + ) + .unwrap(), + ) } fn bench_hash_join_probe(c: &mut Criterion) { @@ -134,185 +133,147 @@ fn bench_hash_join_probe(c: &mut Criterion) { .unwrap() .with_batch_size(BATCH_SIZE); let context = Arc::new(TaskContext::default().with_session_config(config)); + let schema = Arc::new(Schema::new(vec![ + Field::new("key", DataType::Int32, false), + Field::new("data", DataType::Int32, false), + Field::new("payload", DataType::Utf8, false), + ])); let mut group = c.benchmark_group("hash_join_probe"); - // Default PHJ settings select ArrayMap only for the dense case. Sparse keys - // span 131,057 values; wide keys span 524,225. - for (name, pattern, key_step, join_type, with_payload) in [ + for (name, join_type, pattern, build_rows, probe_rows, key_step) in [ ( - "low_hit_in_range", - Pattern::InRange, - SPARSE_KEY_STEP, - JoinType::Inner, - false, - ), - ( - "low_hit_out_of_range", - Pattern::OutOfRange, + "right_semi_interleaved_10pct", + JoinType::RightSemi, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - false, ), ( - "high_to_low", - Pattern::HighToLow, + "right_semi_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - false, ), ( - "low_to_high", - Pattern::LowToHigh, + "right_anti_interleaved_10pct", + JoinType::RightAnti, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - false, ), ( - "all_hit", + "right_anti_all_hit", + JoinType::RightAnti, Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - false, - ), - ( - "short_probe", - Pattern::ShortProbe, - SPARSE_KEY_STEP, - JoinType::Inner, - false, ), ( - "dense", - Pattern::OutOfRange, - DENSE_KEY_STEP, + "inner_interleaved_10pct", JoinType::Inner, - false, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, ), ( - "wide_range", - Pattern::InRange, - WIDE_KEY_STEP, + "inner_all_hit", JoinType::Inner, - false, + Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, ), ( - "right_semi_low_hit", - Pattern::InRange, - SPARSE_KEY_STEP, + "right_semi_clustered_10pct", JoinType::RightSemi, - false, + Pattern::ClusteredLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, ), ( - "right_anti_low_hit", - Pattern::InRange, - SPARSE_KEY_STEP, + "right_anti_clustered_10pct", JoinType::RightAnti, - false, + Pattern::ClusteredLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, ), ( - "inner_low_hit_payload", - Pattern::InRange, + "right_semi_high_to_low", + JoinType::RightSemi, + Pattern::HighToLow, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - true, ), ( - "right_semi_low_hit_payload", - Pattern::InRange, + "right_anti_high_to_low", + JoinType::RightAnti, + Pattern::HighToLow, + BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::RightSemi, - true, ), ( - "right_anti_low_hit_payload", - Pattern::InRange, + "right_semi_single_batch_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + BUILD_ROWS, + BATCH_SIZE, SPARSE_KEY_STEP, - JoinType::RightAnti, - true, ), ( - "null_heavy_hits", - Pattern::NullHeavyHits, - SPARSE_KEY_STEP, - JoinType::Inner, - false, + "right_semi_dense_100k_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + LARGE_BUILD_ROWS, + PROBE_ROWS, + DENSE_KEY_STEP, ), ( - "null_heavy_misses", - Pattern::NullHeavyMisses, + "right_semi_sparse_100k_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + LARGE_BUILD_ROWS, + PROBE_ROWS, SPARSE_KEY_STEP, - JoinType::Inner, - false, ), ] { - let nullable = - matches!(pattern, Pattern::NullHeavyHits | Pattern::NullHeavyMisses); - let mut fields = vec![Field::new("key", DataType::Int32, nullable)]; - if with_payload { - fields.push(Field::new("row_id", DataType::Int64, false)); - fields.push(Field::new("payload", DataType::Utf8, false)); - } - let schema = Arc::new(Schema::new(fields)); - let rows = if matches!(pattern, Pattern::ShortProbe) { - SHORT_PROBE_ROWS - } else { - PROBE_ROWS + let build = + make_batches(build_rows, build_rows, key_step, Pattern::AllHit, &schema); + let probe = make_batches(probe_rows, build_rows, key_step, pattern, &schema); + let run = || { + let join = make_join(&build, &probe, join_type); + rt.block_on(collect(join, Arc::clone(&context))).unwrap() }; + let hits = match pattern { - Pattern::AllHit => rows, - Pattern::HighToLow | Pattern::LowToHigh => { - PHASE_ROWS + PHASE_ROWS / HIT_EVERY + Pattern::AllHit => probe_rows, + Pattern::InterleavedLowHit | Pattern::ClusteredLowHit => { + probe_rows / HIT_EVERY } - Pattern::NullHeavyHits => rows / NON_NULL_EVERY, - Pattern::NullHeavyMisses => 0, - _ => rows / HIT_EVERY, + Pattern::HighToLow => probe_rows / 2 + probe_rows / 2 / HIT_EVERY, }; - let expected = if join_type == JoinType::RightAnti { - rows - hits + let expected_rows = if join_type == JoinType::RightAnti { + probe_rows - hits } else { hits }; - let expected_columns = - schema.fields().len() * if join_type == JoinType::Inner { 2 } else { 1 }; - let build: Arc = TestMemoryExec::try_new_exec( - &[make_batches(BUILD_ROWS, key_step, Pattern::AllHit, &schema)], - Arc::clone(&schema), - None, - ) - .unwrap(); - let probe: Arc = TestMemoryExec::try_new_exec( - &[make_batches(rows, key_step, pattern, &schema)], - Arc::clone(&schema), - None, - ) - .unwrap(); - - let diagnostic = make_join(&build, &probe, join_type); - let output_rows = rt.block_on(async { - let mut stream = diagnostic.execute(0, Arc::clone(&context)).unwrap(); - let mut output_rows = 0; - while let Some(batch) = stream.next().await { - let batch = batch.unwrap(); - assert_eq!(batch.num_columns(), expected_columns, "{name}"); - output_rows += batch.num_rows(); - } - output_rows - }); - assert_eq!(output_rows, expected, "{name}"); + let output = run(); + assert_eq!( + output.iter().map(RecordBatch::num_rows).sum::(), + expected_rows, + "{name}", + ); + drop(output); - group.bench_function(name, |b| { - b.iter_batched( - || make_join(&build, &probe, join_type), - |join| { - rt.block_on(async { - let mut stream = join.execute(0, Arc::clone(&context)).unwrap(); - while let Some(batch) = stream.next().await { - black_box(batch.unwrap()); - } - }) - }, - BatchSize::LargeInput, - ); - }); + group.bench_function(name, |b| b.iter(|| black_box(run()))); } group.finish(); } diff --git a/datafusion/physical-plan/src/joins/hash_join/exec.rs b/datafusion/physical-plan/src/joins/hash_join/exec.rs index bb922e1374205..0bd5e18c1818f 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec.rs @@ -1660,12 +1660,12 @@ impl ExecutionPlan for HashJoinExec { .register(context.memory_pool()); (state, reservation) }); - let (integer_prefilter_pruned_rows, integer_prefilter_created_count) = + let (probe_prefilter_rows_pruned, integer_prefilter_created_count) = if integer_prefilter_state.is_some() { ( MetricBuilder::new(&self.metrics) .with_category(MetricCategory::Rows) - .counter("integer_prefilter_pruned_rows", partition), + .counter("probe_prefilter_rows_pruned", partition), MetricBuilder::new(&self.metrics) .counter("integer_prefilter_created_count", partition), ) @@ -1806,7 +1806,7 @@ impl ExecutionPlan for HashJoinExec { null_aware, self.fetch, integer_prefilter_state, - integer_prefilter_pruned_rows, + probe_prefilter_rows_pruned, ))) } @@ -3132,6 +3132,7 @@ async fn collect_left_input( // Reserve optional memory only after all mandatory join state has been // allocated. Reuse the bounds already computed for perfect hash join. let integer_prefilter = if config.execution.enable_join_integer_prefilter + && null_aware.is_none() && matches!(map.as_ref(), Map::HashMap(_)) && left_values.len() == 1 { @@ -3143,7 +3144,6 @@ async fn collect_left_input( left_values[0].as_ref(), (&bounds.min, &bounds.max), config.execution.join_integer_prefilter_max_key_range, - null_equality, &reservation, ) }) @@ -3182,53 +3182,9 @@ async fn collect_left_input( mod tests { use super::*; - #[tokio::test] - async fn test_integer_prefilter_prunes_lookup_rows() -> Result<()> { - let left = build_table_two_cols( - ("a", &vec![Some(0), Some(2048)]), - ("b", &vec![Some(1), Some(2)]), - ); - let right = build_table_two_cols( - ("a", &vec![Some(0), Some(1), Some(2049), None]), - ("b", &vec![Some(1); 4]), - ); - let on = vec![(col("a", &left.schema())?, col("a", &right.schema())?)]; - let join = Arc::new(HashJoinExec::try_new( - left, - right, - on, - None, - &JoinType::Inner, - None, - PartitionMode::CollectLeft, - NullEquality::NullEqualsNothing, - false, - )?); - let mut config = SessionConfig::default(); - config.options_mut().execution.enable_join_integer_prefilter = true; - let context = Arc::new(TaskContext::default().with_session_config(config)); - let batches = crate::collect(Arc::clone(&join) as _, context).await?; - assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); - assert_eq!( - join.metrics() - .unwrap() - .sum_by_name("integer_prefilter_pruned_rows") - .map(|value| value.as_usize()) - .unwrap_or(0), - 2 - ); - Ok(()) - } - - /// Duplicate keys cross output chunks; input batches also cross sampling windows. fn integer_prefilter_join( build: ArrayRef, probe: ArrayRef, - join_type: JoinType, - null_equality: NullEquality, - null_aware: bool, - mode: PartitionMode, - with_filter: bool, ) -> Result> { let table = |keys: ArrayRef| -> Result> { let schema = Arc::new(Schema::new(vec![Field::new( @@ -3249,31 +3205,17 @@ mod tests { }; let left = table(build)?; let right = table(probe)?; - let filter = with_filter.then(|| { - JoinFilter::new( - Arc::new(BinaryExpr::new( - Arc::new(Column::new("key", 0)), - Operator::Gt, - lit(0_i32), - )), - vec![ColumnIndex { - index: 0, - side: JoinSide::Left, - }], - left.schema(), - ) - }); let on = vec![(col("key", &left.schema())?, col("key", &right.schema())?)]; Ok(Arc::new(HashJoinExec::try_new( left, right, on, - filter, - &join_type, None, - mode, - null_equality, - null_aware, + &JoinType::Full, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, )?)) } @@ -3283,140 +3225,11 @@ mod tests { config .options_mut() .execution - .join_integer_prefilter_sample_rows = 3; + .join_integer_prefilter_sample_rows = + datafusion_common::config::ConfigNonZeroUsize::try_new(3).unwrap(); Arc::new(TaskContext::default().with_session_config(config)) } - #[tokio::test] - async fn test_integer_prefilter_join_types() -> Result<()> { - for join_type in [ - JoinType::Inner, - JoinType::Left, - JoinType::Right, - JoinType::Full, - JoinType::LeftSemi, - JoinType::RightSemi, - JoinType::LeftAnti, - JoinType::RightAnti, - JoinType::LeftMark, - JoinType::RightMark, - ] { - for null_equality in [ - NullEquality::NullEqualsNothing, - NullEquality::NullEqualsNull, - ] { - let mut expected = None; - for enabled in [false, true] { - let join = integer_prefilter_join( - Arc::new(Int32Array::from(vec![ - None, - Some(0), - Some(0), - Some(0), - Some(2048), - ])), - Arc::new(Int32Array::from(vec![ - Some(-1), - None, - Some(0), - Some(2048), - Some(3000), - Some(1), - ])), - join_type, - null_equality, - false, - PartitionMode::CollectLeft, - false, - )?; - let batches = crate::collect( - Arc::clone(&join) as _, - integer_prefilter_context(enabled), - ) - .await?; - let output = batches_to_sort_string(&batches); - if enabled { - assert_eq!( - &output, - expected.as_ref().unwrap(), - "{join_type:?} {null_equality:?}" - ); - assert_eq!( - join.metrics() - .unwrap() - .sum_by_name("integer_prefilter_created_count") - .unwrap() - .as_usize(), - 1 - ); - assert!( - join.metrics() - .unwrap() - .sum_by_name("integer_prefilter_pruned_rows") - .unwrap() - .as_usize() - > 0 - ); - } else { - expected = Some(output); - } - } - } - } - Ok(()) - } - - #[tokio::test] - async fn test_integer_prefilter_null_aware_and_filter() -> Result<()> { - // Preserve NULL/non-empty state even for probe rows excluded from lookup. - for (join_type, null_aware, mode, with_filter) in [ - (JoinType::LeftAnti, true, PartitionMode::CollectLeft, false), - (JoinType::RightAnti, true, PartitionMode::CollectLeft, false), - (JoinType::LeftMark, true, PartitionMode::CollectLeft, false), - (JoinType::Full, false, PartitionMode::Partitioned, true), - ] { - for (build, probe) in [ - ( - vec![Some(0), Some(0), Some(2048)], - vec![Some(1), Some(0), Some(3000), None], - ), - ( - vec![None, Some(0), Some(2048)], - vec![Some(1), Some(0), Some(3000)], - ), - (vec![None], vec![None, Some(1)]), - (vec![], vec![None, Some(1)]), - (vec![None, Some(0)], vec![]), - ] { - let mut expected = None; - for enabled in [false, true] { - let join = integer_prefilter_join( - Arc::new(Int32Array::from(build.clone())), - Arc::new(Int32Array::from(probe.clone())), - join_type, - NullEquality::NullEqualsNothing, - null_aware, - mode, - with_filter, - )?; - let batches = - crate::collect(join, integer_prefilter_context(enabled)).await?; - let output = batches_to_sort_string(&batches); - if enabled { - assert_eq!( - &output, - expected.as_ref().unwrap(), - "{join_type:?}, build={build:?}, probe={probe:?}" - ); - } else { - expected = Some(output); - } - } - } - } - Ok(()) - } - #[tokio::test] async fn test_integer_prefilter_fallbacks() -> Result<()> { let cases: Vec<(ArrayRef, ArrayRef, bool)> = vec![ @@ -3425,11 +3238,6 @@ mod tests { Arc::new(Int32Array::from(vec![0, 2])), true, ), - ( - Arc::new(Int32Array::from(vec![0, 262144])), - Arc::new(Int32Array::from(vec![0, 2])), - false, - ), ( Arc::new(arrow::array::StringArray::from(vec!["a", "c"])), Arc::new(arrow::array::StringArray::from(vec!["a", "b"])), @@ -3442,15 +3250,7 @@ mod tests { ), ]; for (build, probe, phj) in cases { - let join = integer_prefilter_join( - build, - probe, - JoinType::Full, - NullEquality::NullEqualsNothing, - false, - PartitionMode::CollectLeft, - false, - )?; + let join = integer_prefilter_join(build, probe)?; crate::collect(Arc::clone(&join) as _, integer_prefilter_context(true)) .await?; let metrics = join.metrics().unwrap(); @@ -3464,7 +3264,7 @@ mod tests { ); assert_eq!( metrics - .sum_by_name("integer_prefilter_pruned_rows") + .sum_by_name("probe_prefilter_rows_pruned") .unwrap() .as_usize(), 0 @@ -3480,11 +3280,6 @@ mod tests { integer_prefilter_join( Arc::new(Int32Array::from(vec![0, 2048])), Arc::new(Int32Array::from(vec![0, 1, 2049])), - JoinType::Full, - NullEquality::NullEqualsNothing, - false, - PartitionMode::CollectLeft, - false, ) }; // Measure mandatory build reservations, including the visited bitmap. @@ -3500,7 +3295,7 @@ mod tests { .as_usize(); // Either only mandatory state fits, or the build bitmap fits but the // additional probe masks do not. Both must preserve normal join output. - for bitmap_bytes in [0, 2049_usize.div_ceil(8)] { + for bitmap_bytes in [0, 2049_usize.div_ceil(64) * size_of::()] { let pool = Arc::new(GreedyMemoryPool::new(bytes + bitmap_bytes)); let runtime = RuntimeEnvBuilder::new() .with_memory_pool(Arc::clone(&pool) as _) @@ -3527,7 +3322,7 @@ mod tests { ); assert_eq!( metrics - .sum_by_name("integer_prefilter_pruned_rows") + .sum_by_name("probe_prefilter_rows_pruned") .unwrap() .as_usize(), 0 @@ -3599,7 +3394,7 @@ mod tests { ); assert_eq!( metrics - .sum_by_name("integer_prefilter_pruned_rows") + .sum_by_name("probe_prefilter_rows_pruned") .unwrap() .as_usize(), 12 diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index 9a112dc171615..45d8c473f743d 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -377,7 +377,7 @@ pub(super) struct HashJoinStream { /// Metrics join_metrics: BuildProbeJoinMetrics, integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, - integer_prefilter_pruned_rows: Count, + probe_prefilter_rows_pruned: Count, /// Information of index and left / right placement of columns column_indices: Vec, /// Defines the null equality for the join. @@ -567,7 +567,7 @@ impl HashJoinStream { null_aware: Option, fetch: Option, integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, - integer_prefilter_pruned_rows: Count, + probe_prefilter_rows_pruned: Count, ) -> Self { // Create output buffer with coalescing and optional fetch limit. let output_buffer = @@ -583,7 +583,7 @@ impl HashJoinStream { random_state, join_metrics, integer_prefilter_state, - integer_prefilter_pruned_rows, + probe_prefilter_rows_pruned, column_indices, null_equality, state, @@ -826,18 +826,15 @@ impl HashJoinStream { batch.num_rows(), valid_keys.is_some(), ); - let lookup_keys = if bytes - .is_some_and(|bytes| reservation.try_resize(bytes).is_ok()) + let lookup_keys = if state.should_filter(batch.num_rows()) + && bytes + .is_some_and(|bytes| reservation.try_resize(bytes).is_ok()) { - let (mask, pruned) = state.filter( - filter, - keys_values[0].as_ref(), - valid_keys.as_ref(), - ); - self.integer_prefilter_pruned_rows.add(pruned); - if mask.is_some() { + if let Some(mask) = state.filter(filter, keys_values[0].as_ref()) + { + self.probe_prefilter_rows_pruned.add(mask.null_count()); let lookup = - NullBuffer::union(valid_keys.as_ref(), mask.as_ref()); + NullBuffer::union(valid_keys.as_ref(), Some(&mask)); drop(mask); reservation.resize( lookup diff --git a/datafusion/physical-plan/src/joins/integer_prefilter.rs b/datafusion/physical-plan/src/joins/integer_prefilter.rs index c69aab69f304a..01e5d0d2c6bc1 100644 --- a/datafusion/physical-plan/src/joins/integer_prefilter.rs +++ b/datafusion/physical-plan/src/joins/integer_prefilter.rs @@ -20,123 +20,116 @@ //! This only avoids hash table lookups. Probe rows remain in their original //! batch so outer, anti and mark joins can still produce unmatched results. +use crate::joins::array_map::ArrayMap; use arrow::array::Array; use arrow::array::downcast_integer_array; use arrow::buffer::{BooleanBuffer, NullBuffer}; +use arrow::datatypes::DataType; use datafusion_common::config::ExecutionOptions; -use datafusion_common::{NullEquality, Result, ScalarValue, config_err}; +use datafusion_common::{Result, ScalarValue, config_err}; use datafusion_execution::memory_pool::MemoryReservation; /// One bit per integer in the build key range, shared by all probe streams. #[derive(Debug)] pub(super) struct IntegerPrefilter { - bits: Vec, - min: u64, - range: usize, - null_matches: bool, + offset: u64, + key_count: u64, + words: Vec, + data_type: DataType, } impl IntegerPrefilter { /// Uses already computed build bounds. Failure to reserve this optional /// allocation leaves the normal hash join available. + #[expect( + clippy::unnecessary_cast, + reason = "the integer downcast macro also expands for UInt64" + )] pub(super) fn try_new( values: &dyn Array, bounds: (&ScalarValue, &ScalarValue), - max_key_range: usize, - null_equality: NullEquality, + max_key_range: u64, reservation: &MemoryReservation, ) -> Option { - if !values.data_type().is_integer() { + if !ArrayMap::is_supported_type(values.data_type()) || max_key_range == 0 { return None; } - let min = integer_value(bounds.0)?; - let max = integer_value(bounds.1)?; - let range = usize::try_from(max - min).ok()?.checked_add(1)?; - if range > max_key_range { + let offset = ArrayMap::key_to_u64(bounds.0)?; + let max = ArrayMap::key_to_u64(bounds.1)?; + let key_count = max.wrapping_sub(offset).checked_add(1)?; + if key_count > max_key_range { return None; } - let bytes = range.div_ceil(8); + let word_count = usize::try_from(key_count.div_ceil(64)).ok()?; + let bytes = word_count.checked_mul(size_of::())?; reservation.try_grow(bytes).ok()?; - let mut bits = Vec::new(); - if bits.try_reserve_exact(bytes).is_err() { + let mut words = Vec::new(); + if words.try_reserve_exact(word_count).is_err() { reservation.shrink(bytes); return None; } - let extra = bits.capacity() - bytes; + let extra = (words.capacity() - word_count) * size_of::(); if reservation.try_grow(extra).is_err() { reservation.shrink(bytes); return None; } - bits.resize(bytes, 0); + words.resize(word_count, 0); downcast_integer_array!(values => { for value in values.iter().flatten() { - let offset = (i128::from(value) - min) as usize; - bits[offset / 8] |= 1 << (offset % 8); + let index = (value as u64).wrapping_sub(offset); + if index >= key_count { + reservation.shrink(bytes + extra); + return None; + } + words[(index / 64) as usize] |= 1 << (index % 64); } } _ => unreachable!("integer type checked above")); Some(Self { - bits, - min: min as u64, - range, - null_matches: null_equality == NullEquality::NullEqualsNull - && values.null_count() > 0, + offset, + key_count, + words, + data_type: values.data_type().clone(), }) } pub(super) fn size(&self) -> usize { - self.bits.capacity() + self.words.capacity() * size_of::() } #[inline] fn contains(&self, value: u64) -> bool { - // Build range validation uses i128. Here, same-type integer keys can - // use wrapping offsets: values below min wrap beyond the valid range, - // including signed keys whose range crosses zero. - let offset = value.wrapping_sub(self.min); - offset < self.range as u64 - && self.bits[offset as usize / 8] & (1 << (offset as usize % 8)) != 0 - } -} - -fn integer_value(value: &ScalarValue) -> Option { - match value { - ScalarValue::Int8(v) => v.map(i128::from), - ScalarValue::Int16(v) => v.map(i128::from), - ScalarValue::Int32(v) => v.map(i128::from), - ScalarValue::Int64(v) => v.map(i128::from), - ScalarValue::UInt8(v) => v.map(i128::from), - ScalarValue::UInt16(v) => v.map(i128::from), - ScalarValue::UInt32(v) => v.map(i128::from), - ScalarValue::UInt64(v) => v.map(i128::from), - _ => None, + // As in ArrayMap, wrapping subtraction also handles signed ranges + // crossing zero and values below the build minimum. + let index = value.wrapping_sub(self.offset); + index < self.key_count + && self.words[(index / 64) as usize] & (1 << (index % 64)) != 0 } } /// Each probe stream independently measures additional skipped lookups. /// Windows end at batch boundaries after at least `sample_rows` input rows, -/// including already invalid keys. Savings only count eligible lookups. -/// Unprofitable windows pause filtering for eight windows of input rows, -/// then retry to accommodate changing probe distributions. +/// including NULLs. Unprofitable windows pause for 10 to 128 windows of input +/// rows, doubling the pause until a profitable sample resets it. #[derive(Debug)] pub(super) struct PrefilterState { + rows_observed: usize, + rows_pruned: usize, + rows_to_skip: usize, + pause_rows: usize, sample_rows: usize, min_pruning_ratio: f64, - scanned_rows: usize, - eligible_rows: usize, - pruned_rows: usize, - skip_rows: usize, } impl PrefilterState { fn new(sample_rows: usize, min_pruning_ratio: f64) -> Self { Self { + rows_observed: 0, + rows_pruned: 0, + rows_to_skip: 0, + pause_rows: sample_rows.saturating_mul(10), sample_rows, min_pruning_ratio, - scanned_rows: 0, - eligible_rows: 0, - pruned_rows: 0, - skip_rows: 0, } } @@ -144,16 +137,6 @@ impl PrefilterState { if !config.enable_join_integer_prefilter { return Ok(None); } - if config.join_integer_prefilter_max_key_range == 0 { - return config_err!( - "join_integer_prefilter_max_key_range must be greater than zero" - ); - } - if config.join_integer_prefilter_sample_rows == 0 { - return config_err!( - "join_integer_prefilter_sample_rows must be greater than zero" - ); - } let ratio = config.join_integer_prefilter_min_pruning_ratio; if !(0.0..=1.0).contains(&ratio) { return config_err!( @@ -161,11 +144,21 @@ impl PrefilterState { ); } Ok(Some(Self::new( - config.join_integer_prefilter_sample_rows, + config.join_integer_prefilter_sample_rows.get(), ratio, ))) } + /// Call before reserving or constructing a lookup mask. A paused batch + /// advances only the cooldown and keeps the original validity mask. + pub(super) fn should_filter(&mut self, rows: usize) -> bool { + if self.rows_to_skip > 0 { + self.rows_to_skip = self.rows_to_skip.saturating_sub(rows); + return false; + } + rows > 0 + } + /// Upper bound for simultaneously live membership and combined masks. /// A bitmap union with differing bit offsets may double its allocation /// when appending a partial word. No union allocation is needed without NULLs. @@ -175,69 +168,56 @@ impl PrefilterState { .checked_mul(if has_validity { 3 } else { 1 }) } - /// Returns the additional lookup mask and number of newly excluded rows. - /// Already invalid keys stay set here: the caller combines this mask with - /// the original validity without counting those keys as prefilter savings. + /// Returns a membership mask that retains NULLs. The caller combines it + /// with the original validity and counts excluded rows with `null_count`. pub(super) fn filter( &mut self, filter: &IntegerPrefilter, values: &dyn Array, - valid_keys: Option<&NullBuffer>, - ) -> (Option, usize) { - if self.skip_rows > 0 { - self.skip_rows = self.skip_rows.saturating_sub(values.len()); - return (None, 0); + ) -> Option { + if values.data_type() != &filter.data_type { + return None; } - let eligible_rows = values.len() - valid_keys.map_or(0, NullBuffer::null_count); - if eligible_rows == 0 { - self.record_sample(values.len(), 0, 0); - return (None, 0); + if values.null_count() == values.len() { + self.record_sample(values.len(), 0); + return None; } let mask = downcast_integer_array!(values => { - if values.null_count() == 0 && valid_keys.is_none() { + if values.null_count() == 0 { let values = values.values(); BooleanBuffer::collect_bool(values.len(), |i| { filter.contains(values[i] as u64) }) } else { BooleanBuffer::collect_bool(values.len(), |i| { - if valid_keys.is_some_and(|valid| valid.is_null(i)) { - return true; - } - if values.is_null(i) { - filter.null_matches - } else { - filter.contains(values.value(i) as u64) - } + values.is_null(i) || filter.contains(values.value(i) as u64) }) } } - _ => return (None, 0)); + _ => return None); let mask = NullBuffer::new(mask); let pruned = mask.null_count(); - self.record_sample(values.len(), eligible_rows, pruned); - ((pruned > 0).then_some(mask), pruned) + self.record_sample(values.len(), pruned); + (pruned > 0).then_some(mask) } - fn record_sample( - &mut self, - scanned_rows: usize, - eligible_rows: usize, - pruned: usize, - ) { - self.scanned_rows = self.scanned_rows.saturating_add(scanned_rows); - self.eligible_rows = self.eligible_rows.saturating_add(eligible_rows); - self.pruned_rows = self.pruned_rows.saturating_add(pruned); - if self.scanned_rows >= self.sample_rows { - if self.eligible_rows == 0 - || (self.pruned_rows as f64) - < self.min_pruning_ratio * self.eligible_rows as f64 + fn record_sample(&mut self, rows: usize, pruned: usize) { + self.rows_observed = self.rows_observed.saturating_add(rows); + self.rows_pruned = self.rows_pruned.saturating_add(pruned); + if self.rows_observed >= self.sample_rows { + if (self.rows_pruned as f64 / self.rows_observed as f64) + <= self.min_pruning_ratio { - self.skip_rows = self.sample_rows.saturating_mul(8); + self.rows_to_skip = self.pause_rows; + self.pause_rows = self + .pause_rows + .saturating_mul(2) + .min(self.sample_rows.saturating_mul(128)); + } else { + self.pause_rows = self.sample_rows.saturating_mul(10); } - self.scanned_rows = 0; - self.eligible_rows = 0; - self.pruned_rows = 0; + self.rows_observed = 0; + self.rows_pruned = 0; } } } @@ -266,7 +246,7 @@ mod tests { let min = $min; let build = <$array>::from(vec![Some(min), Some(min + 2), Some(min), None]); - let memory = reservation(1); + let memory = reservation(8); let filter = IntegerPrefilter::try_new( &build, ( @@ -274,11 +254,10 @@ mod tests { &ScalarValue::$scalar(Some(min + 2)), ), 3, - NullEquality::NullEqualsNothing, &memory, ) .unwrap(); - assert_eq!(memory.size(), 1); + assert_eq!(memory.size(), 8); assert!(!filter.contains((min as u64).wrapping_sub(1))); let probe = <$array>::from(vec![ None, @@ -287,14 +266,13 @@ mod tests { Some(min + 2), Some(min + 3), ]); - let valid = probe.nulls(); - let (mask, pruned) = - PrefilterState::new(10, 0.5).filter(&filter, &probe, valid); - assert_eq!(pruned, 2); - let mask = NullBuffer::union(valid, mask.as_ref()).unwrap(); + let mask = PrefilterState::new(10, 0.5) + .filter(&filter, &probe) + .unwrap(); + assert_eq!(mask.null_count(), 2); assert_eq!( mask.iter().collect::>(), - vec![false, true, false, true, false] + vec![true, true, false, true, false] ); }}; } @@ -310,35 +288,23 @@ mod tests { } #[test] - fn null_equals_null() { - for has_null in [false, true] { - let build = if has_null { - Int32Array::from(vec![Some(1), None]) - } else { - Int32Array::from(vec![1]) - }; - let memory = reservation(1); - let filter = IntegerPrefilter::try_new( - &build, - (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), - 1, - NullEquality::NullEqualsNull, - &memory, - ) - .unwrap(); - let probe = Int32Array::from(vec![None, Some(1), Some(2)]); - let (mask, count) = - PrefilterState::new(10, 0.5).filter(&filter, &probe, None); - assert_eq!(count, if has_null { 1 } else { 2 }); - assert_eq!( - mask.unwrap().iter().collect::>(), - vec![has_null, true, false] - ); - } + fn mismatched_probe_type_is_not_filtered() { + let memory = reservation(8); + let filter = IntegerPrefilter::try_new( + &Int32Array::from(vec![1]), + (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), + 1, + &memory, + ) + .unwrap(); + assert_eq!( + PrefilterState::new(4, 0.5).filter(&filter, &UInt64Array::from(vec![1, 2])), + None + ); } #[test] - fn range_and_memory_fallback() { + fn range_overflow() { let build = Int64Array::from(vec![i64::MIN, i64::MAX]); let memory = reservation(1024); assert!( @@ -348,8 +314,7 @@ mod tests { &ScalarValue::Int64(Some(i64::MIN)), &ScalarValue::Int64(Some(i64::MAX)) ), - usize::MAX, - NullEquality::NullEqualsNothing, + u64::MAX, &memory ) .is_none() @@ -363,103 +328,102 @@ mod tests { &ScalarValue::UInt64(Some(0)), &ScalarValue::UInt64(Some(u64::MAX)) ), - usize::MAX, - NullEquality::NullEqualsNothing, - &memory - ) - .is_none() - ); - let build = Int32Array::from(vec![0, 8]); - let bounds = (ScalarValue::Int32(Some(0)), ScalarValue::Int32(Some(8))); - assert!( - IntegerPrefilter::try_new( - &build, - (&bounds.0, &bounds.1), - 8, - NullEquality::NullEqualsNothing, - &memory - ) - .is_none() - ); - let memory = reservation(1); - memory.try_grow(1).unwrap(); - assert!( - IntegerPrefilter::try_new( - &build, - (&bounds.0, &bounds.1), - 9, - NullEquality::NullEqualsNothing, + u64::MAX, &memory ) .is_none() ); - assert_eq!(memory.size(), 1, "existing reservations must be preserved"); } #[test] - fn sampling_pauses_retries_and_ignores_invalid_keys() { - let memory = reservation(1); + fn bitmap_word_boundaries() { + let build = Int32Array::from(vec![-1, 62, 63, 64]); + let memory = reservation(16); let filter = IntegerPrefilter::try_new( - &Int32Array::from(vec![1]), - (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), - 1, - NullEquality::NullEqualsNothing, + &build, + (&ScalarValue::Int32(Some(-1)), &ScalarValue::Int32(Some(64))), + 66, &memory, ) .unwrap(); - let mut state = PrefilterState::new(8, 0.5); - let hits = Int32Array::from(vec![Some(1), None, None, None]); - // Both batches consume the scan budget even though only two keys are - // eligible for lookup. NULLs must not prolong an unprofitable sample. - assert_eq!(state.filter(&filter, &hits, hits.nulls()).1, 0); - assert_eq!(state.skip_rows, 0); - state.filter(&filter, &hits, hits.nulls()); - assert_eq!(state.skip_rows, 64); - let misses = Int32Array::from(vec![2; 4]); - for _ in 0..16 { - assert_eq!(state.filter(&filter, &misses, None).1, 0); - } - // Savings use eligible lookups, not scanned rows: eliminating both - // eligible keys is profitable even with six NULLs in the window. - let sparse_misses = Int32Array::from(vec![Some(2), None, None, None]); - for _ in 0..2 { - let (mask, pruned) = - state.filter(&filter, &sparse_misses, sparse_misses.nulls()); - assert_eq!(pruned, 1); - assert_eq!( - mask.unwrap().iter().collect::>(), - vec![false, true, true, true] - ); + assert_eq!(filter.size(), 16); + assert_eq!(memory.size(), filter.size()); + for key in -2_i32..=65 { + assert_eq!(filter.contains(key as u64), [-1, 62, 63, 64].contains(&key)); } - assert_eq!(state.skip_rows, 0); - // Re-evaluate even after a profitable window. - assert!( - state - .filter(&filter, &Int32Array::from(vec![1; 8]), None) - .0 - .is_none() - ); - assert_eq!(state.skip_rows, 64); } #[test] - fn sampling_without_eligible_keys_pauses() { - let memory = reservation(1); + fn sampling_counts_nulls_and_pauses_at_threshold() { + let memory = reservation(8); let filter = IntegerPrefilter::try_new( &Int32Array::from(vec![1]), (&ScalarValue::Int32(Some(1)), &ScalarValue::Int32(Some(1))), 1, - NullEquality::NullEqualsNothing, &memory, ) .unwrap(); + let mut state = PrefilterState::new(8, 0.5); + let values = Int32Array::from(vec![Some(2), Some(2), None, None]); + for _ in 0..2 { + assert!(state.should_filter(values.len())); + let mask = state.filter(&filter, &values); + assert_eq!(mask.as_ref().unwrap().null_count(), 2); + assert_eq!( + mask.unwrap().iter().collect::>(), + vec![false, false, true, true] + ); + } + // Four misses out of eight input rows reaches, but does not exceed, + // the threshold. The two batches finish one window despite the NULLs. + assert_eq!(state.rows_to_skip, 80); + assert!(!state.should_filter(79)); + assert!(!state.should_filter(2)); + assert!(state.should_filter(1)); + assert_eq!(state.rows_observed, 0); + assert_eq!(state.rows_pruned, 0); + + // The all-NULL fast path must also consume the sampling window. let mut state = PrefilterState::new(4, 0.5); - let empty = Int32Array::from(Vec::::new()); - assert_eq!(state.filter(&filter, &empty, None), (None, 0)); - assert_eq!(state.skip_rows, 0); + assert!(!state.should_filter(0)); let nulls = Int32Array::from(vec![None; 4]); - assert_eq!(state.filter(&filter, &nulls, nulls.nulls()), (None, 0)); - assert_eq!(state.skip_rows, 32); + assert!(state.should_filter(nulls.len())); + assert_eq!(state.filter(&filter, &nulls), None); + assert_eq!(state.rows_to_skip, 40); + } + + #[test] + fn sampling_backoff_caps_and_resets() { + let mut state = PrefilterState::new(4, 0.5); + for multiplier in [10, 20, 40, 80, 128, 128] { + assert!(state.should_filter(4)); + state.record_sample(4, 0); + assert_eq!(state.rows_to_skip, 4 * multiplier); + assert!(!state.should_filter(4 * multiplier)); + } + assert!(state.should_filter(4)); + state.record_sample(4, 3); + assert_eq!(state.rows_to_skip, 0); + assert_eq!(state.pause_rows, 40); + state.record_sample(4, 0); + assert_eq!(state.rows_to_skip, 40); + + // Threshold endpoints and saturating row arithmetic. + let mut state = PrefilterState::new(1, 0.0); + state.record_sample(1, 0); + assert_eq!(state.rows_to_skip, 10); + let mut state = PrefilterState::new(1, 1.0); + state.record_sample(1, 1); + assert_eq!(state.rows_to_skip, 10); + let mut state = PrefilterState::new(usize::MAX, 0.5); + state.record_sample(usize::MAX - 1, 0); + state.record_sample(4, 0); + assert_eq!(state.rows_to_skip, usize::MAX); + assert_eq!(state.pause_rows, usize::MAX); + assert!(!state.should_filter(usize::MAX)); + state.record_sample(usize::MAX - 1, usize::MAX - 1); + state.record_sample(4, 4); + assert_eq!(state.rows_to_skip, 0); } #[test] @@ -471,18 +435,18 @@ mod tests { (0..=rows).map(|i| (i % 3 != 0).then_some((i % 2) as i32)), ) .slice(1, rows); - let memory = reservation(1); + let memory = reservation(8); let filter = IntegerPrefilter::try_new( &Int32Array::from(vec![0]), (&ScalarValue::Int32(Some(0)), &ScalarValue::Int32(Some(0))), 1, - NullEquality::NullEqualsNothing, &memory, ) .unwrap(); - let (mask, pruned) = - PrefilterState::new(rows, 0.5).filter(&filter, &values, values.nulls()); - let mask = mask.unwrap(); + let mask = PrefilterState::new(rows, 0.5) + .filter(&filter, &values) + .unwrap(); + let pruned = mask.null_count(); let lookup = NullBuffer::union(values.nulls(), Some(&mask)).unwrap(); let peak = mask.inner().inner().capacity() + lookup.inner().inner().capacity(); assert!(peak <= PrefilterState::mask_memory_size(rows, true).unwrap()); @@ -492,27 +456,4 @@ mod tests { values.iter().map(|v| v == Some(0)).collect::>() ); } - - #[test] - fn validates_configuration_only_when_enabled() { - let mut config = ExecutionOptions { - join_integer_prefilter_sample_rows: 0, - ..Default::default() - }; - assert!(PrefilterState::try_from_config(&config).unwrap().is_none()); - config.enable_join_integer_prefilter = true; - assert!(PrefilterState::try_from_config(&config).is_err()); - config.join_integer_prefilter_sample_rows = 1; - config.join_integer_prefilter_max_key_range = 0; - assert!(PrefilterState::try_from_config(&config).is_err()); - config.join_integer_prefilter_max_key_range = 1; - for ratio in [f64::NAN, f64::INFINITY, -0.1, 1.1] { - config.join_integer_prefilter_min_pruning_ratio = ratio; - assert!(PrefilterState::try_from_config(&config).is_err()); - } - for ratio in [0.0, 0.5, 1.0] { - config.join_integer_prefilter_min_pruning_ratio = ratio; - assert!(PrefilterState::try_from_config(&config).unwrap().is_some()); - } - } } diff --git a/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt b/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt index b98c16062994d..a4869a460d2b4 100644 --- a/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt +++ b/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt @@ -77,7 +77,7 @@ query TT EXPLAIN ANALYZE SELECT * FROM build b FULL JOIN probe p ON b.k = p.k; ---- Plan with Metrics -01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=1, integer_prefilter_pruned_rows=3, ] +01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=1, probe_prefilter_rows_pruned=3, ] 02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] 03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] @@ -135,14 +135,14 @@ SELECT p.label FROM build b RIGHT SEMI JOIN probe p ON b.k = p.k; hit_a hit_b -# IS NULL around IN requires a null-aware mark join. The rejected 2048 key on -# its probe side must not change SQL's three-valued result. +# IS NULL around IN requires a null-aware mark join, which bypasses the +# prefilter and preserves SQL's three-valued result. query TT EXPLAIN ANALYZE SELECT p.label FROM probe p WHERE (p.k IN (SELECT k FROM build)) IS NULL; ---- Plan with Metrics -HashJoinExec: mode=CollectLeft, join_type=LeftMark, on=[(k@0, k@0)], null_aware, metrics=[output_rows=6, array_map_created_count=0, integer_prefilter_created_count=1, integer_prefilter_pruned_rows=1, ] +HashJoinExec: mode=CollectLeft, join_type=LeftMark, on=[(k@0, k@0)], null_aware, metrics=[output_rows=6, array_map_created_count=0, integer_prefilter_created_count=0, probe_prefilter_rows_pruned=0, ] query T rowsort @@ -189,7 +189,7 @@ query TT EXPLAIN ANALYZE SELECT * FROM build b FULL JOIN probe p ON b.k = p.k; ---- Plan with Metrics -01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=0, integer_prefilter_pruned_rows=0, ] +01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=0, probe_prefilter_rows_pruned=0, ] 02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] 03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] @@ -207,6 +207,18 @@ zero_a hit_b zero_b hit_a zero_b hit_b +# A zero range disables bitmap construction without disabling the feature. +statement ok +SET datafusion.execution.join_integer_prefilter_max_key_range = 0; + +query TT +EXPLAIN ANALYZE SELECT * FROM build b FULL JOIN probe p ON b.k = p.k; +---- +Plan with Metrics +01)HashJoinExec: mode=CollectLeft, join_type=Full, on=[(k@0, k@0)], metrics=[output_rows=10, array_map_created_count=0, integer_prefilter_created_count=0, probe_prefilter_rows_pruned=0, ] +02)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] +03)--DataSourceExec: partitions=1, partition_sizes=[1], metrics=[] + statement ok RESET datafusion.execution.enable_join_integer_prefilter; diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index 573f6e68936a7..7ac065dac0292 100644 --- a/docs/source/user-guide/configs.md +++ b/docs/source/user-guide/configs.md @@ -76,10 +76,10 @@ The following configuration settings are available: | datafusion.execution.batch_size | 8192 | Default batch size while creating new batches, it's especially useful for buffer-in-memory batches since creating tiny batches would result in too much metadata memory consumption | | datafusion.execution.perfect_hash_join_small_build_threshold | 1024 | A perfect hash join (see `HashJoinExec` for more details) will be considered if the range of keys (max - min) on the build side is < this threshold. This provides a fast path for joins with very small key ranges, bypassing the density check. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. | | datafusion.execution.perfect_hash_join_min_key_density | 0.15 | The minimum required density of join keys on the build side to consider a perfect hash join (see `HashJoinExec` for more details). Density is calculated as: `(number of rows) / (max_key - min_key + 1)`. A perfect hash join may be used if the actual key density > this value. Currently only supports cases where build_side.num_rows() < u32::MAX. Support for build_side.num_rows() >= u32::MAX will be added in the future. | -| datafusion.execution.enable_join_integer_prefilter | false | Enable an exact integer membership prefilter for hash joins with a single integer key when the build side uses a hash table. It skips lookups for absent keys while retaining probe rows for unmatched join output. | -| datafusion.execution.join_integer_prefilter_max_key_range | 262144 | Maximum number of integer values covered by the join prefilter bitmap (`max_key - min_key + 1`). Must be greater than zero when enabled. Larger ranges fall back to normal hash table lookups. | -| datafusion.execution.join_integer_prefilter_min_pruning_ratio | 0.5 | Minimum fraction of otherwise eligible hash lookups the integer prefilter must eliminate to keep filtering. Must be finite and in [0, 1]. Unprofitable samples pause filtering, then periodically retry. | -| datafusion.execution.join_integer_prefilter_sample_rows | 12288 | Minimum input probe rows in each integer prefilter sampling window, including NULLs. Pruning ratios only count otherwise eligible lookups. Must be greater than zero when enabled. Windows end at batch boundaries; unprofitable windows pause filtering for eight times this many input rows before retrying at the next batch boundary. | +| datafusion.execution.enable_join_integer_prefilter | false | Enable an exact integer membership prefilter for hash joins with a single integer key when the build side uses a hash table and the join is not null-aware. It skips lookups for absent keys while retaining NULLs and probe rows for the original join logic. | +| datafusion.execution.join_integer_prefilter_max_key_range | 262144 | Maximum number of integer values covered by the join prefilter bitmap (`max_key - min_key + 1`). Zero disables bitmap construction. Larger ranges fall back to normal hash table lookups. | +| datafusion.execution.join_integer_prefilter_min_pruning_ratio | 0.5 | The integer prefilter must prune more than this fraction of all sampled probe rows, including NULLs, to keep filtering. Must be finite and in [0, 1], validated when executing the join. | +| datafusion.execution.join_integer_prefilter_sample_rows | 12288 | Minimum input probe rows in each integer prefilter sampling window, including NULLs. Must be greater than zero. Windows end at batch boundaries. Unprofitable samples initially pause for 10 times this many input rows; consecutive failures double the pause up to 128 times. A profitable sample resets the pause to 10 times this many rows. | | datafusion.execution.coalesce_batches | true | When set to true, record batches will be examined between each operator and small batches will be coalesced into larger batches. This is helpful when there are highly selective filters or joins that could produce tiny output batches. The target batch size is determined by the configuration setting | | datafusion.execution.collect_statistics | true | Should DataFusion collect statistics when first creating a table. Has no effect after the table is created. Defaults to true. | | datafusion.execution.target_partitions | 0 | Number of partitions for query execution. Increasing partitions can increase concurrency. Defaults to the number of CPU cores on the system | From c9414e2a02f4720b32d75b2b70091713d3b3a47e Mon Sep 17 00:00:00 2001 From: linfeng <33561138+lyne7-sc@users.noreply.github.com> Date: Wed, 16 Sep 2026 16:28:09 +0800 Subject: [PATCH 3/3] update `SHOW ALL` expectations for hash join integer prefilter --- datafusion/sqllogictest/test_files/information_schema.slt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index b270eba99d7b0..0246ebd4efa36 100644 --- a/datafusion/sqllogictest/test_files/information_schema.slt +++ b/datafusion/sqllogictest/test_files/information_schema.slt @@ -218,11 +218,15 @@ datafusion.execution.coalesce_batches true datafusion.execution.collect_statistics true datafusion.execution.enable_ansi_mode false datafusion.execution.enable_file_stream_work_stealing true +datafusion.execution.enable_join_integer_prefilter false datafusion.execution.enable_migration_aggregate true datafusion.execution.enable_nlj_coordinated_fallback true datafusion.execution.enable_recursive_ctes true datafusion.execution.enforce_batch_size_in_joins false datafusion.execution.hash_join_buffering_capacity 0 +datafusion.execution.join_integer_prefilter_max_key_range 262144 +datafusion.execution.join_integer_prefilter_min_pruning_ratio 0.5 +datafusion.execution.join_integer_prefilter_sample_rows 12288 datafusion.execution.keep_partition_by_columns false datafusion.execution.listing_table_factory_infer_partitions true datafusion.execution.listing_table_ignore_subdirectory true @@ -379,11 +383,15 @@ datafusion.execution.coalesce_batches true When set to true, record batches will datafusion.execution.collect_statistics true Should DataFusion collect statistics when first creating a table. Has no effect after the table is created. Defaults to true. datafusion.execution.enable_ansi_mode false Whether to enable ANSI SQL mode. The flag is experimental and relevant only for DataFusion Spark built-in functions When `enable_ansi_mode` is set to `true`, the query engine follows ANSI SQL semantics for expressions, casting, and error handling. This means: - **Strict type coercion rules:** implicit casts between incompatible types are disallowed. - **Standard SQL arithmetic behavior:** operations such as division by zero, numeric overflow, or invalid casts raise runtime errors rather than returning `NULL` or adjusted values. - **Consistent ANSI behavior** for string concatenation, comparisons, and `NULL` handling. When `enable_ansi_mode` is `false` (the default), the engine uses a more permissive, non-ANSI mode designed for user convenience and backward compatibility. In this mode: - Implicit casts between types are allowed (e.g., string to integer when possible). - Arithmetic operations are more lenient — for example, `abs()` on the minimum representable integer value returns the input value instead of raising overflow. - Division by zero or invalid casts may return `NULL` instead of failing. # Default `false` — ANSI SQL mode is disabled by default. datafusion.execution.enable_file_stream_work_stealing true When `true` (the default), DataFusion's built-in file scans dynamically rebalance files across partitions at query execution time: a partition that goes idle reads files (or byte-range morsels) originally assigned to a sibling partition, which keeps all partitions busy in a single process. Executors that depend on the plan-time partition assignment — such as Ballista and datafusion-distributed, which run each partition as an isolated task and never poll the siblings — should set this to `false` so each partition reads only its own file group and no runtime reassignment occurs. +datafusion.execution.enable_join_integer_prefilter false Enable an exact integer membership prefilter for hash joins with a single integer key when the build side uses a hash table and the join is not null-aware. It skips lookups for absent keys while retaining NULLs and probe rows for the original join logic. datafusion.execution.enable_migration_aggregate true Whether aggregation uses the implementation from the major refactor completed in the 56.0.0 release. When set to `false`, aggregation falls back to the implementation used before 55.0.0. The fallback exists only as a workaround for bugs in the new implementation and will be removed, together with this option, after the 56.0.0 release. See for details. datafusion.execution.enable_nlj_coordinated_fallback true Enables the memory-limited fallback for `NestedLoopJoinExec` join types that emit unmatched left rows in the final output (LEFT, LEFT SEMI, LEFT ANTI, LEFT MARK, FULL) when the right side has multiple partitions. This fallback coordinates per-chunk left state (visited bitmap and probe-thread counter) across all right-side partitions, which assumes every partition runs in the same process. Distributed engines that execute each output partition as an independent task (e.g. Ballista, datafusion-distributed) build a separate coordinator per task and poll only one partition, so the cross-partition counter never reaches zero and the fallback would stall. Such engines should set this to `false`: the coordinated fallback is then disabled for left-emitting multi-partition joins, which instead fail with a resource-exhaustion error under memory pressure rather than deadlocking. Single-partition and non-left-emitting joins are unaffected and always keep the fallback. datafusion.execution.enable_recursive_ctes true Should DataFusion support recursive CTEs datafusion.execution.enforce_batch_size_in_joins false Should DataFusion enforce batch size in joins or not. By default, DataFusion will not enforce batch size in joins. Enforcing batch size in joins can reduce memory usage when joining large tables with a highly-selective join filter, but is also slightly slower. Note: this option currently only applies to the symmetric hash join. datafusion.execution.hash_join_buffering_capacity 0 How many bytes to buffer in the probe side of hash joins while the build side is concurrently being built. Without this, hash joins will wait until the full materialization of the build side before polling the probe side. This is useful in scenarios where the query is not completely CPU bounded, allowing to do some early work concurrently and reducing the latency of the query. Note that when hash join buffering is enabled, the probe side will start eagerly polling data, not giving time for the producer side of dynamic filters to produce any meaningful predicate. Queries with dynamic filters might see performance degradation. Disabled by default, set to a number greater than 0 for enabling it. +datafusion.execution.join_integer_prefilter_max_key_range 262144 Maximum number of integer values covered by the join prefilter bitmap (`max_key - min_key + 1`). Zero disables bitmap construction. Larger ranges fall back to normal hash table lookups. +datafusion.execution.join_integer_prefilter_min_pruning_ratio 0.5 The integer prefilter must prune more than this fraction of all sampled probe rows, including NULLs, to keep filtering. Must be finite and in [0, 1], validated when executing the join. +datafusion.execution.join_integer_prefilter_sample_rows 12288 Minimum input probe rows in each integer prefilter sampling window, including NULLs. Must be greater than zero. Windows end at batch boundaries. Unprofitable samples initially pause for 10 times this many input rows; consecutive failures double the pause up to 128 times. A profitable sample resets the pause to 10 times this many rows. datafusion.execution.keep_partition_by_columns false Should DataFusion keep the columns used for partition_by in the output RecordBatches datafusion.execution.listing_table_factory_infer_partitions true Should a `ListingTable` created through the `ListingTableFactory` infer table partitions from Hive compliant directories. Defaults to true (partition columns are inferred and will be represented in the table schema). datafusion.execution.listing_table_ignore_subdirectory true Should sub directories be ignored when scanning directories for data files. Defaults to true (ignores subdirectories), consistent with Hive. Note that this setting does not affect reading partitioned tables (e.g. `/table/year=2021/month=01/data.parquet`).