mbutrovich commented on code in PR #27746:
URL: https://github.com/apache/datafusion/pull/27746#discussion_r4698334188


##########
datafusion/physical-plan/src/joins/join_index/directory/general.rs:
##########
@@ -0,0 +1,336 @@
+// 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
+
+//! General-key directory with batched comparison of candidate representatives.
+//!
+//! A hash match is only a candidate. Compare representatives column by column,
+//! once per key rather than per duplicate. If `A` and `B` share a hash, 
rejecting
+//! representative `A` must retry the directory: another entry may hold `B`.
+//! Both paths resolve candidates into handles. Unique builds convert these to
+//! row pairs at return; duplicate keys retain handles for later expansion.
+
+use std::mem::size_of;
+use std::sync::Arc;
+
+use arrow::array::ArrayRef;
+use arrow::buffer::NullBuffer;
+use arrow::compute::SortOptions;
+use datafusion_common::float_semantics::{has_float_leaf, normalize};
+use datafusion_common::utils::memory::estimate_memory_size;
+use datafusion_common::{NullEquality, Result};
+use datafusion_execution::memory_pool::MemoryReservation;
+use hashbrown::{HashTable, hash_table::Entry};
+
+use super::super::keys::{LookupScratch, compare_column, hash_probe_keys};
+use super::super::matches::{
+    HandleBuilder, JoinHashLookup, MatchHandle, MatchedGroupsBuilder, RowId,
+};
+use super::super::reserve;
+use super::Probe;
+use crate::joins::utils::{JoinKeyComparator, matchable_join_keys};
+
+/// One directory entry per equal join key(s).
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+///
+/// # Example
+///
+/// Build keys `[A, B, A]`, with zero-based row IDs, produce:
+///
+/// ```text
+/// key | hash | representative_row | group_plus_one | matches()
+/// ----+------+--------------------+----------------+------------------------
+/// A   | h(A) | 0                  | 1              | Group(0) -> rows [0, 2]
+/// B   | h(B) | 1                  | 0              | One(1)   -> row 1
+/// ```
+///
+/// `h(key)` is the key's hash. `representative_row` indexes the concatenated
+/// build batch, letting lookup read the actual key to verify equality.
+/// Duplicate members are stored separately; `group_plus_one = 1` refers to
+/// group 0, while zero means the representative is the only matching row.
+#[derive(Clone, Copy, Debug)]
+struct KeyEntry<T> {
+    hash: u64,
+    representative_row: T,
+    // Zero means One(representative_row); otherwise this is Group(id - 1).
+    group_plus_one: T,
+}
+
+impl<T: RowId> KeyEntry<T> {
+    fn matches(&self) -> MatchHandle<T> {
+        match self.group_plus_one.as_index() {
+            0 => MatchHandle::One(self.representative_row),
+            group => MatchHandle::Group(T::from_index(group - 1)),
+        }
+    }
+}
+
+/// Hash candidates identify representative build rows whose keys establish 
equality.
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+#[derive(Debug)]
+pub(super) struct GeneralDirectory<T> {
+    table: HashTable<KeyEntry<T>>,
+    /// Every matchable build key has at most one row, including NULL.
+    build_unique: bool,
+}
+
+impl<T: RowId> GeneralDirectory<T> {
+    /// Only exact matches share a group, even when different keys have the 
same hash.
+    pub(super) fn build(
+        keys: &[ArrayRef],
+        hashes: &[u64],
+        valid: Option<&NullBuffer>,
+        reservation: &MemoryReservation,
+        groups: &mut MatchedGroupsBuilder<T>,
+    ) -> Result<Self> {
+        reservation.try_grow(estimate_memory_size::<KeyEntry<T>>(
+            hashes.len(),
+            size_of::<HashTable<KeyEntry<T>>>(),
+        )?)?;
+        let mut table: HashTable<KeyEntry<T>> = 
HashTable::with_capacity(hashes.len());
+        // NULL != NULL rows are excluded before comparison. Using NULL
+        // equality here avoids rebuilding dictionary logical-null masks;
+        // it does not change equality of nested children.
+        let comparator = JoinKeyComparator::new_with_normalized_left(
+            keys,
+            keys,
+            &vec![SortOptions::default(); keys.len()],
+            NullEquality::NullEqualsNull,
+        )?;
+        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(),
+                    });
+                }
+            }
+        }

