sunchao commented on code in PR #27884:
URL: https://github.com/apache/datafusion/pull/27884#discussion_r4750027602
##########
datafusion/physical-plan/src/joins/sort_merge_join/bitwise_stream.rs:
##########
@@ -1046,14 +1092,96 @@ impl BitwiseSortMergeJoinStream {
return Ok(false);
}
- for i in outer_from..outer_group_end {
- self.matched.set_bit(i, true);
+ if self.filter.is_some() {
+ let outer_len = outer_group_end - outer_from;
+ let inner_len = inner_group_end - inner_from;
+ // Both lengths are at least 1, so comparing the quotient avoids
+ // overflowing the product.
+ if inner_len > MAX_DEFERRED_PAIRS_PER_GROUP / outer_len {
+ return Ok(false);
+ }
+ // Batches hold far fewer than `u32::MAX` rows; the hash join
+ // indexes its probe batches with `u32` in the same way.
+ debug_assert!(u32::try_from(num_outer.max(num_inner)).is_ok());
+ for outer_row in outer_from..outer_group_end {
+ for inner_row in inner_from..inner_group_end {
+ self.deferred_outer_rows.push(outer_row as u32);
+ self.deferred_inner_rows.push(inner_row as u32);
Review Comment:
Could we fall back to the buffered path before enqueueing if either batch’s
indices don’t fit in `u32`? A `RunArray<Int64Type>` can represent more than
2^32 logical rows in just three runs. With inner keys `[0 × 2^32, 1, 3]` and
outer keys `[1, 2]`, the match for key 1 is at inner row `2^32`. This cast
reads the filter payload from row 0 instead. With debug assertions disabled,
the mark join returned `[false, false]` instead of `[true, false]`. A runtime
guard or `UInt64` indices would cover this.
##########
datafusion/physical-plan/src/joins/sort_merge_join/bitwise_stream.rs:
##########
@@ -1046,14 +1092,96 @@ impl BitwiseSortMergeJoinStream {
return Ok(false);
}
- for i in outer_from..outer_group_end {
- self.matched.set_bit(i, true);
+ if self.filter.is_some() {
+ let outer_len = outer_group_end - outer_from;
+ let inner_len = inner_group_end - inner_from;
+ // Both lengths are at least 1, so comparing the quotient avoids
+ // overflowing the product.
+ if inner_len > MAX_DEFERRED_PAIRS_PER_GROUP / outer_len {
+ return Ok(false);
+ }
+ // Batches hold far fewer than `u32::MAX` rows; the hash join
+ // indexes its probe batches with `u32` in the same way.
+ debug_assert!(u32::try_from(num_outer.max(num_inner)).is_ok());
+ for outer_row in outer_from..outer_group_end {
+ for inner_row in inner_from..inner_group_end {
+ self.deferred_outer_rows.push(outer_row as u32);
+ self.deferred_inner_rows.push(inner_row as u32);
+ }
+ }
+ if self.deferred_outer_rows.len() >= self.deferred_pair_limit {
Review Comment:
There’s also a type-specific row limit on the gathered output. With
`batch_size = 32768`, 512 groups of 8 × 8 pairs plus a trailing unmatched row
on each side, a valid 4,097-row inner `RunEndEncoded<Int16>` filter column gets
gathered into 32,768 rows. [Arrow unwraps the final run
end](https://github.com/apache/arrow-rs/blob/60.2.0/arrow-select/src/take.rs#L1513)
and panics because it cannot fit in `i16`. Could we exclude this encoding or
flush *before* adding a group that would exceed the run-end type’s limit?
##########
datafusion/physical-plan/src/joins/sort_merge_join/bitwise_stream.rs:
##########
@@ -1046,14 +1092,96 @@ impl BitwiseSortMergeJoinStream {
return Ok(false);
}
- for i in outer_from..outer_group_end {
- self.matched.set_bit(i, true);
+ if self.filter.is_some() {
+ let outer_len = outer_group_end - outer_from;
+ let inner_len = inner_group_end - inner_from;
+ // Both lengths are at least 1, so comparing the quotient avoids
+ // overflowing the product.
+ if inner_len > MAX_DEFERRED_PAIRS_PER_GROUP / outer_len {
+ return Ok(false);
+ }
+ // Batches hold far fewer than `u32::MAX` rows; the hash join
+ // indexes its probe batches with `u32` in the same way.
+ debug_assert!(u32::try_from(num_outer.max(num_inner)).is_ok());
+ for outer_row in outer_from..outer_group_end {
+ for inner_row in inner_from..inner_group_end {
+ self.deferred_outer_rows.push(outer_row as u32);
+ self.deferred_inner_rows.push(inner_row as u32);
+ }
+ }
+ if self.deferred_outer_rows.len() >= self.deferred_pair_limit {
+ self.evaluate_deferred_pairs()?;
+ }
+ } else {
+ for i in outer_from..outer_group_end {
+ self.matched.set_bit(i, true);
+ }
}
self.outer_offset = outer_group_end;
self.inner_offset = inner_group_end;
Ok(true)
}
+ /// Evaluate the join filter once over all queued `(outer, inner)` row
+ /// pairs and set the matched bit of every outer row with a passing pair.
+ ///
+ /// Must run before `outer_batch` or `inner_batch` is replaced, because
+ /// the queued pairs index those batches, and before the matched bitset
+ /// is emitted.
+ fn evaluate_deferred_pairs(&mut self) -> Result<()> {
+ if self.deferred_outer_rows.is_empty() {
+ return Ok(());
+ }
+ let (Some(filter), Some(outer_batch), Some(inner_batch)) =
+ (&self.filter, &self.outer_batch, &self.inner_batch)
+ else {
+ return internal_err!(
+ "Deferred filter pairs require a filter and both current
batches"
+ );
+ };
+
+ let num_pairs = self.deferred_outer_rows.len();
+ let outer_rows = UInt32Array::from(std::mem::take(&mut
self.deferred_outer_rows));
+ let inner_rows = UInt32Array::from(std::mem::take(&mut
self.deferred_inner_rows));
+
+ // Build the filter input columns in the order the filter expects.
+ let mut columns: Vec<ArrayRef> =
+ Vec::with_capacity(filter.column_indices().len());
+ for col_idx in filter.column_indices() {
+ let from_outer = match col_idx.side {
+ JoinSide::Left => self.outer_is_left,
+ JoinSide::Right => !self.outer_is_left,
+ JoinSide::None => {
+ return internal_err!("Unexpected JoinSide::None in
filter");
+ }
+ };
+ let (batch, rows) = if from_outer {
+ (outer_batch, &outer_rows)
+ } else {
+ (inner_batch, &inner_rows)
+ };
+ columns.push(take(batch.column(col_idx.index).as_ref(), rows,
None)?);
Review Comment:
The pair cap doesn’t bound the number of bytes `take` copies. For `l.s <>
r.s`, one 32 MiB outer `Utf8` value paired with 64 inner `'a'` values needs
2^31 bytes in the gathered outer column. With an unmatched trailing key on each
side to keep the group inside both batches, this returns
`OffsetOverflowError(2147483648)`. The buffered path references the outer slice
and finishes after the first match. Could we fall back for variable-width
inputs, or split the gather using a byte limit that also handles a single
oversized group?
##########
datafusion/physical-plan/src/joins/sort_merge_join/bitwise_stream.rs:
##########
@@ -1046,14 +1092,96 @@ impl BitwiseSortMergeJoinStream {
return Ok(false);
}
- for i in outer_from..outer_group_end {
- self.matched.set_bit(i, true);
+ if self.filter.is_some() {
+ let outer_len = outer_group_end - outer_from;
+ let inner_len = inner_group_end - inner_from;
+ // Both lengths are at least 1, so comparing the quotient avoids
+ // overflowing the product.
+ if inner_len > MAX_DEFERRED_PAIRS_PER_GROUP / outer_len {
+ return Ok(false);
+ }
+ // Batches hold far fewer than `u32::MAX` rows; the hash join
+ // indexes its probe batches with `u32` in the same way.
+ debug_assert!(u32::try_from(num_outer.max(num_inner)).is_ok());
+ for outer_row in outer_from..outer_group_end {
+ for inner_row in inner_from..inner_group_end {
+ self.deferred_outer_rows.push(outer_row as u32);
+ self.deferred_inner_rows.push(inner_row as u32);
+ }
+ }
+ if self.deferred_outer_rows.len() >= self.deferred_pair_limit {
+ self.evaluate_deferred_pairs()?;
+ }
+ } else {
+ for i in outer_from..outer_group_end {
+ self.matched.set_bit(i, true);
+ }
}
self.outer_offset = outer_group_end;
self.inner_offset = inner_group_end;
Ok(true)
}
+ /// Evaluate the join filter once over all queued `(outer, inner)` row
+ /// pairs and set the matched bit of every outer row with a passing pair.
+ ///
+ /// Must run before `outer_batch` or `inner_batch` is replaced, because
+ /// the queued pairs index those batches, and before the matched bitset
+ /// is emitted.
+ fn evaluate_deferred_pairs(&mut self) -> Result<()> {
+ if self.deferred_outer_rows.is_empty() {
+ return Ok(());
+ }
+ let (Some(filter), Some(outer_batch), Some(inner_batch)) =
+ (&self.filter, &self.outer_batch, &self.inner_batch)
+ else {
+ return internal_err!(
+ "Deferred filter pairs require a filter and both current
batches"
+ );
+ };
+
+ let num_pairs = self.deferred_outer_rows.len();
+ let outer_rows = UInt32Array::from(std::mem::take(&mut
self.deferred_outer_rows));
+ let inner_rows = UInt32Array::from(std::mem::take(&mut
self.deferred_inner_rows));
+
+ // Build the filter input columns in the order the filter expects.
+ let mut columns: Vec<ArrayRef> =
+ Vec::with_capacity(filter.column_indices().len());
+ for col_idx in filter.column_indices() {
+ let from_outer = match col_idx.side {
+ JoinSide::Left => self.outer_is_left,
+ JoinSide::Right => !self.outer_is_left,
+ JoinSide::None => {
+ return internal_err!("Unexpected JoinSide::None in
filter");
+ }
+ };
+ let (batch, rows) = if from_outer {
+ (outer_batch, &outer_rows)
+ } else {
+ (inner_batch, &inner_rows)
+ };
+ columns.push(take(batch.column(col_idx.index).as_ref(), rows,
None)?);
+ }
+
+ let filter_batch = RecordBatch::try_new_with_options(
+ Arc::clone(filter.schema()),
+ columns,
+ &RecordBatchOptions::new().with_row_count(Some(num_pairs)),
+ )?;
+ let result = filter
+ .expression()
+ .evaluate(&filter_batch)?
Review Comment:
Evaluating all pairs changes which errors the join exposes. For a left semi
join with `l.c / r.c > 0`, one outer value `8` and inner values `[2, 0]` for
the same key, the buffered path stops at `8 / 2`. The queued path evaluates `8
/ 0` and fails. I could switch between success and failure by moving just the
input batch boundary. Could we keep potentially fallible predicates on the
buffered path and start with comparisons that are safe to evaluate eagerly?
--
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]