Copilot commented on code in PR #26442:
URL: https://github.com/apache/datafusion/pull/26442#discussion_r4750662223
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -3553,14 +3523,59 @@ fn build_in_memory(
}
ok
});
- PushdownStrategy::Map(Arc::clone(&map), pruning_bitmap)
+ PushdownStrategy::Large(pruning_bitmap)
}
};
if is_phj_candidate && !should_compute_dynamic_filters {
bounds = None;
}
+ // Fill the bloom filter of this partition's keys here, in its build task,
+ // so the finalizing task only ORs the partition filters. Partitions hold
+ // disjoint keys of similar counts, so the filter is sized for the keys of
+ // all partitions estimated from this one.
+ let bloom_filter = if !should_compute_dynamic_filters
+ || matches!(membership, PushdownStrategy::Empty)
+ || left_values.is_empty()
+ {
+ None
+ } else {
+ let num_distinct = map
+ .num_of_distinct_key()
+ .saturating_mul(num_build_partitions);
+ let options = GlobalFilterOptions::new(config).bloom_filter;
+ // Insert one hash per distinct key, not one per build row.
+ let filter = match &**map {
+ // The map hashes the keys with `random_state`, which is
+ // `HASH_JOIN_SEED`, the seed the filter is probed with. Keys whose
+ // hashes collide share an entry, and also share their filter bits.
+ Map::HashMap(hash_map) =>
bloom_filter::partition_filter_from_hashes(
+ |f| hash_map.for_each_entry_hash(f),
+ num_distinct,
+ options,
+ &reservation,
+ ),
+ Map::ArrayMap(array_map) => {
+ let rows = array_map.distinct_rows();
+ let keys = left_values
+ .iter()
+ .map(|values| take(values.as_ref(), &rows, None))
+ .collect::<std::result::Result<Vec<_>, _>>()?;
Review Comment:
The ArrayMap path materializes every distinct row index and copies its key
before checking the bloom filter's size limit or memory reservation. Even with
`hash_join_bloom_filter_max_bytes = 0`, a dense Int64 build allocates roughly
12 extra bytes per distinct key outside the memory pool, which can exhaust
process memory before falling back. Admit the filter before gathering keys,
then reserve the scratch space or process representative rows in bounded
batches.
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -3581,6 +3596,7 @@ fn build_in_memory(
values: normalized_values,
bounds,
membership,
+ bloom_filter,
Review Comment:
`JoinBuildData` keeps each partition's bloom filter throughout probing, even
after it has been merged into the global filter. Since each is sized for the
whole build, 128 partitions can retain up to 1 GiB of extra reserved memory and
cause otherwise viable joins to fail or spill. Transfer or release these
filters and their charges after finalization, independently of clearing the
accumulator's reports.
##########
datafusion/physical-plan/src/joins/hash_join/bloom_filter.rs:
##########
@@ -0,0 +1,694 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Bloom filter membership test over the build side keys of a hash join, for
+//! the join's dynamic filter.
+//!
+//! Each build partition inserts the hash join hashes of its keys into its own
+//! bloom filter ([`partition_filter`]), in its own build task. Once every
+//! partition is done, one task ORs the partition filters into one filter
+//! ([`Sbbf::union`]) and folds it to the target false positive probability.
+//! Folding and union commute, so this is the filter of all build keys.
+
+use std::fmt::{self, Display};
+use std::hash::Hash;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, BooleanArray};
+use arrow::buffer::NullBuffer;
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_execution::memory_pool::{MemoryConsumer, MemoryPool,
MemoryReservation};
+use datafusion_expr::ColumnarValue;
+use datafusion_expr_common::dyn_eq::DynHash;
+use datafusion_physical_expr_common::physical_expr::{PhysicalExpr,
PhysicalExprRef};
+use parquet::bloom_filter::Sbbf;
+
+use crate::joins::hash_join::exec::HASH_JOIN_SEED;
+use crate::joins::key_range_bitmap::KeyRangeBitmap;
+
+/// Sizing options of a [`BloomFilterExpr`].
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct BloomFilterOptions {
+ /// Target false positive probability.
+ pub(crate) fpp: f64,
+ /// Largest filter, in bytes. A build side that needs a larger filter at
+ /// `fpp` gets no bloom filter.
+ pub(crate) max_bytes: usize,
+ /// Do not use the filter when its estimated false positive probability is
+ /// above this value.
+ pub(crate) max_fpp: f64,
+}
+
+impl BloomFilterOptions {
+ /// Bytes of a filter for `num_distinct` keys at `fpp`, or `None` when
+ /// that is more than `max_bytes`.
+ fn bytes(&self, num_distinct: usize) -> Option<usize> {
+ let bits = -8.0 * num_distinct as f64 / (1.0 - self.fpp.powf(1.0 /
8.0)).ln();
+ let bytes = (bits / 8.0) as usize;
+ (bytes <= self.max_bytes).then_some(bytes)
+ }
+}
+
+fn parquet_err(e: parquet::errors::ParquetError) -> DataFusionError {
+ DataFusionError::External(Box::new(e))
+}
+
+/// Rows hashed at a time when filling a filter.
+const HASH_BATCH_SIZE: usize = 8192;
+
+/// Hashes `keys` like the hash join and calls `f` with the hashes of each
+/// batch of rows. A row with a NULL key gets no hash.
+fn for_each_hash_batch(
+ keys: &[ArrayRef],
+ mut f: impl FnMut(&[u64]) -> Result<()>,
+) -> Result<()> {
+ let num_rows = keys.first().map_or(0, |k| k.len());
+ let mut hashes = Vec::with_capacity(HASH_BATCH_SIZE.min(num_rows));
+ for offset in (0..num_rows).step_by(HASH_BATCH_SIZE) {
+ let len = HASH_BATCH_SIZE.min(num_rows - offset);
+ let batch: Vec<ArrayRef> = keys.iter().map(|k| k.slice(offset,
len)).collect();
+ hashes.clear();
+ hashes.resize(len, 0);
+ create_hashes(&batch, HASH_JOIN_SEED.random_state(), &mut hashes)?;
+ if let Some(valid) = valid_rows(&batch) {
+ let mut num_valid = 0;
+ for i in valid.valid_indices() {
+ hashes[num_valid] = hashes[i];
+ num_valid += 1;
+ }
+ hashes.truncate(num_valid);
+ }
+ f(&hashes)?;
+ }
+ Ok(())
+}
+
+/// The rows where no key is NULL, or `None` when no key has NULLs.
+fn valid_rows(keys: &[ArrayRef]) -> Option<NullBuffer> {
+ let nulls: Vec<_> = keys.iter().map(|k| k.logical_nulls()).collect();
+ NullBuffer::union_many(nulls.iter().map(Option::as_ref))
+}
+
+/// The bloom filter of the keys of one build partition, sized for
+/// `num_distinct` keys (the estimated number of distinct keys of all
+/// partitions, so that the partition filters can be ORed). `None` when that
+/// filter would be larger than `options.max_bytes`.
+///
+/// The filter memory is charged to `reservation`. `None` also when it cannot
+/// grow.
+pub(crate) fn partition_filter(
+ keys: &[ArrayRef],
+ num_distinct: usize,
+ options: BloomFilterOptions,
+ reservation: &MemoryReservation,
+) -> Result<Option<Sbbf>> {
+ let Some(mut filter) = new_partition_filter(num_distinct, options,
reservation)
+ else {
+ return Ok(None);
+ };
+ for_each_hash_batch(keys, |hashes| {
+ for &hash in hashes {
+ filter.insert_hash(hash);
+ }
+ Ok(())
+ })?;
+ Ok(Some(filter))
+}
+
+/// Like [`partition_filter`], but fills the filter from key hashes that the
+/// caller already computed with `HASH_JOIN_SEED`.
+pub(crate) fn partition_filter_from_hashes(
+ for_each_hash: impl FnOnce(&mut dyn FnMut(u64)),
+ num_distinct: usize,
+ options: BloomFilterOptions,
+ reservation: &MemoryReservation,
+) -> Option<Sbbf> {
+ let mut filter = new_partition_filter(num_distinct, options, reservation)?;
+ for_each_hash(&mut |hash| filter.insert_hash(hash));
+ Some(filter)
+}
+
+/// An empty filter sized for `num_distinct` keys, with its memory charged to
+/// `reservation`.
+fn new_partition_filter(
+ num_distinct: usize,
+ options: BloomFilterOptions,
+ reservation: &MemoryReservation,
+) -> Option<Sbbf> {
+ let bytes = options.bytes(num_distinct)?;
+ // The size that `Sbbf::new_with_num_of_bytes` allocates
+ reservation
+ .try_grow(bytes.max(32).next_power_of_two())
+ .ok()?;
+ Some(Sbbf::new_with_num_of_bytes(bytes))
+}
+
+/// The bloom filter of a [`BloomFilterExpr`] and the reservation for its
+/// memory, which is released when the filter is dropped.
+struct Filter {
+ filter: Sbbf,
+ _reservation: MemoryReservation,
+}
+
+/// ORs the filters of all build partitions and folds the result. Returns
+/// `None` (no bloom filter) when `pool` cannot hold the filter or it is
+/// saturated.
+fn merge(
+ partitions: &[&Sbbf],
+ options: BloomFilterOptions,
+ pool: &Arc<dyn MemoryPool>,
+) -> Result<Option<Filter>> {
+ // Partitions estimate the number of keys of all partitions from their own,
+ // so their filters can differ in size: fold the larger ones into the
+ // smallest.
+ let Some((smallest, first)) = partitions
+ .iter()
+ .enumerate()
+ .min_by_key(|(_, f)| f.num_blocks())
+ .map(|(i, f)| (i, *f))
+ else {
+ return Ok(None);
+ };
+ let reservation =
MemoryConsumer::new("HashJoinBloomFilter").register(pool);
+ if reservation.try_grow(first.num_blocks() * 32).is_err() {
+ return Ok(None);
+ }
+ let mut filter = first.clone();
+ for (i, partition) in partitions.iter().enumerate() {
+ if i != smallest {
+ filter.union(partition).map_err(parquet_err)?;
+ }
+ }
+ filter.fold_to_target_fpp(options.fpp);
+ // A saturated filter costs CPU time and removes almost no rows
+ if filter.estimated_fpp() > options.max_fpp {
+ return Ok(None);
+ }
+ reservation.resize(filter.num_blocks() * 32);
+ Ok(Some(Filter {
+ filter,
+ _reservation: reservation,
+ }))
+}
+
+/// Physical expression that tests join keys against a bloom filter of the
+/// build side keys of a hash join.
+///
+/// The result is `true` for a row whose keys may be on the build side, and
+/// `false` for a row whose keys are definitely not on the build side (or are
+/// NULL). The filter holds the hash join hashes of the keys (all key columns
+/// together), so it supports every key type that the hash join supports.
+pub struct BloomFilterExpr {
+ /// Probe side join key expressions
+ on_columns: Vec<PhysicalExprRef>,
+ /// `None` when no bloom filter was built
+ filter: Option<Arc<Filter>>,
+ /// Which parts of the build side's key range hold keys, for container
pruning
+ pruning_bitmap: Option<Arc<KeyRangeBitmap>>,
+}
+
+impl BloomFilterExpr {
+ /// ORs the bloom filters of every build partition ([`partition_filter`])
+ /// into one filter, charged to `pool`.
+ ///
+ /// When no useful filter is possible (`partitions` is `None` because a
+ /// partition has no filter, `pool` cannot hold the filter, or the filter
+ /// is saturated), the expression has no filter: it is `true` for every
+ /// row and only carries `pruning_bitmap` (see [`Self::has_filter`]).
+ pub(crate) fn try_new(
+ on_columns: Vec<PhysicalExprRef>,
+ partitions: Option<&[&Sbbf]>,
+ options: BloomFilterOptions,
+ pool: &Arc<dyn MemoryPool>,
+ pruning_bitmap: Option<Arc<KeyRangeBitmap>>,
+ ) -> Result<Self> {
+ let filter = match partitions {
+ Some(partitions) => merge(partitions, options,
pool)?.map(Arc::new),
+ None => None,
+ };
+ Ok(Self {
+ on_columns,
+ filter,
+ pruning_bitmap,
+ })
+ }
+
+ /// Returns `true` if the expression tests rows against a bloom filter.
+ /// Without a filter it only carries the pruning bitmap.
+ pub fn has_filter(&self) -> bool {
+ self.filter.is_some()
+ }
+
+ /// Which parts of the build side's key range hold keys, for container
pruning.
+ pub fn pruning_bitmap(&self) -> Option<&Arc<KeyRangeBitmap>> {
+ self.pruning_bitmap.as_ref()
+ }
+
+ /// Bytes of the bloom filter, 0 without a filter.
+ #[cfg(test)]
+ pub(crate) fn filter_bytes(&self) -> usize {
+ self.filter
+ .as_ref()
+ .map_or(0, |filter| filter.filter.num_blocks() * 32)
+ }
+
+ /// The probe side key expressions.
+ pub fn on_columns(&self) -> &[PhysicalExprRef] {
+ &self.on_columns
+ }
+}
+
+impl fmt::Debug for BloomFilterExpr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let cols = self
+ .on_columns
+ .iter()
+ .map(|e| e.to_string())
+ .collect::<Vec<_>>()
+ .join(", ");
+ write!(f, "bloom_filter({cols})")
+ }
+}
+
+impl Hash for BloomFilterExpr {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.on_columns.dyn_hash(state);
+ self.filter.as_ref().map(Arc::as_ptr).hash(state);
+ }
+}
+
+impl PartialEq for BloomFilterExpr {
+ fn eq(&self, other: &Self) -> bool {
+ self.on_columns == other.on_columns
+ && match (&self.filter, &other.filter) {
+ (Some(a), Some(b)) => Arc::ptr_eq(a, b),
+ (None, None) => true,
+ _ => false,
+ }
+ }
+}
+
+impl Eq for BloomFilterExpr {}
+
+impl Display for BloomFilterExpr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.has_filter() {
+ write!(f, "bloom_filter")
+ } else {
+ write!(f, "key_range_pruning")
+ }
+ }
+}
+
+impl PhysicalExpr for BloomFilterExpr {
+ fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
+ self.on_columns.iter().collect()
+ }
+
+ fn with_new_children(
+ self: Arc<Self>,
+ children: Vec<Arc<dyn PhysicalExpr>>,
+ ) -> Result<Arc<dyn PhysicalExpr>> {
+ Ok(Arc::new(Self {
+ on_columns: children,
+ filter: self.filter.clone(),
+ pruning_bitmap: self.pruning_bitmap.clone(),
+ }))
+ }
+
+ fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
+ Ok(DataType::Boolean)
+ }
+
+ fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
+ Ok(false)
+ }
+
+ fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
+ let Some(filter) = &self.filter else {
+ // No filter: only the pruning bitmap, which is not tested per row
+ return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(true))));
+ };
+ let num_rows = batch.num_rows();
+ let keys = self
+ .on_columns
+ .iter()
+ .map(|c| c.evaluate(batch)?.into_array(num_rows))
+ .collect::<Result<Vec<_>>>()?;
+ let mut hashes = vec![0; num_rows];
+ create_hashes(&keys, HASH_JOIN_SEED.random_state(), &mut hashes)?;
+ let matches = filter.filter.check_hashes(&hashes);
+ // A NULL key matches no build key
+ let matches = match valid_rows(&keys) {
+ Some(valid) => &matches & valid.inner(),
+ None => matches,
+ };
+ Ok(ColumnarValue::Array(Arc::new(BooleanArray::new(
+ matches, None,
+ ))))
+ }
+
+ #[cfg(feature = "proto")]
+ fn try_to_proto(
+ &self,
+ _ctx:
&datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
+ ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
+ use datafusion_proto_models::protobuf;
+ use datafusion_proto_models::protobuf::physical_expr_node::ExprType;
+
+ // The expression holds runtime build side
+ // state that is not serialized. It is replaced with lit(true), which
+ // keeps every row: the dynamic filter is only an optimization. A plan
+ // that is executed again calls reset_state(), and the join builds a
new
+ // dynamic filter at runtime.
+ let Self {
+ on_columns: _,
+ filter: _,
+ pruning_bitmap: _,
+ } = self;
+ let value = datafusion_proto_common::ScalarValue {
+ value:
Some(datafusion_proto_common::scalar_value::Value::BoolValue(
+ true,
+ )),
+ };
+ Ok(Some(protobuf::PhysicalExprNode {
+ expr_id: None,
+ expr_type: Some(ExprType::Literal(value)),
+ }))
+ }
+
+ fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{self}")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow::array::{Float64Array, Int64Array, StringArray};
+ use arrow::datatypes::Field;
+ use datafusion_execution::memory_pool::{GreedyMemoryPool,
UnboundedMemoryPool};
+ use datafusion_physical_expr::expressions::Column;
+
+ const OPTIONS: BloomFilterOptions = BloomFilterOptions {
+ fpp: 0.01,
+ max_bytes: 8 * 1024 * 1024,
+ max_fpp: 0.15,
+ };
+
+ fn unbounded() -> Arc<dyn MemoryPool> {
+ Arc::new(UnboundedMemoryPool::default())
+ }
+
+ /// The filters of `partitions`, each sized for the keys of all partitions.
+ fn partition_filters(
+ partitions: &[Vec<ArrayRef>],
+ options: BloomFilterOptions,
+ ) -> Option<Vec<Sbbf>> {
+ let num_distinct = partitions.iter().map(|p| p[0].len()).sum();
+ partitions
+ .iter()
+ .map(|keys| filter_of(keys, num_distinct, options))
+ .collect()
+ }
+
+ fn filter_of(
+ keys: &[ArrayRef],
+ num_distinct: usize,
+ options: BloomFilterOptions,
+ ) -> Option<Sbbf> {
+ let reservation = MemoryConsumer::new("test").register(&unbounded());
+ partition_filter(keys, num_distinct, options, &reservation).unwrap()
+ }
+
+ fn expr_with(
+ columns: Vec<PhysicalExprRef>,
+ partitions: &[Vec<ArrayRef>],
+ options: BloomFilterOptions,
+ pool: &Arc<dyn MemoryPool>,
+ ) -> Option<BloomFilterExpr> {
+ let filters = partition_filters(partitions, options);
+ let refs = filters.as_ref().map(|f| f.iter().collect::<Vec<_>>());
+ let expr =
+ BloomFilterExpr::try_new(columns, refs.as_deref(), options, pool,
None)
+ .unwrap();
+ expr.has_filter().then_some(expr)
+ }
+
+ fn int_keys(keys: Vec<i64>) -> Vec<ArrayRef> {
+ vec![Arc::new(Int64Array::from(keys))]
+ }
+
+ fn int_expr_with(
+ partitions: Vec<Vec<i64>>,
+ options: BloomFilterOptions,
+ pool: &Arc<dyn MemoryPool>,
+ ) -> Option<BloomFilterExpr> {
+ let partitions: Vec<_> =
partitions.into_iter().map(int_keys).collect();
+ expr_with(
+ vec![Arc::new(Column::new("k", 0))],
+ &partitions,
+ options,
+ pool,
+ )
+ }
+
+ fn int_expr(partitions: Vec<Vec<i64>>) -> BloomFilterExpr {
+ int_expr_with(partitions, OPTIONS, &unbounded()).unwrap()
+ }
+
+ fn int_batch(keys: Vec<Option<i64>>) -> RecordBatch {
+ let schema = Schema::new(vec![Field::new("k", DataType::Int64, true)]);
+ RecordBatch::try_new(Arc::new(schema),
vec![Arc::new(Int64Array::from(keys))])
+ .unwrap()
+ }
+
+ fn eval(expr: &BloomFilterExpr, batch: &RecordBatch) -> Vec<bool> {
+ let result = expr
+ .evaluate(batch)
+ .unwrap()
+ .into_array(batch.num_rows())
+ .unwrap();
+ let result = result.as_any().downcast_ref::<BooleanArray>().unwrap();
+ result.iter().map(|v| v.unwrap()).collect()
+ }
+
+ #[test]
+ fn finds_build_keys_and_rejects_others() {
+ let expr = int_expr(vec![(0..1000).collect(), (5000..6000).collect()]);
+ let batch = int_batch((0..10_000).map(Some).collect());
+ let result = eval(&expr, &batch);
+ // No false negatives
+ for k in (0..1000).chain(5000..6000) {
+ assert!(result[k], "key {k} dropped");
+ }
+ // Few false positives
+ let false_positives = result.iter().filter(|v| **v).count() - 2000;
+ assert!(false_positives < 200, "{false_positives} false positives");
Review Comment:
The `hash-collisions` CI suite forces every key hash to zero, so the new
false-positive limits, exact-miss expectations, and saturation test fail. Make
these expectations collision-aware here and in
`shared_bounds.rs:1263,1322–1325`, while keeping no-false-negative and NULL
checks active. Gate only distribution-dependent assertions or tests, or use
explicit synthetic hashes for saturation.
##########
datafusion/physical-plan/src/joins/hash_join/bloom_filter.rs:
##########
@@ -0,0 +1,694 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Bloom filter membership test over the build side keys of a hash join, for
+//! the join's dynamic filter.
+//!
+//! Each build partition inserts the hash join hashes of its keys into its own
+//! bloom filter ([`partition_filter`]), in its own build task. Once every
+//! partition is done, one task ORs the partition filters into one filter
+//! ([`Sbbf::union`]) and folds it to the target false positive probability.
+//! Folding and union commute, so this is the filter of all build keys.
+
+use std::fmt::{self, Display};
+use std::hash::Hash;
+use std::sync::Arc;
+
+use arrow::array::{Array, ArrayRef, BooleanArray};
+use arrow::buffer::NullBuffer;
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::{DataFusionError, Result, ScalarValue};
+use datafusion_execution::memory_pool::{MemoryConsumer, MemoryPool,
MemoryReservation};
+use datafusion_expr::ColumnarValue;
+use datafusion_expr_common::dyn_eq::DynHash;
+use datafusion_physical_expr_common::physical_expr::{PhysicalExpr,
PhysicalExprRef};
+use parquet::bloom_filter::Sbbf;
+
+use crate::joins::hash_join::exec::HASH_JOIN_SEED;
+use crate::joins::key_range_bitmap::KeyRangeBitmap;
+
+/// Sizing options of a [`BloomFilterExpr`].
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct BloomFilterOptions {
+ /// Target false positive probability.
+ pub(crate) fpp: f64,
+ /// Largest filter, in bytes. A build side that needs a larger filter at
+ /// `fpp` gets no bloom filter.
+ pub(crate) max_bytes: usize,
+ /// Do not use the filter when its estimated false positive probability is
+ /// above this value.
+ pub(crate) max_fpp: f64,
+}
+
+impl BloomFilterOptions {
+ /// Bytes of a filter for `num_distinct` keys at `fpp`, or `None` when
+ /// that is more than `max_bytes`.
+ fn bytes(&self, num_distinct: usize) -> Option<usize> {
+ let bits = -8.0 * num_distinct as f64 / (1.0 - self.fpp.powf(1.0 /
8.0)).ln();
+ let bytes = (bits / 8.0) as usize;
+ (bytes <= self.max_bytes).then_some(bytes)
Review Comment:
The size limit is checked before rounding to the actual allocation size.
With 800 distinct keys, FPP 0.01 and `max_bytes = 1000`, the 968-byte estimate
is admitted even though `new_partition_filter` reserves and allocates 1024
bytes. Compare the power-of-two-rounded size, including the 32-byte minimum,
against the configured maximum.
##########
datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs:
##########
@@ -708,200 +723,189 @@ impl SharedBuildAccumulator {
}
}
- /// Builds one probe-side filter from finalized partitioned build data.
+ /// Builds the global filter from finalized partitioned build data.
+ ///
/// Empty and canceled partitions contribute no key.
- fn build_partitioned_filter(&self, partitions: Vec<PartitionStatus>) ->
Result<()> {
- let num_partitions = partitions.len();
- let mut members = Vec::with_capacity(num_partitions);
- let mut merged_bounds: Option<PartitionBounds> = None;
- let mut keys_have_null = false;
-
- for (partition_id, partition) in partitions.into_iter().enumerate() {
+ fn build_partitioned_filter(&self, partitions: &[PartitionStatus]) ->
Result<()> {
+ let mut reported = Vec::with_capacity(partitions.len());
+ for partition in partitions {
match partition {
+ PartitionStatus::Reported(data) => reported.push(data),
// A canceled partition's stream never probes, so no key of its
// build side can matter.
- PartitionStatus::CanceledUnknown
- | PartitionStatus::Reported(PartitionData {
- pushdown: PushdownStrategy::Empty,
- ..
- }) => {}
- PartitionStatus::Reported(PartitionData {
- bounds,
- pushdown,
- keys_have_null: partition_keys_have_null,
- }) => {
- keys_have_null |= partition_keys_have_null;
- merged_bounds = Some(match merged_bounds {
- None => bounds.clone(),
- Some(merged) => merged.union(&bounds),
- });
- members.push((partition_id, pushdown, bounds));
- }
+ PartitionStatus::CanceledUnknown => {}
PartitionStatus::Pending => {
- return internal_err!(
+ return datafusion_common::internal_err!(
"attempted to finalize dynamic filter with pending
partition"
);
}
}
}
-
- let filter_expr = match members.as_slice() {
- // No build row exists, so no probe row can match.
- [] => lit(false),
- // Only one build partition holds rows, so its own filter covers
every
- // probe match without routing, and an IN list keeps its pruning.
- [(_, pushdown, bounds)] => combine_membership_and_bounds(
- create_membership_predicate(
- &self.on_right,
- pushdown.clone(),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?,
- create_bounds_predicate(&self.on_right, bounds),
- )
- .expect("membership predicate is always present"),
- _ => {
- self.merged_membership_filter(&members, merged_bounds,
num_partitions)?
- }
- };
self.dynamic_filter
- .update(self.preserve_probe_nulls(filter_expr, keys_have_null)?)
+ .update(self.build_global_filter(&reported)?)
}
- /// `members` holds each non-empty partition's id, strategy (an IN list, a
- /// hash table or an array map) and bounds, out of `num_partitions`
partitions.
- fn merged_membership_filter(
+ /// Builds one filter for all probe rows from the build data of every
partition,
+ /// with no routing to partitions:
+ ///
+ /// ```text
+ /// [key IS NULL OR] key >= min AND key <= max AND membership(key)
+ /// ```
+ ///
+ /// `min` and `max` are the global bounds. `membership` is an InList of the
+ /// keys of all partitions when they have at most
+ /// `hash_join_dynamic_filter_inlist_max_distinct_values` distinct keys
together,
+ /// and a [`BloomFilterExpr`] otherwise. The filter is true for every build
+ /// key, whatever the partitioning of the build and probe sides, so it is
+ /// correct for hash, range and collect-left joins.
+ fn build_global_filter(
&self,
- members: &[(usize, PushdownStrategy, PartitionBounds)],
- merged_bounds: Option<PartitionBounds>,
- num_partitions: usize,
+ partitions: &[&PartitionData],
) -> Result<Arc<dyn PhysicalExpr>> {
- let lists = members
+ let non_empty: Vec<&PartitionData> = partitions
.iter()
- .filter_map(|(_, pushdown, _)| match pushdown {
- PushdownStrategy::InList(values) => Some(values),
+ .copied()
+ .filter(|p| !matches!(p.pushdown, PushdownStrategy::Empty))
+ .collect();
+ if non_empty.is_empty() {
+ // No build row exists, so no probe row can match.
+ return Ok(lit(false));
+ }
+ let keys_have_null = non_empty.iter().any(|p| p.keys_have_null);
+ let bounds = PartitionBounds::merge(non_empty.iter().map(|p|
&p.bounds));
+ let num_distinct: usize =
+ non_empty.iter().map(|p| p.build_keys.num_distinct).sum();
+
+ let in_lists = non_empty
+ .iter()
+ .map(|p| match &p.pushdown {
+ PushdownStrategy::InList(values) => Some(Arc::clone(values)),
_ => None,
})
- .collect::<Vec<_>>();
-
- // Every partition is an IN list, and together they still fit the
limits a
- // single build uses to pick an IN list: one combined list keeps the
- // statistics and bloom filter pruning an IN list allows. Past those
- // limits, a hash lookup is cheaper per row and carries a pruning
bitmap.
- let combined_in_list = lists.len() == members.len() && {
- let values = lists.iter().map(|list| list.len()).sum::<usize>();
- let bytes = lists
- .iter()
- .map(|list| list.get_array_memory_size())
- .sum::<usize>();
- values <= self.in_list_max_values && bytes <= self.in_list_max_size
- };
- let membership = if combined_in_list {
- let values = concat(&lists.iter().map(|l|
l.as_ref()).collect::<Vec<_>>())?;
- create_membership_predicate(
- &self.on_right,
- PushdownStrategy::InList(values),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?
- .expect("an IN list always has a membership predicate")
- } else {
- // Each probe row is looked up in the table of the partition its
key
- // routes to, so the partitions' tables are shared as they are: no
- // merged table to build while every probe stream waits on the
filter.
- let mut maps = vec![None; num_partitions];
- for (partition_id, pushdown, _) in members {
- maps[*partition_id] = Some(match pushdown {
- PushdownStrategy::Map(map, _) => Arc::clone(map),
- PushdownStrategy::InList(values) =>
self.in_list_hash_map(values)?,
- PushdownStrategy::Empty => {
- return internal_err!("empty partitions have no
members");
- }
- });
+ .collect::<Option<Vec<_>>>();
+ let membership_expr = match &in_lists {
+ // The partitions hold disjoint keys, so the sum of their distinct
+ // counts is the number of distinct keys of the build side.
+ Some(in_lists)
+ if num_distinct
+ <= self.global_filter_options.inlist_max_distinct_values =>
+ {
+ let arrays: Vec<&dyn Array> =
+ in_lists.iter().map(|a| a.as_ref()).collect();
+ let values =
distinct_values(&arrow::compute::concat(&arrays)?)?;
+ Some(create_in_list_predicate(
+ &self.on_right,
+ values,
+ self.probe_schema.as_ref(),
+ )?)
}
- Arc::new(HashTableLookupExpr::new_reserved(
- self.on_right.clone(),
- HASH_JOIN_SEED,
- Some(self.partition_router(num_partitions)?),
- maps,
- String::from("hash_lookup"),
- self.merged_pruning_bitmap(members, merged_bounds.as_ref()),
- )?)
- };
-
- let bounds = merged_bounds
- .and_then(|bounds| create_bounds_predicate(&self.on_right,
&bounds));
- Ok(combine_membership_and_bounds(Some(membership), bounds)
- .expect("membership predicate is always present"))
- }
-
- /// How probe rows find their build partition: as the probe side was
- /// partitioned.
- fn partition_router(&self, num_partitions: usize) ->
Result<PartitionRouter> {
- Ok(match &self.probe_range_partitioning {
- Some(range_partitioning) => {
- assert_or_internal_err!(
- num_partitions == range_partitioning.partition_count(),
- "Dynamic filter partition count {} does not match Range
partition count {}",
- num_partitions,
- range_partitioning.partition_count()
- );
- PartitionRouter::Range(Arc::new(RangeExpr::try_new_with_schema(
+ _ => {
+ let pruning_bitmap =
+ self.merge_pruning_bitmaps(&non_empty, bounds.as_ref());
+ // Every partition must have its filter. A partition has none
+ // when the build side is too big for a bloom filter, or its
+ // memory reservation failed.
+ let pool = self
+ .global_filter_options
+ .memory_pool
+ .clone()
+ .unwrap_or_else(||
Arc::new(UnboundedMemoryPool::default()));
+ // Each partition sizes its filter for the keys of all
partitions,
+ // estimated from its own count. With few keys per partition
the
+ // counts vary a lot, and the merge folds into the smallest
+ // filter, which then cannot hold every key. Partitions with an
+ // IN list hold their keys, so build one filter of all of them,
+ // sized for the real count.
+ let from_in_lists = in_lists
+ .as_deref()
+ .map(|in_lists| {
+ self.filter_from_in_lists(in_lists, num_distinct,
&pool)
+ })
+ .transpose()?
+ .flatten();
+ let filters = match &from_in_lists {
+ Some(filter) => Some(vec![filter]),
+ None => non_empty
+ .iter()
+ .map(|p| p.build_keys.bloom_filter.as_deref())
+ .collect::<Option<Vec<_>>>(),
+ };
+ let bloom = BloomFilterExpr::try_new(
self.on_right.clone(),
- range_partitioning,
- &self.probe_schema,
- )?))
+ filters.as_deref(),
+ self.global_filter_options.bloom_filter,
+ &pool,
+ pruning_bitmap,
+ )?;
+ // Without a bloom filter, keep the expression only for its
+ // pruning bitmap
+ (bloom.has_filter() || bloom.pruning_bitmap().is_some())
+ .then(|| Arc::new(bloom) as Arc<dyn PhysicalExpr>)
}
- None =>
PartitionRouter::Hash(self.repartition_random_state.clone()),
- })
+ };
+ let bounds_expr = bounds
+ .as_ref()
+ .and_then(|b| create_bounds_predicate(&self.on_right, b));
+ let filter_expr = combine_membership_and_bounds(membership_expr,
bounds_expr)
+ .unwrap_or_else(|| lit(true));
+ self.preserve_probe_nulls(filter_expr, keys_have_null)
+ }
+
+ /// A bloom filter of the IN list values of all partitions, sized for
+ /// `num_distinct` keys. `None` when that filter is too large or `pool`
+ /// cannot hold it.
+ fn filter_from_in_lists(
+ &self,
+ in_lists: &[ArrayRef],
+ num_distinct: usize,
+ pool: &Arc<dyn MemoryPool>,
+ ) -> Result<Option<Sbbf>> {
+ let arrays: Vec<&dyn Array> = in_lists.iter().map(|a|
a.as_ref()).collect();
+ let values = arrow::compute::concat(&arrays)?;
+ // Multi-column keys are a struct of the key columns.
+ let keys = if self.on_right.len() == 1 {
+ vec![values]
+ } else {
+ values.as_struct().columns().to_vec()
+ };
+ // Only for the build: the merge copies the filter into its own
+ // reservation.
+ let reservation =
MemoryConsumer::new("HashJoinBloomFilterBuild").register(pool);
+ bloom_filter::partition_filter(
Review Comment:
The local reservation is dropped when this function returns, but its `Sbbf`
stays alive while `BloomFilterExpr::try_new` clones it. Both bitsets then
coexist while the pool accounts for only one, so the merge can exceed its
memory limit by another filter's size. Keep the temporary filter's reservation
alive through the merge, or transfer ownership and its reservation into the
final expression.
##########
datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs:
##########
@@ -708,200 +723,189 @@ impl SharedBuildAccumulator {
}
}
- /// Builds one probe-side filter from finalized partitioned build data.
+ /// Builds the global filter from finalized partitioned build data.
+ ///
/// Empty and canceled partitions contribute no key.
- fn build_partitioned_filter(&self, partitions: Vec<PartitionStatus>) ->
Result<()> {
- let num_partitions = partitions.len();
- let mut members = Vec::with_capacity(num_partitions);
- let mut merged_bounds: Option<PartitionBounds> = None;
- let mut keys_have_null = false;
-
- for (partition_id, partition) in partitions.into_iter().enumerate() {
+ fn build_partitioned_filter(&self, partitions: &[PartitionStatus]) ->
Result<()> {
+ let mut reported = Vec::with_capacity(partitions.len());
+ for partition in partitions {
match partition {
+ PartitionStatus::Reported(data) => reported.push(data),
// A canceled partition's stream never probes, so no key of its
// build side can matter.
- PartitionStatus::CanceledUnknown
- | PartitionStatus::Reported(PartitionData {
- pushdown: PushdownStrategy::Empty,
- ..
- }) => {}
- PartitionStatus::Reported(PartitionData {
- bounds,
- pushdown,
- keys_have_null: partition_keys_have_null,
- }) => {
- keys_have_null |= partition_keys_have_null;
- merged_bounds = Some(match merged_bounds {
- None => bounds.clone(),
- Some(merged) => merged.union(&bounds),
- });
- members.push((partition_id, pushdown, bounds));
- }
+ PartitionStatus::CanceledUnknown => {}
PartitionStatus::Pending => {
- return internal_err!(
+ return datafusion_common::internal_err!(
"attempted to finalize dynamic filter with pending
partition"
);
}
}
}
-
- let filter_expr = match members.as_slice() {
- // No build row exists, so no probe row can match.
- [] => lit(false),
- // Only one build partition holds rows, so its own filter covers
every
- // probe match without routing, and an IN list keeps its pruning.
- [(_, pushdown, bounds)] => combine_membership_and_bounds(
- create_membership_predicate(
- &self.on_right,
- pushdown.clone(),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?,
- create_bounds_predicate(&self.on_right, bounds),
- )
- .expect("membership predicate is always present"),
- _ => {
- self.merged_membership_filter(&members, merged_bounds,
num_partitions)?
- }
- };
self.dynamic_filter
- .update(self.preserve_probe_nulls(filter_expr, keys_have_null)?)
+ .update(self.build_global_filter(&reported)?)
}
- /// `members` holds each non-empty partition's id, strategy (an IN list, a
- /// hash table or an array map) and bounds, out of `num_partitions`
partitions.
- fn merged_membership_filter(
+ /// Builds one filter for all probe rows from the build data of every
partition,
+ /// with no routing to partitions:
+ ///
+ /// ```text
+ /// [key IS NULL OR] key >= min AND key <= max AND membership(key)
+ /// ```
+ ///
+ /// `min` and `max` are the global bounds. `membership` is an InList of the
+ /// keys of all partitions when they have at most
+ /// `hash_join_dynamic_filter_inlist_max_distinct_values` distinct keys
together,
+ /// and a [`BloomFilterExpr`] otherwise. The filter is true for every build
+ /// key, whatever the partitioning of the build and probe sides, so it is
+ /// correct for hash, range and collect-left joins.
+ fn build_global_filter(
&self,
- members: &[(usize, PushdownStrategy, PartitionBounds)],
- merged_bounds: Option<PartitionBounds>,
- num_partitions: usize,
+ partitions: &[&PartitionData],
) -> Result<Arc<dyn PhysicalExpr>> {
- let lists = members
+ let non_empty: Vec<&PartitionData> = partitions
.iter()
- .filter_map(|(_, pushdown, _)| match pushdown {
- PushdownStrategy::InList(values) => Some(values),
+ .copied()
+ .filter(|p| !matches!(p.pushdown, PushdownStrategy::Empty))
+ .collect();
+ if non_empty.is_empty() {
+ // No build row exists, so no probe row can match.
+ return Ok(lit(false));
+ }
+ let keys_have_null = non_empty.iter().any(|p| p.keys_have_null);
+ let bounds = PartitionBounds::merge(non_empty.iter().map(|p|
&p.bounds));
+ let num_distinct: usize =
+ non_empty.iter().map(|p| p.build_keys.num_distinct).sum();
+
+ let in_lists = non_empty
+ .iter()
+ .map(|p| match &p.pushdown {
+ PushdownStrategy::InList(values) => Some(Arc::clone(values)),
_ => None,
})
- .collect::<Vec<_>>();
-
- // Every partition is an IN list, and together they still fit the
limits a
- // single build uses to pick an IN list: one combined list keeps the
- // statistics and bloom filter pruning an IN list allows. Past those
- // limits, a hash lookup is cheaper per row and carries a pruning
bitmap.
- let combined_in_list = lists.len() == members.len() && {
- let values = lists.iter().map(|list| list.len()).sum::<usize>();
- let bytes = lists
- .iter()
- .map(|list| list.get_array_memory_size())
- .sum::<usize>();
- values <= self.in_list_max_values && bytes <= self.in_list_max_size
- };
- let membership = if combined_in_list {
- let values = concat(&lists.iter().map(|l|
l.as_ref()).collect::<Vec<_>>())?;
- create_membership_predicate(
- &self.on_right,
- PushdownStrategy::InList(values),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?
- .expect("an IN list always has a membership predicate")
- } else {
- // Each probe row is looked up in the table of the partition its
key
- // routes to, so the partitions' tables are shared as they are: no
- // merged table to build while every probe stream waits on the
filter.
- let mut maps = vec![None; num_partitions];
- for (partition_id, pushdown, _) in members {
- maps[*partition_id] = Some(match pushdown {
- PushdownStrategy::Map(map, _) => Arc::clone(map),
- PushdownStrategy::InList(values) =>
self.in_list_hash_map(values)?,
- PushdownStrategy::Empty => {
- return internal_err!("empty partitions have no
members");
- }
- });
+ .collect::<Option<Vec<_>>>();
+ let membership_expr = match &in_lists {
+ // The partitions hold disjoint keys, so the sum of their distinct
+ // counts is the number of distinct keys of the build side.
+ Some(in_lists)
+ if num_distinct
+ <= self.global_filter_options.inlist_max_distinct_values =>
+ {
+ let arrays: Vec<&dyn Array> =
+ in_lists.iter().map(|a| a.as_ref()).collect();
+ let values =
distinct_values(&arrow::compute::concat(&arrays)?)?;
+ Some(create_in_list_predicate(
+ &self.on_right,
+ values,
+ self.probe_schema.as_ref(),
+ )?)
}
- Arc::new(HashTableLookupExpr::new_reserved(
- self.on_right.clone(),
- HASH_JOIN_SEED,
- Some(self.partition_router(num_partitions)?),
- maps,
- String::from("hash_lookup"),
- self.merged_pruning_bitmap(members, merged_bounds.as_ref()),
- )?)
- };
-
- let bounds = merged_bounds
- .and_then(|bounds| create_bounds_predicate(&self.on_right,
&bounds));
- Ok(combine_membership_and_bounds(Some(membership), bounds)
- .expect("membership predicate is always present"))
- }
-
- /// How probe rows find their build partition: as the probe side was
- /// partitioned.
- fn partition_router(&self, num_partitions: usize) ->
Result<PartitionRouter> {
- Ok(match &self.probe_range_partitioning {
- Some(range_partitioning) => {
- assert_or_internal_err!(
- num_partitions == range_partitioning.partition_count(),
- "Dynamic filter partition count {} does not match Range
partition count {}",
- num_partitions,
- range_partitioning.partition_count()
- );
- PartitionRouter::Range(Arc::new(RangeExpr::try_new_with_schema(
+ _ => {
+ let pruning_bitmap =
+ self.merge_pruning_bitmaps(&non_empty, bounds.as_ref());
+ // Every partition must have its filter. A partition has none
+ // when the build side is too big for a bloom filter, or its
+ // memory reservation failed.
+ let pool = self
+ .global_filter_options
+ .memory_pool
+ .clone()
+ .unwrap_or_else(||
Arc::new(UnboundedMemoryPool::default()));
+ // Each partition sizes its filter for the keys of all
partitions,
+ // estimated from its own count. With few keys per partition
the
+ // counts vary a lot, and the merge folds into the smallest
+ // filter, which then cannot hold every key. Partitions with an
+ // IN list hold their keys, so build one filter of all of them,
+ // sized for the real count.
+ let from_in_lists = in_lists
+ .as_deref()
+ .map(|in_lists| {
+ self.filter_from_in_lists(in_lists, num_distinct,
&pool)
+ })
+ .transpose()?
+ .flatten();
+ let filters = match &from_in_lists {
+ Some(filter) => Some(vec![filter]),
+ None => non_empty
+ .iter()
+ .map(|p| p.build_keys.bloom_filter.as_deref())
+ .collect::<Option<Vec<_>>>(),
+ };
+ let bloom = BloomFilterExpr::try_new(
self.on_right.clone(),
- range_partitioning,
- &self.probe_schema,
- )?))
+ filters.as_deref(),
+ self.global_filter_options.bloom_filter,
+ &pool,
+ pruning_bitmap,
+ )?;
+ // Without a bloom filter, keep the expression only for its
+ // pruning bitmap
+ (bloom.has_filter() || bloom.pruning_bitmap().is_some())
+ .then(|| Arc::new(bloom) as Arc<dyn PhysicalExpr>)
}
- None =>
PartitionRouter::Hash(self.repartition_random_state.clone()),
- })
+ };
+ let bounds_expr = bounds
+ .as_ref()
+ .and_then(|b| create_bounds_predicate(&self.on_right, b));
+ let filter_expr = combine_membership_and_bounds(membership_expr,
bounds_expr)
+ .unwrap_or_else(|| lit(true));
+ self.preserve_probe_nulls(filter_expr, keys_have_null)
+ }
+
+ /// A bloom filter of the IN list values of all partitions, sized for
+ /// `num_distinct` keys. `None` when that filter is too large or `pool`
+ /// cannot hold it.
+ fn filter_from_in_lists(
+ &self,
+ in_lists: &[ArrayRef],
+ num_distinct: usize,
+ pool: &Arc<dyn MemoryPool>,
+ ) -> Result<Option<Sbbf>> {
+ let arrays: Vec<&dyn Array> = in_lists.iter().map(|a|
a.as_ref()).collect();
+ let values = arrow::compute::concat(&arrays)?;
Review Comment:
Two partitions with 80 distinct `Dictionary(Int8, Utf8)` keys each can pass
the local InList limits but overflow Int8 when this concatenation merges their
dictionaries, aborting a valid join ([Arrow concat test, default branch at
0f1fd35](https://github.com/apache/arrow-rs/blob/0f1fd354bb9341289827099d115f9b49edc193c9/arrow-select/src/concat.rs#L1910-L1916)).
Fill the common bloom filter from each partition separately, or safely fall
back to the existing partition filters when concatenation fails.
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -1154,57 +1164,12 @@ impl HashJoinExec {
return false;
}
- // Under `preserve_file_partitions`, file groups can report Hash
without following
- // the dynamic filter hash router and look like a real hash
repartition, so reject
- // Hash. Range inputs with matching split points are safe.
- // Follow-up work: enable dynamic filtering for
preserve_file_partitioned scans (issue #20195).
- // https://github.com/apache/datafusion/issues/20195
- if config.optimizer.preserve_file_partitions > 0
- && self.mode == PartitionMode::Partitioned
- && matches!(
- (
- self.left.output_partitioning(),
- self.right.output_partitioning()
- ),
- (Partitioning::Hash(_, _), Partitioning::Hash(_, _))
- )
- {
- return false;
- }
-
- if self.mode == PartitionMode::Partitioned
- && !self.has_partitioned_dynamic_filter_routing()
- {
- return false;
- }
-
+ // The partitioning of the inputs does not matter. The filter holds the
+ // keys of every build partition whose stream can probe, so it passes
+ // every row that a stream can join.
true
Review Comment:
The new partitioning test checks only that this method returns `true`; it
does not exercise a file-partitioned scan, the case requested in #20195. Add an
end-to-end join with `preserve_file_partitions` enabled and a partition-column
join key, checking equal results with filtering on/off and pruning of
nonmatching files without a repartition.
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -3553,14 +3523,59 @@ fn build_in_memory(
}
ok
});
- PushdownStrategy::Map(Arc::clone(&map), pruning_bitmap)
+ PushdownStrategy::Large(pruning_bitmap)
}
};
if is_phj_candidate && !should_compute_dynamic_filters {
bounds = None;
}
+ // Fill the bloom filter of this partition's keys here, in its build task,
+ // so the finalizing task only ORs the partition filters. Partitions hold
+ // disjoint keys of similar counts, so the filter is sized for the keys of
+ // all partitions estimated from this one.
+ let bloom_filter = if !should_compute_dynamic_filters
Review Comment:
`prepare_build` disables `should_compute_dynamic_filters` for Utf8 and
FixedSizeBinary keys to avoid materializing bounds and InList values. This
guard also suppresses bloom membership, leaving those prepared builds with a
`lit(true)` dynamic filter and no probe filtering. Allow prepared builds to
fill the bloom filter independently of bounds collection, and extend the
prepared byte-key test to inspect the published filter.
##########
datafusion/pruning/src/pruning_predicate.rs:
##########
@@ -1530,18 +1531,18 @@ fn min_max_non_null_exprs(
statistics
}
-/// Builds a "may match" expression for a [`HashTableLookupExpr`] (a large join
-/// build side pushed down as an opaque hash-table lookup): tests container
-/// min/max stats against the build side's key-range bitmap, which is fixed
size
-/// and built once with the join's hash table.
-fn build_hash_lookup_pruning_expr(
- lookup: &HashTableLookupExpr,
+/// Builds a "may match" expression for a [`BloomFilterExpr`] (a large join
+/// build side pushed down as an opaque membership test) with key-range bitmap
+/// `bitmap`: tests container min/max stats against the build side's key-range
+/// bitmap, which is fixed size and built once with the join's build side.
+fn build_key_range_bitmap_pruning_expr(
+ bitmap: &Arc<KeyRangeBitmap>,
+ on_columns: &[&Arc<dyn PhysicalExpr>],
Review Comment:
The bitmap pruning rewrite loses its min/max test and six
widening/narrowing-cast cases, without replacement coverage for the cast guard.
Restore those cases against `build_key_range_bitmap_pruning_expr` directly:
widening casts should prune the gaps, while narrowing casts must keep
containers conservatively.
##########
datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs:
##########
@@ -708,200 +723,189 @@ impl SharedBuildAccumulator {
}
}
- /// Builds one probe-side filter from finalized partitioned build data.
+ /// Builds the global filter from finalized partitioned build data.
+ ///
/// Empty and canceled partitions contribute no key.
- fn build_partitioned_filter(&self, partitions: Vec<PartitionStatus>) ->
Result<()> {
- let num_partitions = partitions.len();
- let mut members = Vec::with_capacity(num_partitions);
- let mut merged_bounds: Option<PartitionBounds> = None;
- let mut keys_have_null = false;
-
- for (partition_id, partition) in partitions.into_iter().enumerate() {
+ fn build_partitioned_filter(&self, partitions: &[PartitionStatus]) ->
Result<()> {
+ let mut reported = Vec::with_capacity(partitions.len());
+ for partition in partitions {
match partition {
+ PartitionStatus::Reported(data) => reported.push(data),
// A canceled partition's stream never probes, so no key of its
// build side can matter.
- PartitionStatus::CanceledUnknown
- | PartitionStatus::Reported(PartitionData {
- pushdown: PushdownStrategy::Empty,
- ..
- }) => {}
- PartitionStatus::Reported(PartitionData {
- bounds,
- pushdown,
- keys_have_null: partition_keys_have_null,
- }) => {
- keys_have_null |= partition_keys_have_null;
- merged_bounds = Some(match merged_bounds {
- None => bounds.clone(),
- Some(merged) => merged.union(&bounds),
- });
- members.push((partition_id, pushdown, bounds));
- }
+ PartitionStatus::CanceledUnknown => {}
PartitionStatus::Pending => {
- return internal_err!(
+ return datafusion_common::internal_err!(
"attempted to finalize dynamic filter with pending
partition"
);
}
}
}
-
- let filter_expr = match members.as_slice() {
- // No build row exists, so no probe row can match.
- [] => lit(false),
- // Only one build partition holds rows, so its own filter covers
every
- // probe match without routing, and an IN list keeps its pruning.
- [(_, pushdown, bounds)] => combine_membership_and_bounds(
- create_membership_predicate(
- &self.on_right,
- pushdown.clone(),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?,
- create_bounds_predicate(&self.on_right, bounds),
- )
- .expect("membership predicate is always present"),
- _ => {
- self.merged_membership_filter(&members, merged_bounds,
num_partitions)?
- }
- };
self.dynamic_filter
- .update(self.preserve_probe_nulls(filter_expr, keys_have_null)?)
+ .update(self.build_global_filter(&reported)?)
}
- /// `members` holds each non-empty partition's id, strategy (an IN list, a
- /// hash table or an array map) and bounds, out of `num_partitions`
partitions.
- fn merged_membership_filter(
+ /// Builds one filter for all probe rows from the build data of every
partition,
+ /// with no routing to partitions:
+ ///
+ /// ```text
+ /// [key IS NULL OR] key >= min AND key <= max AND membership(key)
+ /// ```
+ ///
+ /// `min` and `max` are the global bounds. `membership` is an InList of the
+ /// keys of all partitions when they have at most
+ /// `hash_join_dynamic_filter_inlist_max_distinct_values` distinct keys
together,
+ /// and a [`BloomFilterExpr`] otherwise. The filter is true for every build
+ /// key, whatever the partitioning of the build and probe sides, so it is
+ /// correct for hash, range and collect-left joins.
+ fn build_global_filter(
&self,
- members: &[(usize, PushdownStrategy, PartitionBounds)],
- merged_bounds: Option<PartitionBounds>,
- num_partitions: usize,
+ partitions: &[&PartitionData],
) -> Result<Arc<dyn PhysicalExpr>> {
- let lists = members
+ let non_empty: Vec<&PartitionData> = partitions
.iter()
- .filter_map(|(_, pushdown, _)| match pushdown {
- PushdownStrategy::InList(values) => Some(values),
+ .copied()
+ .filter(|p| !matches!(p.pushdown, PushdownStrategy::Empty))
+ .collect();
+ if non_empty.is_empty() {
+ // No build row exists, so no probe row can match.
+ return Ok(lit(false));
+ }
+ let keys_have_null = non_empty.iter().any(|p| p.keys_have_null);
+ let bounds = PartitionBounds::merge(non_empty.iter().map(|p|
&p.bounds));
+ let num_distinct: usize =
+ non_empty.iter().map(|p| p.build_keys.num_distinct).sum();
+
+ let in_lists = non_empty
+ .iter()
+ .map(|p| match &p.pushdown {
+ PushdownStrategy::InList(values) => Some(Arc::clone(values)),
_ => None,
})
- .collect::<Vec<_>>();
-
- // Every partition is an IN list, and together they still fit the
limits a
- // single build uses to pick an IN list: one combined list keeps the
- // statistics and bloom filter pruning an IN list allows. Past those
- // limits, a hash lookup is cheaper per row and carries a pruning
bitmap.
- let combined_in_list = lists.len() == members.len() && {
- let values = lists.iter().map(|list| list.len()).sum::<usize>();
- let bytes = lists
- .iter()
- .map(|list| list.get_array_memory_size())
- .sum::<usize>();
- values <= self.in_list_max_values && bytes <= self.in_list_max_size
- };
- let membership = if combined_in_list {
- let values = concat(&lists.iter().map(|l|
l.as_ref()).collect::<Vec<_>>())?;
- create_membership_predicate(
- &self.on_right,
- PushdownStrategy::InList(values),
- &HASH_JOIN_SEED,
- self.probe_schema.as_ref(),
- )?
- .expect("an IN list always has a membership predicate")
- } else {
- // Each probe row is looked up in the table of the partition its
key
- // routes to, so the partitions' tables are shared as they are: no
- // merged table to build while every probe stream waits on the
filter.
- let mut maps = vec![None; num_partitions];
- for (partition_id, pushdown, _) in members {
- maps[*partition_id] = Some(match pushdown {
- PushdownStrategy::Map(map, _) => Arc::clone(map),
- PushdownStrategy::InList(values) =>
self.in_list_hash_map(values)?,
- PushdownStrategy::Empty => {
- return internal_err!("empty partitions have no
members");
- }
- });
+ .collect::<Option<Vec<_>>>();
+ let membership_expr = match &in_lists {
+ // The partitions hold disjoint keys, so the sum of their distinct
+ // counts is the number of distinct keys of the build side.
+ Some(in_lists)
+ if num_distinct
+ <= self.global_filter_options.inlist_max_distinct_values =>
+ {
+ let arrays: Vec<&dyn Array> =
+ in_lists.iter().map(|a| a.as_ref()).collect();
+ let values =
distinct_values(&arrow::compute::concat(&arrays)?)?;
+ Some(create_in_list_predicate(
+ &self.on_right,
+ values,
+ self.probe_schema.as_ref(),
+ )?)
}
- Arc::new(HashTableLookupExpr::new_reserved(
- self.on_right.clone(),
- HASH_JOIN_SEED,
- Some(self.partition_router(num_partitions)?),
- maps,
- String::from("hash_lookup"),
- self.merged_pruning_bitmap(members, merged_bounds.as_ref()),
- )?)
- };
-
- let bounds = merged_bounds
- .and_then(|bounds| create_bounds_predicate(&self.on_right,
&bounds));
- Ok(combine_membership_and_bounds(Some(membership), bounds)
- .expect("membership predicate is always present"))
- }
-
- /// How probe rows find their build partition: as the probe side was
- /// partitioned.
- fn partition_router(&self, num_partitions: usize) ->
Result<PartitionRouter> {
- Ok(match &self.probe_range_partitioning {
- Some(range_partitioning) => {
- assert_or_internal_err!(
- num_partitions == range_partitioning.partition_count(),
- "Dynamic filter partition count {} does not match Range
partition count {}",
- num_partitions,
- range_partitioning.partition_count()
- );
- PartitionRouter::Range(Arc::new(RangeExpr::try_new_with_schema(
+ _ => {
+ let pruning_bitmap =
+ self.merge_pruning_bitmaps(&non_empty, bounds.as_ref());
+ // Every partition must have its filter. A partition has none
+ // when the build side is too big for a bloom filter, or its
+ // memory reservation failed.
+ let pool = self
+ .global_filter_options
+ .memory_pool
+ .clone()
+ .unwrap_or_else(||
Arc::new(UnboundedMemoryPool::default()));
+ // Each partition sizes its filter for the keys of all
partitions,
+ // estimated from its own count. With few keys per partition
the
+ // counts vary a lot, and the merge folds into the smallest
+ // filter, which then cannot hold every key. Partitions with an
+ // IN list hold their keys, so build one filter of all of them,
+ // sized for the real count.
+ let from_in_lists = in_lists
+ .as_deref()
+ .map(|in_lists| {
+ self.filter_from_in_lists(in_lists, num_distinct,
&pool)
+ })
+ .transpose()?
+ .flatten();
+ let filters = match &from_in_lists {
+ Some(filter) => Some(vec![filter]),
+ None => non_empty
+ .iter()
+ .map(|p| p.build_keys.bloom_filter.as_deref())
+ .collect::<Option<Vec<_>>>(),
+ };
+ let bloom = BloomFilterExpr::try_new(
self.on_right.clone(),
- range_partitioning,
- &self.probe_schema,
- )?))
+ filters.as_deref(),
+ self.global_filter_options.bloom_filter,
+ &pool,
+ pruning_bitmap,
+ )?;
+ // Without a bloom filter, keep the expression only for its
+ // pruning bitmap
+ (bloom.has_filter() || bloom.pruning_bitmap().is_some())
+ .then(|| Arc::new(bloom) as Arc<dyn PhysicalExpr>)
}
- None =>
PartitionRouter::Hash(self.repartition_random_state.clone()),
- })
+ };
+ let bounds_expr = bounds
+ .as_ref()
+ .and_then(|b| create_bounds_predicate(&self.on_right, b));
+ let filter_expr = combine_membership_and_bounds(membership_expr,
bounds_expr)
+ .unwrap_or_else(|| lit(true));
+ self.preserve_probe_nulls(filter_expr, keys_have_null)
+ }
+
+ /// A bloom filter of the IN list values of all partitions, sized for
+ /// `num_distinct` keys. `None` when that filter is too large or `pool`
+ /// cannot hold it.
+ fn filter_from_in_lists(
+ &self,
+ in_lists: &[ArrayRef],
+ num_distinct: usize,
+ pool: &Arc<dyn MemoryPool>,
+ ) -> Result<Option<Sbbf>> {
+ let arrays: Vec<&dyn Array> = in_lists.iter().map(|a|
a.as_ref()).collect();
+ let values = arrow::compute::concat(&arrays)?;
+ // Multi-column keys are a struct of the key columns.
+ let keys = if self.on_right.len() == 1 {
+ vec![values]
+ } else {
+ values.as_struct().columns().to_vec()
+ };
+ // Only for the build: the merge copies the filter into its own
+ // reservation.
+ let reservation =
MemoryConsumer::new("HashJoinBloomFilterBuild").register(pool);
+ bloom_filter::partition_filter(
+ &keys,
+ num_distinct,
+ self.global_filter_options.bloom_filter,
+ &reservation,
+ )
}
- /// A hash table of an IN list partition's keys, hashed as the probe side
- /// hashes its join keys: one column per join key.
- ///
- /// The table is not reserved, same as the IN list it is built from. Its
- /// size follows that list, which `hash_join_inlist_pushdown_max_size`
caps.
- fn in_list_hash_map(&self, values: &ArrayRef) -> Result<Arc<ReservedMap>> {
- let columns = match values.as_struct_opt() {
- Some(columns) if self.on_right.len() > 1 => columns.columns(),
- _ => std::slice::from_ref(values),
- };
- let mut hashes = vec![0; values.len()];
- create_hashes(columns, HASH_JOIN_SEED.random_state(), &mut hashes)?;
- let mut map = JoinHashMapU32::with_capacity(hashes.len());
- map.update_from_iter(Box::new(hashes.iter().enumerate()), 0);
- let map = Arc::new(Map::HashMap(Box::new(map)));
- Ok(Arc::new(ReservedMap::unreserved(map)))
- }
-
- /// Container pruning reads one bitmap, so merge the partitions' key
ranges:
- /// a hash table's bitmap, an IN list's keys, or else a partition's whole
- /// bounds. `None` when nothing can be excluded.
- fn merged_pruning_bitmap(
+ /// One [`KeyRangeBitmap`] for the keys of all partitions, so that scans
can
+ /// prune containers (for example parquet row groups and pages) with the
+ /// global filter. Only for a single integer key.
+ fn merge_pruning_bitmaps(
&self,
- members: &[(usize, PushdownStrategy, PartitionBounds)],
- merged_bounds: Option<&PartitionBounds>,
+ partitions: &[&PartitionData],
+ bounds: Option<&PartitionBounds>,
) -> Option<Arc<KeyRangeBitmap>> {
if self.on_right.len() != 1 {
return None;
}
- let merged = merged_bounds?.get_column_bounds(0)?;
- let parts = members
+ let column_bounds = bounds?.get_column_bounds(0)?;
+ let parts = partitions
.iter()
- .map(|(_, pushdown, bounds)| match pushdown {
- PushdownStrategy::Map(_, Some(bitmap)) => {
- Some(KeyRangePart::Bitmap(bitmap))
+ .map(|p| match &p.pushdown {
+ PushdownStrategy::Large(Some(bitmap)) => {
+ Some(KeyRangePart::Bitmap(bitmap.as_ref()))
}
- PushdownStrategy::InList(keys) =>
Some(KeyRangePart::Keys(keys.as_ref())),
- _ => bounds
- .get_column_bounds(0)
- .map(|bounds| KeyRangePart::Range {
- min: &bounds.min,
- max: &bounds.max,
- }),
+ _ => p
+ .build_keys
+ .keys
+ .first()
+ .map(|keys| KeyRangePart::Keys(keys.as_ref())),
Review Comment:
For `Large(None)` partitions, this now passes every build key to
`KeyRangeBitmap::union`, which scans them on the single finalizer while all
probe streams wait. Dense keys commonly take this path even though their union
is fully set and provides no pruning. Keep `Keys` for small InLists and use
each partition's bounds as `KeyRangePart::Range` when it has no bitmap.
##########
datafusion/physical-plan/src/joins/hash_join/shared_bounds.rs:
##########
@@ -78,101 +89,132 @@ impl PartitionBounds {
self.column_bounds.get(index)
}
- /// Bounds covering both `self` and `other`, which must describe the same
- /// columns. A NULL bound means the partition holds no non-null key in that
- /// column, so it never widens the other side's bound.
- fn union(self, other: &PartitionBounds) -> PartitionBounds {
- // Every non-empty partition of a join reports one bound per join key.
- debug_assert_eq!(
- self.column_bounds.len(),
- other.column_bounds.len(),
- "partitions report bounds for different numbers of columns"
- );
- let column_bounds = self
- .column_bounds
- .into_iter()
- .zip(&other.column_bounds)
- .map(|(a, b)| {
- let min = if !b.min.is_null() && (a.min.is_null() || b.min <
a.min) {
- b.min.clone()
- } else {
- a.min
- };
- let max = if !b.max.is_null() && (a.max.is_null() || b.max >
a.max) {
- b.max.clone()
- } else {
- a.max
- };
- ColumnBounds::new(min, max)
- })
- .collect();
- PartitionBounds::new(column_bounds)
+ /// Bounds that hold the keys of every partition: the smallest minimum and
the
+ /// largest maximum of each column.
+ ///
+ /// `None` when a partition has no bounds or a column's values cannot be
+ /// compared. Then a bounds predicate is not possible.
+ fn merge<'a>(
+ mut partitions: impl Iterator<Item = &'a PartitionBounds>,
+ ) -> Option<Self> {
+ let mut merged = partitions.next()?.clone();
+ if merged.column_bounds.is_empty() {
+ return None;
+ }
+ for bounds in partitions {
+ if bounds.column_bounds.len() != merged.column_bounds.len() {
+ return None;
+ }
+ for (acc, b) in
merged.column_bounds.iter_mut().zip(&bounds.column_bounds) {
+ // A NULL bound comes from a partition with no non-NULL key in
this
+ // column. It must not widen (or, as a NULL comparison,
disable) the
+ // bounds of the keys of other partitions.
+ if acc.min.is_null()
+ || (!b.min.is_null() &&
b.min.partial_cmp(&acc.min)?.is_lt())
+ {
+ acc.min = b.min.clone();
+ }
+ if acc.max.is_null()
+ || (!b.max.is_null() &&
b.max.partial_cmp(&acc.max)?.is_gt())
+ {
+ acc.max = b.max.clone();
+ }
+ }
+ }
+ Some(merged)
}
}
-/// Creates a membership predicate for filter pushdown.
-///
-/// If `inlist_values` is provided (for small build sides), creates an InList
expression.
-/// Otherwise, creates a HashTableLookup expression (for large build sides).
-///
-/// Supports both single-column and multi-column joins using struct
expressions.
-fn create_membership_predicate(
- on_right: &[PhysicalExprRef],
- pushdown: PushdownStrategy,
- random_state: &SeededRandomState,
- schema: &Schema,
-) -> Result<Option<Arc<dyn PhysicalExpr>>> {
- match pushdown {
- // Use InList expression for small build sides
- PushdownStrategy::InList(in_list_array) => {
- // Build the expression to compare against
- let expr = if on_right.len() == 1 {
- // Single column: col IN (val1, val2, ...)
- Arc::clone(&on_right[0])
- } else {
- let fields = build_struct_fields(
- on_right
- .iter()
- .map(|r| r.data_type(schema))
- .collect::<Result<Vec<_>>>()?
- .as_ref(),
- )?;
+/// The build side key columns of one partition, for the global dynamic filter.
+#[derive(Clone, Default)]
+pub(crate) struct BuildKeys {
+ /// One array per join key
+ pub(crate) keys: Vec<ArrayRef>,
+ /// Bloom filter of the keys. `None` when this partition has no filter,
+ /// then the global filter has no bloom filter.
+ pub(crate) bloom_filter: Option<Arc<Sbbf>>,
Review Comment:
The accumulator clones finalized reports and never clears the originals, so
it retains every build-key array and partition bloom filter until the plan is
dropped. In partitioned mode, completed streams release the reservations for
those still-live buffers, allowing later operators to overcommit the memory
pool. Consume or clear the report payloads after finalization while preserving
completion bookkeeping, and check this lifetime before dropping the plan.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]