You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "mertak-synnada (via GitHub)" <gi...@apache.org> on 2024/12/16 14:45:00 UTC

[PR] Chore: Remove empty batches [datafusion]

mertak-synnada opened a new pull request, #13794:
URL: https://github.com/apache/datafusion/pull/13794

   ## 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. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   ## 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.  
   -->
   Some plans generate and emit empty RecordBatches. Since this behavior is unnecessary and incurs costs during stream execution, this change implements a solution for handling them in the streaming process.
   
   ## 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 add the `api change` label.
   -->
   


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: do not return empty record batches from Aggregate operators [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#discussion_r1887372503


##########
datafusion/physical-plan/src/aggregates/row_hash.rs:
##########
@@ -693,9 +696,12 @@ impl Stream for GroupedHashAggregateStream {
                             }
 
                             if let Some(to_emit) = self.group_ordering.emit_to() {
-                                let batch = extract_ok!(self.emit(to_emit, false));
-                                self.exec_state = ExecutionState::ProducingOutput(batch);
                                 timer.done();
+                                let Some(batch) = extract_ok!(self.emit(to_emit, false))

Review Comment:
   same comment as above



##########
datafusion/physical-plan/src/aggregates/row_hash.rs:
##########
@@ -937,7 +944,8 @@ impl GroupedHashAggregateStream {
         // over the target memory size after emission, we can emit again rather than returning Err.
         let _ = self.update_memory_reservation();
         let batch = RecordBatch::try_new(schema, output)?;
-        Ok(batch)
+        debug_assert!(batch.num_rows() > 0);

Review Comment:
   Maybe it would be good to document in comments somewhere the expectation / behavior that no empty record batches are produced



##########
datafusion/physical-plan/src/aggregates/row_hash.rs:
##########
@@ -654,9 +654,12 @@ impl Stream for GroupedHashAggregateStream {
                             }
 
                             if let Some(to_emit) = self.group_ordering.emit_to() {
-                                let batch = extract_ok!(self.emit(to_emit, false));
-                                self.exec_state = ExecutionState::ProducingOutput(batch);
                                 timer.done();
+                                let Some(batch) = extract_ok!(self.emit(to_emit, false))
+                                else {
+                                    break 'reading_input;
+                                };
+                                self.exec_state = ExecutionState::ProducingOutput(batch);

Review Comment:
   Nit: I think I would find this easier to read if it it avoid a redundant `break`:
   
   ```suggestion
                                   if let let Some(batch) = extract_ok!(self.emit(to_emit, false)) {
                                     self.exec_state = ExecutionState::ProducingOutput(batch);
                                   }
   ```



##########
datafusion/physical-plan/src/aggregates/row_hash.rs:
##########
@@ -902,14 +909,14 @@ impl GroupedHashAggregateStream {
 
     /// Create an output RecordBatch with the group keys and
     /// accumulator states/values specified in emit_to
-    fn emit(&mut self, emit_to: EmitTo, spilling: bool) -> Result<RecordBatch> {
+    fn emit(&mut self, emit_to: EmitTo, spilling: bool) -> Result<Option<RecordBatch>> {
         let schema = if spilling {
             Arc::clone(&self.spill_state.spill_schema)
         } else {
             self.schema()
         };
         if self.group_values.is_empty() {
-            return Ok(RecordBatch::new_empty(schema));
+            return Ok(None);

Review Comment:
   👍 



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: do not return empty record batches from Aggregate operators [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#discussion_r1887393005


##########
datafusion/physical-plan/src/windows/window_agg_exec.rs:
##########
@@ -386,12 +382,19 @@ impl WindowAggStream {
                     continue;
                 }
                 Some(Err(e)) => Err(e),
-                None => self.compute_aggregates(),
-            };
+                None => {
+                    let batch = concat_batches(&self.input.schema(), &self.batches)?;

Review Comment:
   I think we should fix this prior to merge



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: do not return empty record batches from Aggregate operators [datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on code in PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#discussion_r1888572337


##########
datafusion/physical-plan/src/unnest.rs:
##########
@@ -278,28 +279,31 @@ impl UnnestStream {
     fn poll_next_impl(
         &mut self,
         cx: &mut std::task::Context<'_>,
-    ) -> std::task::Poll<Option<Result<RecordBatch>>> {
-        self.input
-            .poll_next_unpin(cx)
-            .map(|maybe_batch| match maybe_batch {
+    ) -> Poll<Option<Result<RecordBatch>>> {
+        loop {
+            return Poll::Ready(match ready!(self.input.poll_next_unpin(cx)) {
                 Some(Ok(batch)) => {
                     let timer = self.metrics.elapsed_compute.timer();
+                    self.metrics.input_batches.add(1);
+                    self.metrics.input_rows.add(batch.num_rows());
                     let result = build_batch(
                         &batch,
                         &self.schema,
                         &self.list_type_columns,
                         &self.struct_column_indices,
                         &self.options,
-                    );
-                    self.metrics.input_batches.add(1);
-                    self.metrics.input_rows.add(batch.num_rows());
-                    if let Ok(ref batch) = result {
-                        timer.done();
-                        self.metrics.output_batches.add(1);
-                        self.metrics.output_rows.add(batch.num_rows());
-                    }
-
-                    Some(result)
+                    )?;
+                    timer.done();
+                    let Some(result_batch) = result else {
+                        continue;
+                    };
+                    self.metrics.output_batches.add(1);
+                    self.metrics.output_rows.add(result_batch.num_rows());
+
+                    // Empty record batches should not be emitted.
+                    // They need to be treated as  [`Option<RecordBatch>`]es and handle separately

Review Comment:
   ```suggestion
                       // They need to be treated as  [`Option<RecordBatch>`]es and handled separately
   ```



##########
datafusion/physical-plan/src/aggregates/row_hash.rs:
##########
@@ -768,6 +776,9 @@ impl Stream for GroupedHashAggregateStream {
                         let output = batch.slice(0, size);
                         (ExecutionState::ProducingOutput(remaining), output)
                     };
+                    // Empty record batches should not be emitted.
+                    // They need to be treated as  [`Option<RecordBatch>`]es and handle separately

Review Comment:
   ```suggestion
                       // They need to be treated as  [`Option<RecordBatch>`]es and handled separately
   ```



##########
datafusion/physical-plan/src/sorts/partial_sort.rs:
##########
@@ -407,6 +407,9 @@ impl PartialSortStream {
                 self.is_closed = true;
             }
         }
+        // Empty record batches should not be emitted.
+        // They need to be treated as [`Option<RecordBatch>`]es and handle separately

Review Comment:
   ```suggestion
           // They need to be treated as [`Option<RecordBatch>`]es and handled separately
   ```



##########
datafusion/physical-plan/src/unnest.rs:
##########
@@ -573,16 +578,16 @@ fn build_batch(
                     true => batch.columns(),
                     false => &flatten_arrs,
                 };
-                let (temp_result, num_rows) = list_unnest_at_level(
+                let temp_result = list_unnest_at_level(
                     input,
                     list_type_columns,
                     &mut temp_unnested_result,
                     depth,
                     options,
                 )?;
-                if num_rows == 0 {
-                    return Ok(RecordBatch::new_empty(Arc::clone(schema)));
-                }
+                let Some(temp_result) = temp_result else {
+                    return Ok(None);
+                };

Review Comment:
   We can use the more succinct
   ```rust
                   let Some(temp_result) = list_unnest_at_level(
                       input,
                       list_type_columns,
                       &mut temp_unnested_result,
                       depth,
                       options,
                   )? else {
                       continue;
                   };
   ```



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -979,26 +979,33 @@ impl BoundedWindowAggStream {
             return Poll::Ready(None);
         }
 
-        let result = match ready!(self.input.poll_next_unpin(cx)) {
+        match ready!(self.input.poll_next_unpin(cx)) {
             Some(Ok(batch)) => {
                 self.search_mode.update_partition_batch(
                     &mut self.input_buffer,
                     batch,
                     &self.window_expr,
                     &mut self.partition_buffers,
                 )?;
-                self.compute_aggregates()
+                let batch = self.compute_aggregates()?;
+                if let Some(batch) = batch {
+                    return Poll::Ready(Some(Ok(batch)));
+                }

Review Comment:
   Can we say
   ```suggestion
                   if let Some(batch) = self.compute_aggregates()? {
                       return Poll::Ready(Some(Ok(batch)));
                   }
   ```



##########
datafusion/physical-plan/src/windows/bounded_window_agg_exec.rs:
##########
@@ -979,26 +979,33 @@ impl BoundedWindowAggStream {
             return Poll::Ready(None);
         }
 
-        let result = match ready!(self.input.poll_next_unpin(cx)) {
+        match ready!(self.input.poll_next_unpin(cx)) {
             Some(Ok(batch)) => {
                 self.search_mode.update_partition_batch(
                     &mut self.input_buffer,
                     batch,
                     &self.window_expr,
                     &mut self.partition_buffers,
                 )?;
-                self.compute_aggregates()
+                let batch = self.compute_aggregates()?;
+                if let Some(batch) = batch {
+                    return Poll::Ready(Some(Ok(batch)));
+                }
+                self.poll_next_inner(cx)
             }
-            Some(Err(e)) => Err(e),
+            Some(Err(e)) => Poll::Ready(Some(Err(e))),
             None => {
                 self.finished = true;
                 for (_, partition_batch_state) in self.partition_buffers.iter_mut() {
                     partition_batch_state.is_end = true;
                 }
-                self.compute_aggregates()
+                let batch = self.compute_aggregates()?;
+                if let Some(batch) = batch {
+                    return Poll::Ready(Some(Ok(batch)));
+                }

Review Comment:
   Can we say
   ```suggestion
                   if let Some(batch) = self.compute_aggregates()? {
                       return Poll::Ready(Some(Ok(batch)));
                   }
   ```



##########
datafusion/physical-plan/src/windows/window_agg_exec.rs:
##########
@@ -380,18 +381,23 @@ impl WindowAggStream {
         }
 
         loop {
-            let result = match ready!(self.input.poll_next_unpin(cx)) {
+            let maybe_batch = match ready!(self.input.poll_next_unpin(cx)) {
                 Some(Ok(batch)) => {
                     self.batches.push(batch);
                     continue;
                 }
                 Some(Err(e)) => Err(e),
                 None => self.compute_aggregates(),
+            }?;
+            let Some(result) = maybe_batch else {
+                return Poll::Ready(None);
             };

Review Comment:
   Can this go inside the `None` arm of the match above?



##########
datafusion/physical-plan/src/windows/window_agg_exec.rs:
##########
@@ -380,18 +381,23 @@ impl WindowAggStream {
         }
 
         loop {
-            let result = match ready!(self.input.poll_next_unpin(cx)) {
+            let maybe_batch = match ready!(self.input.poll_next_unpin(cx)) {
                 Some(Ok(batch)) => {
                     self.batches.push(batch);
                     continue;
                 }
                 Some(Err(e)) => Err(e),
                 None => self.compute_aggregates(),
+            }?;
+            let Some(result) = maybe_batch else {
+                return Poll::Ready(None);
             };
 
             self.finished = true;
-
-            return Poll::Ready(Some(result));
+            // Empty record batches should not be emitted.
+            // They need to be treated as  [`Option<RecordBatch>`]es and handle separately

Review Comment:
   ```suggestion
               // They need to be treated as  [`Option<RecordBatch>`]es and handled separately
   ```



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: Do not return empty record batches from streams [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#issuecomment-2552468435

   Thank you everyone!


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: Remove empty batches [datafusion]

Posted by "Dandandan (via GitHub)" <gi...@apache.org>.
Dandandan commented on code in PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#discussion_r1887043813


##########
datafusion/physical-plan/src/windows/window_agg_exec.rs:
##########
@@ -386,12 +382,19 @@ impl WindowAggStream {
                     continue;
                 }
                 Some(Err(e)) => Err(e),
-                None => self.compute_aggregates(),
-            };
+                None => {
+                    let batch = concat_batches(&self.input.schema(), &self.batches)?;

Review Comment:
   This change moves `concat_batches` out of `elapsed_compute` 



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: Do not return empty record batches from streams [datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak merged PR #13794:
URL: https://github.com/apache/datafusion/pull/13794


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: do not return empty record batches from Aggregate operators [datafusion]

Posted by "mertak-synnada (via GitHub)" <gi...@apache.org>.
mertak-synnada commented on PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#issuecomment-2547806547

   Thanks for the review, @alamb and @Dandandan! I tried to implement your suggestions, including adding some unit tests and assertions for some existing tests. I hope it's in a better state now.


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] Chore: Do not return empty record batches from streams [datafusion]

Posted by "ozankabak (via GitHub)" <gi...@apache.org>.
ozankabak commented on PR #13794:
URL: https://github.com/apache/datafusion/pull/13794#issuecomment-2550580115

   I will go ahead and merge this in the next few hours unless new feedback arrives, since the reviews has been addressed and it is a fairly straightforward change


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org