mbutrovich commented on code in PR #27278:
URL: https://github.com/apache/datafusion/pull/27278#discussion_r4680995279
##########
datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs:
##########
@@ -1771,33 +1809,179 @@ impl MaterializingSortMergeJoinStream {
Ok(())
}
- /// Materializes right-side columns across all matched chunks.
+ /// Freezes the matched pairs of an Inner join with a filter, and returns
+ /// whether it did. The filter runs on just the columns it reads, and only
the
+ /// pairs that pass are materialized, which saves most of the freeze when
the
+ /// filter rejects most pairs of a many-to-many join. Outer joins keep a
+ /// rejected pair for the deferred pipeline, which may null-join its row.
Only
+ /// an Inner join filters here, so its streamed side is the left input.
+ ///
+ /// Returns false, leaving the caller to materialize the batch whole and
filter
+ /// it, when [`Self::filter_first_pays`] says filtering first does not
pay, or
+ /// when both sides' indices span ranges, as in a 1:1 join, so that the
columns
+ /// materialize as slices.
+ fn freeze_inner_filtered(
+ &mut self,
+ matched_chunks: &[MatchedChunk],
+ total_matched_rows: usize,
+ streamed_indices: &UInt64Array,
+ ) -> Result<bool> {
+ let (JoinType::Inner, Some(filter)) = (self.join_type, &self.filter)
else {
+ return Ok(false);
+ };
+ if !self.filter_first_pays(filter) {
+ return Ok(false);
+ }
+ let single_source = matched_chunks
+ .iter()
+ .all(|c| c.buffered_batch_idx ==
matched_chunks[0].buffered_batch_idx);
+ let buffered_indices =
+ concat_indices(matched_chunks.iter().map(|c|
&c.buffered_indices))?;
+ if single_source
+ && spans_range(streamed_indices)
+ && spans_range(&buffered_indices)
+ {
+ return Ok(false);
+ }
+
+ let streamed_filter_arrays = materialize_left_columns(
+ &self
+ .streamed_batch
+ .batch
+ .project(&self.streamed_filter_columns)?,
+ streamed_indices,
+ )?;
+ let buffered_filter_arrays = self.materialize_right_columns(
+ matched_chunks,
+ total_matched_rows,
+ &self.buffered_filter_columns,
+ )?;
+ let mut streamed_arrays = streamed_filter_arrays.iter().cloned();
+ let mut buffered_arrays = buffered_filter_arrays.iter().cloned();
+ let columns = filter
+ .column_indices()
+ .iter()
+ .map(|column_index| match column_index.side {
+ JoinSide::Left => streamed_arrays.next().ok_or_else(|| {
+ internal_datafusion_err!("missing streamed filter column")
+ }),
+ JoinSide::Right => buffered_arrays.next().ok_or_else(|| {
+ internal_datafusion_err!("missing buffered filter column")
+ }),
+ JoinSide::None => internal_err!("Unexpected JoinSide::None in
filter"),
+ })
+ .collect::<Result<Vec<_>>>()?;
+ let passed =
+ evaluate_join_filter(filter, filter.schema(), columns,
total_matched_rows)?;
+ let kept_rows = passed.true_count();
+ self.freeze_filter_evaluated += total_matched_rows as u64;
+ self.freeze_filter_passed += kept_rows as u64;
+ if kept_rows == 0 {
+ return Ok(true);
+ }
+
+ // Filter the index arrays of all chunks at once, and give each chunk
+ // with a pair that passed a slice of the result.
+ let predicate = FilterBuilder::new(&passed).optimize().build();
+ let kept_streamed =
+ as_uint64_array(&predicate.filter(streamed_indices)?)?.clone();
+ let kept_buffered =
+ as_uint64_array(&predicate.filter(&buffered_indices)?)?.clone();
+ let mut kept = Vec::with_capacity(matched_chunks.len());
+ let (mut offset, mut kept_offset) = (0, 0);
+ for chunk in matched_chunks {
+ let count = passed.slice(offset, chunk.len()).true_count();
+ offset += chunk.len();
+ if count > 0 {
+ kept.push(MatchedChunk {
+ buffered_batch_idx: chunk.buffered_batch_idx,
+ streamed_indices: kept_streamed.slice(kept_offset, count),
+ buffered_indices: kept_buffered.slice(kept_offset, count),
+ });
+ kept_offset += count;
+ }
+ }
+
+ let streamed_columns = output_columns(
+ self.streamed_schema.fields().len(),
+ &self.streamed_filter_columns,
+ &streamed_filter_arrays,
+ &predicate,
+ |others| {
+ materialize_left_columns(
+ &self.streamed_batch.batch.project(others)?,
+ &kept_streamed,
+ )
+ },
+ )?;
+ let buffered_columns = output_columns(
+ self.buffered_schema.fields().len(),
+ &self.buffered_filter_columns,
+ &buffered_filter_arrays,
+ &predicate,
+ |others| self.materialize_right_columns(&kept, kept_rows, others),
+ )?;
+ let output_batch = RecordBatch::try_new(
+ Arc::clone(&self.schema),
+ [streamed_columns, buffered_columns].concat(),
+ )?;
+ self.joined_record_batches
+ .push_batch_without_metadata(output_batch);
+ Ok(true)
+ }
+
+ /// Whether filtering the pairs of a freeze before materializing them is
cheaper
+ /// than materializing every column of every pair and filtering the batch.
+ ///
+ /// Filtering first gathers the filter's `f` columns for every pair,
filters them
+ /// and the pairs' two index arrays, and gathers the other `k - f` output
+ /// columns for the share `p` of pairs that pass. The other way gathers
the `k`
+ /// columns for every pair and copies the share `p` of them to filter the
batch.
+ /// Counting a gathered value as 1 and a copied one as 1/2, filtering
first is
+ /// cheaper while `f + 1 + f·p/2 + (k - f)·p < k + k·p/2`, that is while
+ /// `(k - f)·(2 - p) > 2`. `p` is the share that passed in the earlier
freezes,
+ /// or 0 before the first.
+ ///
+ /// The model counts columns rather than bytes, so a string column weighs
the
+ /// same as an integer one, and `p` averages over the life of the stream
+ /// rather than tracking recent freezes.
+ fn filter_first_pays(&self, filter: &JoinFilter) -> bool {
+ let k = self.schema.fields().len() as f64;
+ let f = filter.column_indices().len() as f64;
+ let p = if self.freeze_filter_evaluated == 0 {
+ 0.0
+ } else {
+ self.freeze_filter_passed as f64 / self.freeze_filter_evaluated as
f64
+ };
+ (k - f) * (2.0 - p) > 2.0
Review Comment:
> Would a static `k - f >= 2` computed once at construction be enough? That
would drop the two counters and their updates in both freeze paths. Fine as a
follow-up, or to leave as is if you've seen the all-pass case matter.
@comphead, could we make this change in this PR? `p` changes the answer only
when `k - f == 2` and every pair so far has passed. In that case the two paths
do the same gathers. When every pair passes, `FilterPredicate::filter` returns
a slice of each filter column and of both index arrays
([`filter_array`](https://github.com/apache/arrow-rs/blob/b391e5af7dff9f6909af45c01f7dddb68ba08c0f/arrow-select/src/filter.rs#L608)).
Filtering first then gathers each of the `k` columns once for every pair,
which is what the whole-batch path does. For `k - f >= 3` the inequality holds
for every `p <= 1`, and for `k - f <= 1` it never holds.
That drops `freeze_filter_evaluated` and `freeze_filter_passed`, their
updates in [the whole-batch
path](https://github.com/apache/datafusion/blob/b8efd107bcfc92a9fd544cc6a46c529ff78c8dbe/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs#L1763-L1764)
and [the filter-first
path](https://github.com/apache/datafusion/blob/b8efd107bcfc92a9fd544cc6a46c529ff78c8dbe/datafusion/physical-plan/src/joins/sort_merge_join/materializing_stream.rs#L1877-L1878),
and the floating-point math. `filter_first_pays` can stay as the home for the
doc comment:
```rust
fn filter_first_pays(&self, filter: &JoinFilter) -> bool {
self.schema.fields().len() >= filter.column_indices().len() + 2
}
```
The doc comment can keep the cost derivation and add one sentence on why `p`
drops out. The one bench case with `k - f == 2`,
`inner_1to10_high_pass_filtered_narrow`, keeps 90% of its pairs, so it takes
the same path under both rules.
--
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]