comphead commented on code in PR #27278:
URL: https://github.com/apache/datafusion/pull/27278#discussion_r4746121815


##########
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:
   Thanks @viirya and @mbutrovich. Done in 51b7ae602: `filter_first` is 
computed once at construction, and the counters and their updates are gone. It 
counts the emitted columns that the filter does not read, so that it stays 
right when the join's projection drops the filter's columns (see the 
description).
   
   Before the change I measured the all-pass case. With a key group in one 
buffered batch, the two paths do the same gathers, as you say. When a key group 
spans many small buffered batches, they didn't: filtering first built the 
`interleave` plan a second time for the pairs that passed, from rebuilt chunks. 
That cost showed at 90% to 99% kept too, where the old rule also filtered 
first. 51b7ae602 builds the plan once and filters it by runs of passing pairs. 
With 64-row buffered batches and a filter that reads two of four columns, as a 
ratio to `main` (best of 5 alternating rounds on an M5 Max):
   
   | Kept | b8efd107b | 51b7ae602 |
   |---|---:|---:|
   | 90% | 1.16 | 1.02 |
   | 99% | 1.18 | 1.02 |
   | 100% | 1.00 (whole batch) | 1.01 |
   
   The same change takes the 8-row case from the description from 1.10x to 
0.96x of `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