diff --git a/datafusion/common/src/config.rs b/datafusion/common/src/config.rs index 040d32cd77fe2..c23ac681a1693 100644 --- a/datafusion/common/src/config.rs +++ b/datafusion/common/src/config.rs @@ -925,6 +925,29 @@ 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 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`). Zero disables bitmap construction. + /// Larger ranges fall back to normal hash table lookups. + pub join_integer_prefilter_max_key_range: u64, default = 262144 + + /// 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. 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 /// 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 82a2215581f22..73edbbdcdf773 100644 --- a/datafusion/physical-plan/Cargo.toml +++ b/datafusion/physical-plan/Cargo.toml @@ -173,6 +173,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..ddd853c1df463 --- /dev/null +++ b/datafusion/physical-plan/benches/hash_join_probe.rs @@ -0,0 +1,282 @@ +// 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. +//! 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, StringArray}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use arrow::record_batch::RecordBatch; +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::joins::{HashJoinExec, PartitionMode}; +use datafusion_physical_plan::test::TestMemoryExec; +use datafusion_physical_plan::{ExecutionPlan, collect}; +use tokio::runtime::Runtime; + +const BATCH_SIZE: usize = 8_192; +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 HIT_EVERY: usize = 10; + +#[derive(Clone, Copy)] +enum Pattern { + AllHit, + InterleavedLowHit, + ClusteredLowHit, + HighToLow, +} + +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_values((start..end).map(|row| { + let hit = match pattern { + Pattern::AllHit => true, + Pattern::InterleavedLowHit => row % HIT_EVERY == 0, + Pattern::ClusteredLowHit => row < rows / HIT_EVERY, + Pattern::HighToLow => row < rows / 2 || row % HIT_EVERY == 0, + }; + 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 + } + })); + 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_batches: &[RecordBatch], + probe_batches: &[RecordBatch], + join_type: JoinType, +) -> Arc { + let schema = build_batches[0].schema(); + let build = TestMemoryExec::try_new_exec( + &[build_batches.to_vec()], + Arc::clone(&schema), + None, + ) + .unwrap(); + let probe = TestMemoryExec::try_new_exec( + &[probe_batches.to_vec()], + Arc::clone(&schema), + None, + ) + .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) { + 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 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"); + for (name, join_type, pattern, build_rows, probe_rows, key_step) in [ + ( + "right_semi_interleaved_10pct", + JoinType::RightSemi, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_semi_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_anti_interleaved_10pct", + JoinType::RightAnti, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_anti_all_hit", + JoinType::RightAnti, + Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "inner_interleaved_10pct", + JoinType::Inner, + Pattern::InterleavedLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "inner_all_hit", + JoinType::Inner, + Pattern::AllHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_semi_clustered_10pct", + JoinType::RightSemi, + Pattern::ClusteredLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_anti_clustered_10pct", + JoinType::RightAnti, + Pattern::ClusteredLowHit, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_semi_high_to_low", + JoinType::RightSemi, + Pattern::HighToLow, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_anti_high_to_low", + JoinType::RightAnti, + Pattern::HighToLow, + BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ( + "right_semi_single_batch_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + BUILD_ROWS, + BATCH_SIZE, + SPARSE_KEY_STEP, + ), + ( + "right_semi_dense_100k_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + LARGE_BUILD_ROWS, + PROBE_ROWS, + DENSE_KEY_STEP, + ), + ( + "right_semi_sparse_100k_all_hit", + JoinType::RightSemi, + Pattern::AllHit, + LARGE_BUILD_ROWS, + PROBE_ROWS, + SPARSE_KEY_STEP, + ), + ] { + 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 => probe_rows, + Pattern::InterleavedLowHit | Pattern::ClusteredLowHit => { + probe_rows / HIT_EVERY + } + Pattern::HighToLow => probe_rows / 2 + probe_rows / 2 / HIT_EVERY, + }; + let expected_rows = if join_type == JoinType::RightAnti { + probe_rows - hits + } else { + hits + }; + let output = run(); + assert_eq!( + output.iter().map(RecordBatch::num_rows).sum::(), + expected_rows, + "{name}", + ); + drop(output); + + group.bench_function(name, |b| b.iter(|| black_box(run()))); + } + 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 f6ff292556c24..845945d8073f9 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::key_range_bitmap::KeyRangeBitmap; use crate::joins::utils::{ @@ -347,6 +348,8 @@ impl NullAwareMode { struct JoinBuildData { /// Hash table with row indices into `batch`, also shared with dynamic filters. map: Arc, + /// Optional exact integer membership bitmap shared by probe streams. + integer_prefilter: Option, /// The input rows for the build side. batch: RecordBatch, /// Evaluated build-side key expressions, with float `-0.0` rewritten to @@ -394,6 +397,10 @@ impl JoinLeftData { &self.build.map } + pub(super) fn integer_prefilter(&self) -> Option<&IntegerPrefilter> { + self.build.integer_prefilter.as_ref() + } + pub(super) fn null_aware_scope_map(&self) -> Option<&dyn JoinHashMapType> { self.null_aware_scope_map.as_deref() } @@ -1812,6 +1819,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 (probe_prefilter_rows_pruned, integer_prefilter_created_count) = + if integer_prefilter_state.is_some() { + ( + MetricBuilder::new(&self.metrics) + .with_category(MetricCategory::Rows) + .counter("probe_prefilter_rows_pruned", 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 null_aware = self.null_aware_mode()?; @@ -1877,6 +1906,7 @@ impl ExecutionPlan for HashJoinExec { self.null_equality, null_aware, array_map_created_count, + integer_prefilter_created_count, BuildMode::Ordinary, )) })?, @@ -1899,6 +1929,7 @@ impl ExecutionPlan for HashJoinExec { self.null_equality, null_aware, array_map_created_count, + integer_prefilter_created_count, BuildMode::Ordinary, )) } @@ -1951,6 +1982,8 @@ impl ExecutionPlan for HashJoinExec { self.mode, null_aware, self.fetch, + integer_prefilter_state, + probe_prefilter_rows_pruned, ))) } @@ -3195,6 +3228,7 @@ async fn collect_left_input( null_equality: NullEquality, null_aware: Option, array_map_created_count: Count, + integer_prefilter_created_count: Count, mode: BuildMode, ) -> Result { let schema = left_stream.schema(); @@ -3535,10 +3569,6 @@ 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; @@ -3556,9 +3586,40 @@ 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 + { + 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, + &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 { build: Arc::new(JoinBuildData { map, + integer_prefilter, batch, values: normalized_values, bounds, @@ -3580,6 +3641,230 @@ async fn collect_left_input( mod tests { use super::*; + fn integer_prefilter_join( + build: ArrayRef, + probe: ArrayRef, + ) -> 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 on = vec![(col("key", &left.schema())?, col("key", &right.schema())?)]; + Ok(Arc::new(HashJoinExec::try_new( + left, + right, + on, + None, + &JoinType::Full, + None, + PartitionMode::CollectLeft, + NullEquality::NullEqualsNothing, + false, + )?)) + } + + 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 = + datafusion_common::config::ConfigNonZeroUsize::try_new(3).unwrap(); + Arc::new(TaskContext::default().with_session_config(config)) + } + + #[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(StringArray::from(vec!["a", "c"])), + Arc::new(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)?; + 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("probe_prefilter_rows_pruned") + .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])), + ) + }; + // 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(64) * size_of::()] { + 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("probe_prefilter_rows_pruned") + .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("probe_prefilter_rows_pruned") + .unwrap() + .as_usize(), + 12 + ); + } else { + expected = Some(output); + } + } + Ok(()) + } + fn assert_phj_used(metrics: &MetricsSet, use_phj: bool) { if use_phj { assert!( @@ -3667,7 +3952,7 @@ mod tests { }; 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, }; @@ -4446,6 +4731,7 @@ mod tests { NullEquality::NullEqualsNothing, None, Count::new(), + Count::new(), BuildMode::Ordinary, ) .await?; diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs index fb46cedf96cf1..a83e5df9a5b72 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec/prepared.rs @@ -197,6 +197,7 @@ impl HashJoinExec { self.null_equality, None, count, + Count::new(), BuildMode::Prepared, ) .await?; diff --git a/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs b/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs index 48281e5f481b1..8b0e8d361d72f 100644 --- a/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs +++ b/datafusion/physical-plan/src/joins/hash_join/exec/prepared/tests.rs @@ -163,6 +163,82 @@ fn payload_filter(op: Operator) -> JoinFilter { ) } +#[tokio::test] +async fn prepared_build_integer_prefilter() -> Result<()> { + use datafusion_execution::config::SessionConfig; + + let batches = vec![ + batch(vec![Some(0), Some(1024)]), + batch(vec![Some(2048), Some(3072)]), + ]; + let probe = batch(vec![ + Some(0), + Some(1), + Some(1024), + Some(1025), + Some(2048), + Some(2049), + Some(3072), + ]); + let base = join(batches[0].schema(), probe.clone())?; + let mut baseline_bytes = 0; + let mut expected = None; + for build_enabled in [false, true] { + let mut config = ConfigOptions::default(); + config.execution.enable_join_integer_prefilter = build_enabled; + let prepared = base + .prepare_build( + input(batches.clone(), batches[0].schema()), + Arc::new(GreedyMemoryPool::new(1 << 20)), + Arc::new(config), + ) + .await?; + if build_enabled { + let bitmap = prepared.build.integer_prefilter.as_ref().unwrap(); + assert!(bitmap.size() > 0); + assert_eq!(prepared.reserved_bytes(), baseline_bytes + bitmap.size()); + } else { + assert!(prepared.build.integer_prefilter.is_none()); + baseline_bytes = prepared.reserved_bytes(); + } + + // Repeated consumers share the bitmap, but each chooses whether to use it. + for probe_enabled in [false, true, true] { + let consumer = Arc::new( + join(base.left().schema(), probe.clone())? + .builder() + .with_prepared_build(Arc::clone(&prepared)) + .build()?, + ); + let mut config = SessionConfig::default(); + config.options_mut().execution.enable_join_integer_prefilter = probe_enabled; + let context = Arc::new(TaskContext::default().with_session_config(config)); + let output = crate::collect(Arc::clone(&consumer) as _, context).await?; + assert_eq!(output.iter().map(RecordBatch::num_rows).sum::(), 4); + let output = batches_to_sort_string(&output); + if let Some(expected) = &expected { + assert_eq!(&output, expected); + } else { + expected = Some(output); + } + let metrics = consumer.metrics().unwrap(); + assert_eq!( + metrics + .sum_by_name("integer_prefilter_created_count") + .map_or(0, |count| count.as_usize()), + 0, + ); + assert_eq!( + metrics + .sum_by_name("probe_prefilter_rows_pruned") + .map_or(0, |count| count.as_usize()), + if build_enabled && probe_enabled { 3 } else { 0 }, + ); + } + } + Ok(()) +} + #[tokio::test] async fn prepared_build_placeholder_properties_and_reset() -> Result<()> { let ascending = |name, index| PhysicalSortExpr { diff --git a/datafusion/physical-plan/src/joins/hash_join/stream.rs b/datafusion/physical-plan/src/joins/hash_join/stream.rs index fb2263ebcca71..48f0827b3cda6 100644 --- a/datafusion/physical-plan/src/joins/hash_join/stream.rs +++ b/datafusion/physical-plan/src/joins/hash_join/stream.rs @@ -32,9 +32,11 @@ use crate::joins::hash_join::probe_completion::ProbeSideSummary; use crate::joins::hash_join::shared_bounds::{ PartitionBounds, PartitionBuildData, SharedBuildAccumulator, }; +use crate::joins::integer_prefilter::PrefilterState; use crate::joins::utils::{ JoinKeyComparator, OnceFut, equal_rows_arr_with_normalized_left, matchable_join_keys, }; +use crate::metrics::Count; use crate::stream::EmptyRecordBatchStream; use crate::{ RecordBatchStream, SendableRecordBatchStream, handle_state, @@ -55,6 +57,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_expr::{ColumnarValue, Operator}; use datafusion_physical_expr::PhysicalExprRef; use datafusion_physical_expr_common::datum::apply_cmp; @@ -188,6 +191,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 @@ -378,6 +383,8 @@ pub(super) struct HashJoinStream { random_state: RandomState, /// Metrics join_metrics: BuildProbeJoinMetrics, + integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, + probe_prefilter_rows_pruned: Count, /// Information of index and left / right placement of columns column_indices: Vec, /// Defines the null equality for the join. @@ -571,6 +578,8 @@ impl HashJoinStream { mode: PartitionMode, null_aware: Option, fetch: Option, + integer_prefilter_state: Option<(PrefilterState, MemoryReservation)>, + probe_prefilter_rows_pruned: Count, ) -> Self { // Create output buffer with coalescing and optional fetch limit. let output_buffer = @@ -585,6 +594,8 @@ impl HashJoinStream { right, random_state, join_metrics, + integer_prefilter_state, + probe_prefilter_rows_pruned, column_indices, null_equality, state, @@ -782,6 +793,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 @@ -810,6 +825,47 @@ 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(), + ) { + 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 state.should_filter(batch.num_rows()) + && bytes + .is_some_and(|bytes| reservation.try_resize(bytes).is_ok()) + { + 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(), Some(&mask)); + 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()); @@ -818,6 +874,7 @@ impl HashJoinStream { batch, values: keys_values, valid_keys, + lookup_keys, offset: (0, None), joined_probe_idx: None, matched_probe_idx: None, @@ -909,7 +966,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..01e5d0d2c6bc1 --- /dev/null +++ b/datafusion/physical-plan/src/joins/integer_prefilter.rs @@ -0,0 +1,459 @@ +// 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 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::{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 { + 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: u64, + reservation: &MemoryReservation, + ) -> Option { + if !ArrayMap::is_supported_type(values.data_type()) || max_key_range == 0 { + return None; + } + 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 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 words = Vec::new(); + if words.try_reserve_exact(word_count).is_err() { + reservation.shrink(bytes); + return None; + } + let extra = (words.capacity() - word_count) * size_of::(); + if reservation.try_grow(extra).is_err() { + reservation.shrink(bytes); + return None; + } + words.resize(word_count, 0); + downcast_integer_array!(values => { + for value in values.iter().flatten() { + 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 { + offset, + key_count, + words, + data_type: values.data_type().clone(), + }) + } + + pub(super) fn size(&self) -> usize { + self.words.capacity() * size_of::() + } + + #[inline] + fn contains(&self, value: u64) -> bool { + // 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 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, +} + +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, + } + } + + pub(super) fn try_from_config(config: &ExecutionOptions) -> Result> { + if !config.enable_join_integer_prefilter { + return Ok(None); + } + 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.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. + 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 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, + ) -> Option { + if values.data_type() != &filter.data_type { + return None; + } + 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 { + let values = values.values(); + BooleanBuffer::collect_bool(values.len(), |i| { + filter.contains(values[i] as u64) + }) + } else { + BooleanBuffer::collect_bool(values.len(), |i| { + values.is_null(i) || filter.contains(values.value(i) as u64) + }) + } + } + _ => return None); + let mask = NullBuffer::new(mask); + let pruned = mask.null_count(); + self.record_sample(values.len(), pruned); + (pruned > 0).then_some(mask) + } + + 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.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.rows_observed = 0; + self.rows_pruned = 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(8); + let filter = IntegerPrefilter::try_new( + &build, + ( + &ScalarValue::$scalar(Some(min)), + &ScalarValue::$scalar(Some(min + 2)), + ), + 3, + &memory, + ) + .unwrap(); + assert_eq!(memory.size(), 8); + 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 mask = PrefilterState::new(10, 0.5) + .filter(&filter, &probe) + .unwrap(); + assert_eq!(mask.null_count(), 2); + assert_eq!( + mask.iter().collect::>(), + vec![true, 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 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_overflow() { + 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)) + ), + u64::MAX, + &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)) + ), + u64::MAX, + &memory + ) + .is_none() + ); + } + + #[test] + fn bitmap_word_boundaries() { + let build = Int32Array::from(vec![-1, 62, 63, 64]); + let memory = reservation(16); + let filter = IntegerPrefilter::try_new( + &build, + (&ScalarValue::Int32(Some(-1)), &ScalarValue::Int32(Some(64))), + 66, + &memory, + ) + .unwrap(); + 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)); + } + } + + #[test] + 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, + &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); + assert!(!state.should_filter(0)); + let nulls = Int32Array::from(vec![None; 4]); + 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] + 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(8); + let filter = IntegerPrefilter::try_new( + &Int32Array::from(vec![0]), + (&ScalarValue::Int32(Some(0)), &ScalarValue::Int32(Some(0))), + 1, + &memory, + ) + .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()); + assert_eq!(pruned, values.iter().filter(|v| *v == Some(1)).count()); + assert_eq!( + lookup.iter().collect::>(), + values.iter().map(|v| v == Some(0)).collect::>() + ); + } +} diff --git a/datafusion/physical-plan/src/joins/mod.rs b/datafusion/physical-plan/src/joins/mod.rs index c5d5fbe543f6f..ed42766a57173 100644 --- a/datafusion/physical-plan/src/joins/mod.rs +++ b/datafusion/physical-plan/src/joins/mod.rs @@ -44,6 +44,7 @@ mod asof_join; mod chain; mod cross_join; mod hash_join; +mod integer_prefilter; mod logical_batch; mod nested_loop_join; mod piecewise_merge_join; 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..a4869a460d2b4 --- /dev/null +++ b/datafusion/sqllogictest/test_files/hash_join_integer_prefilter.slt @@ -0,0 +1,242 @@ +# 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, probe_prefilter_rows_pruned=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, 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=0, probe_prefilter_rows_pruned=0, ] + + +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, probe_prefilter_rows_pruned=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 + +# 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; + +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/datafusion/sqllogictest/test_files/information_schema.slt b/datafusion/sqllogictest/test_files/information_schema.slt index 82cef82f7bb9a..b9ff18f5d3816 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 @@ -382,11 +386,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 shares left-side state (the current left chunk, the visited bitmap and the 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) give each task its own copy of this state 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`). diff --git a/docs/source/user-guide/configs.md b/docs/source/user-guide/configs.md index ab68aa6a11639..95e309d929b06 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 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 |