sunchao commented on code in PR #7696:
URL: https://github.com/apache/datafusion-comet/pull/7696#discussion_r4746927463


##########
native/operators/src/sort_input_coalesce.rs:
##########
@@ -0,0 +1,1148 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Combines small input batches before a native sort.
+//!
+//! On its spill path DataFusion's sort merges one stream per buffered batch, 
so thousands of
+//! tiny shuffle blocks make it very slow. Below the in-place threshold the 
sort concatenates its
+//! input itself, so batches pass through until a partition's input reaches 
that threshold. The
+//! gate never closes again, so a sort whose share is below the threshold gets 
a copy it does not
+//! need.
+//!
+//! This sits in front of the sort rather than in the shuffle reader because 
only the sort's merge
+//! cost grows with the number of batches. Arrow's `BatchCoalescer` has no 
byte limit and copies
+//! as batches arrive, and `DecodedBatchCoalescer` takes only flat types, so 
neither lets the held
+//! memory be reserved exactly for any input.
+
+use std::fmt::Formatter;
+use std::sync::Arc;
+
+use arrow::compute::concat_batches;
+use arrow::datatypes::DataType;
+use arrow::record_batch::RecordBatch;
+use datafusion::common::tree_node::TreeNodeRecursion;
+use datafusion::common::utils::memory::get_record_batch_memory_size;
+use datafusion::common::{DataFusionError, Result};
+use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
+use datafusion::execution::{async_try_stream, TaskContext};
+use datafusion::physical_expr::PhysicalExpr;
+use datafusion::physical_plan::execution_plan::CardinalityEffect;
+use datafusion::physical_plan::metrics::{
+    BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, 
MetricsSet, RecordOutput,
+};
+use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+use datafusion::physical_plan::{
+    DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, 
SendableRecordBatchStream,
+};
+use futures::TryStreamExt;
+
+/// The cap is half the in-place threshold because the sort reserves about 
twice a batch's size.
+/// The bounds also keep string and binary offsets far below the i32 limit.
+const MIN_GROUP_BYTES: usize = 64 * 1024;
+const MAX_GROUP_BYTES: usize = 4 * 1024 * 1024;
+
+/// In `sort_small_batches`, combining 512-row batches made a spilling 
single-key sort slower,
+/// while 384 rows or fewer was never slower.
+const MAX_SMALL_BATCH_ROWS: usize = 512;
+
+/// Small batches passed through after a refusal, so a pool under pressure is 
not asked again for
+/// each one.
+const REFUSED_BACKOFF_BATCHES: usize = 64;
+
+#[derive(Debug)]
+pub struct SortInputCoalesceExec {
+    input: Arc<dyn ExecutionPlan>,
+    target_rows: usize,
+    gate_bytes: usize,
+    max_bytes: usize,
+    metrics: ExecutionPlanMetricsSet,
+}
+
+impl SortInputCoalesceExec {
+    /// `gate_bytes` is the sort's in-place threshold.
+    pub fn new(input: Arc<dyn ExecutionPlan>, target_rows: usize, gate_bytes: 
usize) -> Self {
+        Self {
+            input,
+            target_rows: target_rows.max(1),
+            gate_bytes,
+            max_bytes: (gate_bytes / 2).clamp(MIN_GROUP_BYTES, 
MAX_GROUP_BYTES),
+            metrics: ExecutionPlanMetricsSet::new(),
+        }
+    }
+
+    #[cfg(test)]
+    fn with_max_bytes(mut self, max_bytes: usize) -> Self {
+        self.max_bytes = max_bytes;
+        self
+    }
+
+    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
+        &self.input
+    }
+
+    /// The plan below a coalescer, or `plan` itself when it is not one.
+    pub fn unwrap_input(plan: &Arc<dyn ExecutionPlan>) -> &Arc<dyn 
ExecutionPlan> {
+        plan.downcast_ref::<Self>().map_or(plan, Self::input)
+    }
+}
+
+impl DisplayAs for SortInputCoalesceExec {
+    fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> 
std::fmt::Result {
+        write!(
+            f,
+            "CometSortInputCoalesceExec: target_rows={}, gate_bytes={}, 
max_bytes={}",
+            self.target_rows, self.gate_bytes, self.max_bytes
+        )
+    }
+}
+
+impl ExecutionPlan for SortInputCoalesceExec {
+    fn name(&self) -> &str {
+        "CometSortInputCoalesceExec"
+    }
+
+    fn properties(&self) -> &Arc<PlanProperties> {
+        self.input.properties()
+    }
+
+    fn maintains_input_order(&self) -> Vec<bool> {
+        vec![true]
+    }
+
+    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
+        vec![&self.input]
+    }
+
+    fn apply_expressions(
+        &self,
+        _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> 
Result<TreeNodeRecursion>,
+    ) -> Result<TreeNodeRecursion> {
+        Ok(TreeNodeRecursion::Continue)
+    }
+
+    fn cardinality_effect(&self) -> CardinalityEffect {
+        CardinalityEffect::Equal
+    }
+
+    fn with_new_children(
+        self: Arc<Self>,
+        children: Vec<Arc<dyn ExecutionPlan>>,
+    ) -> Result<Arc<dyn ExecutionPlan>> {
+        let [input]: [_; 1] = children.try_into().map_err(|_| {
+            DataFusionError::Internal("Sort input coalescing requires one 
child".into())
+        })?;
+        Ok(Arc::new(Self {
+            input,
+            target_rows: self.target_rows,
+            gate_bytes: self.gate_bytes,
+            max_bytes: self.max_bytes,
+            // Shared, so the copy reports through the node the Spark plan 
registered for its
+            // metrics if a rewrite rebuilds the sort's input.
+            metrics: self.metrics.clone(),
+        }))
+    }
+
+    fn execute(
+        &self,
+        partition: usize,
+        context: Arc<TaskContext>,
+    ) -> Result<SendableRecordBatchStream> {
+        let mut input = self.input.execute(partition, Arc::clone(&context))?;
+        let reservation = 
MemoryConsumer::new(format!("SortInputCoalesceExec[{partition}]"))
+            .register(context.memory_pool());
+        let baseline = BaselineMetrics::new(&self.metrics, partition);
+        let mut grouper = Grouper::new(self, reservation, partition);
+        let stream = async_try_stream(|mut out| async move {
+            while let Some(batch) = input.try_next().await? {
+                // A group that has to go out first is emitted before the new 
batch is held, so
+                // the sort reserves it while this operator holds nothing.
+                let (step, flushed) = {
+                    let _timer = baseline.elapsed_compute().timer();
+                    grouper.prepare(&batch)?
+                };
+                if let Some(batch) = flushed {
+                    (&batch).record_output(&baseline);
+                    out.emit(batch).await;
+                }
+                let ready = {
+                    let _timer = baseline.elapsed_compute().timer();
+                    grouper.add(batch, step)?
+                };
+                for batch in ready.into_iter().flatten() {
+                    (&batch).record_output(&baseline);
+                    out.emit(batch).await;
+                }
+            }
+            let last = {
+                let _timer = baseline.elapsed_compute().timer();
+                grouper.flush()?
+            };
+            if let Some(batch) = last {
+                (&batch).record_output(&baseline);
+                out.emit(batch).await;
+            }
+            Ok(())
+        });
+        Ok(Box::pin(RecordBatchStreamAdapter::new(
+            self.schema(),
+            stream,
+        )))
+    }
+
+    fn metrics(&self) -> Option<MetricsSet> {
+        Some(self.metrics.clone_inner())
+    }
+}
+
+/// Concatenating dictionaries merges their values, which can overflow a small 
key type where
+/// the batches on their own fit. Dictionaries nested in structs, lists and 
maps count too.
+fn has_small_dictionary_keys(batch: &RecordBatch) -> bool {
+    fn small(data_type: &DataType) -> bool {
+        match data_type {
+            DataType::Dictionary(key, value) => {
+                key.primitive_width().is_some_and(|width| width < 4) || 
small(value)
+            }
+            DataType::Struct(fields) => fields.iter().any(|f| 
small(f.data_type())),
+            DataType::List(f)
+            | DataType::LargeList(f)
+            | DataType::ListView(f)
+            | DataType::LargeListView(f)
+            | DataType::FixedSizeList(f, _)
+            | DataType::Map(f, _) => small(f.data_type()),
+            // Run ends count rows, so a small run-end type can overflow too.
+            DataType::RunEndEncoded(run_ends, values) => {
+                run_ends
+                    .data_type()
+                    .primitive_width()
+                    .is_some_and(|width| width < 4)
+                    || small(values.data_type())
+            }
+            _ => false,
+        }
+    }
+    batch.schema().fields().iter().any(|f| small(f.data_type()))
+}
+
+/// The bytes the batch's rows take, without unused buffer capacity, as 
DataFusion's sort counts
+/// it.
+fn sliced_size(batch: &RecordBatch) -> Result<usize> {
+    batch.columns().iter().try_fold(0usize, |total, column| {
+        Ok(total + column.to_data().get_slice_memory_size()?)
+    })
+}
+
+/// `held` is what a batch keeps alive, counting a shared buffer once. `copy` 
is what concatenating
+/// it writes, which counts a buffer once per column that uses it.
+#[derive(Clone, Copy)]
+struct Size {
+    held: usize,
+    copy: usize,
+}
+
+enum Step {
+    Skip,
+    PassThrough,
+    Hold(Size),
+}
+
+/// Groups whole input batches in arrival order and concatenates each group. 
Inputs are never
+/// split, so the reservation always covers the batches being held.
+struct Grouper {
+    target_rows: usize,
+    small_rows: usize,
+    gate_bytes: usize,
+    max_bytes: usize,
+    seen_bytes: usize,
+    past_gate: bool,
+    pending: Vec<RecordBatch>,
+    rows: usize,
+    held: usize,
+    copy: usize,
+    reservation: MemoryReservation,
+    backoff: usize,
+    input_batches: Count,
+    output_batches: Count,
+}
+
+impl Grouper {
+    fn new(exec: &SortInputCoalesceExec, reservation: MemoryReservation, 
partition: usize) -> Self {
+        let metrics = MetricBuilder::new(&exec.metrics);
+        Self {
+            target_rows: exec.target_rows,
+            small_rows: exec.target_rows.div_ceil(2).min(MAX_SMALL_BATCH_ROWS),
+            gate_bytes: exec.gate_bytes,
+            max_bytes: exec.max_bytes,
+            seen_bytes: 0,
+            past_gate: exec.gate_bytes == 0,
+            pending: Vec::new(),
+            rows: 0,
+            held: 0,
+            copy: 0,
+            reservation,
+            backoff: 0,
+            input_batches: metrics
+                .clone()
+                .counter("coalesced_input_batches", partition),
+            output_batches: metrics.counter("coalesced_output_batches", 
partition),
+        }
+    }
+
+    /// Decides what `add` does with `batch`. Returns the held group too when 
it has to go out
+    /// first: before a batch that passes through, or before one that does not 
fit in the group.
+    fn prepare(&mut self, batch: &RecordBatch) -> Result<(Step, 
Option<RecordBatch>)> {
+        let rows = batch.num_rows();
+        if rows == 0 {
+            return Ok((Step::Skip, None));
+        }
+        // A small slice of a large batch is held by its whole buffer, so it 
passes through.
+        let size = if !self.past_gate {
+            // Counted as DataFusion's `get_reserved_bytes_for_record_batch` 
counts it, which the
+            // sort compares with the threshold.
+            self.seen_bytes = self
+                .seen_bytes
+                .saturating_add(get_record_batch_memory_size(batch) + 
sliced_size(batch)?);
+            self.past_gate = self.seen_bytes >= self.gate_bytes;
+            None
+        } else if rows >= self.small_rows || has_small_dictionary_keys(batch) {
+            None
+        } else if self.backoff > 0 {
+            self.backoff -= 1;
+            None
+        } else {
+            Some(Size {
+                held: get_record_batch_memory_size(batch),
+                copy: sliced_size(batch)?,
+            })
+        };
+        match size.filter(|size| size.held.max(size.copy) <= self.max_bytes) {
+            Some(size) => {
+                // A batch with another schema starts a new group, since the 
concat needs one.
+                let fits = rows <= self.target_rows - self.rows
+                    && size.copy <= self.max_bytes - self.copy

Review Comment:
   `fits` caps the cumulative copy bytes, but checks held bytes only per input. 
With a 512 KiB cap I fed it 16 one-row Int32 slices from distinct 256 KiB 
buffers. One pending group held 4,194,304 bytes for 64 bytes of rows and 
reserved 4,194,368 bytes. This is a non-spillable reservation, so it reduces 
the fair share available to upstream spillable operators until a flush or 
refusal. Could we check `size.held <= self.max_bytes - self.held` here too, and 
test that a third such slice flushes the first two? The current per-input check 
accepts all three.
   
   I tried that extra condition locally with the locked dependencies. Peak 
reservation on the 16-slice input fell from 4,194,368 to 524,296 bytes (512 KiB 
held plus 8 bytes copied), with all 24 existing coalescer tests passing.



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