You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/05/07 06:25:51 UTC

(datafusion) branch gh-readonly-queue/main/pr-22017-6b27d2d55235c7c86c8033b6e1211ba1a72fb0bb created (now 6148b57007)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-22017-6b27d2d55235c7c86c8033b6e1211ba1a72fb0bb
in repository https://gitbox.apache.org/repos/asf/datafusion.git


      at 6148b57007 fix: drop input plan early in `CoalescePartitionsExec` (#22017)

This branch includes the following new commits:

     new 6148b57007 fix: drop input plan early in `CoalescePartitionsExec` (#22017)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



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


(datafusion) 01/01: fix: drop input plan early in `CoalescePartitionsExec` (#22017)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-22017-6b27d2d55235c7c86c8033b6e1211ba1a72fb0bb
in repository https://gitbox.apache.org/repos/asf/datafusion.git

commit 6148b57007a63921361b8d47462bc60a116a454c
Author: Samyak Sarnayak <sa...@gmail.com>
AuthorDate: Thu May 7 11:55:29 2026 +0530

    fix: drop input plan early in `CoalescePartitionsExec` (#22017)
    
    ## 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 https://github.com/apache/datafusion/issues/22016
    
    ## 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.
    -->
    
    - `CoalescePartitionsExec` uses `RecordBatchReceiverStreamBuilder` which
    was holding to an Arc ref of the input plan, until the stream was done.
    - More details in the issue.
    
    ## 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.
    -->
    
    - Now we drop the input plan early.
    - The only other usage of `input` was in debug prints, to display the
    input plan. We now take the display string early, but only when debug
    logging is enabled.
    
    ## 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)?
    -->
    
    - Added a test that ensures this. Verified that the test fails without
    the fix.
    
    The reproducer (https://github.com/Samyak2/datafusion/pull/1) before the
    fix:
    ```
    repartition_task_group=0 input_partition=0 kind=pull_from_input drop_elapsed_ms=68
    repartition_task_group=1 input_partition=0 kind=pull_from_input drop_elapsed_ms=80
    repartition_task_group=1 input_partition=1 kind=pull_from_input drop_elapsed_ms=85
    output_partitions=32 input_rows_per_partition=1024000 all_repartition_operator_drop_elapsed_ms=80
    all_repartition_task_drop_elapsed_ms=85
    all_observed_drop_elapsed_ms=85
    ```
    ~85ms to cancel repartition tasks.
    
    After fix:
    ```
    repartition_task_group=0 input_partition=0 kind=pull_from_input drop_elapsed_ms=16
    repartition_task_group=1 input_partition=0 kind=pull_from_input drop_elapsed_ms=0
    repartition_task_group=1 input_partition=1 kind=pull_from_input drop_elapsed_ms=0
    output_partitions=32 input_rows_per_partition=1024000 all_repartition_operator_drop_elapsed_ms=0
    all_repartition_task_drop_elapsed_ms=16
    all_observed_drop_elapsed_ms=16
    ```
    ~16ms to cancel repartition tasks.
    
    ## 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.
    -->
    
    CPU/memory gets released earlier on cancellation
    
    ---------
    
    Co-authored-by: Kumar Ujjawal <uj...@gmail.com>
---
 .../physical-plan/src/coalesce_partitions.rs       | 44 +++++++++++++++++++++-
 datafusion/physical-plan/src/stream.rs             | 21 +++++++----
 2 files changed, 56 insertions(+), 9 deletions(-)

diff --git a/datafusion/physical-plan/src/coalesce_partitions.rs b/datafusion/physical-plan/src/coalesce_partitions.rs
index 9290d72516..3399554612 100644
--- a/datafusion/physical-plan/src/coalesce_partitions.rs
+++ b/datafusion/physical-plan/src/coalesce_partitions.rs
@@ -351,11 +351,14 @@ impl ExecutionPlan for CoalescePartitionsExec {
 mod tests {
     use super::*;
     use crate::test::exec::{
-        BlockingExec, PanicExec, assert_strong_count_converges_to_zero,
+        BarrierExec, BlockingExec, PanicExec, assert_strong_count_converges_to_zero,
     };
     use crate::test::{self, assert_is_pending};
     use crate::{collect, common};
 
+    use std::time::Duration;
+
+    use arrow::array::RecordBatch;
     use arrow::datatypes::{DataType, Field, Schema};
 
     use futures::FutureExt;
@@ -390,6 +393,45 @@ mod tests {
         Ok(())
     }
 
+    #[tokio::test]
+    async fn drops_input_plan_after_input_streams_start() -> Result<()> {
+        let task_ctx = Arc::new(TaskContext::default());
+        let schema =
+            Arc::new(Schema::new(vec![Field::new("a", DataType::Float32, true)]));
+        let input_partitions = 2;
+        let batch = RecordBatch::new_empty(Arc::clone(&schema));
+        let input = Arc::new(
+            BarrierExec::new(vec![vec![batch]; input_partitions], schema)
+                .without_start_barrier()
+                .with_finish_barrier()
+                .with_log(false),
+        );
+        let refs = Arc::downgrade(&input);
+
+        let input_plan: Arc<BarrierExec> = Arc::clone(&input);
+        let coalesce = CoalescePartitionsExec::new(input_plan);
+        let stream = coalesce.execute(0, task_ctx)?;
+        drop(coalesce);
+
+        tokio::time::timeout(Duration::from_secs(5), async {
+            // Why not `wait_finish` here: that releases the barrier which lets the input tasks
+            // finish, which drops the input Arcs and hides the bug.
+            while !input.is_finish_barrier_reached() {
+                tokio::task::yield_now().await;
+            }
+        })
+        .await
+        .expect("input streams should reach pending");
+
+        drop(input);
+
+        assert_strong_count_converges_to_zero(refs).await;
+
+        drop(stream);
+
+        Ok(())
+    }
+
     #[tokio::test]
     async fn test_drop_cancel() -> Result<()> {
         let task_ctx = Arc::new(TaskContext::default());
diff --git a/datafusion/physical-plan/src/stream.rs b/datafusion/physical-plan/src/stream.rs
index 4b7e707fcc..9139a6dd04 100644
--- a/datafusion/physical-plan/src/stream.rs
+++ b/datafusion/physical-plan/src/stream.rs
@@ -330,6 +330,11 @@ impl RecordBatchReceiverStreamBuilder {
         context: Arc<TaskContext>,
     ) {
         let output = self.tx();
+        let input_display = if log::log_enabled!(log::Level::Debug) {
+            displayable(input.as_ref()).one_line().to_string()
+        } else {
+            String::new()
+        };
 
         self.inner.spawn(async move {
             let mut stream = match input.execute(partition, context) {
@@ -338,14 +343,18 @@ impl RecordBatchReceiverStreamBuilder {
                     // is no place to send the error and no reason to continue.
                     output.send(Err(e)).await.ok();
                     debug!(
-                        "Stopping execution: error executing input: {}",
-                        displayable(input.as_ref()).one_line()
+                        "Stopping execution: error executing input: {input_display}",
                     );
                     return Ok(());
                 }
                 Ok(stream) => stream,
             };
 
+            // Drop the input early, as soon as we're done with it.
+            // Holding on to it can cause delays in cancelling the child plan when the query is
+            // cancelled.
+            drop(input);
+
             // Transfer batches from inner stream to the output tx
             // immediately.
             while let Some(item) = stream.next().await {
@@ -355,8 +364,7 @@ impl RecordBatchReceiverStreamBuilder {
                 // place to send the error and no reason to continue.
                 if output.send(item).await.is_err() {
                     debug!(
-                        "Stopping execution: output is gone, plan cancelling: {}",
-                        displayable(input.as_ref()).one_line()
+                        "Stopping execution: output is gone, plan cancelling: {input_display}",
                     );
                     return Ok(());
                 }
@@ -364,10 +372,7 @@ impl RecordBatchReceiverStreamBuilder {
                 // Stop after the first error is encountered (Don't
                 // drive all streams to completion)
                 if is_err {
-                    debug!(
-                        "Stopping execution: plan returned error: {}",
-                        displayable(input.as_ref()).one_line()
-                    );
+                    debug!("Stopping execution: plan returned error: {input_display}");
                     return Ok(());
                 }
             }


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