You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "zhuqi-lucas (via GitHub)" <gi...@apache.org> on 2025/08/10 13:22:44 UTC

[PR] Draft POC: Push batch with filter without copy [arrow-rs]

zhuqi-lucas opened a new pull request, #8103:
URL: https://github.com/apache/arrow-rs/pull/8103

   # Which issue does this PR close?
   
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax.
   
   - Closes #NNN.
   
   # Rationale for this change
   
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   
   # What changes are included in this PR?
   
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   
   # Are these changes tested?
   
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   
   # Are there any user-facing changes?
   
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   
   If there are any breaking changes to public APIs, please call them out.
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#issuecomment-4805866349

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#discussion_r2267167118


##########
arrow-select/src/filter.rs:
##########
@@ -164,6 +164,44 @@ fn multiple_arrays(data_type: &DataType) -> bool {
     }
 }
 
+/// A public, lightweight plan describing how to apply a Boolean filter.
+///
+/// Used for zero-copy filtering externally (e.g., in BatchCoalescer):
+/// - `None`: no rows selected
+/// - `All`: all rows selected
+/// - `Slices`: list of continuous ranges `[start, end)` (can be used directly for `copy_rows`)
+/// - `Indices`: list of single-row indices (can be merged into continuous ranges externally)
+#[derive(Debug, Clone)]
+pub enum FilterPlan {
+    None,
+    All,
+    Slices(Vec<(usize, usize)>),
+    Indices(Vec<usize>),
+}
+
+/// Compute a filtering plan based on `FilterBuilder::optimize`.
+///
+/// This function calls `FilterBuilder::new(filter).optimize()`, then
+/// converts the optimized `IterationStrategy` into the above `FilterPlan`
+/// to enable zero-copy execution externally.
+pub fn compute_filter_plan(filter: &BooleanArray) -> FilterPlan {
+    let fb = FilterBuilder::new(filter);
+    let pred = fb.build();
+
+    match pred.strategy {
+        IterationStrategy::None => FilterPlan::None,
+        IterationStrategy::All => FilterPlan::All,
+        IterationStrategy::Slices(s) => FilterPlan::Slices(s), // moved directly
+        IterationStrategy::Indices(i) => FilterPlan::Indices(i), // moved directly
+        IterationStrategy::SlicesIterator => {
+            FilterPlan::Slices(SlicesIterator::new(&pred.filter).collect())

Review Comment:
   Thank you @alamb , i tried now, but it not improved the regression. 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#discussion_r2266795289


##########
arrow-select/src/coalesce.rs:
##########
@@ -198,15 +198,139 @@ impl BatchCoalescer {
     /// let expected_batch = record_batch!(("a", Int32, [1, 3, 4, 6])).unwrap();
     /// assert_eq!(completed_batch, expected_batch);
     /// ```
+    /// Zero-copy implementation using `compute_filter_plan`.
     pub fn push_batch_with_filter(
         &mut self,
         batch: RecordBatch,
-        filter: &BooleanArray,
+        predicate: &BooleanArray,
     ) -> Result<(), ArrowError> {
-        // TODO: optimize this to avoid materializing (copying the results
-        // of filter to a new batch)
-        let filtered_batch = filter_record_batch(&batch, filter)?;
-        self.push_batch(filtered_batch)
+        // First compute the filter plan based on the predicate
+        // (calls FilterBuilder::optimize internally)
+        let plan = compute_filter_plan(predicate);
+
+        match plan {
+            FilterPlan::None => {
+                // No rows selected
+                Ok(())
+            }
+            FilterPlan::All => {
+                // All rows selected: directly call push_batch (consumes batch)
+                self.push_batch(batch)
+            }
+            FilterPlan::Slices(slices) => {
+                // Consume the batch and set sources on in_progress arrays
+                let (_schema, arrays, _nrows) = batch.into_parts();
+                assert_eq!(arrays.len(), self.in_progress_arrays.len());
+
+                self.in_progress_arrays
+                    .iter_mut()
+                    .zip(arrays)
+                    .for_each(|(in_progress, array)| {
+                        in_progress.set_source(Some(array));
+                    });
+
+                // For each contiguous slice, copy rows in chunks fitting target_batch_size
+                for (mut start, end) in slices {

Review Comment:
   I suspect to really make this fast it will need to have specialized implementations for the different array types (not use mutable array data)
   
   I think we could yoink / reuse some of the existing code from the filter kernel: https://github.com/apache/arrow-rs/blob/04f217b6708eed2804c3b0a669a65ea111c2c5f1/arrow-select/src/filter.rs#L322



##########
arrow-select/src/filter.rs:
##########
@@ -164,6 +164,44 @@ fn multiple_arrays(data_type: &DataType) -> bool {
     }
 }
 
+/// A public, lightweight plan describing how to apply a Boolean filter.
+///
+/// Used for zero-copy filtering externally (e.g., in BatchCoalescer):
+/// - `None`: no rows selected
+/// - `All`: all rows selected
+/// - `Slices`: list of continuous ranges `[start, end)` (can be used directly for `copy_rows`)
+/// - `Indices`: list of single-row indices (can be merged into continuous ranges externally)
+#[derive(Debug, Clone)]
+pub enum FilterPlan {
+    None,
+    All,
+    Slices(Vec<(usize, usize)>),
+    Indices(Vec<usize>),
+}
+
+/// Compute a filtering plan based on `FilterBuilder::optimize`.
+///
+/// This function calls `FilterBuilder::new(filter).optimize()`, then
+/// converts the optimized `IterationStrategy` into the above `FilterPlan`
+/// to enable zero-copy execution externally.
+pub fn compute_filter_plan(filter: &BooleanArray) -> FilterPlan {
+    let fb = FilterBuilder::new(filter);
+    let pred = fb.build();
+
+    match pred.strategy {
+        IterationStrategy::None => FilterPlan::None,
+        IterationStrategy::All => FilterPlan::All,
+        IterationStrategy::Slices(s) => FilterPlan::Slices(s), // moved directly
+        IterationStrategy::Indices(i) => FilterPlan::Indices(i), // moved directly
+        IterationStrategy::SlicesIterator => {
+            FilterPlan::Slices(SlicesIterator::new(&pred.filter).collect())

Review Comment:
   avoiding this allocation will likely help



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#discussion_r2267167118


##########
arrow-select/src/filter.rs:
##########
@@ -164,6 +164,44 @@ fn multiple_arrays(data_type: &DataType) -> bool {
     }
 }
 
+/// A public, lightweight plan describing how to apply a Boolean filter.
+///
+/// Used for zero-copy filtering externally (e.g., in BatchCoalescer):
+/// - `None`: no rows selected
+/// - `All`: all rows selected
+/// - `Slices`: list of continuous ranges `[start, end)` (can be used directly for `copy_rows`)
+/// - `Indices`: list of single-row indices (can be merged into continuous ranges externally)
+#[derive(Debug, Clone)]
+pub enum FilterPlan {
+    None,
+    All,
+    Slices(Vec<(usize, usize)>),
+    Indices(Vec<usize>),
+}
+
+/// Compute a filtering plan based on `FilterBuilder::optimize`.
+///
+/// This function calls `FilterBuilder::new(filter).optimize()`, then
+/// converts the optimized `IterationStrategy` into the above `FilterPlan`
+/// to enable zero-copy execution externally.
+pub fn compute_filter_plan(filter: &BooleanArray) -> FilterPlan {
+    let fb = FilterBuilder::new(filter);
+    let pred = fb.build();
+
+    match pred.strategy {
+        IterationStrategy::None => FilterPlan::None,
+        IterationStrategy::All => FilterPlan::All,
+        IterationStrategy::Slices(s) => FilterPlan::Slices(s), // moved directly
+        IterationStrategy::Indices(i) => FilterPlan::Indices(i), // moved directly
+        IterationStrategy::SlicesIterator => {
+            FilterPlan::Slices(SlicesIterator::new(&pred.filter).collect())

Review Comment:
   Thank you @alamb , i tried now, but it not improved the regression.  The compute_filter_plan almost cost nothing for the benchmark profile.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#discussion_r2267160776


##########
arrow-select/src/coalesce.rs:
##########
@@ -198,15 +198,139 @@ impl BatchCoalescer {
     /// let expected_batch = record_batch!(("a", Int32, [1, 3, 4, 6])).unwrap();
     /// assert_eq!(completed_batch, expected_batch);
     /// ```
+    /// Zero-copy implementation using `compute_filter_plan`.
     pub fn push_batch_with_filter(
         &mut self,
         batch: RecordBatch,
-        filter: &BooleanArray,
+        predicate: &BooleanArray,
     ) -> Result<(), ArrowError> {
-        // TODO: optimize this to avoid materializing (copying the results
-        // of filter to a new batch)
-        let filtered_batch = filter_record_batch(&batch, filter)?;
-        self.push_batch(filtered_batch)
+        // First compute the filter plan based on the predicate
+        // (calls FilterBuilder::optimize internally)
+        let plan = compute_filter_plan(predicate);
+
+        match plan {
+            FilterPlan::None => {
+                // No rows selected
+                Ok(())
+            }
+            FilterPlan::All => {
+                // All rows selected: directly call push_batch (consumes batch)
+                self.push_batch(batch)
+            }
+            FilterPlan::Slices(slices) => {
+                // Consume the batch and set sources on in_progress arrays
+                let (_schema, arrays, _nrows) = batch.into_parts();
+                assert_eq!(arrays.len(), self.in_progress_arrays.len());
+
+                self.in_progress_arrays
+                    .iter_mut()
+                    .zip(arrays)
+                    .for_each(|(in_progress, array)| {
+                        in_progress.set_source(Some(array));
+                    });
+
+                // For each contiguous slice, copy rows in chunks fitting target_batch_size
+                for (mut start, end) in slices {

Review Comment:
   Thank you @alamb for review and good suggestion.
   
   I found the hot path for profile is, copy_rows:
   
   Especially for the code for null handling:
   
   ```rust
   
           // add nulls if necessary
           if let Some(nulls) = s.nulls().as_ref() {
               let nulls = nulls.slice(offset, len);
               self.nulls.append_buffer(&nulls);
           } else {
               self.nulls.append_n_non_nulls(len);
           };
   ```
   
   It may due to we will call more times for copy_rows here, but the original logic is just filter and concact to a batch, and then to push_batch, so it will be friendly for SIMD. So the original run is pretty faster for most cases.
   
   May be we need to only change this logic for selective < 0.005 for example, but it's hard for me to decide. 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #8103: Draft POC: Push batch with filter without copy
URL: https://github.com/apache/arrow-rs/pull/8103


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Draft POC: Push batch with filter without copy [arrow-rs]

Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #8103:
URL: https://github.com/apache/arrow-rs/pull/8103#discussion_r2267160776


##########
arrow-select/src/coalesce.rs:
##########
@@ -198,15 +198,139 @@ impl BatchCoalescer {
     /// let expected_batch = record_batch!(("a", Int32, [1, 3, 4, 6])).unwrap();
     /// assert_eq!(completed_batch, expected_batch);
     /// ```
+    /// Zero-copy implementation using `compute_filter_plan`.
     pub fn push_batch_with_filter(
         &mut self,
         batch: RecordBatch,
-        filter: &BooleanArray,
+        predicate: &BooleanArray,
     ) -> Result<(), ArrowError> {
-        // TODO: optimize this to avoid materializing (copying the results
-        // of filter to a new batch)
-        let filtered_batch = filter_record_batch(&batch, filter)?;
-        self.push_batch(filtered_batch)
+        // First compute the filter plan based on the predicate
+        // (calls FilterBuilder::optimize internally)
+        let plan = compute_filter_plan(predicate);
+
+        match plan {
+            FilterPlan::None => {
+                // No rows selected
+                Ok(())
+            }
+            FilterPlan::All => {
+                // All rows selected: directly call push_batch (consumes batch)
+                self.push_batch(batch)
+            }
+            FilterPlan::Slices(slices) => {
+                // Consume the batch and set sources on in_progress arrays
+                let (_schema, arrays, _nrows) = batch.into_parts();
+                assert_eq!(arrays.len(), self.in_progress_arrays.len());
+
+                self.in_progress_arrays
+                    .iter_mut()
+                    .zip(arrays)
+                    .for_each(|(in_progress, array)| {
+                        in_progress.set_source(Some(array));
+                    });
+
+                // For each contiguous slice, copy rows in chunks fitting target_batch_size
+                for (mut start, end) in slices {

Review Comment:
   Thank you @alamb for review and good suggestion.
   
   I found the hot path for profile is, copy_rows:
   
   Especially for the code for null handling:
   
   ```rust
   
           // add nulls if necessary
           if let Some(nulls) = s.nulls().as_ref() {
               let nulls = nulls.slice(offset, len);
               self.nulls.append_buffer(&nulls);
           } else {
               self.nulls.append_n_non_nulls(len);
           };
   ```
   
   It may due to we will call more times for copy_rows here, but the original logic is just filter and concact to a batch, and then to push_batch, so it will be friendly for SIMD. Also it will make copy_rows SIMD friendly for bigger batch. So the original run is pretty faster for most cases.
   
   May be we need to only change this logic for selective < 0.005 for example, but it's hard for me to decide. 



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org