mbutrovich commented on code in PR #27746:
URL: https://github.com/apache/datafusion/pull/27746#discussion_r4786938263
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -8985,69 +9115,60 @@ mod tests {
Arc::new(Column::new_with_schema("b2", &right.schema())?) as _,
)];
- // Reserved on top of the copy, once the inputs are dropped
- let build_rows = batches.len() * num_rows as usize;
- let cases = if use_perfect_hash_join_as_possible {
- let map = ArrayMap::estimate_memory_size(0, num_rows as u64 - 1,
build_rows);
- assert!(map < inputs / 2);
- vec![
- // Room for the inputs plus the map, not for the inputs plus
their copy
- (inputs * 7 / 4, false),
- // The map fits next to the copy
- (inputs * 2 + map / 2, true),
- ]
- } else {
- let map = estimate_memory_size::<(u32, u64)>(
- build_rows,
- size_of::<JoinHashMapU32>(),
- )? + build_rows * size_of::<u32>();
- assert!(map > inputs * 2);
- vec![
- // The copy fits next to the inputs, the map does not fit next
- // to the copy
- (map + inputs / 2, false),
- // The map fits next to the copy, not next to the inputs too
- (map + inputs * 3 / 2, true),
- ]
+ let run = |pool: Arc<dyn MemoryPool>| {
+ let batches = batches.clone();
+ let left_schema = Arc::clone(&left_schema);
+ let right = Arc::clone(&right);
+ let on = on.clone();
+ async move {
+ let left = TestMemoryExec::try_new_exec(&[batches],
left_schema, None)?;
+ let join = HashJoinExec::try_new(
+ left,
+ right,
+ on,
+ None,
+ &JoinType::Inner,
+ None,
+ mode,
+ NullEquality::NullEqualsNothing,
+ false,
+ )?;
+ let runtime = RuntimeEnvBuilder::new()
+ .with_memory_pool(pool)
+ .build_arc()?;
+ let config = prepare_task_ctx(8192,
use_perfect_hash_join_as_possible)
+ .session_config()
+ .clone();
+ let task_ctx = Arc::new(
+ TaskContext::default()
+ .with_session_config(config)
+ .with_runtime(runtime),
+ );
+ common::collect(join.execute(0, task_ctx)?).await
+ }
};
- for (limit, fits) in cases {
- let left = TestMemoryExec::try_new_exec(
- std::slice::from_ref(&batches),
- Arc::clone(&left_schema),
- None,
- )?;
- let join = HashJoinExec::try_new(
- left,
- Arc::clone(&right),
- on.clone(),
- None,
- &JoinType::Inner,
- None,
- mode,
- NullEquality::NullEqualsNothing,
- false,
- )?;
-
- let runtime = RuntimeEnvBuilder::new()
- .with_memory_limit(limit, 1.0)
- .build_arc()?;
- let task_ctx = prepare_task_ctx(8192,
use_perfect_hash_join_as_possible);
- let task_ctx = Arc::new(
- TaskContext::default()
- .with_session_config(task_ctx.session_config().clone())
- .with_runtime(runtime),
- );
-
- let result = common::collect(join.execute(0, task_ctx)?).await;
+ // Measure the selected index's peak rather than assuming a bucket or
+ // chain layout. The inputs and concatenated copy must overlap.
+ let recording = Arc::new(PeakRecordingPool::new(Arc::new(
+ UnboundedMemoryPool::default(),
+ )));
+ run(Arc::clone(&recording) as _).await?;
+ let peak = recording.peak_reserved();
+ assert!(peak >= inputs * 2);
Review Comment:
The doc comment on this test says the map is reserved only after the input
batches are dropped, but this version doesn't check that anymore. `peak - 1`
and `peak` both come from a run of the same build, so they pass no matter what
the build holds at its peak. The fixed limits on `main` failed if the map
overlapped the inputs.
Could we keep an absolute bound as well? One option is `assert!(peak <
inputs + build_mem_used)`, with `build_mem_used` read from the join's metrics.
`build_mem_used` covers the copy, the keys, and the index, so the peak reaches
that bound only if the index is reserved while the inputs are still held.
##########
datafusion/physical-plan/src/joins/hash_join/probe_cursor.rs:
##########
@@ -0,0 +1,311 @@
+// 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
+
+//! Expand duplicate groups at output-batch granularity.
+//!
+//! Lookup results contain only successful matches, with their original probe
+//! indices. The cursor remembers the next result and the next member of its
group.
+//! See [`GroupCursor`] for an example.
+//!
+//! Completion means all key matches were enumerated. It does not say whether
+//! any pair survived the residual ON predicate; that is the join's decision.
+
+use arrow::array::{UInt32Array, UInt64Array};
+use arrow::buffer::ScalarBuffer;
+use datafusion_common::{Result, internal_err};
+
+use crate::joins::join_index::{
+ GroupRows, JoinIndexMap, LookupResult, MatchHandles, RowId,
+};
+
+/// At most one batch of key-equal pairs, before residual filtering.
+pub(super) struct MatchChunk {
+ pub(super) build_rows: UInt64Array,
+ pub(super) probe_rows: UInt32Array,
+ /// Probe rows whose first equality pair was enumerated in this chunk.
+ /// Continuing a large group must not count that probe row again.
+ pub(super) newly_matched_probe_rows: usize,
+}
+
+/// Expands lookup results into build/probe pairs, remembering the next pair
to emit.
+///
+/// # Example
+///
+/// For handle `1` matching probe row `1`, with `batch_size = 2`,
+/// [`next_batch`](Self::next_batch) moves the cursor from `pos1` to `pos2`,
+/// emitting the build row IDs in between (`[22, 33]`).
+///
+/// ```text
+/// MatchHandles:
+/// 0 -> [...]
+/// 1 -> [22, 33, 44, 55]
+/// ^ ^
+/// pos1 pos2
+///
+/// Before:
+/// pos1: (match_index, offset_in_group) = (1, 0)
+///
+/// After `next_batch()`:
+/// pos2: (match_index, offset_in_group) = (1, 2)
+/// emitted build rows: [22, 33]
+/// emitted probe rows: [1, 1]
+/// ```
+pub(super) struct GroupCursor {
+ matches: LookupResult,
+ position: GroupPosition,
+}
+
+/// Position of the next build/probe pair to emit.
+///
+/// See [`GroupCursor`] for an example.
+#[derive(Default)]
+struct GroupPosition {
+ match_index: usize,
+ offset_in_group: usize,
+}
+
+impl GroupCursor {
+ pub(super) fn new(matches: LookupResult) -> Self {
+ Self {
+ matches,
+ position: GroupPosition::default(),
+ }
+ }
+
+ pub(super) fn is_finished(&self) -> bool {
+ self.position.match_index == self.matches.len()
+ }
+
+ /// Return the next chunk of at most `batch_size` build/probe row-index
pairs,
+ /// resuming from the saved position, which may be partway through a group.
+ ///
+ /// See [`GroupCursor`] for an example.
+ pub(super) fn next_batch(
+ &mut self,
+ index: &JoinIndexMap,
+ batch_size: usize,
+ buffers: &mut PairBuffer,
+ ) -> Result<MatchChunk> {
+ if batch_size == 0 {
+ return internal_err!("Join pair batch size must be positive");
+ }
+ if self.is_finished() {
+ return Ok(MatchChunk {
+ build_rows: UInt64Array::new_null(0),
+ probe_rows: UInt32Array::new_null(0),
+ newly_matched_probe_rows: 0,
+ });
+ }
+
+ // Case 1: All matches are singletons.
+ // By convention, upstream batches follow the configured `batch_size`,
+ // so materialize all matches directly without slicing or coalescing.
+ let singletons = match &self.matches {
+ LookupResult::U32(matches) if !matches.has_groups() => {
+ buffers.clear_for(matches.len(), 0);
+ buffers
+ .build_rows
+ .extend(matches.row_or_start().iter().map(|&row|
u64::from(row)));
+ let (build_rows, _) = buffers.finish();
+ Some((
+ build_rows,
+ UInt32Array::new(matches.probe_indices().clone(), None),
+ ))
+ }
+ LookupResult::U64(matches) if !matches.has_groups() => Some((
+ UInt64Array::new(matches.row_or_start().clone(), None),
+ UInt32Array::new(matches.probe_indices().clone(), None),
+ )),
+ _ => None,
+ };
+ if let Some((build_rows, probe_rows)) = singletons {
+ self.position.match_index = self.matches.len();
+ return Ok(MatchChunk {
+ build_rows,
+ probe_rows,
+ newly_matched_probe_rows: self.matches.len(),
+ });
+ }
Review Comment:
This returns every singleton match in the probe batch as one chunk, so a
probe batch longer than `batch_size` gives an output batch longer than
`batch_size`. The output coalescer doesn't split it, because it passes through
any batch over `batch_size / 2`
([coalesce/mod.rs](https://github.com/apache/datafusion/blob/b9756bd146c4e1c498b72d8c22ab576cfbec2a57/datafusion/physical-plan/src/coalesce/mod.rs#L57)).
On `main`, both lookups stop at `batch_size` pairs
([batched_join_processor.rs](https://github.com/apache/datafusion/blob/b9756bd146c4e1c498b72d8c22ab576cfbec2a57/datafusion/physical-plan/src/joins/hash_join/batched_join_processor.rs#L358-L379)),
and #27398 describes this layer as processing matches "in chunks bounded by
`batch_size`".
`join_emits_final_build_rows_in_batch_size_chunks` checks that bound. The
change to `final_build_rows_inputs`
([exec.rs](https://github.com/apache/datafusion/blob/bc2061bfd3212ab5971eb28c37987258282085d5/datafusion/physical-plan/src/joins/hash_join/exec.rs#L6088-L6098))
splits its probe input into one-row batches, which hides the problem. With the
probe side back to one 3-row batch, the Left and Full cases at `batch_size = 1`
fail with "Left join emitted a batch of 3 rows with batch_size 1".
Could Case 1 emit at most `batch_size` singletons per call? The handle
buffers are `ScalarBuffer`s, so slicing them doesn't copy.
`final_build_rows_inputs` can then go back to a single probe batch.
```suggestion
// Case 1: All matches are singletons. Emit at most `batch_size` of
// them; the handle buffers slice without copying.
let start = self.position.match_index;
let len = batch_size.min(self.matches.len() - start);
let singletons = match &self.matches {
LookupResult::U32(matches) if !matches.has_groups() => {
buffers.clear_for(len, 0);
buffers.build_rows.extend(
matches.row_or_start()[start..start + len]
.iter()
.map(|&row| u64::from(row)),
);
let (build_rows, _) = buffers.finish();
Some((
build_rows,
UInt32Array::new(matches.probe_indices().slice(start,
len), None),
))
}
LookupResult::U64(matches) if !matches.has_groups() => Some((
UInt64Array::new(matches.row_or_start().slice(start, len),
None),
UInt32Array::new(matches.probe_indices().slice(start, len),
None),
)),
_ => None,
};
if let Some((build_rows, probe_rows)) = singletons {
self.position.match_index = start + len;
return Ok(MatchChunk {
build_rows,
probe_rows,
newly_matched_probe_rows: len,
});
}
```
##########
datafusion/physical-plan/src/joins/join_index/directory/integer.rs:
##########
@@ -0,0 +1,273 @@
+// 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
+
+//! Single-integer-key directory with exact keys stored in hash entries.
+
+#[cfg(not(feature = "force_hash_collisions"))]
+use std::hash::BuildHasher;
+use std::mem::size_of;
+
+use arrow::array::*;
+use arrow::datatypes::{ArrowPrimitiveType, DataType};
+use datafusion_common::hash_utils::RandomState;
+use datafusion_common::utils::memory::estimate_memory_size;
+use datafusion_common::{NullEquality, Result, internal_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+use hashbrown::{HashTable, hash_table::Entry};
+use num_traits::AsPrimitive;
+
+use super::super::keys::{LookupScratch, for_each_hash_chunk, hash_probe_keys};
+use super::super::matches::{
+ LookupResult, MatchHandle, MatchHandles, MatchedGroups,
MatchedGroupsBuilder, RowId,
+};
+use super::Probe;
+
+/// Stores the exact integer join key in place of the general directory's
cached
+/// hash, avoiding an indirection into the build arrays on the lookup hot path.
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+///
+/// # Example
+///
+/// Build keys `[10, 20, 10]`, with zero-based row IDs, produce:
+///
+/// ```text
+/// key | representative_row | group_plus_one | matches()
+/// ----+--------------------+----------------+------------------------
+/// 10 | 0 | 1 | Group(0) -> rows [0, 2]
+/// 20 | 1 | 0 | One(1) -> row 1
+/// ```
+///
+/// Lookup hashes the probe key to find candidates, then compares `key`
directly.
+///
+/// - `representative_row`: the first build-row ID for this key.
+/// - `group_plus_one`: zero for a single row; otherwise the group ID plus one.
+/// The group's row IDs occupy a contiguous slice of
+/// [`MatchedGroups::rows`](super::super::matches::MatchedGroups::rows).
+#[derive(Clone, Copy, Debug)]
+struct IntegerKeyEntry<T> {
+ key: u64,
+ representative_row: T,
+ group_plus_one: T,
+}
+
+/// Hash directory for a single integer join key, comparing keys inline in
+/// [`IntegerKeyEntry`].
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+#[derive(Debug)]
+pub(super) struct IntegerDirectory<T> {
+ table: HashTable<IntegerKeyEntry<T>>,
+ null: Option<MatchHandle<T>>,
+ // Reconstruct the native signedness and width before hashing. This matches
+ // create_hashes and keeps hash-only dynamic filters selective.
+ hash_key: fn(u64, &RandomState) -> u64,
+ /// Every matchable build key has at most one row, including NULL.
+ build_unique: bool,
+}
+
+pub(super) fn integer_hasher(
+ data_type: &DataType,
+) -> Option<fn(u64, &RandomState) -> u64> {
+ macro_rules! hasher {
+ ($type:ty) => {{
+ #[cfg(not(feature = "force_hash_collisions"))]
+ let hash: fn(u64, &RandomState) -> u64 =
+ |key, state| state.hash_one(key as $type);
+ #[cfg(feature = "force_hash_collisions")]
+ let hash: fn(u64, &RandomState) -> u64 = |_, _| 0;
+ Some(hash)
+ }};
Review Comment:
This closure has to produce the same hashes as `create_hashes` in
`datafusion-common`, including under `force_hash_collisions`. The `cfg` here
checks `datafusion-physical-plan`'s feature, which doesn't turn on
`datafusion-common`'s
([Cargo.toml](https://github.com/apache/datafusion/blob/b9756bd146c4e1c498b72d8c22ab576cfbec2a57/datafusion/physical-plan/Cargo.toml#L28)).
With `cargo test -p datafusion-physical-plan --lib --features
force_hash_collisions joins::`, the build side gets real hashes while
`contains_hash` compares them to 0. The dynamic filter then rejects every probe
row. `build_map_stays_reserved_with_dynamic_filter` (both modes) and
`pruning_bitmap_is_optional` return 0 rows instead of 3. The same command
passes on `main`. CI enables both features through `--workspace`, so it doesn't
see this.
Could `datafusion-physical-plan`'s feature forward to `datafusion-common`,
as `force_hash_collisions = ["datafusion-common/force_hash_collisions"]`?
##########
datafusion/physical-plan/src/joins/join_index/directory.rs:
##########
@@ -0,0 +1,357 @@
+// 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
+
+//! Exact-key directory layouts, construction, and typed integer lookup.
+//!
+//! Dense integers use an array slot: keys `[10, 11, 12]` live at `key - 10`.
+//! Sparse integers such as `[10, 1_000_000]` use SwissTable with the actual
key
+//! in each entry. General keys use a cached hash and a representative build
row
+//! whose Arrow values establish equality. All three identify exact keys and
+//! return compact successful matches with their probe-row indices; only row
IDs
+//! are grouped.
+
+use arrow::array::{ArrayRef, BooleanArray};
+use arrow::buffer::BooleanBuffer;
+use datafusion_common::hash_utils::RandomState;
+use datafusion_common::{NullEquality, Result, internal_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+
+use super::keys::LookupScratch;
+use super::matches::{
+ GroupRows, LookupResult, MatchedGroups, MatchedGroupsBuilder, RowId,
+};
+use crate::joins::array_map::ArrayMap;
+use crate::joins::utils::matchable_join_keys;
+
+mod dense;
+mod general;
+mod integer;
+
+use dense::DenseIntegerDirectory;
+use general::GeneralDirectory;
+use integer::{IntegerDirectory, integer_hasher};
+
+/// See [`JoinHashIndex`] for the design overview.
+struct Probe<'a> {
+ build_keys: &'a [ArrayRef],
+ probe_keys: &'a [ArrayRef],
+ null_equality: NullEquality,
+ random_state: &'a RandomState,
+}
+
+/// See [`JoinHashIndex`] for the design overview.
+#[derive(Debug)]
+pub(super) enum IndexWidth {
+ U32(JoinHashIndex<u32>),
+ U64(JoinHashIndex<u64>),
+}
+
+impl IndexWidth {
+ /// See [`JoinHashIndex::build`] and
+ /// [`JoinIndexMap::try_new`](super::JoinIndexMap::try_new) for shared
argument documentation.
+ ///
+ /// When `force_u64` is `true`, use `u64` row/group IDs regardless of
build size.
+ /// See [`JoinHashIndex`] for normal row-width selection.
+ /// Set it to `true` only in tests to exercise wide IDs without allocating
+ /// large arrays; use `false` otherwise.
+ pub(super) fn build(
+ keys: &[ArrayRef],
+ random_state: &RandomState,
+ null_equality: NullEquality,
+ dense_range: Option<(u64, u64)>,
+ hash_chunk_size: usize,
+ reservation: &MemoryReservation,
+ force_u64: bool,
+ ) -> Result<Self> {
+ let Some(first) = keys.first() else {
+ return internal_err!("A join index requires at least one key
column");
+ };
+ let num_rows = first.len();
+ let scratch = reservation.new_empty();
+ // Build validity masks scale with the full build input.
+ scratch.try_grow(num_rows.div_ceil(8) * (keys.len() + 1))?;
Review Comment:
Following up on
https://github.com/apache/datafusion/pull/27746#discussion_r4698325783: 8282c74
bounds the build's hash buffer to `hash_chunk_size` rows, but nothing reserves
that buffer
([keys.rs](https://github.com/apache/datafusion/blob/bc2061bfd3212ab5971eb28c37987258282085d5/datafusion/physical-plan/src/joins/join_index/keys.rs#L172-L173)).
For keys with shared values, such as dictionaries, `hash_chunk_rows` makes a
chunk 16 times the length of the shared values, up to the whole build side
([exec.rs](https://github.com/apache/datafusion/blob/b9756bd146c4e1c498b72d8c22ab576cfbec2a57/datafusion/physical-plan/src/joins/hash_join/exec.rs#L140-L153)).
`main` reserves the buffer when it's longer than a batch, and always in
prepared builds
([exec.rs](https://github.com/apache/datafusion/blob/b9756bd146c4e1c498b72d8c22ab576cfbec2a57/datafusion/physical-plan/src/joins/hash_join/exec.rs#L3410-L3420)).
The legacy path in this PR still does.
Could we add it to the scratch reservation here? Reserving it for every
hash-based build keeps the code simple and costs at most one batch of hashes
beyond what `main` reserves.
```suggestion
let scratch = reservation.new_empty();
// Build validity masks scale with the full build input. Hash-based
// directories also hash up to `hash_chunk_size` rows at a time.
let hash_rows = if dense_range.is_some() {
0
} else {
hash_chunk_size.min(num_rows)
};
scratch.try_grow(
num_rows.div_ceil(8) * (keys.len() + 1) + hash_rows *
size_of::<u64>(),
)?;
```
--
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]