Review 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](https://github.com/apache/datafusion/blob/73043acbe3fbe681a0219c2060eb4eb6e9d47228/datafusion/physical-plan/src/joins/join_hash_map.rs#L346-L350)),
 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](https://github.com/duckdb/duckdb/blob/e44770f1ed6103c656a28c333a70d2b1491e0fbb/src/execution/join_hashtable.cpp#L1110-L1118)).



##########
datafusion/physical-plan/src/joins/join_index/matches.rs:
##########
@@ -0,0 +1,488 @@
+// 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
+
+//! Groups of build rows with equal keys, plus lookup results and their memory
+//! reservations.
+//!
+//! Build keys `[A, B, A]` give `A -> Group(0)` and `B -> One(1)`. Only rows 
with
+//! duplicate keys occupy [`MatchedGroups`]: `offsets = [0, 2]`, `rows = [0, 
2]`.
+//! Payload columns stay untouched. Batch handles keep IDs separate from 
nullable
+//! flags: true means group, false means singleton, and NULL means lookup miss.
+//!
+//! If the entire build is unique, results are already compact row pairs and
+//! need neither flags nor group expansion. Both forms own their memory charge.
+
+use std::fmt::Debug;
+use std::mem::size_of;
+
+use arrow::array::{Array, BooleanArray, BooleanBufferBuilder};
+use arrow::buffer::{BooleanBuffer, NullBuffer, ScalarBuffer};
+use arrow::datatypes::ArrowNativeType;
+use datafusion_common::{Result, exec_datafusion_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+
+/// See [`JoinHashIndex`](super::directory::JoinHashIndex) for the design 
overview.
+pub(crate) trait RowId: ArrowNativeType + Copy + Debug + Default {
+    fn from_index(value: usize) -> Self;
+    fn as_index(self) -> usize;
+    fn as_u64(self) -> u64;
+}
+
+macro_rules! row_id {
+    ($type:ty) => {
+        impl RowId for $type {
+            #[inline]
+            fn from_index(value: usize) -> Self {
+                Self::try_from(value).expect("row ID fits the selected index 
width")
+            }
+            #[inline]
+            fn as_index(self) -> usize {
+                self as usize
+            }
+            #[inline]
+            fn as_u64(self) -> u64 {
+                self as u64
+            }
+        }
+    };
+}
+row_id!(u32);
+row_id!(u64);
+
+/// A row ID or a group ID, both using the index's row-ID width.
+///
+/// See [`JoinHashIndex`](super::directory::JoinHashIndex) for the design 
overview.
+#[derive(Clone, Copy, Debug)]
+pub(crate) enum MatchHandle<T> {
+    One(T),
+    Group(T),
+}
+
+/// Build-row IDs grouped by exact join key. Only keys with multiple build rows
+/// have groups; singleton rows are represented directly by directory handles.
+///
+/// See [`JoinHashIndex`](super::directory::JoinHashIndex) for the design 
overview.
+#[derive(Debug)]
+pub(super) struct MatchedGroups<T> {
+    pub(super) offsets: Vec<usize>,
+    pub(super) rows: Vec<T>,
+}
+
+impl<T> MatchedGroups<T> {
+    #[inline]
+    pub(super) fn group_rows(&self, group: usize) -> &[T] {
+        &self.rows[self.offsets[group]..self.offsets[group + 1]]
+    }
+}
+
+/// Builds [`MatchedGroups`].
+///
+/// See [`JoinHashIndex`](super::directory::JoinHashIndex) for the design 
overview.
+///
+/// # Building process
+///
+/// Each group needs a contiguous slice, but its size is unknown until all 
build
+/// rows have been seen. The builder therefore uses two passes:
+///
+/// 1. While scanning build rows, [`Self::add_duplicate`] counts each group's
+///    rows and buffers their IDs. A group is created only when its key 
repeats.
+/// 2. [`Self::finish`] uses the counts to lay out one slice per group and 
writes
+///    each group's first row. It then walks the buffered IDs to fill the rest
+///    of each slice in input order.
+///
+/// This algorithm is amenable to vectorization.
+///
+/// ## Example
+///
+/// For build keys `[A, B, A, B, A, C]`:
+///
+/// Pass 1: Assign groups 0 and 1 to `A` and `B`, count their rows, and
+/// buffer later `(group, row)` pairs:
+///
+/// ```text
+/// first_rows: [0, 1]
+/// counts: [3, 2]
+/// pending: [(0, 2), (1, 3), (0, 4)]
+/// ```
+///
+/// `C` stays `One(5)` in the directory.
+///
+/// Pass 2: [`Self::finish`] computes offsets and packs each group's rows:
+///
+/// ```text
+/// offsets: [0, 3, 5]
+/// rows: [0, 2, 4, 1, 3]
+/// ```
+pub(super) struct MatchedGroupsBuilder<T> {
+    /// First build-row ID per group, indexed by group ID.
+    first_rows: Vec<T>,
+    /// Total rows per group; reused as write cursors in `finish`.
+    counts: Vec<usize>,
+    /// Subsequent `(group_id, build_row_id)` pairs in input order.
+    pending: Vec<(T, T)>,
+    /// Memory charge for the temporary buffers.
+    _reservation: MemoryReservation,
+}
+
+impl<T: RowId> MatchedGroupsBuilder<T> {
+    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,
+        })
+    }

