1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// 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
//! Final aggregate stream for partial-state input with group-clustering
//! guarantees.
use std::sync::Arc;
use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_execution::{TaskContext, TryEmitter, async_try_stream};
use futures::stream::StreamExt;
use super::AggregateExec;
use super::aggregate_hash_table::{
ClusteredAggregateTable, ClusteredAggregateTableMetrics, FinalMarker,
};
use super::order::GroupClusteringMode;
use super::spill::AggregateSpill;
use crate::SendableRecordBatchStream;
use crate::aggregates::AggregateMode;
use crate::metrics::{BaselineMetrics, SpillMetrics};
use crate::stream::{ObservedStream, RecordBatchStreamAdapter};
/// Final aggregate stream for [`GroupClusteringMode::Partial`] and
/// [`GroupClusteringMode::Full`].
///
/// See comments at [`super::clustered_partial_stream::ClusteredPartialAggregateStream`] for details.
///
/// # Spilling
///
/// This section is only for implementation notes, for background, see [`super::clustered_partial_stream::ClusteredPartialAggregateStream`]
///
/// For partial group clustering, spilling works as follows:
///
/// - Reserve the table footprint plus one `u32` sort index per buffered group. The
/// extra index array is used in later sorting before spilling.
/// - On memory pressure, materialize all group states into one batch.
/// - Use [`IncrementalSortIterator`](crate::sorts::IncrementalSortIterator) to compute the full-batch index, then
/// materialize and write one sorted slice at a time. The original batch and
/// full index remain live until the run is written.
/// - After input ends, merge the sorted runs and replay them through a fully
/// ordered final aggregate stream.
pub(crate) struct ClusteredFinalAggregateStream {
reservation: MemoryReservation,
context: ClusteredFinalAggregateContext,
stage: ExecutionStage,
}
/// Execution stages described in [`ClusteredFinalAggregateStream::into_stream`].
enum ExecutionStage {
Aggregating(Aggregating),
Outputting(Outputting),
MergingSpills(SendableRecordBatchStream),
}
struct Aggregating {
input: SendableRecordBatchStream,
table: ClusteredAggregateTable<FinalMarker>,
/// None when temporary files are disabled or group clustering is full.
spill_context: Option<Box<AggregateSpill>>,
}
struct Outputting {
/// Materialized final results, emitted in slices of `batch_size` rows.
batch: RecordBatch,
/// Aggregation stage to resume after output; `None` after EOF.
resume: Option<Aggregating>,
}
/// Immutable execution context shared by aggregation and output emission.
struct ClusteredFinalAggregateContext {
schema: SchemaRef,
batch_size: usize,
baseline_metrics: BaselineMetrics,
}
impl ClusteredFinalAggregateStream {
pub fn new(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
) -> Result<Self> {
debug_assert!(matches!(
agg.mode,
AggregateMode::Final | AggregateMode::FinalPartitioned
));
debug_assert_ne!(agg.group_clustering_mode, GroupClusteringMode::None);
let input = agg.input.execute(partition, Arc::clone(context))?;
Self::new_with_input(agg, context, partition, input, &agg.group_clustering_mode)
}
pub(in crate::aggregates) fn new_with_input(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
input: SendableRecordBatchStream,
group_clustering_mode: &GroupClusteringMode,
) -> Result<Self> {
let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);
let metrics = ClusteredAggregateTableMetrics::new(agg, partition);
let spill_metrics = SpillMetrics::new(&agg.metrics, partition);
let reservation =
MemoryConsumer::new(format!("ClusteredFinalAggregateStream[{partition}]"))
// HACK: Full group clustering uses a non-spilling execution
// path. There is a known race
// condition bug, and we set it to spillable to let it have larger
// memory budget to suppress the bug.
// Bug issue: https://github.com/apache/datafusion/issues/17334
.with_can_spill(true)
.register(context.memory_pool());
Self::new_with_input_and_metrics(
agg,
context,
partition,
input,
group_clustering_mode,
baseline_metrics,
metrics,
Some(spill_metrics),
reservation,
)
}
#[expect(
clippy::too_many_arguments,
reason = "keeps replay metric reuse explicit"
)]
/// Builds the stream with the reservation of its logical aggregate operator.
/// Replay callers pass a sibling of the reservation used by the merge input,
/// keeping both components under one memory-consumer registration.
pub(in crate::aggregates) fn new_with_input_and_metrics(
agg: &AggregateExec,
context: &Arc<TaskContext>,
partition: usize,
input: SendableRecordBatchStream,
group_clustering_mode: &GroupClusteringMode,
baseline_metrics: BaselineMetrics,
metrics: ClusteredAggregateTableMetrics,
spill_metrics: Option<SpillMetrics>,
reservation: MemoryReservation,
) -> Result<Self> {
debug_assert!(matches!(
agg.mode,
AggregateMode::Final | AggregateMode::FinalPartitioned
));
debug_assert_ne!(*group_clustering_mode, GroupClusteringMode::None);
let schema = Arc::clone(&agg.schema);
let input_schema = input.schema();
let batch_size = context.session_config().batch_size();
let can_spill = matches!(group_clustering_mode, GroupClusteringMode::Partial(_))
&& context.runtime_env().disk_manager.tmp_files_enabled();
let spill_context = if can_spill {
let Some(spill_metrics) = spill_metrics else {
return internal_err!(
"Spillable clustered final stream requires metrics"
);
};
Some(Box::new(AggregateSpill::try_new(
"ClusteredFinalAggregateSpill",
agg,
context,
partition,
batch_size,
group_clustering_mode,
&input_schema,
spill_metrics,
)?))
} else {
None
};
let table = ClusteredAggregateTable::<FinalMarker>::new_with_group_clustering(
agg,
&input_schema,
Arc::clone(&schema),
group_clustering_mode,
metrics,
)?;
// Reserve memory for the initial hash table. that we hold for the lifetime of the stream.
reservation.try_grow(table.memory_size())?;
Ok(Self {
reservation,
context: ClusteredFinalAggregateContext {
schema,
batch_size,
baseline_metrics,
},
stage: ExecutionStage::Aggregating(Aggregating {
input,
table,
spill_context,
}),
})
}
/// Entry point for the clustered final aggregate execution stages.
///
/// See [`ClusteredFinalAggregateStream`] for high-level ideas.
///
/// # Stage transition graph:
///
/// ```text
/// +----[2]----+ +----[5]----+
/// | | | |
/// v | v |
/// +-------------------+ +------------------+
/// | | | |
/// (start)-[1]->| Aggregating |---[3]-->| Outputting |
/// | |<--[6]---| |
/// +-------------------+ +------------------+
/// | | |
/// [8] +------[4]-----+ [7]
/// | | |
/// v v v
/// +-------------------+ +------------------+
/// | | | |
/// +--->| MergingSpills |---[10-->| Done |-[11]->(end)
/// | | | | |
/// | +-------------------+ +------------------+
/// | |
/// +-----[9]------+
/// ```
///
/// ## Stages
///
/// - [`Aggregating`]: Aggregate input batches.
/// - [`Outputting`]: Handle materialzing all aggregated input.
/// - [`ExecutionStage::MergingSpills`]: If OOM and spilled before, use this
/// stage to finish execution.
///
/// ### Incremental output
///
/// See the [clustered partial aggregate notes] for details.
///
/// [clustered partial aggregate notes]: super::clustered_partial_stream::ClusteredPartialAggregateStream::into_stream
///
/// ## Transition Edges
///
/// 1. Start.
/// 2. Merge one input batch:
/// - If memory fits and no groups are complete, continue reading input.
/// - If OOM with a spill context, spill.
/// - If OOM without one, emit the completed groups (edge 3), or return
/// the error when no group is complete.
/// 3. Prepare output:
/// - Before any spill, a prefix of groups is complete: materialize the
/// entire prefix once, retaining the input and active groups to resume
/// aggregation.
/// - At EOF without spills, materialize all remaining results and prepare
/// to output.
/// 4. Input was exhausted, directly end.
/// 5. Incremental output at `batch_size`
/// 6. The batch was fully emitted and retained aggregation can resume.
/// 7. The output batch was fully emitted.
/// 8. Input was exhausted after spilling.
/// 9. Incremental output during reading spill and finalizing results.
/// 10. The merged spill input was fully aggregated and emitted.
/// 11. End.
pub(crate) fn into_stream(self) -> SendableRecordBatchStream {
let Self {
reservation,
context,
stage,
} = self;
let schema = Arc::clone(&context.schema);
let metrics = context.baseline_metrics.clone();
let stream = async_try_stream(|mut emitter| async move {
let mut stage = Some(stage);
while let Some(current_stage) = stage {
stage = match current_stage {
ExecutionStage::Aggregating(aggregating) => {
aggregating.handle_stage(&context, &reservation).await?
}
ExecutionStage::Outputting(outputting) => {
outputting
.handle_stage(&context, &reservation, &mut emitter)
.await?
}
ExecutionStage::MergingSpills(mut stream) => {
while let Some(batch) = stream.next().await.transpose()? {
emitter.emit(batch).await;
}
None
}
};
}
Ok(())
});
let stream = Box::pin(RecordBatchStreamAdapter::new(schema, stream));
Box::pin(ObservedStream::new(stream, metrics, None))
}
}
impl Aggregating {
/// Reserve the table footprint and, when spillable, one sort index per group.
fn reservation_size(&self) -> usize {
let table_size = self.table.memory_size();
if self.spill_context.is_some() {
// See `ClusteredFinalAggregateStream` for the spill memory estimate.
table_size
.saturating_add(self.table.num_groups().saturating_mul(size_of::<u32>()))
} else {
table_size
}
}
/// Merges partial states until final results are ready or spill replay begins.
async fn handle_stage(
mut self,
context: &ClusteredFinalAggregateContext,
reservation: &MemoryReservation,
) -> Result<Option<ExecutionStage>> {
let elapsed_compute = context.baseline_metrics.elapsed_compute();
while let Some(batch) = self.input.next().await.transpose()? {
let timer = elapsed_compute.timer();
self.table.aggregate_batch(&batch)?;
// Check the reservation before taking completed groups, as the partial
// stream does, so spilling is unchanged. Without spilling, the refusal
// is returned below only if no group is complete.
let oom = match reservation.try_resize(self.reservation_size()) {
Ok(()) => None,
Err(oom @ DataFusionError::ResourcesExhausted(_)) => {
match self.spill_context.as_mut() {
None => Some(oom),
Some(spill_context) => {
if self.table.is_empty() {
return Err(oom);
}
spill_context
.sort_and_spill(self.table.take_state_batch()?)?;
reservation.try_resize(self.table.memory_size()).map_err(
|e| {
e.context(
"Decreasing allocation after spilling should succeed",
)
},
)?;
continue;
}
}
}
Err(e) => return Err(e),
};
if self.spill_context.as_ref().is_some_and(|s| s.has_spills()) {
// Spilled groups may recur, so all remaining states must go
// through replay before any more final results can be emitted.
continue;
}
let Some(batch) = self.table.take_completed_result_batch()? else {
match oom {
Some(oom) => return Err(oom),
None => continue,
}
};
if oom.is_some() {
// Release the capacity the table grew for this batch so that
// reserving the remaining groups can succeed.
self.table.shrink_to_fit();
}
timer.done();
return Ok(Some(ExecutionStage::Outputting(Outputting {
batch,
resume: Some(self),
})));
}
// Release upstream resources before materializing output or replaying spills.
drop(self.input);
let timer = elapsed_compute.timer();
if let Some(mut spill_context) = self.spill_context.filter(|s| s.has_spills()) {
spill_context.sort_and_spill(self.table.take_state_batch()?)?;
let metrics = self.table.metrics();
drop(self.table);
reservation.try_resize(0)?;
// The outer ObservedStream counts output; replay only shares compute time.
let stream = (*spill_context).into_replay_stream(
&context.baseline_metrics.intermediate(),
metrics,
reservation.new_empty(),
)?;
timer.done();
return Ok(Some(ExecutionStage::MergingSpills(stream)));
}
self.table.input_done();
let output = self.table.take_completed_result_batch()?;
drop(self.table);
timer.done();
let Some(batch) = output else {
reservation.try_resize(0)?;
return Ok(None);
};
Ok(Some(ExecutionStage::Outputting(Outputting {
batch,
resume: None,
})))
}
}
impl Outputting {
/// Emits slices of one materialized batch without touching the aggregate table.
async fn handle_stage(
self,
context: &ClusteredFinalAggregateContext,
reservation: &MemoryReservation,
emitter: &mut TryEmitter<RecordBatch, DataFusionError>,
) -> Result<Option<ExecutionStage>> {
let Self { mut batch, resume } = self;
let elapsed_compute = context.baseline_metrics.elapsed_compute();
let mut timer = elapsed_compute.timer();
let (table_memory, next_stage) = match resume {
Some(aggregating) => (
aggregating.reservation_size(),
Some(ExecutionStage::Aggregating(aggregating)),
),
None => (0, None),
};
let batch_memory = batch.get_array_memory_size();
match reservation.try_resize(table_memory + batch_memory) {
Ok(()) => {}
Err(DataFusionError::ResourcesExhausted(_)) => {
// If we cannot hold the batch while slicing, hand it off whole.
reservation.try_resize(table_memory)?;
timer.done();
emitter.emit(batch).await;
return Ok(next_stage);
}
Err(e) => return Err(e),
}
while batch.num_rows() > context.batch_size {
let output = batch.slice(0, context.batch_size);
batch =
batch.slice(context.batch_size, batch.num_rows() - context.batch_size);
timer.done();
emitter.emit(output).await;
timer = elapsed_compute.timer();
}
// The final slice transfers ownership of the buffers to the consumer.
reservation.try_shrink(batch_memory)?;
timer.done();
emitter.emit(batch).await;
Ok(next_stage)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ExecutionPlan;
use crate::aggregates::GroupClusteringMode;
use crate::aggregates::PhysicalGroupBy;
use crate::aggregates::clustered_test_util::{
assert_completed_groups_emitted_under_limit, assert_output_unchanged_under_limit,
assert_resources_exhausted_under_limit, distinct_key_batches, full_batches,
held_memory, single_key_batches, sum_over_sorted_input,
};
use crate::common::collect;
use crate::test::TestMemoryExec;
use arrow::array::{Int64Array, StringViewArray};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_execution::config::SessionConfig;
use datafusion_execution::memory_pool::{GreedyMemoryPool, MemoryPool};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_functions_aggregate::{min_max::min_udaf, sum::sum_udaf};
use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_expr::aggregate::AggregateExprBuilder;
use datafusion_physical_expr::expressions::col;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use futures::channel::mpsc;
use futures::{FutureExt, TryStreamExt};
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
enum Finish {
Collect,
DropDuringMerge,
DropDuringReplay,
InputError,
}
#[tokio::test]
async fn spill_replay_with_another_ordered_partition() -> Result<()> {
for input_batches in [28, 36, 55, 63] {
run_shared_pool_case(input_batches, 600 * 1024, Finish::Collect).await?;
}
// The same input also produces the reference results without spilling.
run_shared_pool_case(63, 10 * 1024 * 1024, Finish::Collect).await
}
#[tokio::test]
async fn spill_replay_releases_memory_on_drop() -> Result<()> {
run_shared_pool_case(36, 600 * 1024, Finish::DropDuringMerge).await?;
run_shared_pool_case(36, 600 * 1024, Finish::DropDuringReplay).await
}
#[tokio::test]
async fn ordered_spill_releases_memory_on_input_error() -> Result<()> {
run_shared_pool_case(36, 600 * 1024, Finish::InputError).await
}
async fn run_shared_pool_case(
input_batches: i64,
limit: usize,
finish: Finish,
) -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("a", DataType::Int64, false),
Field::new("b", DataType::Int64, false),
Field::new("v", DataType::Int64, false),
Field::new("s", DataType::Utf8View, false),
]));
let groups = PhysicalGroupBy::new_single(vec![
(col("a", &schema)?, "a".into()),
(col("b", &schema)?, "b".into()),
]);
let expressions = vec![
Arc::new(
AggregateExprBuilder::new(sum_udaf(), vec![col("v", &schema)?])
.schema(Arc::clone(&schema))
.alias("sum")
.build()?,
),
Arc::new(
AggregateExprBuilder::new(min_udaf(), vec![col("s", &schema)?])
.schema(Arc::clone(&schema))
.alias("min")
.build()?,
),
];
let empty = TestMemoryExec::try_new_exec(&[vec![]], Arc::clone(&schema), None)?;
let partial = AggregateExec::try_new(
AggregateMode::Partial,
groups.clone(),
expressions.clone(),
vec![None; 2],
empty,
Arc::clone(&schema),
)?;
let partial_schema = partial.schema();
let ordering =
LexOrdering::new([PhysicalSortExpr::new_default(col("a", &partial_schema)?)])
.unwrap();
let input = TestMemoryExec::try_new(
&[vec![], vec![]],
Arc::clone(&partial_schema),
None,
)?
.try_with_sort_information(vec![ordering])?;
let aggregate = AggregateExec::try_new(
AggregateMode::FinalPartitioned,
groups.as_final(),
expressions,
vec![None; 2],
Arc::new(TestMemoryExec::update_cache(&Arc::new(input))),
schema,
)?;
assert_eq!(
aggregate.group_clustering_mode(),
&GroupClusteringMode::Partial(vec![0])
);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
let context = Arc::new(
TaskContext::default()
.with_session_config(
SessionConfig::new().with_batch_size(128).set_bool(
"datafusion.execution.enable_migration_aggregate",
true,
),
)
.with_runtime(
RuntimeEnvBuilder::new()
.with_max_spill_merge_fan_in(2)
.with_memory_pool(Arc::clone(&pool))
.build_arc()?,
),
);
let new_stream = |partition| -> Result<_> {
let (sender, receiver) = mpsc::unbounded();
let input = Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(&partial_schema),
receiver,
));
let stream = ClusteredFinalAggregateStream::new_with_input(
&aggregate,
&context,
partition,
input,
&aggregate.group_clustering_mode,
)?;
Ok((sender, stream.into_stream()))
};
let mut expected = BTreeMap::new();
let mut make_batch = |partition: i64, start: i64| {
for value in start..start + 128 {
let entry = expected
.entry((
partition,
if partition == 0 && value % 128 == 0 {
0
} else {
value
},
))
.or_insert_with(|| (0, (value % 2).to_string()));
entry.0 += value * 2;
}
RecordBatch::try_new(
Arc::clone(&partial_schema),
vec![
Arc::new(Int64Array::from(vec![partition; 128])),
Arc::new(Int64Array::from_iter_values((start..start + 128).map(
|value| {
if partition == 0 && value % 128 == 0 {
0
} else {
value
}
},
))),
Arc::new(Int64Array::from_iter_values(
(start..start + 128).map(|v| v * 2),
)),
Arc::new(StringViewArray::from_iter_values(
(start..start + 128).map(|v| if v % 2 == 0 { "0" } else { "1" }),
)),
],
)
.unwrap()
};
// Keep partition 1's incomplete ordered run live while partition 0 spills
// and replays. Channel inputs return Pending after each supplied batch,
// making this interleaving independent of task scheduling.
let (second_sender, mut second) = new_stream(1)?;
for batch in 0..55 {
second_sender
.unbounded_send(Ok(make_batch(1, batch * 128)))
.unwrap();
assert!(second.next().now_or_never().is_none());
}
let held = pool.reserved();
assert!(held > 500 * 1024);
// Created after `held` is measured, since the stream reserves its initial table.
let (first_sender, mut first) = new_stream(0)?;
for batch in 0..input_batches {
// Repeated keys cross spill runs, so replay must merge their sums.
first_sender
.unbounded_send(Ok(make_batch(0, batch * 128)))
.unwrap();
assert!(first.next().now_or_never().is_none());
}
if limit == 600 * 1024 {
assert!(aggregate.metrics().unwrap().spill_count().unwrap() > 0);
}
match finish {
Finish::Collect => {
first_sender.close_channel();
let mut output = collect(first).await?;
assert_eq!(pool.reserved(), held);
second_sender.close_channel();
output.extend(second.by_ref().try_collect::<Vec<_>>().await?);
let mut actual = BTreeMap::new();
for batch in output {
let a = batch
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let b = batch
.column(1)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let sum = batch
.column(2)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let min = batch
.column(3)
.as_any()
.downcast_ref::<StringViewArray>()
.unwrap();
for row in 0..batch.num_rows() {
assert!(
actual
.insert(
(a.value(row), b.value(row)),
(sum.value(row), min.value(row).to_string())
)
.is_none()
);
}
}
assert_eq!(actual, expected);
assert_eq!(
aggregate.metrics().unwrap().spill_count().unwrap() > 0,
limit == 600 * 1024
);
}
Finish::DropDuringMerge => {
first_sender.close_channel();
assert!(first.next().now_or_never().is_none());
drop(first);
}
Finish::DropDuringReplay => {
first_sender.close_channel();
first.next().await.unwrap()?;
assert!(pool.reserved() > held);
drop(first);
assert_eq!(pool.reserved(), held);
}
Finish::InputError => {
first_sender
.unbounded_send(datafusion_common::exec_err!(
"injected input failure"
))
.unwrap();
let error = first.next().await.unwrap().unwrap_err();
assert!(error.to_string().contains("injected input failure"));
assert_eq!(pool.reserved(), held);
drop(first);
}
}
drop(second);
assert_eq!(pool.reserved(), 0);
Ok(())
}
#[tokio::test]
async fn fully_clustered_completed_groups_under_memory_pressure() -> Result<()> {
let plan = sum_over_sorted_input(AggregateMode::Final, &["k"], full_batches())?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_completed_groups_emitted_under_limit(&plan).await
}
/// The limit fits the active group, but not the capacity the table grows
/// for one batch, so the table must release it after the completed groups
/// are emitted.
#[tokio::test]
async fn completed_groups_release_batch_capacity() -> Result<()> {
let plan =
sum_over_sorted_input(AggregateMode::Final, &["k"], distinct_key_batches())?;
assert_eq!(plan.group_clustering_mode(), &GroupClusteringMode::Full);
assert_output_unchanged_under_limit(&plan, 100 * 1024).await
}
/// A single key never completes a group before the input ends. The limit
/// fits only the initial table.
#[tokio::test]
async fn memory_pressure_without_completed_groups() -> Result<()> {
let plan =
sum_over_sorted_input(AggregateMode::Final, &["k"], single_key_batches())?;
let limit = held_memory(&plan).await?;
assert_resources_exhausted_under_limit(&plan, limit).await
}
}