2010YOUY01 commented on code in PR #27746:
URL: https://github.com/apache/datafusion/pull/27746#discussion_r4737772505
##########
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:
good point, addressed in
[a5ab595](https://github.com/apache/datafusion/pull/27746/commits/a5ab595f1c67a1940153afa5088e65ed8dd45615)
--
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]