Review 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.



##########
datafusion/physical-plan/src/joins/join_index/directory/dense.rs:
##########
@@ -0,0 +1,302 @@
+// 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
+
+//! Dense integer directory addressed directly by key offsets.
+
+use std::mem::size_of;
+
+use arrow::array::*;
+use arrow::buffer::{BooleanBuffer, NullBuffer};
+use arrow::datatypes::{ArrowPrimitiveType, DataType};
+use datafusion_common::{Result, exec_datafusion_err, internal_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+use num_traits::AsPrimitive;
+
+use super::super::keys::LookupScratch;
+use super::super::matches::{
+    JoinHashLookup, MatchHandle, MatchHandleArray, MatchedGroupsBuilder, RowId,
+    UniqueMatches, bitmap_bytes,
+};
+use super::Probe;
+use crate::joins::array_map::ArrayMap;
+
+/// Direct lookup for a single integer join key in a compact range.
+///
+/// # Overview
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+///
+/// # Dense integer specialization
+///
+/// Use `key - min` as an array index. [`Self::build`] fills the slots;
+/// [`Self::lookup_batch`] probes them directly, without hashing.
+///
+/// ```text
+/// Build keys: [10, 12, 10]     range: 10..=12
+///
+/// Key   Slot (key - min)   Match
+/// 10    0                  Group(0) -> build rows [0, 2]
+/// 11    1                  miss
+/// 12    2                  One(1)   -> build row 1
+/// ```
+///
+/// Groups still use [`MatchedGroups`](super::super::matches::MatchedGroups)
+/// for lazy expansion. Gaps consume slots too, so compact ranges work best.
+#[derive(Debug)]
+pub(super) struct DenseIntegerDirectory<T> {
+    /// Minimum key, represented by slot 0.
+    offset: u64,
+    /// Zero means absent; otherwise stores a row/group ID plus one.
+    slots: Vec<T>,
+    /// For occupied slots: `true` = group ID, `false` = row ID.
+    /// `None` means no bitmap: all occupied slots hold row IDs.
+    /// Bits cannot be NULL; `slots[i] == 0` marks a miss.
+    is_group: Option<BooleanBuffer>,
+    /// Separate handle for build-side NULLs when NULL equals NULL.
+    /// `None` if no build key is NULL or NULLs cannot match.
+    null: Option<MatchHandle<T>>,
+    /// Distinct matchable build keys, counting NULL once if stored.
+    distinct: usize,
+    /// Every matchable build key has at most one row, including NULL.
+    build_unique: bool,
+}
+
+impl<T: RowId> DenseIntegerDirectory<T> {
+    /// Map dense integer keys directly to slots at `key - min`, promoting
+    /// repeated keys to group handles.
+    ///
+    /// # Arguments
+    ///
+    /// See [`JoinIndexMap::try_new`](super::super::JoinIndexMap::try_new) for
+    /// shared argument documentation.
+    ///
+    /// - `key_array`: the build-side integer join-key column, including NULLs.
+    ///   Read values directly, casting non-NULL keys to `u64` for slot 
addressing.
+    pub(super) fn build(
+        key_array: &ArrayRef,
+        valid: Option<&NullBuffer>,
+        range: (u64, u64),
+        reservation: &MemoryReservation,
+        groups: &mut MatchedGroupsBuilder<T>,
+    ) -> Result<Self> {
+        // 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)
+            }
+            _ => internal_err!("Dense join index requires an integer key"),
+        )
+    }
+
+    /// 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>
+    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
+        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)?;
+
+        // 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;
+
+        // 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;
+            }
+            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);
+        }

