kumarUjjawal commented on code in PR #27994:
URL: https://github.com/apache/datafusion/pull/27994#discussion_r4795477007


##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;
+            let options =
+                
RecordBatchOptions::new().with_row_count(Some(indices_array.len()));
+            let taken =
+                RecordBatch::try_new_with_options(batch.schema(), columns, 
&options)?;
+            let taken = if compact {
+                gc_view_arrays(&taken)?

Review Comment:
   `gc_view_arrays` runs with `dictionaries=false`. It only shrinks a 
dictionary that has more values than rows, so after `take` each partition batch 
still holds every value of the input's dictionary and is charged for all of 
them.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;

Review Comment:
   The unshared path calls `take_arrays` once per output partition instead of 
once per batch. Allocations and kernel calls grow with partitions times 
columns, and the PR only measured 8 partitions with 2 columns.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -2871,6 +2970,61 @@ mod tests {
         );
     }
 
+    #[test]
+    fn unshared_output_charges_each_partition_for_its_own_rows() -> Result<()> 
{

Review Comment:
   The new tests only cover hash partitioning of Int64 + Utf8View. Nothing 
tests the Range partitioning path that now calls `partition_take`, dictionary 
or nested columns, or the all-rows-to-one-partition branch.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;
+            let options =
+                
RecordBatchOptions::new().with_row_count(Some(indices_array.len()));
+            let taken =
+                RecordBatch::try_new_with_options(batch.schema(), columns, 
&options)?;
+            let taken = if compact {
+                gc_view_arrays(&taken)?
+            } else {

Review Comment:
   Preserve sharing between repeated string views during compaction



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -2871,6 +2970,61 @@ mod tests {
         );
     }
 
+    #[test]
+    fn unshared_output_charges_each_partition_for_its_own_rows() -> Result<()> 
{
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k", DataType::Int64, false),
+            Field::new("s", DataType::Utf8View, false),
+        ]));
+        let batch = RecordBatch::try_new(
+            Arc::clone(&schema),
+            vec![
+                Arc::new(Int64Array::from_iter_values(0..8192)),
+                Arc::new(StringViewArray::from_iter_values(
+                    (0..8192).map(|i| format!("{}{i}", "x".repeat(100))),
+                )),
+            ],
+        )?;
+        let input_size = get_record_batch_memory_size(&batch);
+
+        let metrics = ExecutionPlanMetricsSet::new();
+        let timer = MetricBuilder::new(&metrics).subset_time("test", 0);
+        let partition = |unshared: bool| -> Result<Vec<(usize, RecordBatch)>> {
+            let mut partitioner = BatchPartitioner::new_hash_partitioner(
+                vec![col("k", &schema)?],
+                8,
+                timer.clone(),
+            )?;
+            if unshared {
+                partitioner = partitioner.with_unshared_output();
+            }
+            partitioner.partition_iter(batch.clone())?.collect()
+        };
+        let total_size = |outputs: &[(usize, RecordBatch)]| -> usize {
+            outputs
+                .iter()
+                .map(|(_, batch)| get_record_batch_memory_size(batch))
+                .sum()
+        };
+
+        let shared = partition(false)?;
+        let unshared = partition(true)?;
+        assert_eq!(shared.len(), 8);
+        assert_eq!(shared, unshared);

Review Comment:
   Make the memory test independent of hash collisions. With the workspace's 
`force_hash_collisions` feature, `hash_single_array` writes zero for every row. 
All 8,192 rows therefore go to one partition, both partitioners take the 
whole-batch shortcut, and this assertion fails. Use explicit routing indices or 
a range partitioner with fixed split points for the memory comparison; that 
keeps the test meaningful in the collision build rather than just skipping it.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1393,6 +1474,18 @@ impl BatchPartitioner {
     }
 }
 
