use std::sync::Arc;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{Result, internal_err};
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::MemoryReservation;
use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use futures::StreamExt;
use super::aggregate_hash_table::ClusteredAggregateTableMetrics;
use super::clustered_final_stream::ClusteredFinalAggregateStream;
use super::order::GroupClusteringMode;
use super::{AggregateExec, AggregateMode};
use crate::SendableRecordBatchStream;
use crate::metrics::{BaselineMetrics, SpillMetrics};
use crate::sorts::IncrementalSortIterator;
use crate::sorts::streaming_merge::{SortedSpillFile, StreamingMergeBuilder};
use crate::spill::gc_nested_arrays;
use crate::spill::spill_manager::SpillManager;
use crate::stream::RecordBatchStreamAdapter;
const SPILL_BATCH_TARGET_BYTES: usize = 1024 * 1024;
pub(super) struct AggregateSpill {
replay_agg: AggregateExec,
context: Arc<TaskContext>,
partition: usize,
batch_size: usize,
spill_expr: LexOrdering,
spill_manager: SpillManager,
spills: Vec<SortedSpillFile>,
min_spill_batch_rows: usize,
label: &'static str,
}
impl AggregateSpill {
#[expect(clippy::too_many_arguments)]
pub(super) fn try_new(
label: &'static str,
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
batch_size: usize,
group_clustering_mode: &GroupClusteringMode,
spill_schema: &SchemaRef,
spill_metrics: SpillMetrics,
) -> Result<Self> {
let mut replay_agg = agg.clone();
replay_agg.group_clustering_mode = GroupClusteringMode::Full;
let group_schema = match agg.mode {
AggregateMode::Final | AggregateMode::FinalPartitioned => {
agg.group_by().group_schema(spill_schema)?
}
AggregateMode::Single | AggregateMode::SinglePartitioned => {
replay_agg.mode = if agg.mode == AggregateMode::Single {
AggregateMode::Final
} else {
AggregateMode::FinalPartitioned
};
*replay_agg.group_by_mut() = Arc::new(agg.group_by().as_final());
agg.group_by().group_schema(&agg.input().schema())?
}
mode => {
return internal_err!("{label}: cannot replay aggregate mode {mode:?}");
}
};
let num_group_columns = group_schema.fields().len();
let contiguous_indices: &[usize] = match group_clustering_mode {
GroupClusteringMode::None => &[],
GroupClusteringMode::Partial(contiguous_indices) => contiguous_indices,
GroupClusteringMode::Full => {
return internal_err!("{label}: fully contiguous groups do not spill");
}
};
let spill_indices = contiguous_indices.iter().copied().chain(
(0..num_group_columns).filter(|idx| !contiguous_indices.contains(idx)),
);
let output_ordering = agg.cache.output_ordering();
let spill_sort_exprs = spill_indices.map(|idx| {
let output_expr = Column::new(group_schema.field(idx).name(), idx);
let sort_options = output_ordering
.and_then(|ordering| ordering.get_sort_options(&output_expr))
.unwrap_or_default();
PhysicalSortExpr::new(Arc::new(output_expr), sort_options)
});
let Some(spill_expr) = LexOrdering::new(spill_sort_exprs) else {
return internal_err!("{label}: spill expression is empty");
};
let spill_manager = SpillManager::new(
context.runtime_env(),
spill_metrics,
Arc::clone(spill_schema),
)
.with_compression_type(context.session_config().spill_compression());
Ok(Self {
replay_agg,
context: Arc::clone(context),
partition,
batch_size,
spill_expr,
spill_manager,
spills: vec![],
min_spill_batch_rows: batch_size,
label,
})
}
pub(super) fn has_spills(&self) -> bool {
!self.spills.is_empty()
}
pub(super) fn sort_and_spill(
&mut self,
state_batch: Option<RecordBatch>,
) -> Result<()> {
let Some(state_batch) = state_batch else {
return Ok(());
};
let mut max_batch_rows = 0;
let sorted_iter = IncrementalSortIterator::new(
state_batch,
self.spill_expr.clone(),
self.batch_size,
)
.with_max_batch_bytes(SPILL_BATCH_TARGET_BYTES)
.inspect(|batch| {
if let Ok(batch) = batch {
max_batch_rows = max_batch_rows.max(batch.num_rows());
}
});
let spill_file = self
.spill_manager
.spill_record_batch_iter_and_return_max_batch_memory(
sorted_iter,
self.label,
)?;
let Some((file, max_record_batch_memory)) = spill_file else {
return internal_err!("{}: produced an empty spill", self.label);
};
self.spills.push(SortedSpillFile {
file,
max_record_batch_memory,
});
self.min_spill_batch_rows = self.min_spill_batch_rows.min(max_batch_rows);
Ok(())
}
pub(super) fn spill_output(
&self,
schema: SchemaRef,
batches: impl Iterator<Item = Result<RecordBatch>>,
) -> Result<SendableRecordBatchStream> {
let spill_manager = SpillManager::new(
self.context.runtime_env(),
self.spill_manager.metrics.clone(),
schema,
)
.with_compression_type(self.spill_manager.compression);
let spill_file = spill_manager
.spill_record_batch_iter_and_return_max_batch_memory(batches, self.label)?;
let Some((file, max_record_batch_memory)) = spill_file else {
return internal_err!("{}: produced an empty output spill", self.label);
};
spill_manager.read_spill_as_stream(file, Some(max_record_batch_memory))
}
pub(super) fn into_replay_stream(
self,
baseline_metrics: &BaselineMetrics,
metrics: ClusteredAggregateTableMetrics,
reservation: MemoryReservation,
) -> Result<SendableRecordBatchStream> {
let Self {
replay_agg,
context,
partition,
batch_size,
spill_expr,
spill_manager,
spills,
min_spill_batch_rows,
label: _,
} = self;
let spill_schema = Arc::clone(spill_manager.schema());
let merge_reservation = reservation.new_empty();
let merged = StreamingMergeBuilder::new()
.with_schema(spill_schema)
.with_spill_manager(spill_manager)
.with_sorted_spill_files(spills)
.with_expressions(&spill_expr)
.with_metrics(baseline_metrics.intermediate())
.with_batch_size(batch_size)
.with_max_batch_bytes(Some(SPILL_BATCH_TARGET_BYTES))
.with_reservation(merge_reservation)
.with_replay_headroom()
.with_intermediate_merge_sizing(Some(min_spill_batch_rows))
.build()?;
let merged: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new(
merged.schema(),
merged.map(|batch| gc_nested_arrays(&batch?)),
));
let replay = ClusteredFinalAggregateStream::new_with_input_and_metrics(
&replay_agg,
&context,
partition,
merged,
&GroupClusteringMode::Full,
baseline_metrics.clone(),
metrics,
None,
reservation,
)?;
Ok(replay.into_stream())
}
}