Review 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?
   
   <details>
   <summary>Counting sort for the dense directory, against 2f6c665</summary>
   
   ```diff
   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(
   ```
   
   </details>



##########
datafusion/physical-plan/src/joins/join_index.rs:
##########
@@ -0,0 +1,182 @@
+// 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
+
+//! Immutable join index, independent of payload storage.
+//!
+//! Lookup resolves exact keys; the join operator handles output batching and
+//! residual predicates. For build keys `[A, B, A]`, the directory maps `A` to
+//! group `[0, 2]` and `B` to row `1`. An all-unique build returns verified row
+//! pairs, avoiding handle-to-pair conversion during output.
+//!
+//! `directory` owns layouts and construction, `keys` owns hashing and exact
+//! comparison, and `matches` owns grouped row IDs and lookup-result memory.
+
+mod directory;
+mod keys;
+mod matches;
+
+use std::mem::size_of;
+use std::ops::Deref;
+
+use arrow::array::{ArrayRef, BooleanArray};
+use datafusion_common::hash_utils::RandomState;
+use datafusion_common::{NullEquality, Result};
+use datafusion_execution::memory_pool::MemoryReservation;
+
+use directory::IndexWidth;
+pub(crate) use keys::LookupScratch;
+pub(crate) use matches::{
+    GroupRows, LookupResult, MatchHandle, MatchHandleArray, MatchHandles, 
RowId,
+    UniqueMatches,
+};
+
+/// 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,