+/// Whether an array of `data_type` can hold anything [`gc_view_arrays`] 
compacts
+fn may_compact(data_type: &DataType) -> bool {

Review Comment:
   may_compact` re-implements `sorted_copy_keeps_buffers` from `sorts/sort.rs`, 
only less precisely. It returns true for every nested type, including 
List<Int64> and Struct<Int32>, which hold nothing the GC can shrink.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;
+            let options =
+                
RecordBatchOptions::new().with_row_count(Some(indices_array.len()));
+            let taken =
+                RecordBatch::try_new_with_options(batch.schema(), columns, 
&options)?;
+            let taken = if compact {
+                gc_view_arrays(&taken)?

Review Comment:
   Prune unused dictionary values after partitioning



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;
+            let options =
+                
RecordBatchOptions::new().with_row_count(Some(indices_array.len()));
+            let taken =
+                RecordBatch::try_new_with_options(batch.schema(), columns, 
&options)?;

Review Comment:
   This repeats the take-and-rebuild sequence from `partition_grouped_take`. 
Arrow's existing `take_record_batch` preserves the schema and zero-column row 
count, and checks the indices once for the batch instead of dispatching checked 
takes separately for every column. Using it here avoids maintaining a second 
implementation of that sequence on the new per-partition hot path.



##########
datafusion/sqllogictest/test_files/repartition_preserve_order_memory.slt:
##########
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: Apache-2.0
+# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under 
one or more contributor license agreements
+
+# https://github.com/apache/datafusion/issues/27323
+#
+# A streaming window over a file sorted by k reads an order-preserving hash
+# repartition, which merges what each input sends to its output partition.
+# Each output partition must hold only its own rows. Otherwise every merge is
+# charged for the rows and strings of all output partitions, and runs out of
+# memory under the limit below.
+
+statement ok
+SET datafusion.execution.target_partitions = 8
+
+# Split the small file into 8 scan partitions, so that 8 inputs are merged
+statement ok
+SET datafusion.optimizer.repartition_file_min_size = 1024

Review Comment:
   Write multiple row groups for the multi-input merge test



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;
+            let options =
+                
RecordBatchOptions::new().with_row_count(Some(indices_array.len()));
+            let taken =
+                RecordBatch::try_new_with_options(batch.schema(), columns, 
&options)?;
+            let taken = if compact {
+                gc_view_arrays(&taken)?

Review Comment:
   Base view compaction on retained memory, not spill size



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));

Review Comment:
   Precompute which output columns can benefit from GC. Compute eligible column 
indices once from the stream schema and share the recursive type classification 
with `sorted_copy_keeps_buffers` where applicable.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1200,6 +1207,18 @@ impl BatchPartitioner {
         }
     }
 
+    /// Give each output batch its own buffers, instead of a slice of one batch
+    /// shared by all outputs.
+    ///
+    /// A batch is charged for every buffer it references, so a shared slice
+    /// is charged for the whole input. That matters when the consumer holds on
+    /// to batches, like the merge of an order-preserving [`RepartitionExec`].
+    /// The cost is copying the strings of view arrays.
+    pub(crate) fn with_unshared_output(mut self) -> Self {

Review Comment:
   Keep the partitioner mode setter private



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -2871,6 +2970,61 @@ mod tests {
         );
     }
 
+    #[test]
+    fn unshared_output_charges_each_partition_for_its_own_rows() -> Result<()> 
{
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("k", DataType::Int64, false),
+            Field::new("s", DataType::Utf8View, false),
+        ]));
+        let batch = RecordBatch::try_new(
+            Arc::clone(&schema),
+            vec![
+                Arc::new(Int64Array::from_iter_values(0..8192)),
+                Arc::new(StringViewArray::from_iter_values(
+                    (0..8192).map(|i| format!("{}{i}", "x".repeat(100))),
+                )),
+            ],
+        )?;
+        let input_size = get_record_batch_memory_size(&batch);
+
+        let metrics = ExecutionPlanMetricsSet::new();
+        let timer = MetricBuilder::new(&metrics).subset_time("test", 0);
+        let partition = |unshared: bool| -> Result<Vec<(usize, RecordBatch)>> {
+            let mut partitioner = BatchPartitioner::new_hash_partitioner(
+                vec![col("k", &schema)?],
+                8,
+                timer.clone(),
+            )?;
+            if unshared {
+                partitioner = partitioner.with_unshared_output();
+            }
+            partitioner.partition_iter(batch.clone())?.collect()
+        };
+        let total_size = |outputs: &[(usize, RecordBatch)]| -> usize {
+            outputs
+                .iter()
+                .map(|(_, batch)| get_record_batch_memory_size(batch))
+                .sum()
+        };
+
+        let shared = partition(false)?;
+        let unshared = partition(true)?;
+        assert_eq!(shared.len(), 8);
+        assert_eq!(shared, unshared);
+
+        assert!(
+            total_size(&shared) > 7 * input_size,
+            "{} vs input {input_size}",
+            total_size(&shared)
+        );

Review Comment:
   Test the ordered memory bound without requiring overcharging



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {

Review Comment:
   When all rows of a batch go to one partition, the input batch is sent as is 
with no compaction. That breaks the 'give each output batch its own buffers' 
rule `with_unshared_output` documents, on the path that sorted input hits most.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch

Review Comment:
   `compact` is recomputed from the schema for every input batch, though the 
schema is fixed for the stream. It could be computed once when 
`with_unshared_output` is set up, for example from `stream.schema()` in 
`pull_from_input`.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -2311,6 +2406,9 @@ impl RepartitionExec {
                 num_input_partitions,
             )?,
         };
+        if preserve_order {
+            partitioner = partitioner.with_unshared_output();
+        }

Review Comment:
   Keep the grouped take available for unlimited memory pools



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;
+            }
+            if p_indices.len() == batch.num_rows() {
+                p_indices.clear();
+                batches.push(Ok((partition, batch.clone())));
+                continue;
+            }
+
+            let indices_array =
+                
PrimitiveArray::<UInt32Type>::from_iter_values(p_indices.drain(..));
+            let columns = take_arrays(batch.columns(), &indices_array, None)?;

Review Comment:
   Gather only the reachable children of ListView outputs



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########
@@ -1327,6 +1354,60 @@ impl BatchPartitioner {
         }
     }
 
+    fn partition_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+        unshared_output: bool,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        if unshared_output {
+            Self::partition_unshared_take(batch, indices, timer)
+        } else {
+            Self::partition_grouped_take(batch, indices, timer)
+        }
+    }
+
+    /// Like [`Self::partition_grouped_take`], but takes each partition
+    /// separately. See [`Self::with_unshared_output`].
+    fn partition_unshared_take(
+        batch: &RecordBatch,
+        indices: &mut [Vec<u32>],
+        timer: &metrics::Time,
+    ) -> Result<Vec<Result<(usize, RecordBatch)>>> {
+        let _timer = timer.timer();
+        let compact = batch
+            .schema()
+            .fields()
+            .iter()
+            .any(|field| may_compact(field.data_type()));
+        let mut batches = vec![];
+        for (partition, p_indices) in indices.iter_mut().enumerate() {
+            if p_indices.is_empty() {
+                continue;

Review Comment:
   Skip takes for outputs whose receivers have closed.Pass the active outputs 
into the unshared take or defer materialization until the caller knows the 
output still has a receiver.



##########
datafusion/physical-plan/src/repartition/mod.rs:
##########


Review Comment:
   
https://github.com/apache/datafusion/blob/a38c2d84b2ee7f604ece1a14b694ae82ececeb59/datafusion/physical-plan/src/repartition/mod.rs#L2438
   
   `partition_iter` takes and compacts every partition, including those whose 
receiver has hung up and been removed from `output_channels`. The unshared path 
now copies strings for output that is thrown away.



-- 
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