andygrove commented on code in PR #27530:
URL: https://github.com/apache/datafusion/pull/27530#discussion_r4658826270
##########
datafusion/physical-plan/src/joins/join_hash_map.rs:
##########
@@ -324,24 +401,257 @@ 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 } = rows else {
+ return false;
+ };
+ if *chained_rows == 0 {
+ 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 the hash values have fewer than two rows each on average, or if a
+/// position in the groups would not fit in `T`. Rows left out of the map, such
+/// as NULL keys, count towards neither.
+fn grouped_rows_len<T: ArrowNativeType>(
+ map_len: usize,
+ chained_rows: usize,
+) -> Option<usize> {
+ if chained_rows < map_len {
Review Comment:
Thanks for the numbers and the prototype. I took the comparison as you wrote
it: `update_from_iter` now also counts the chained rows whose previous row
isn't the next row number, and `group_rows` compares that count with `map.len()
* (MIN_GROUPED_ROWS_PER_KEY - 1)`. `chained_rows` still decides the unique-key
fast path.
I set the threshold to 16 rows per key for both modes. That's where shuffled
`CollectLeft` breaks even in your table, so nothing in it regresses. It gives
up the `Partitioned` wins at 4 to 8 rows per key. I'd rather not tune a
per-mode constant, or add a config option, from one machine's numbers.
Your queries on an M3 Ultra (16M build rows, median of 5 warm runs, two
rounds, PR / main):
| Build rows per key | CollectLeft | Partitioned |
|---|---|---|
| shuffled, 2 | 1.02–1.07x | 1.03–1.10x |
| shuffled, 16 | 0.72x | 0.65–0.66x |
| shuffled, 100 | 0.49–0.52x | 0.50–0.53x |
| stored together, 2 | 1.01–1.03x | 1.00–1.01x |
| stored together, 100 | 0.96–1.00x | 1.04–1.05x |
The 100-rows-per-key cases probe 1.6M rows instead of 16M, to keep the
output size reasonable. None of the cases at 2 rows per key, or stored
together, group now. What's left there is the extra comparison while inserting,
and run-to-run noise at about 0.1 s per query in `Partitioned`.
`test_which_build_rows_are_grouped` now covers 15 vs 16 rows per key, and 40
rows per key stored together, which stays chained.
##########
datafusion/physical-plan/src/joins/hash_join/exec.rs:
##########
@@ -3500,6 +3508,24 @@ fn build_in_memory(
})
.transpose()?;
+ // Grouping the rows of repeated keys is optional: it keeps the chain if
+ // the memory for the groups is not available. Doing it after every
+ // reservation the build needs keeps it from making one of them fail.
+ let ungrouped_size = map_reservation.size();
+ let grouped = match &mut join_hash_map {
+ Map::HashMap(hashmap) => hashmap.group_rows(&map_reservation),
+ Map::ArrayMap(_) => false,
+ };
+ if grouped {
+ grouped_map_count.add(1);
+ let grouped_size = map_reservation.size();
+ if grouped_size >= ungrouped_size {
+ metrics.build_mem_used.add(grouped_size - ungrouped_size);
+ } else {
+ metrics.build_mem_used.sub(ungrouped_size - grouped_size);
+ }
+ }
Review Comment:
Applied, thanks.
--
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]