Review 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](https://github.com/apache/datafusion/blob/b89e906b26ef41cf6f9cc158693a257ea714b05f/datafusion/physical-plan/src/joins/join_hash_map.rs#L1138-L1166)).



##########
datafusion/physical-plan/src/joins/join_index/directory/dense.rs:
##########
@@ -0,0 +1,302 @@
+// 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
+
+//! Dense integer directory addressed directly by key offsets.
+
+use std::mem::size_of;
+
+use arrow::array::*;
+use arrow::buffer::{BooleanBuffer, NullBuffer};
+use arrow::datatypes::{ArrowPrimitiveType, DataType};
+use datafusion_common::{Result, exec_datafusion_err, internal_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+use num_traits::AsPrimitive;
+
+use super::super::keys::LookupScratch;
+use super::super::matches::{
+    JoinHashLookup, MatchHandle, MatchHandleArray, MatchedGroupsBuilder, RowId,
+    UniqueMatches, bitmap_bytes,
+};
+use super::Probe;
+use crate::joins::array_map::ArrayMap;
+
+/// Direct lookup for a single integer join key in a compact range.
+///
+/// # Overview
+///
+/// See [`JoinHashIndex`](super::JoinHashIndex) for the design overview.
+///
+/// # Dense integer specialization
+///
+/// Use `key - min` as an array index. [`Self::build`] fills the slots;
+/// [`Self::lookup_batch`] probes them directly, without hashing.
+///
+/// ```text
+/// Build keys: [10, 12, 10]     range: 10..=12
+///
+/// Key   Slot (key - min)   Match
+/// 10    0                  Group(0) -> build rows [0, 2]
+/// 11    1                  miss
+/// 12    2                  One(1)   -> build row 1
+/// ```
+///
+/// Groups still use [`MatchedGroups`](super::super::matches::MatchedGroups)
+/// for lazy expansion. Gaps consume slots too, so compact ranges work best.
+#[derive(Debug)]
+pub(super) struct DenseIntegerDirectory<T> {
+    /// Minimum key, represented by slot 0.
+    offset: u64,
+    /// Zero means absent; otherwise stores a row/group ID plus one.
+    slots: Vec<T>,
+    /// For occupied slots: `true` = group ID, `false` = row ID.
+    /// `None` means no bitmap: all occupied slots hold row IDs.
+    /// Bits cannot be NULL; `slots[i] == 0` marks a miss.
+    is_group: Option<BooleanBuffer>,
+    /// Separate handle for build-side NULLs when NULL equals NULL.
+    /// `None` if no build key is NULL or NULLs cannot match.
+    null: Option<MatchHandle<T>>,
+    /// Distinct matchable build keys, counting NULL once if stored.
+    distinct: usize,
+    /// Every matchable build key has at most one row, including NULL.
+    build_unique: bool,
+}
+
+impl<T: RowId> DenseIntegerDirectory<T> {
+    /// Map dense integer keys directly to slots at `key - min`, promoting
+    /// repeated keys to group handles.
+    ///
+    /// # Arguments
+    ///
+    /// See [`JoinIndexMap::try_new`](super::super::JoinIndexMap::try_new) for
+    /// shared argument documentation.
+    ///
+    /// - `key_array`: the build-side integer join-key column, including NULLs.
+    ///   Read values directly, casting non-NULL keys to `u64` for slot 
addressing.
+    pub(super) fn build(
+        key_array: &ArrayRef,
+        valid: Option<&NullBuffer>,
+        range: (u64, u64),
+        reservation: &MemoryReservation,
+        groups: &mut MatchedGroupsBuilder<T>,
+    ) -> Result<Self> {
+        // 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)
+            }
+            _ => internal_err!("Dense join index requires an integer key"),
+        )
+    }
+
+    /// 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>
+    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
+        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)?;
+
+        // 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;
+
+        // 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;
+            }
+            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;
+            }

Review Comment:
   `array_map_key_range` doesn't pick the dense directory when NULLs equal 
NULLs and the key has NULLs 
([exec.rs](https://github.com/apache/datafusion/blob/2f6c665fef63936f08a4aa7a4fb01b87a4d2b009/datafusion/physical-plan/src/joins/hash_join/exec.rs#L186-L188)).
 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?



##########
datafusion/physical-plan/src/joins/join_index/directory.rs:
##########
@@ -0,0 +1,368 @@
+// 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 the same singleton/group representation; only row IDs are grouped.
+
+use std::mem::size_of;
+
+use arrow::array::{ArrayRef, BooleanArray};
+use arrow::buffer::BooleanBuffer;
+use datafusion_common::hash_utils::{RandomState, create_hashes};
+use datafusion_common::{NullEquality, Result, internal_err};
+use datafusion_execution::memory_pool::MemoryReservation;
+
+use super::keys::{LookupScratch, hash_scratch_bytes};
+use super::matches::{
+    GroupRows, JoinHashLookup, LookupResult, MatchHandles, 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.
+    pub(super) fn build(
+        keys: &[ArrayRef],
+        random_state: &RandomState,
+        null_equality: NullEquality,
+        dense_range: Option<(u64, u64)>,
+        reservation: &MemoryReservation,
+    ) -> 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();
+        // 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()
+        };

Review 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](https://github.com/apache/datafusion/blob/73043acbe3fbe681a0219c2060eb4eb6e9d47228/datafusion/physical-plan/src/joins/hash_join/exec.rs#L3404-L3448)),
 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`?



-- 
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]

Reply via email to