Repository navigation
perf: join hash table redesign (9 hj bench queries 3–8× faster) - #27746
2010YOUY01 wants to merge 6 commits into
Conversation
Notes for the reviewerWhat I've reviewed carefully in this PR:
Still to refine (I'm working on these in parallel with the initial reviews):
Possible PR split:Below are possible PR splits; whether and how to split depends on reviewers' preferences, though I currently lean toward shipping them together and iterating in follow-up PRs to finish the HJ refactor sooner and reduce disruption to ongoing development.
TODO for myself:
|
|
I'd like to share the results of an independent research study relevant to this hash join redesign. I recently published When Contiguous Hash Joins Pay Off in DuckDB and DataFusion, motivated by Birler et al.'s Unchained hash table paper (DaMoN 2024). The study includes experimental integrations into DuckDB 1.5.6 and DataFusion 55.2.0, an analytical break-even model, and reproducible artifacts backed by 24,282 benchmark observations. In DataFusion, automatic CSR selection reduced aggregate query time compared to native execution in single-threaded experiments:
A particularly interesting finding is the workload-dependent cost of constructing contiguous layouts. Lowering the build threshold from 200K to 50K rows yielded a 2.177× speedup on 12 held-out graph queries, while producing essentially no change on 31 affected analytical queries. The paper also examines why build-side multiplicity alone is insufficient to characterize probe demand and derives a break-even condition accounting for both key distributions and layout construction costs. Research artifacts:
Although my experimental implementation differs from the design proposed here, I believe these findings and graph workloads could complement the existing I'd be interested in contributing comparative benchmark results for this redesign and discussing potential follow-up optimizations. |
@rusanoph Thanks, that would help. This PR differs from your CSR adapter in what the build moves and when. It keeps one directory entry per distinct key and stores a key with one row inline in that entry. Only the row IDs of repeated keys move into contiguous groups, and that happens in the same pass that builds the directory. There is no second organization pass and no admission gate. The |
mbutrovich
left a comment
There was a problem hiding this comment.
@2010YOUY01 thanks for bringing the hash table work together here. The layout matches #27398. Building the groups in the same pass as the directory also avoids the second pass that made #26447 1% to 10% slower on the low-hit hj queries.
Could you also run the imdb (JOB) suite, along with the TPC-H and TPC-DS runs on your list? In the study linked in #27746 (comment), JOB is where contiguous groups gave DataFusion its largest gain outside the graph workloads (11.7% of total time, Table 1). It also has joins with large builds and few probes, so it should show both the gain and the build-side cost.
| let scratch = reservation.new_empty(); | ||
| // Keep validity unions and per-column metadata charged for every layout. | ||
| // Dense keys are read directly, so only hash-based directories need hashes. | ||
| scratch.try_grow(num_rows.div_ceil(8) * (keys.len() + 1) + keys.len() * 256)?; | ||
| let hashes = if dense_range.is_none() { | ||
| scratch.try_grow(num_rows * size_of::<u64>() + hash_scratch_bytes(keys))?; | ||
| let mut hashes = vec![0; num_rows]; | ||
| create_hashes(keys, random_state, &mut hashes)?; | ||
| hashes | ||
| } else { | ||
| Vec::new() | ||
| }; |
There was a problem hiding this comment.
datafusion/physical-plan/src/joins/join_index/directory.rs lines 66-77
This hashes the whole build side into one Vec<u64>, 8 bytes per row, held for the whole build. On main the build hashes slices of at most hash_chunk_rows rows (exec.rs), which #26793 added to keep that buffer near one batch.
Together with the up-front MatchedGroupsBuilder reservation (next comment), this raises the build's peak reservation. I measured it with PeakRecordingPool on a CollectLeft inner join with 1M Int64 build rows in 8192-row batches and three probe rows:
| Build keys | main |
This PR |
|---|---|---|
| Hash path, unique | 55.7 MB | 73.9 MB |
| Hash path, 100 rows per key | 55.7 MB | 78.0 MB |
| Dense, unique | 32.0 MB | 34.3 MB |
| Dense, 100 rows per key | 32.0 MB | 34.4 MB |
A build that fits under a memory limit on main can fail with this PR. Could the directories insert one slice at a time, sized by hash_chunk_rows, so the hash buffer stays bounded as it is on main?
There was a problem hiding this comment.
I was able to reproduce the memory-limit regression on x86-64 using controlled workloads similar to those in your review: 1M build rows, 8,192-row batches and three probe rows.
A is the main merge-base, B is this PR, and C includes the dense counting-sort patch.
| Build shape | Peak pool A / B / C (MiB) | Successful runs at 64 MiB (A / B / C) |
|---|---|---|
| Dense unique | 22.95 / 32.66 / 22.95 | 5 / 5 / 5 |
| Dense duplicates | 30.58 / 32.78 / 30.58 | 5 / 5 / 5 |
| Sparse integer unique | 53.07 / 70.48 / 70.48 | 5 / 0 / 0 |
| Sparse integer duplicates | 53.07 / 74.37 / 74.37 | 5 / 0 / 0 |
Both sparse integer cases consistently succeed on A but return ResourcesExhausted on B and C under the same memory-pool limit.
The counting-sort patch restores the baseline pool watermark for the dense cases, but the non-dense resource regression remains.
The current experiment does not isolate the individual contributions of the whole-build hash buffer and the group-builder reservations.
Memory report, fixtures, raw measurements and failure evidence
If this is intended to be addressed in a follow-up PR, I'd be interested in helping with the regression tests or investigating the allocation overhead further.
There was a problem hiding this comment.
- RE hashing in chunk: addressed in 8282c74
MatchedGroupsBuilderconservative reservation: I'll address it after more perf investigations on other benchmarks
| pub(super) fn new(num_rows: usize, reservation: &MemoryReservation) -> Result<Self> { | ||
| // Estimate the memory and update the reservation. The conservative estimation | ||
| // is on purpose for simplicity. | ||
| // Each group needs at least two rows; each key's first row is not pending. | ||
| // E.g. [A, A, A] has one group and two pending rows. | ||
| let max_groups = num_rows / 2; | ||
| let max_pending = num_rows.saturating_sub(1); | ||
| let bytes = max_groups | ||
| .checked_mul(size_of::<T>() + size_of::<usize>()) | ||
| .and_then(|bytes| { | ||
| let pending_bytes = max_pending.checked_mul(size_of::<(T, T)>())?; | ||
| bytes.checked_add(pending_bytes) | ||
| }) | ||
| .ok_or_else(|| { | ||
| exec_datafusion_err!("Join group construction size overflow") | ||
| })?; | ||
| let reservation = reservation.new_empty(); | ||
| reservation.try_grow(bytes)?; | ||
| Ok(Self { | ||
| first_rows: Vec::with_capacity(max_groups), | ||
| counts: Vec::with_capacity(max_groups), | ||
| pending: Vec::with_capacity(max_pending), | ||
| _reservation: reservation, | ||
| }) | ||
| } |
There was a problem hiding this comment.
new reserves and allocates for the worst case before it sees any row. With u32 IDs that's num_rows / 2 groups at 12 bytes each plus num_rows - 1 pending pairs at 8 bytes each, about 14 bytes per build row, or 28 with u64 IDs. A unique build pushes nothing but still holds the whole reservation. finish then reserves the groups while this reservation is still held. That's why the duplicate-heavy rows in the table above are 4 MB higher than the unique ones.
Could add_duplicate grow these vectors through the reservation as rows arrive, returning Result? Unique builds would then pay nothing, and duplicate-heavy builds would pay only for their duplicate rows. Storing counts as T instead of usize would also halve that vector with u32 IDs.
| for (row, &hash) in hashes.iter().enumerate() { | ||
| if valid.is_some_and(|valid| valid.is_null(row)) { | ||
| continue; | ||
| } | ||
| match table.entry( | ||
| hash, | ||
| |entry| { | ||
| entry.hash == hash | ||
| && comparator.is_equal(entry.representative_row.as_index(), row) | ||
| }, | ||
| |entry| entry.hash, | ||
| ) { | ||
| Entry::Occupied(mut entry) => { | ||
| let entry = entry.get_mut(); | ||
| let mut handle = entry.matches(); | ||
| groups.add_duplicate(&mut handle, T::from_index(row)); | ||
| let MatchHandle::Group(group) = handle else { | ||
| unreachable!() | ||
| }; | ||
| entry.group_plus_one = T::from_index(group.as_index() + 1); | ||
| } | ||
| Entry::Vacant(entry) => { | ||
| let row = T::from_index(row); | ||
| entry.insert(KeyEntry { | ||
| hash, | ||
| representative_row: row, | ||
| group_plus_one: T::default(), | ||
| }); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
This loop checks key equality for every build row whose hash matches an existing entry, with one boxed JoinKeyComparator call per row and key column. On main the build compares hashes only (join_hash_map.rs), and the probe compares keys for each candidate pair. So the PR moves equality work from probe pairs to build rows, which pays off when the build is probed often.
The hj queries with string or composite keys (Q23 to Q25) build at most 32K rows, so nothing measures this loop on a large duplicate-heavy build with few probes. Could we add an hj query of that shape, for example a few million build rows on a long string key with about 100 rows per key and a 1% hit rate? If the loop shows up in that query, the probe side of this PR already compares keys in batches (compare_column). DuckDB's build does the same: it collects the rows whose salt matches an existing entry, then compares their keys in one vectorized pass (join_hashtable.cpp).
There was a problem hiding this comment.
I agree there is some extra overhead for such workload.
The hj benchmark is extended as suggested in #27766
The result is approximately main: 20ms, PR: 23ms on my Mac. My interpretation is that the additional cost scales linearly with the build-side size and is unlikely to cause pathological end-to-end slowdowns, since hash table construction is not a bottleneck for the overall query now.
However we could still explore whether there are any straightforward ways to speed it up.
| for (row, &key) in key_array.values().iter().enumerate() { | ||
| if valid.is_some_and(|valid| valid.is_null(row)) { | ||
| continue; | ||
| } | ||
| if key_array.is_null(row) { | ||
| match &mut dense.null { | ||
| Some(handle) => groups.add_duplicate(handle, T::from_index(row)), | ||
| slot @ None => { | ||
| *slot = Some(MatchHandle::One(T::from_index(row))); | ||
| dense.distinct += 1; | ||
| } | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| let key: u64 = key.as_(); | ||
| let position = key.wrapping_sub(min); | ||
| if position >= len as u64 { | ||
| return internal_err!("Build key is outside the dense join index range"); | ||
| } | ||
| let position = position as usize; | ||
| let slot = dense.slots[position].as_index(); | ||
|
|
||
| if slot == 0 { | ||
| dense.slots[position] = T::from_index(row + 1); | ||
| dense.distinct += 1; | ||
| continue; | ||
| } | ||
| // E.g. key 10 at rows 0 and 2: One(0) becomes Group(0) -> [0, 2]. | ||
| let already_group = group_flags | ||
| .as_ref() | ||
| .is_some_and(|flags| flags.get_bit(position)); | ||
| let mut handle = if already_group { | ||
| MatchHandle::Group(T::from_index(slot - 1)) | ||
| } else { | ||
| MatchHandle::One(T::from_index(slot - 1)) | ||
| }; | ||
| groups.add_duplicate(&mut handle, T::from_index(row)); | ||
| let MatchHandle::Group(group) = handle else { | ||
| unreachable!() | ||
| }; | ||
| // Allocate group flags only when a non-NULL key repeats. | ||
| if group_flags.is_none() { | ||
| reservation.try_grow(bitmap_bytes(len))?; | ||
| let mut flags = BooleanBufferBuilder::new(len); | ||
| flags.append_n(len, false); | ||
| group_flags = Some(flags); | ||
| } | ||
| group_flags.as_mut().unwrap().set_bit(position, true); | ||
| dense.slots[position] = T::from_index(group.as_index() + 1); | ||
| } |
There was a problem hiding this comment.
On duplicate-heavy dense keys this build takes about 2.8x the CPU of the ArrayMap build on main. I profiled dfbench hj with samply on SF10 (20 iterations per query, the profiling profile with thin LTO) and summed the CPU under build_in_memory across threads:
| Query | main |
This PR |
|---|---|---|
| Q2 | 59 ms | 111 ms |
| Q4 | 3,209 ms | 8,871 ms |
| Q5 | 3,277 ms | 8,951 ms |
| Q28 | 1,088 ms | 1,201 ms |
Q4 and Q5 build about 60M lineitem rows over dense keys with about 600 rows per key. There, the build functions take 28% (Q4) and 23% (Q5) of the query's CPU. Q4 and Q5 are still faster overall because the probe gain is larger. Q2 is not. With join reordering off, its build side is the 1.5M customer rows over 25 keys, so this build cost is the Q2 regression.
In Q4, about a quarter of the build time is in add_duplicate: the out-of-line call for each duplicate row, the handle match, counts[group] += 1, and the pending push. About a fifth is the pending scatter in finish. About a seventh is the checked RowId::from_index conversions, and the rest is this loop. These shares are approximate, because they come from sampling.
I tried a counting sort for the dense directory. It counts each slot's rows (slots[key - min] += 1), gives each repeated key a range of rows, and then scatters the row IDs in a second pass over the keys, using each group's slot as its write cursor. It keeps build order, and a slot with one row still holds One(row). It needs no MatchedGroupsBuilder, so for dense keys the pending and first_rows memory from the MatchedGroupsBuilder::new comment goes away. It is the exact dense variant in the study linked above (section 5.2). The patch against this PR's head is below.
On the same machine, with main, this PR, and the patch interleaved over three rounds (medians of 54 iterations each):
| Query | main |
This PR | Counting sort |
|---|---|---|---|
| Q2 | 2.99 ms | 3.41 ms | 2.80 ms |
| Q4 | 110.89 ms | 103.24 ms | 87.11 ms |
| Q5 | 402.08 ms | 116.51 ms | 100.79 ms |
| Q26 | 30.37 ms | 29.99 ms | 29.86 ms |
| Q23 (general directory, unchanged) | 84.85 ms | 18.74 ms | 19.19 ms |
Build CPU drops from 8,871 ms to 5,607 ms on Q4 and from 8,951 ms to 5,206 ms on Q5. That's still above main's 3,209 ms, because scattering 60M row IDs into rows is the price of contiguous groups. My first version iterated with try_for_each. It was slower than this PR, because the per-row closure didn't inline, so plain loops matter here. These numbers are from an Apple M5 Max and need confirming on x86. Could the dense directory use this approach, or something like it?
Counting sort for the dense directory, against 2f6c665
diff --git a/datafusion/physical-plan/src/joins/join_index/directory.rs b/datafusion/physical-plan/src/joins/join_index/directory.rs
index 6ff1580fd..803f3eeb3 100644
--- a/datafusion/physical-plan/src/joins/join_index/directory.rs
+++ b/datafusion/physical-plan/src/joins/join_index/directory.rs
@@ -304,22 +304,21 @@ impl<T: RowId> JoinHashIndex<T> {
reservation: &MemoryReservation,
random_state: &RandomState,
) -> Result<Self> {
- let mut groups = MatchedGroupsBuilder::new(keys[0].len(), reservation)?;
let valid = matchable_join_keys(keys, null_equality);
- let directory = if let Some(range) = dense_range {
+ if let Some(range) = dense_range {
let key = match keys {
[key] if ArrayMap::is_supported_type(key.data_type()) => key,
_ => return internal_err!("Dense join index requires one integer key"),
};
- DenseIntegerDirectory::build(
- key,
- valid.as_ref(),
- range,
- reservation,
- &mut groups,
- )
- .map(KeyDirectory::Dense)?
- } else if let Some(hash_key) = (keys.len() == 1)
+ let (directory, groups) =
+ DenseIntegerDirectory::build(key, valid.as_ref(), range, reservation)?;
+ return Ok(Self {
+ directory: KeyDirectory::Dense(directory),
+ groups,
+ });
+ }
+ let mut groups = MatchedGroupsBuilder::new(keys[0].len(), reservation)?;
+ let directory = if let Some(hash_key) = (keys.len() == 1)
.then(|| integer_hasher(keys[0].data_type()))
.flatten()
{
diff --git a/datafusion/physical-plan/src/joins/join_index/directory/dense.rs b/datafusion/physical-plan/src/joins/join_index/directory/dense.rs
index f40174ab5..a7c4f4bd0 100644
--- a/datafusion/physical-plan/src/joins/join_index/directory/dense.rs
+++ b/datafusion/physical-plan/src/joins/join_index/directory/dense.rs
@@ -15,12 +15,28 @@ use num_traits::AsPrimitive;
use super::super::keys::LookupScratch;
use super::super::matches::{
- JoinHashLookup, MatchHandle, MatchHandleArray, MatchedGroupsBuilder, RowId,
- UniqueMatches, bitmap_bytes,
+ JoinHashLookup, MatchHandle, MatchHandleArray, MatchedGroups, RowId, UniqueMatches,
+ bitmap_bytes,
};
use super::Probe;
use crate::joins::array_map::ArrayMap;
+/// Runs `$body` for each row that `$valid` keeps. Plain loops, unlike
+/// `try_for_each`, let the body inline, and builds without NULL keys get a
+/// separate loop.
+macro_rules! for_each_valid {
+ ($len:expr, $valid:expr, |$row:ident| $body:block) => {
+ match $valid {
+ Some(valid) => {
+ for $row in valid.valid_indices() $body
+ }
+ None => {
+ for $row in 0..$len $body
+ }
+ }
+ };
+}
+
/// Direct lookup for a single integer join key in a compact range.
///
/// # Overview
@@ -78,110 +94,123 @@ impl<T: RowId> DenseIntegerDirectory<T> {
valid: Option<&NullBuffer>,
range: (u64, u64),
reservation: &MemoryReservation,
- groups: &mut MatchedGroupsBuilder<T>,
- ) -> Result<Self> {
+ ) -> Result<(Self, MatchedGroups<T>)> {
// Dispatch once per column; the typed build reads values without a copy.
downcast_integer_array!(
- key_array => {
- Self::build_typed(key_array, valid, range, reservation, groups)
- }
+ key_array => Self::build_typed(key_array, valid, range, reservation),
_ => internal_err!("Dense join index requires an integer key"),
)
}
+ /// Counting sort: count each slot's rows, give each repeated key a
+ /// contiguous range, then scatter the row IDs in build order.
+ ///
/// See [`Self::build`] for shared argument documentation.
fn build_typed<K: ArrowPrimitiveType>(
key_array: &PrimitiveArray<K>,
valid: Option<&NullBuffer>,
(min, max): (u64, u64),
reservation: &MemoryReservation,
- groups: &mut MatchedGroupsBuilder<T>,
- ) -> Result<Self>
+ ) -> Result<(Self, MatchedGroups<T>)>
where
K::Native: AsPrimitive<u64>,
{
- // Step 1: Sanity check
let range = ArrayMap::calculate_range(min, max);
if range >= usize::MAX as u64 {
return internal_err!("Dense join index key range is too large");
}
-
- // Step 2: update memory reservation
+ // `array_map_key_range` rejects NULL-equal builds with NULL keys.
+ if valid.is_none() && key_array.null_count() > 0 {
+ return internal_err!("Dense join index cannot store NULL keys");
+ }
let len = range as usize + 1;
let bytes = len
.checked_mul(size_of::<T>())
.ok_or_else(|| exec_datafusion_err!("Dense join index size overflow"))?;
reservation.try_grow(bytes)?;
+ let values = key_array.values();
- // Step 3: initialize flat array directory
- let mut dense = Self {
- offset: min,
- slots: vec![T::default(); len],
- is_group: None,
- null: None,
- distinct: 0,
- build_unique: true,
- };
- let mut group_flags: Option<BooleanBufferBuilder> = None;
+ // Pass 1: count rows per slot. Counts fit `T` because the row count does.
+ let mut slots = vec![T::default(); len];
+ for_each_valid!(values.len(), valid, |row| {
+ let position = values[row].as_().wrapping_sub(min);
+ if position >= len as u64 {
+ return internal_err!("Build key is outside the dense join index range");
+ }
+ let slot = &mut slots[position as usize];
+ *slot = T::usize_as(slot.as_usize() + 1);
+ });
- // Step 4: build the index
- for (row, &key) in key_array.values().iter().enumerate() {
- if valid.is_some_and(|valid| valid.is_null(row)) {
- continue;
+ // Pass 2: give each repeated key a group and a range of `rows`.
+ let (mut distinct, mut num_groups, mut grouped_rows) = (0, 0, 0);
+ for slot in &slots {
+ let count = slot.as_usize();
+ distinct += usize::from(count != 0);
+ if count > 1 {
+ num_groups += 1;
+ grouped_rows += count;
}
- if key_array.is_null(row) {
- match &mut dense.null {
- Some(handle) => groups.add_duplicate(handle, T::from_index(row)),
- slot @ None => {
- *slot = Some(MatchHandle::One(T::from_index(row)));
- dense.distinct += 1;
- }
+ }
+ let mut is_group = None;
+ let mut offsets = Vec::new();
+ let mut rows = Vec::new();
+ if num_groups > 0 {
+ reservation.try_grow(
+ bitmap_bytes(len)
+ + (num_groups + 1) * size_of::<usize>()
+ + grouped_rows * size_of::<T>(),
+ )?;
+ // A group's slot holds its next write position until pass 3 ends.
+ let mut flags = BooleanBufferBuilder::new(len);
+ flags.append_n(len, false);
+ offsets.reserve_exact(num_groups + 1);
+ offsets.push(0);
+ for (position, slot) in slots.iter_mut().enumerate() {
+ let count = slot.as_usize();
+ if count > 1 {
+ let start = offsets[offsets.len() - 1];
+ *slot = T::usize_as(start);
+ offsets.push(start + count);
+ flags.set_bit(position, true);
}
- continue;
}
+ let flags = flags.finish();
+ rows = vec![T::default(); grouped_rows];
- let key: u64 = key.as_();
- let position = key.wrapping_sub(min);
- if position >= len as u64 {
- return internal_err!("Build key is outside the dense join index range");
- }
- let position = position as usize;
- let slot = dense.slots[position].as_index();
+ // Pass 3: a single row's slot takes its row ID, and a group's row
+ // goes to the slot's write position. Pass 1 checked every position.
+ for_each_valid!(values.len(), valid, |row| {
+ let position = values[row].as_().wrapping_sub(min) as usize;
+ let slot = &mut slots[position];
+ if flags.value(position) {
+ rows[slot.as_usize()] = T::usize_as(row);
+ *slot = T::usize_as(slot.as_usize() + 1);
+ } else {
+ *slot = T::usize_as(row + 1);
+ }
+ });
- if slot == 0 {
- dense.slots[position] = T::from_index(row + 1);
- dense.distinct += 1;
- continue;
+ // Pass 4: replace each group's write position with its group ID.
+ for (group, position) in flags.set_indices().enumerate() {
+ slots[position] = T::usize_as(group + 1);
}
- // E.g. key 10 at rows 0 and 2: One(0) becomes Group(0) -> [0, 2].
- let already_group = group_flags
- .as_ref()
- .is_some_and(|flags| flags.get_bit(position));
- let mut handle = if already_group {
- MatchHandle::Group(T::from_index(slot - 1))
- } else {
- MatchHandle::One(T::from_index(slot - 1))
- };
- groups.add_duplicate(&mut handle, T::from_index(row));
- let MatchHandle::Group(group) = handle else {
- unreachable!()
- };
- // Allocate group flags only when a non-NULL key repeats.
- if group_flags.is_none() {
- reservation.try_grow(bitmap_bytes(len))?;
- let mut flags = BooleanBufferBuilder::new(len);
- flags.append_n(len, false);
- group_flags = Some(flags);
- }
- group_flags.as_mut().unwrap().set_bit(position, true);
- dense.slots[position] = T::from_index(group.as_index() + 1);
+ is_group = Some(flags);
+ } else {
+ for_each_valid!(values.len(), valid, |row| {
+ let position = values[row].as_().wrapping_sub(min) as usize;
+ slots[position] = T::usize_as(row + 1);
+ });
}
- // Step 5: Freeze the group bitmap; without grouped slots it stays None.
- dense.is_group = group_flags.map(|mut flags| flags.finish());
- // Include NULL groups, which do not appear in the slot bitmap.
- dense.build_unique = !groups.has_groups();
- Ok(dense)
+ let dense = Self {
+ offset: min,
+ slots,
+ is_group,
+ null: None,
+ distinct,
+ build_unique: num_groups == 0,
+ };
+ Ok((dense, MatchedGroups { offsets, rows }))
}
pub(super) fn lookup_batch(There was a problem hiding this comment.
I tested your exact patch on x86-64 (Ryzen 5 7500F, WSL2), using the official dfbench hj SF10 workload with one logical CPU and one execution partition.
A is the main merge-base 6a06058, B is PR head 2f6c665, and C is B with your counting-sort patch.
| Query | A (ms) | B (ms) | C (ms) | Paired B/C [95% CI] |
|---|---|---|---|---|
| Q2 | 16.27 | 18.95 | 12.07 | 1.569 [1.524, 1.603] |
| Q4 | 1749.89 | 1780.93 | 1267.06 | 1.415 [1.360, 1.435] |
| Q5 | 8115.49 | 2011.94 | 1404.90 | 1.432 [1.309, 1.462] |
The patch reverses the Q2 regression and improves Q4 and Q5, consistent with your M5 Max observations. The B/C confidence intervals for Q23, Q26 and Q28 include parity.
Another interesting result is peak memory-pool reservation on Q4:
- A: 915.31 MiB
- B: 1506.78 MiB
- C: 915.31 MiB
Q5 shows the same pattern. The full-result correctness checks agreed across all three arms for all six queries.
These measurements support the proposed counting-sort approach for the dense directory. I couldn't collect sampled build CPU under the installed WSL kernel, so the timing comparison is based on elapsed time rather than sampled CPU time.
| if key_array.is_null(row) { | ||
| match &mut dense.null { | ||
| Some(handle) => groups.add_duplicate(handle, T::from_index(row)), | ||
| slot @ None => { | ||
| *slot = Some(MatchHandle::One(T::from_index(row))); | ||
| dense.distinct += 1; | ||
| } | ||
| } | ||
| continue; | ||
| } |
There was a problem hiding this comment.
array_map_key_range doesn't pick the dense directory when NULLs equal NULLs and the key has NULLs (exec.rs). Under NullEqualsNothing, the valid check above skips NULL rows. So null is always None in a dense directory built by HashJoinExec, and this branch, the NULL handling in lookup, and the NULL case in contain_keys never run. The IS NOT DISTINCT FROM case at line 178 of join_exact_index.slt goes through IntegerDirectory for that reason. Should we drop this code and return an internal error if a dense build sees a matchable NULL?
There was a problem hiding this comment.
Cleaned up in baa77ff, I think support for nulls in the dense directory can be added in the future.
| /// Maps exact join keys (one or more columns) to matching build-row IDs. | ||
| /// Lookup returns row pairs or group handles for the join processor to consume. | ||
| /// See [`directory::JoinHashIndex`] for the storage design and a small example. | ||
| #[derive(Debug)] | ||
| pub(crate) struct JoinIndexMap { | ||
| /// Index implementation specialized on row-id width. | ||
| index: IndexWidth, | ||
| random_state: RandomState, | ||
| /// See [`NullEquality`] for semantics. | ||
| /// | ||
| /// For implementation: | ||
| /// - `NullEqualsNothing`: skip NULL-key rows during build and probe. | ||
| /// - `NullEqualsNull`: hash and compare NULL keys | ||
| null_equality: NullEquality, |
There was a problem hiding this comment.
The new index has no unit tests, so only SQL exercises it. SQL can't reach the u64 row-ID width, which needs more than u32::MAX build rows. Could we add tests that build each directory directly (dense, integer, general, and JoinHashIndex<u64> on a small input) from random keys with duplicates and NULLs? They could run under both NullEquality values and compare lookup_batch plus group expansion against a brute-force map. #27530 had tests of this shape for the grouped JoinHashMap that could be adapted (join_hash_map.rs).
There was a problem hiding this comment.
Good point. Added some UTs covering combinations for
- join Null semantics
- row width specialization u32/u64
- directory dense/integer/general
- duplicated matches/unique matches
In 5eb078b
I think this u64 row-width is also good to get covered in SQL test, maybe by exposing a test-only config to force this path. This could be done in follow-ups.
|
Quick update: I've started running the comparative benchmarks on SNAP and JOB against this PR and main, including the query shapes where my CSR adapter regressed. I'm also planning to validate the proposed dense-directory counting-sort patch on x86-64 (AMD Ryzen 5 7500F). If possible, I'd appreciate keeping this PR open until I can share the initial results, as they may help assess the remaining performance trade-offs before merging. |
@mbutrovich Thanks for the suggestions! I've completed the SNAP and JOB comparison, as well as the x86-64 validation of your counting-sort patch and the controlled memory experiments. Setup: AMD Ryzen 5 7500F, WSL2, Rust 1.97.0, one logical CPU, one execution partition. Presets:
SNAP and JOB (A vs B)
All 1,918 observations succeeded with matching outputs and physical plan text. The JOB improvement is concentrated in the six family-17 queries, which account for approximately 99% of the net time saved. JOB 7b regressed from 277.5 to 360.4 ms. Selective Slashdot and Amazon out-star workloads also showed smaller slowdowns. The counting-sort experiment confirms the direction of your M5 Max results on x86-64. I also reproduced the resource regression for sparse integer keys under a 64 MiB memory-pool limit. Results and reproducibility: The package includes the benchmark worker, SQL workloads, raw observations, query plans, correctness evidence, source revisions and reproduction scripts. The published statistics can be recomputed using |
|
run benchmark tpch10 tpcds imdb hj |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark tpch10Results will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark tpcdsResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark imdbResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark running (GKE) | trigger CPU Details (lscpu)Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark hjResults will be posted here when complete File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark hjCPU Details (lscpu)Details
Resource Usagehj — base (merge-base)
hj — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark tpch10CPU Details (lscpu)Details
Resource Usagetpch10 — base (merge-base)
tpch10 — branch
File an issue against this benchmark runner |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark tpcdsCPU Details (lscpu)Details
Resource Usagetpcds — base (merge-base)
tpcds — branch
File an issue against this benchmark runner |
|
@mbutrovich Thanks for the thoughtful feedbacks! Previous suggestions has been addressed (except for #27746 (comment), I plan to do it after checking full benchmark numbers) Next I'll run and investigate hj/tpch/tpcds/JOB benchmark results on this PR. |
|
@rusanoph Thanks for the detailed benchmarking, and TIL about the SNAP benchmark! The original motivation for this design was to optimize regular hash joins with duplicate build-side keys. I hadn't specifically considered graph workloads, and I'm not sure how common they are among DataFusion users, but it's nice to see the design works for that. |
|
🤖 Benchmark completed (GKE) | trigger Instance: Comparing redesign-join-ht (5eb078b) to 6a06058 (merge-base) diff Run configurationrun benchmark imdbCPU Details (lscpu)Details
Resource Usageimdb — base (merge-base)
imdb — branch
File an issue against this benchmark runner |
Important
Fork CI setup: For pull requests from a fork to
main, enable workflows in your fork's Actions tab before you push.See the fork CI setup guide.
Which issue does this PR close?
Rationale for this change
Background and dependencies
HashJoinExecby splitting regular/existence join into dedicated streams #26361 (which can reuse the same index design).This PR
Despite the large diff, you only need to understand two things to understand this PR:
Both are explained in #27398.
Benchmark Result
Comparing
hjbenchmark with main:Full benchmark results
What changes are included in this PR?
Suggested reading order:
hash_join/mod.rs— comments explain the three-layer hash join architecture.join_index.rs—JoinIndexMap: this PR introduces a new layer for the physical hash table implementation (all changes are insideBatchedJoinProcessor, without changing the state machine).join_index/directory.rs—JoinHashIndex: join hash table implementation.batched_join_processor.rs—BatchedJoinProcessor: interaction between the raw hash index and the join processor.directory/dense.rs—DenseIntegerDirectory: specialization 1.directory/integer.rs—IntegerDirectory: specialization 2.What is the testing strategy for this PR?
join_exact_index.slt(TODO for myself: check for overlap with existing tests.)Are there any user-facing changes?
No SQL behavior changes.