mbutrovich commented on code in PR #27530:
URL: https://github.com/apache/datafusion/pull/27530#discussion_r4681988325
##########
datafusion/physical-plan/src/joins/join_hash_map.rs:
##########
@@ -358,14 +718,19 @@ where
*index = T::try_from(row + 1).unwrap();
// Update chained Vec at `row` with previous value
next[row - deleted_offset] = prev_index;
- chained = true;
+ chained_rows += 1;
+ // Rows are inserted last to first, so the rows of a hash value
+ // stored next to each other chain each row to the one after
it.
+ if prev_index != T::try_from(row + 2).unwrap() {
Review Comment:
This `unwrap()` can panic where `main` doesn't. `JoinHashMapU32` is used for
up to `u32::MAX` rows, so for the last row `row + 1` fits in `u32` and `row +
2` doesn't. Today every `HashJoinExec` build inserts last to first, so that row
is always the first one inserted and never reaches this branch.
`update_from_iter` doesn't require that order, though, and a call with
ascending rows `u32::MAX - 2` and `u32::MAX - 1` with the same hash panics here
with `TryFromIntError(PosOverflow)`. A row number that doesn't fit in `T` can't
equal `prev_index`, so the comparison doesn't need the `unwrap()`:
```suggestion
if !T::try_from(row + 2).is_ok_and(|after| prev_index ==
after) {
```
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -3986,6 +4008,87 @@ mod tests {
Ok(())
}
+ /// Joins 10 build batches of 1,000 rows, whose keys are `key(row)`, with
+ /// three probe rows, in `pool`, and returns how many maps had their rows
+ /// grouped. Asserts that `build_mem_used` is what the build holds in
+ /// `pool` once it is done.
+ async fn grouped_build(
+ key: impl Fn(i64) -> i64,
+ pool: Arc<dyn MemoryPool>,
+ ) -> Result<usize> {
+ let schema = Arc::new(Schema::new(vec![Field::new("k",
DataType::Int64, false)]));
+ let batch = |keys: Vec<i64>| {
+ let column = Arc::new(Int64Array::from(keys)) as ArrayRef;
+ RecordBatch::try_new(Arc::clone(&schema), vec![column])
+ };
+ let build_batches = (0..10)
+ .map(|b| batch((b * 1_000..(b + 1) * 1_000).map(&key).collect()))
+ .collect::<Result<Vec<_>, _>>()?;
+ let build =
+ TestMemoryExec::try_new_exec(&[build_batches],
Arc::clone(&schema), None)?;
+ let probe = batch(vec![key(0), key(1), key(999)])?;
+ let probe =
+ TestMemoryExec::try_new_exec(&[vec![probe]], Arc::clone(&schema),
None)?;
+ let on = vec![(
+ Arc::new(Column::new_with_schema("k", &schema)?) as _,
+ Arc::new(Column::new_with_schema("k", &schema)?) as _,
+ )];
+ let join = join(
+ build,
+ probe,
+ on,
+ &JoinType::Inner,
+ NullEquality::NullEqualsNothing,
+ )?;
+
+ let runtime = RuntimeEnvBuilder::new()
+ .with_memory_pool(Arc::clone(&pool))
+ .build_arc()?;
+ let task_ctx = Arc::new(TaskContext::default().with_runtime(runtime));
+ let mut stream = join.execute(0, task_ctx)?;
+ while stream.next().await.transpose()?.is_some() {}
+ let metrics = join.metrics().unwrap();
+ let build_mem_used = metrics.sum_by_name("build_mem_used").unwrap();
+ assert_eq!(build_mem_used.as_usize(), pool.reserved());
+ drop(stream);
+ Ok(metrics
+ .sum_by_name(GROUPED_MAP_COUNT_METRIC_NAME)
+ .unwrap()
+ .as_usize())
+ }
+
+ /// Grouping the rows of repeated keys comes after every reservation the
+ /// build needs, and is skipped without the memory for it, so a build that
+ /// fits without its groups never fails for them, and groups them once the
+ /// memory for the groups is available.
+ #[tokio::test]
+ async fn grouping_never_fails_the_build() -> Result<()> {
+ // The memory a build of 10,000 rows needs without grouping: that of a
+ // build with unique keys, whose map and chain take the same room
+ let pool = Arc::new(PeakRecordingPool::new(Arc::new(
+ UnboundedMemoryPool::default(),
+ )));
+ grouped_build(|row| row * 1_000_003, Arc::clone(&pool) as _).await?;
+ let limit = pool.peak_reserved();
+
+ // With 20 rows for each of 500 sparse keys, for a hash map
+ let key = |row| (row % 500) * 1_000_003;
+
+ // The build still fits, whether or not there is room to group
+ let pool = Arc::new(GreedyMemoryPool::new(limit));
+ grouped_build(key, pool).await?;
Review Comment:
This is the case the test is named for, but it passes whether or not the
build groups. Today the pool is exactly the size of the ungrouped build
(398,600 bytes against a grouped peak of 440,600), so grouping is skipped. A
later change to the threshold or to the memory estimate could let it group
here, and the test would keep passing without covering the skip. Could it
assert that?
```suggestion
// Without room for the groups, the build keeps its chain and still
fits
let pool = Arc::new(GreedyMemoryPool::new(limit));
assert_eq!(grouped_build(key, pool).await?, 0);
```
##########
datafusion/physical-plan/src/joins/join_hash_map.rs:
##########
@@ -679,6 +1048,240 @@ mod tests {
assert_eq!(match_indices, vec![1, 0]);
}
+ /// Collects every match of `hash_values`, `limit` at a time.
+ fn all_matches(
+ hash_map: &dyn JoinHashMapType,
+ hash_values: &[u64],
+ valid_keys: Option<&NullBuffer>,
+ limit: usize,
+ ) -> Vec<(u32, u64)> {
+ let mut matches = vec![];
+ let mut input_indices = vec![];
+ let mut match_indices = vec![];
+ let mut offset = AtRow { row: 0 };
+ loop {
+ let next_offset = hash_map.get_matched_indices_with_limit_offset(
+ hash_values,
+ valid_keys,
+ limit,
+ offset,
+ &mut input_indices,
+ &mut match_indices,
+ );
+ assert!(input_indices.len() <= limit);
+ assert_eq!(input_indices.len(), match_indices.len());
+ matches.extend(
+ input_indices
+ .iter()
+ .copied()
+ .zip(match_indices.iter().copied()),
+ );
+ match next_offset {
+ Some(next) => offset = next,
+ None => return matches,
+ }
+ }
+ }
+
+ /// Builds a map from `build_hashes`, inserted batch by batch and last to
+ /// first as `update_hash` does, leaving out the rows without a hash as it
+ /// leaves out NULL keys.
+ fn build_map<M: JoinHashMapType>(
+ new_map: impl Fn(usize) -> M,
+ build_hashes: &[Option<u64>],
+ ) -> M {
+ let mut hash_map = new_map(build_hashes.len());
+ for (batch_idx, hashes) in build_hashes.chunks(64).enumerate().rev() {
+ let offset = batch_idx * 64;
+ hash_map.update_from_iter(
+ Box::new(
+ hashes
+ .iter()
+ .enumerate()
+ .filter_map(move |(i, hash)| {
+ hash.as_ref().map(|h| (offset + i, h))
+ })
+ .rev(),
+ ),
+ 0,
+ );
+ }
+ hash_map
+ }
+
+ /// A reservation of `size` bytes from an unbounded pool
+ fn reserved(size: usize) -> MemoryReservation {
+ let pool: Arc<dyn MemoryPool> =
Arc::new(UnboundedMemoryPool::default());
+ let reservation = MemoryConsumer::new("test").register(&pool);
+ reservation.grow(size);
+ reservation
+ }
+
+ /// Builds two maps from the same rows, with row 7 left out as a NULL key
+ /// would be, and groups the rows of the second.
+ fn chained_and_grouped<M: JoinHashMapType>(
+ new_map: impl Fn(usize) -> M,
+ build_hashes: &[u64],
+ ) -> (M, M) {
+ let build_hashes: Vec<Option<u64>> = build_hashes
+ .iter()
+ .enumerate()
+ .map(|(row, &hash)| (row != 7).then_some(hash))
+ .collect();
+ let chained = build_map(&new_map, &build_hashes);
+ let mut grouped = build_map(&new_map, &build_hashes);
+ let reservation = reserved(build_hashes.len() * size_of::<u64>());
+ assert!(grouped.group_rows(&reservation));
+ (chained, grouped)
+ }
+
+ #[test]
+ fn test_grouped_rows_match_the_chain() {
+ // 13 hash values over 300 build rows, and probe rows that repeat,
+ // miss (13 to 16) or have a NULL key.
+ let build_hashes: Vec<u64> = (0..300u64).map(|i| (i * 7919) %
13).collect();
+ let probe_hashes: Vec<u64> = (0..50u64).map(|i| (i * 31) %
17).collect();
+ let valid_keys =
+ NullBuffer::from((0..50).map(|i| i % 9 != 4).collect::<Vec<_>>());
+
+ let (chained, grouped) =
+ chained_and_grouped(JoinHashMapU32::with_capacity, &build_hashes);
+ let (_, grouped_u64) =
+ chained_and_grouped(JoinHashMapU64::with_capacity, &build_hashes);
+ for limit in [1, 2, 3, 5, 23, 64, 8192] {
+ for valid in [None, Some(&valid_keys)] {
+ let expected = all_matches(&chained, &probe_hashes, valid,
limit);
+ assert!(!expected.is_empty());
+ assert_eq!(all_matches(&grouped, &probe_hashes, valid, limit),
expected);
+ assert_eq!(
+ all_matches(&grouped_u64, &probe_hashes, valid, limit),
+ expected
+ );
+ }
+ }
+ assert_eq!(
+ grouped.contain_hashes(&probe_hashes),
+ chained.contain_hashes(&probe_hashes)
+ );
+ }
+
+ #[test]
+ fn test_grouped_rows_match_the_chain_for_long_chains() {
+ // Hash values 0 and 1 have chains too long for grouping to hold their
+ // rows until their end, among 1,000 short chains.
+ let build_hashes: Vec<u64> = (0..30_000u64)
+ .map(|i| if i % 3 == 0 { i % 2 } else { 2 + i % 1_000 })
+ .collect();
+ let probe_hashes: Vec<u64> = vec![0, 5, 1, 7, 1_001, 3_000, 0];
+
+ let (chained, grouped) =
+ chained_and_grouped(JoinHashMapU32::with_capacity, &build_hashes);
+ for limit in [1, 7, 4_096, 5_000, 8_192, 100_000] {
+ let expected = all_matches(&chained, &probe_hashes, None, limit);
+ assert_eq!(expected.len(), 2 * 5_000 + 5_000 + 3 * 20);
Review Comment:
This puts the two long chains on both sides of `MAX_HELD`. The other short
chains get 21 or 22 rows, because the build rows left over from hash values 0
and 1 go to them.
```suggestion
// Hash values 0 and 1 have chains of 4,096 rows, the longest that
// grouping holds until its end, and 4,097 rows, which it places in a
// second pass, among 1,000 short chains.
let build_hashes: Vec<u64> = (0..30_000u64)
.map(|i| match i / 3 {
k if i % 3 == 0 && k < 4_096 => 0,
k if i % 3 == 0 && k < 4_096 + 4_097 => 1,
_ => 2 + i % 1_000,
})
.collect();
let probe_hashes: Vec<u64> = vec![0, 5, 1, 7, 1_001, 3_000, 0];
let (chained, grouped) =
chained_and_grouped(JoinHashMapU32::with_capacity,
&build_hashes);
for limit in [1, 7, 4_096, 4_097, 8_192, 100_000] {
let expected = all_matches(&chained, &probe_hashes, None, limit);
assert_eq!(expected.len(), 2 * 4_096 + 4_097 + 21 + 22 + 22);
```
##########
datafusion/physical-plan/src/joins/join_hash_map.rs:
##########
@@ -324,24 +444,264 @@ impl JoinHashMapType for JoinHashMapU64 {
fn len(&self) -> usize {
self.map.len()
}
+
+ fn group_rows(&mut self, reservation: &MemoryReservation) -> bool {
+ group_rows(&mut self.map, &mut self.rows, reservation)
+ }
}
-use crate::joins::chain::traverse_chain;
+use crate::joins::chain::{grouped_matched_indices, traverse_chain};
use crate::joins::join_hash_map::ProbeOffset::{AtRow, MidChain};
-/// Inserts the rows of `iter` into `map` and `next`. Returns `true` if any row
-/// was chained onto an existing hash value.
+/// See [`JoinHashMapType::get_matched_indices_with_limit_offset`].
+#[expect(clippy::too_many_arguments)]
+fn key_rows_matched_indices<T>(
+ map: &HashTable<(u64, T)>,
+ rows: &KeyRows<T>,
+ hash_values: &[u64],
+ valid_keys: Option<&NullBuffer>,
+ limit: usize,
+ offset: ProbeOffset,
+ input_indices: &mut Vec<u32>,
+ match_indices: &mut Vec<u64>,
+) -> Option<ProbeOffset>
+where
+ T: ArrowNativeType + TryFrom<usize> + PartialOrd + Into<u64> + Sub<Output
= T>,
+ <T as TryFrom<usize>>::Error: Debug,
+{
+ match rows {
+ KeyRows::Chain {
+ next, chained_rows, ..
+ } => get_matched_indices_with_limit_offset(
+ map,
+ next,
+ *chained_rows == 0,
+ hash_values,
+ valid_keys,
+ limit,
+ offset,
+ input_indices,
+ match_indices,
+ ),
+ KeyRows::Grouped { groups } => grouped_matched_indices(
+ groups,
+ hash_values.len(),
+ |row| {
+ // NULL keys cannot match any build row
+ if valid_keys.is_some_and(|valid| valid.is_null(row)) {
+ return None;
+ }
+ let hash = hash_values[row];
+ let (_, pos) = map.find(hash, |(h, _)| hash == *h)?;
+ Some(group_rows_range(groups, pos.as_usize()))
+ },
+ limit,
+ offset,
+ input_indices,
+ match_indices,
+ ),
+ }
+}
+
+/// See [`JoinHashMapType::group_rows`].
+fn group_rows<T>(
+ map: &mut HashTable<(u64, T)>,
+ rows: &mut KeyRows<T>,
+ reservation: &MemoryReservation,
+) -> bool
+where
+ T: ArrowNativeType + Sub<Output = T> + PartialEq,
+{
+ let KeyRows::Chain {
+ next,
+ chained_rows,
+ scattered_rows,
+ } = rows
+ else {
+ return false;
+ };
+ if *chained_rows == 0
+ || *scattered_rows < map.len().saturating_mul(MIN_GROUPED_ROWS_PER_KEY
- 1)
+ {
+ return false;
+ }
+ let Some(len) = grouped_rows_len::<T>(map.len(), *chained_rows) else {
+ return false;
+ };
+ let size = len * size_of::<T>();
+ if reservation.try_grow(size).is_err() {
+ return false;
+ }
+ let groups = group_chains(map, next, len);
+ let freed = next.capacity() * size_of::<T>();
+ *rows = KeyRows::Grouped { groups };
+ reservation.shrink(freed);
+ true
+}
+
+/// Returns the range in `groups` of the rows of the group at `pos`, which
+/// starts with their number.
+#[inline]
+fn group_rows_range<T: ArrowNativeType>(groups: &[T], pos: usize) -> (usize,
usize) {
+ (pos + 1, pos + 1 + groups[pos].as_usize())
+}
+
+/// Returns the length of the groups of the `map_len` hash values, with
+/// `chained_rows` rows inserted after the first of their hash value, or `None`
+/// if a position in the groups would not fit in `T`. Rows left out of the map,
+/// such as NULL keys, do not count.
+fn grouped_rows_len<T: ArrowNativeType>(
+ map_len: usize,
+ chained_rows: usize,
+) -> Option<usize> {
+ // Each group holds its number of rows and then its rows.
+ let len = map_len.checked_mul(2)?.checked_add(chained_rows)?;
+ T::from_usize(len).map(|_| len)
+}
+
+/// Lays out the rows of each hash value in `map` next to each other, in the
+/// order of their chain in `next`, in groups of length `len` in all, and
points
+/// each map entry at its group: at `pos` the group holds its number of rows,
+/// followed by the rows (0-based). Returns the groups.
+fn group_chains<T>(map: &mut HashTable<(u64, T)>, next: &[T], len: usize) ->
Vec<T>
+where
+ T: ArrowNativeType + Sub<Output = T> + PartialEq,
+{
+ /// Chains followed at once. Each step of a chain loads its next index
+ /// from the previous one, so following one chain at a time would wait for
+ /// a cache miss at every step; the steps of different chains overlap.
+ const LANES: usize = 16;
+ /// Rows of a chain held until its end, when they are appended to the
+ /// groups. A longer chain is only measured, then placed in a second pass,
+ /// so that what the lanes hold stays small.
+ const MAX_HELD: usize = 4096;
+
+ /// A chain being followed: its map entry, its first and next index
+ /// (1-based), its length so far, and its rows unless it is too long.
+ struct Lane<'a, T> {
+ value: &'a mut T,
+ head: T,
+ index: T,
+ len: usize,
+ rows: Vec<T>,
+ }
+
+ let zero = T::usize_as(0);
+ let one = T::usize_as(1);
+ let mut groups = Vec::with_capacity(len);
+ let mut entries = map.iter_mut().map(|(_, value)| value);
+ let mut lanes: Vec<Lane<'_, T>> = entries
+ .by_ref()
+ .take(LANES)
+ .map(|value| Lane {
+ head: *value,
+ index: *value,
+ value,
+ len: 0,
+ rows: vec![],
+ })
+ .collect();
+ // The chains longer than `MAX_HELD`: their map entry, first index and
length
+ let mut long_chains = vec![];
+
+ while !lanes.is_empty() {
+ let mut i = 0;
+ while i < lanes.len() {
+ let lane = &mut lanes[i];
+ let row = lane.index - one;
+ lane.len += 1;
+ if lane.len <= MAX_HELD {
Review Comment:
Could the long-chain test cover both sides of `MAX_HELD`? Its chains have 20
or 5,000 rows, so it never builds a chain of exactly 4,096 or 4,097 rows. If
this line becomes `lane.len < MAX_HELD`, a 4,096-row chain loses its last row
and every test in `join_hash_map.rs` and `grouping_never_fails_the_build` still
passes. I've put a suggestion on
`test_grouped_rows_match_the_chain_for_long_chains`.
--
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]