datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
Documentation
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
// 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

use crate::sorts::cursor::{ArrayValues, CursorArray, RowValues};
use crate::spill::gc_columns;
use crate::spill::spilled_row_sizes::SpilledRowSizes;
use crate::{EmptyRecordBatchStream, SendableRecordBatchStream};
use crate::{PhysicalExpr, PhysicalSortExpr};
use arrow::array::{Array, UInt32Array};
use arrow::compute::take_record_batch;
use arrow::datatypes::Schema;
use arrow::record_batch::RecordBatch;
use arrow::row::{RowConverter, Rows, SortField};
use arrow_ord::sort::lexsort_to_indices;
use datafusion_common::{Result, internal_datafusion_err};
use datafusion_execution::memory_pool::MemoryReservation;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
use futures::stream::{Fuse, StreamExt};
use std::iter::FusedIterator;
use std::marker::PhantomData;
use std::mem;
use std::sync::Arc;
use std::task::{Context, Poll, ready};

/// A [`Stream`](futures::Stream) that has multiple partitions that can
/// be polled separately but not concurrently
///
/// Used by sort preserving merge to decouple the cursor merging logic from
/// the source of the cursors, the intention being to allow preserving
/// any row encoding performed for intermediate sorts
pub trait PartitionedStream: std::fmt::Debug + Send {
    type Output;

    /// Returns the number of partitions
    fn partitions(&self) -> usize;

    fn poll_next(
        &mut self,
        cx: &mut Context<'_>,
        stream_idx: usize,
    ) -> Poll<Option<Self::Output>>;
}

/// A new type wrapper around a set of fused [`SendableRecordBatchStream`]
/// that implements debug, and skips over empty [`RecordBatch`]
struct FusedStreams(Vec<Fuse<SendableRecordBatchStream>>);

impl std::fmt::Debug for FusedStreams {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FusedStreams")
            .field("num_streams", &self.0.len())
            .finish()
    }
}

impl FusedStreams {
    fn poll_next(
        &mut self,
        cx: &mut Context<'_>,
        stream_idx: usize,
    ) -> Poll<Option<Result<RecordBatch>>> {
        loop {
            let poll_result = self.0[stream_idx].poll_next_unpin(cx);
            match &poll_result {
                Poll::Pending => return Poll::Pending,
                // Skip empty batches
                Poll::Ready(Some(Ok(b))) if b.num_rows() == 0 => {}
                Poll::Ready(Some(Ok(_))) => return poll_result,
                Poll::Ready(None) | Poll::Ready(Some(Err(_))) => {
                    let stream_schema = self.0[stream_idx].get_ref().schema();

                    // Replace the stream with an empty stream, so we can drop memory usage
                    let empty_stream: SendableRecordBatchStream =
                        Box::pin(EmptyRecordBatchStream::new(stream_schema));
                    self.0[stream_idx] = empty_stream.fuse();

                    return poll_result;
                }
            }
        }
    }
}

/// An `Arc<Rows>` that can be reused.
///
/// Owns the reservation covering every retained buffer for as long as it is
/// retained, so the cache is visible to the pool rather than held off-book.
/// A retained buffer keeps its capacity, so the cost is the high-water mark of
/// each stream, not the size of the batch currently in flight.
#[derive(Debug)]
struct ReusableRows {
    inner: Vec<Option<Arc<Rows>>>,
    /// Each stream's charge stays reserved while its buffer is taken for reuse.
    /// The sum of these sizes equals `reservation.size()`.
    reserved_sizes: Vec<usize>,
    reservation: MemoryReservation,
}

impl ReusableRows {
    // return a Rows for writing,
    // does not clone if the existing rows can be reused
    fn take_next(&mut self, stream_idx: usize, converter: &RowConverter) -> Result<Rows> {
        match self.inner[stream_idx].take() {
            Some(rows) => Arc::try_unwrap(rows).map_err(|_| {
                internal_datafusion_err!(
                    "Rows from RowCursorStream is still in use by consumer"
                )
            }),
            // Nothing retained yet, or already released, so start over.
            None => Ok(converter.empty_rows(0, 0)),
        }
    }

    /// Account for a freshly built buffer, and retain it for reuse.
    ///
    /// The reservation is mandatory rather than best-effort. The buffer is live in the
    /// cursor whether or not this slot keeps a handle to it, so declining to reserve
    /// would hide it from the pool instead of avoiding it, and it frees nothing at this
    /// point either, since the cursor holds the same `Arc`. Retention on top of the
    /// reservation is free for the same reason. A pool that cannot cover the buffer
    /// fails the query here, as it did before the buffer was cached at all.
    fn save(&mut self, stream_idx: usize, rows: &Arc<Rows>) -> Result<()> {
        let size = rows.size();
        let retained = self.reservation.size() - self.reserved_sizes[stream_idx] + size;
        debug_assert!(retained >= self.reservation.size());
        if let Err(e) = self.reservation.try_resize(retained) {
            self.release(stream_idx);
            return Err(e);
        }
        self.inner[stream_idx] = Some(Arc::clone(rows));
        self.reserved_sizes[stream_idx] = size;
        Ok(())
    }

    // drop whatever a finished stream was holding
    fn release(&mut self, stream_idx: usize) {
        debug_assert!(self.reservation.size() >= self.retained_size());
        self.inner[stream_idx] = None;
        let reserved = mem::take(&mut self.reserved_sizes[stream_idx]);
        self.reservation.resize(self.reservation.size() - reserved);
        // Verify the incremental accounting against a full recomputation, avoiding
        // the cost of scanning all buffers in release builds.
        debug_assert_eq!(self.reservation.size(), self.retained_size());
    }

    fn retained_size(&self) -> usize {
        self.inner.iter().flatten().map(|rows| rows.size()).sum()
    }
}

/// A [`PartitionedStream`] that wraps a set of [`SendableRecordBatchStream`]
/// and computes [`RowValues`] based on the provided [`PhysicalSortExpr`]
/// Note: the stream returns an error if the consumer buffers even one RowValues (i.e. holds on to one RowValues
/// from the same partition at the same time).
#[derive(Debug)]
pub struct RowCursorStream {
    /// Converter to convert output of physical expressions
    converter: RowConverter,
    /// The physical expressions to sort by
    column_expressions: Vec<Arc<dyn PhysicalExpr>>,
    /// Input streams
    streams: FusedStreams,
    /// Tracks the memory used by `converter`
    reservation: MemoryReservation,
    /// Reused `Rows` allocation for each partition. The consumer must not
    /// buffer the `RowValues` returned for a partition, since the old
    /// `Arc<Rows>` must be dropped before that partition can be polled again.
    rows: ReusableRows,
}

impl RowCursorStream {
    pub fn try_new(
        schema: &Schema,
        expressions: &LexOrdering,
        streams: Vec<SendableRecordBatchStream>,
        reservation: MemoryReservation,
    ) -> Result<Self> {
        let sort_fields = expressions
            .iter()
            .map(|expr| {
                let data_type = expr.expr.data_type(schema)?;
                Ok(SortField::new_with_options(data_type, expr.options))
            })
            .collect::<Result<Vec<_>>>()?;

        let streams: Vec<_> = streams.into_iter().map(|s| s.fuse()).collect();
        let stream_count = streams.len();
        let converter = RowConverter::new(sort_fields)?;
        let rows_reservation = reservation.new_empty();
        Ok(Self {
            converter,
            reservation,
            column_expressions: expressions.iter().map(|x| Arc::clone(&x.expr)).collect(),
            streams: FusedStreams(streams),
            rows: ReusableRows {
                inner: vec![None; stream_count],
                reserved_sizes: vec![0; stream_count],
                reservation: rows_reservation,
            },
        })
    }

    fn convert_batch(
        &mut self,
        batch: &RecordBatch,
        stream_idx: usize,
    ) -> Result<RowValues> {
        let cols = evaluate_expressions_to_arrays(&self.column_expressions, batch)?;

        // At this point, ownership should of this Rows should be unique
        let mut rows = self.rows.take_next(stream_idx, &self.converter)?;

        rows.clear();

        self.converter.append(&mut rows, &cols)?;
        self.reservation.try_resize(self.converter.size())?;

        let rows = Arc::new(rows);

        self.rows.save(stream_idx, &rows)?;

        // `self.rows` now holds the reservation for this buffer unconditionally, and
        // holds it for at least as long as the cursor does. `take_next` cannot reclaim
        // the slot while the consumer still owns the `Arc`, so the cursor is handed an
        // empty reservation rather than accounting for the same bytes a second time.
        Ok(RowValues::new(rows, self.reservation.new_empty()))
    }
}

impl PartitionedStream for RowCursorStream {
    type Output = Result<(RowValues, RecordBatch)>;

    fn partitions(&self) -> usize {
        self.streams.0.len()
    }

    fn poll_next(
        &mut self,
        cx: &mut Context<'_>,
        stream_idx: usize,
    ) -> Poll<Option<Self::Output>> {
        let polled = ready!(self.streams.poll_next(cx, stream_idx));
        if polled.is_none() {
            // The stream is finished, so its retained buffer will never be reused.
            self.rows.release(stream_idx);
        }
        Poll::Ready(polled.map(|r| {
            r.and_then(|batch| {
                let cursor = self.convert_batch(&batch, stream_idx)?;
                Ok((cursor, batch))
            })
        }))
    }
}

/// Specialized stream for sorts on single primitive columns
pub struct FieldCursorStream<T: CursorArray> {
    /// The physical expressions to sort by
    sort: PhysicalSortExpr,
    /// Input streams
    streams: FusedStreams,
    /// Create new reservations for each array
    reservation: MemoryReservation,
    phantom: PhantomData<fn(T) -> T>,
}

impl<T: CursorArray> std::fmt::Debug for FieldCursorStream<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PrimitiveCursorStream")
            .field("num_streams", &self.streams)
            .finish()
    }
}

impl<T: CursorArray> FieldCursorStream<T> {
    pub fn new(
        sort: PhysicalSortExpr,
        streams: Vec<SendableRecordBatchStream>,
        reservation: MemoryReservation,
    ) -> Self {
        let streams = streams.into_iter().map(|s| s.fuse()).collect();
        Self {
            sort,
            streams: FusedStreams(streams),
            reservation,
            phantom: Default::default(),
        }
    }

    fn convert_batch(&mut self, batch: &RecordBatch) -> Result<ArrayValues<T::Values>> {
        let value = self.sort.expr.evaluate(batch)?;
        let array = value.into_array(batch.num_rows())?;
        let size_in_mem = array.get_buffer_memory_size();
        let array = array.as_any().downcast_ref::<T>().expect("field values");
        let array_reservation = self.reservation.new_empty();
        array_reservation.try_grow(size_in_mem)?;
        Ok(ArrayValues::new(
            self.sort.options,
            array,
            array_reservation,
        ))
    }
}

impl<T: CursorArray> PartitionedStream for FieldCursorStream<T> {
    type Output = Result<(ArrayValues<T::Values>, RecordBatch)>;

    fn partitions(&self) -> usize {
        self.streams.0.len()
    }

    fn poll_next(
        &mut self,
        cx: &mut Context<'_>,
        stream_idx: usize,
    ) -> Poll<Option<Self::Output>> {
        Poll::Ready(ready!(self.streams.poll_next(cx, stream_idx)).map(|r| {
            r.and_then(|batch| {
                let cursor = self.convert_batch(&batch)?;
                Ok((cursor, batch))
            })
        }))
    }
}

/// A lazy, memory-efficient sort iterator used as a fallback during aggregate
/// spill when there is not enough memory for an eager sort (which requires ~2x
/// peak memory to hold both the unsorted and sorted copies simultaneously).
///
/// On the first call to `next()`, a sorted index array (`UInt32Array`) is
/// computed via `lexsort_to_indices`. Subsequent calls yield chunks of up to
/// `batch_size` rows, fewer if [`Self::with_max_batch_bytes`] is set, by
/// `take`-ing from the original batch using slices of this index array. Each
/// `take` copies data for the chunk (not zero-copy), but only one chunk is
/// live at a time since the caller consumes it before requesting the next.
/// Once all rows have been yielded, the original batch and index array are
/// dropped to free memory.
///
/// The caller must reserve `sizeof(batch) + sizeof(one chunk)` for this iterator,
/// and free the reservation once the iterator is depleted.
pub(crate) struct IncrementalSortIterator {
    batch: RecordBatch,
    expressions: LexOrdering,
    batch_size: usize,
    /// See [`Self::with_max_batch_bytes`].
    max_batch_bytes: Option<usize>,
    indices: Option<UInt32Array>,
    /// Row sizes of `batch`, measured with `indices` when `max_batch_bytes` is set
    row_sizes: Option<SpilledRowSizes>,
    cursor: usize,
}

impl IncrementalSortIterator {
    pub(crate) fn new(
        batch: RecordBatch,
        expressions: LexOrdering,
        batch_size: usize,
    ) -> Self {
        Self {
            batch,
            expressions,
            batch_size,
            max_batch_bytes: None,
            cursor: 0,
            indices: None,
            row_sizes: None,
        }
    }

    /// Also limits each chunk to `max_batch_bytes`, by the size its rows take
    /// once spilled (see [`SpilledRowSizes`]). A row larger than that is
    /// returned on its own. Chunks hold only the dictionary values of their
    /// own rows in the columns where that size counts them (see
    /// [`SpilledRowSizes::compacted_columns`]).
    pub(crate) fn with_max_batch_bytes(mut self, max_batch_bytes: usize) -> Self {
        self.max_batch_bytes = Some(max_batch_bytes);
        self
    }

    /// Returns how many of the rows at `indices` fit in `max_batch_bytes`.
    fn rows_within(&self, indices: &[u32]) -> usize {
        let (Some(max_batch_bytes), Some(row_sizes)) =
            (self.max_batch_bytes, &self.row_sizes)
        else {
            return indices.len();
        };
        if let Some(row_bytes) = row_sizes.fixed() {
            return (max_batch_bytes / row_bytes.max(1))
                .max(1)
                .min(indices.len());
        }
        if row_sizes.max_row().saturating_mul(indices.len()) <= max_batch_bytes {
            return indices.len();
        }
        let mut bytes = 0;
        for (rows, &row) in indices.iter().enumerate() {
            bytes += row_sizes.row(row as usize);
            if rows > 0 && bytes > max_batch_bytes {
                return rows;
            }
        }
        indices.len()
    }
}

impl Iterator for IncrementalSortIterator {
    type Item = Result<RecordBatch>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cursor >= self.batch.num_rows() {
            return None;
        }

        match self.indices.as_ref() {
            None => {
                let sort_columns = match self
                    .expressions
                    .iter()
                    .map(|expr| expr.evaluate_to_sort_column(&self.batch))
                    .collect::<Result<Vec<_>>>()
                {
                    Ok(cols) => cols,
                    Err(e) => return Some(Err(e)),
                };

                let indices = match lexsort_to_indices(&sort_columns, None) {
                    Ok(indices) => indices,
                    Err(e) => return Some(Err(e.into())),
                };
                self.indices = Some(indices);
                if self.max_batch_bytes.is_some() {
                    self.row_sizes = Some(SpilledRowSizes::new(&self.batch));
                }

                // Call again, this time it will hit the Some(indices) branch and return the first batch
                self.next()
            }
            Some(indices) => {
                let batch_size = self.batch_size.min(self.batch.num_rows() - self.cursor);
                let batch_size = self.rows_within(
                    &indices.values()[self.cursor..self.cursor + batch_size],
                );

                // Perform the take to produce the next batch
                let new_batch_indices = indices.slice(self.cursor, batch_size);
                let new_batch = match take_record_batch(&self.batch, &new_batch_indices) {
                    Ok(batch) => batch,
                    Err(e) => return Some(Err(e.into())),
                };
                // `take` keeps every dictionary value, while the row sizes
                // count only the values of the rows of `compacted_columns`
                let new_batch = match &self.row_sizes {
                    Some(row_sizes) if !row_sizes.compacted_columns().is_empty() => {
                        match gc_columns(&new_batch, row_sizes.compacted_columns()) {
                            Ok(batch) => batch,
                            Err(e) => return Some(Err(e)),
                        }
                    }
                    _ => new_batch,
                };

                self.cursor += batch_size;

                // If this is the last batch, we can release the memory
                if self.cursor >= self.batch.num_rows() {
                    let schema = self.batch.schema();
                    let _ = mem::replace(&mut self.batch, RecordBatch::new_empty(schema));
                    self.indices = None;
                    self.row_sizes = None;
                }

                // Return the new batch
                Some(Ok(new_batch))
            }
        }
    }

    // Not implementing ExactSizeIterator since in case of an error we stop and don't emit any more
    // so the length would be wrong
    fn size_hint(&self) -> (usize, Option<usize>) {
        let num_rows = self.batch.num_rows().saturating_sub(self.cursor);
        let batch_size = self.batch_size;
        let num_batches = num_rows.div_ceil(batch_size);
        // Limiting bytes can leave as few as one row per batch
        let max_batches = if self.max_batch_bytes.is_some() {
            num_rows
        } else {
            num_batches
        };
        (num_batches, Some(max_batches))
    }
}

impl FusedIterator for IncrementalSortIterator {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::MemoryStream;
    use arrow::array::{ArrayRef, AsArray, DictionaryArray, Int32Array, StringArray};
    use arrow::datatypes::{DataType, Field, Int32Type};
    use arrow_schema::SchemaRef;
    use datafusion_common::DataFusionError;
    use datafusion_execution::RecordBatchStream;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryLimit, MemoryPool,
    };
    use datafusion_physical_expr::expressions::col;
    use futures::Stream;
    use std::pin::Pin;

    fn create_incremental_sort_iter_on(
        input_batch_len: usize,
        output_batch_size: usize,
    ) -> Result<(IncrementalSortIterator, RecordBatch)> {
        // Build a batch with a single Int32 column of descending values
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let col_a: Int32Array =
            Int32Array::from_iter_values((0..input_batch_len as i32).rev());
        let batch = RecordBatch::try_new(schema, vec![Arc::new(col_a)])?;

        // Sort ascending on column "a"
        let expressions = LexOrdering::new(vec![PhysicalSortExpr::new_default(col(
            "a",
            &batch.schema(),
        )?)])
        .unwrap();

        let iter =
            IncrementalSortIterator::new(batch.clone(), expressions, output_batch_size);

        Ok((iter, batch))
    }

    /// Verifies that `take_record_batch` in `IncrementalSortIterator` actually
    /// copies the data into a new allocation rather than returning a zero-copy
    /// slice of the original batch. If the output arrays were slices, their
    /// underlying buffer length would match the original array's length; a true
    /// copy will have a buffer sized to fit only the chunk.
    #[test]
    fn incremental_sort_iterator_copies_data() -> Result<()> {
        let original_len = 10;
        let batch_size = 3;

        let (mut iter, batch) =
            create_incremental_sort_iter_on(original_len, batch_size)?;

        let mut total_rows = 0;
        iter.try_for_each(
            |result| {
                let chunk = result?;
                total_rows += chunk.num_rows();

                // Every output column must be a fresh allocation whose length
                // equals the chunk size, NOT the original array length.
                chunk.columns().iter().zip(batch.columns()).for_each(|(arr, original_arr)| {
                    let (_, scalar_buf, _) = arr.as_primitive::<Int32Type>().clone().into_parts();
                    let (_, original_scalar_buf, _) = original_arr.as_primitive::<Int32Type>().clone().into_parts();

                    assert_ne!(scalar_buf.inner().data_ptr(), original_scalar_buf.inner().data_ptr(), "Expected a copy of the data for each chunk, but got a slice that shares the same buffer as the original array");
                });

                Result::<_, DataFusionError>::Ok(())
            },
        )?;

        assert_eq!(total_rows, original_len);
        Ok(())
    }

    #[test]
    fn test_fused_stream_drop_finished_streams() {
        #[derive(Clone)]
        struct SingleItemManualStream {
            // Held only so its `Arc` strong count reveals when the stream is dropped.
            #[expect(dead_code)]
            hold_ref: Arc<()>,
            record_batch: RecordBatch,
            should_finish: bool,
        }

        impl Stream for SingleItemManualStream {
            type Item = Result<RecordBatch>;

            fn poll_next(
                mut self: Pin<&mut Self>,
                _cx: &mut Context<'_>,
            ) -> Poll<Option<Self::Item>> {
                if !self.should_finish {
                    self.should_finish = true;
                    return Poll::Ready(Some(Ok(self.record_batch.clone())));
                }

                Poll::Ready(None)
            }
        }

        impl RecordBatchStream for SingleItemManualStream {
            fn schema(&self) -> SchemaRef {
                self.record_batch.schema()
            }
        }

        let hold_ref = Arc::new(());
        let record_batch = RecordBatch::try_new(
            Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])),
            vec![Arc::new(Int32Array::from(vec![1]))],
        )
        .unwrap();

        let stream_1 = SingleItemManualStream {
            hold_ref: Arc::clone(&hold_ref),
            should_finish: false,
            record_batch: record_batch.clone(),
        };
        let stream_2 = stream_1.clone();

        let stream_1: SendableRecordBatchStream = Box::pin(stream_1);
        let stream_2: SendableRecordBatchStream = Box::pin(stream_2);

        let mut fused_stream = FusedStreams(vec![stream_1.fuse(), stream_2.fuse()]);

        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);

        // The original plus one clone held by each of the two streams.
        assert_eq!(Arc::strong_count(&hold_ref), 3);

        // First fetch from stream 0 yields its single batch.
        // the stream is not finished yet, so nothing is dropped.
        let poll = fused_stream.poll_next(&mut cx, 0);
        assert!(matches!(poll, Poll::Ready(Some(Ok(_)))));
        assert_eq!(Arc::strong_count(&hold_ref), 3);

        // Second fetch from stream 0 returns `None`, so it is replaced with an
        // empty stream and dropped, releasing its `hold_ref` clone.
        // running 3 times to make sure the stream is fused correctly
        for _ in 0..3 {
            let poll = fused_stream.poll_next(&mut cx, 0);
            assert!(matches!(poll, Poll::Ready(None)));
            assert_eq!(Arc::strong_count(&hold_ref), 2);
        }

        // First fetch from stream 1 yields its single batch
        // the stream is not finished yet, so nothing is dropped.
        let poll = fused_stream.poll_next(&mut cx, 1);
        assert!(matches!(poll, Poll::Ready(Some(Ok(_)))));
        assert_eq!(Arc::strong_count(&hold_ref), 2);

        // Second fetch from stream 1 returns `None`, so it is replaced with an
        // empty stream and dropped, releasing its `hold_ref` clone.
        // running 3 times to make sure the stream is fused correctly
        for _ in 0..3 {
            let poll = fused_stream.poll_next(&mut cx, 1);
            assert!(matches!(poll, Poll::Ready(None)));
            assert_eq!(Arc::strong_count(&hold_ref), 1);
        }
    }

    #[test]
    fn incremental_sort_iterator_limits_batch_bytes() -> Result<()> {
        // Keys 100 down to 0. Keys 0..5 have 1000 byte values, the others 10
        // bytes, so a row takes 1008 or 18 bytes with the Int32 key and the
        // 4 byte offset.
        let keys: Vec<i32> = (0..=100).rev().collect();
        let values: Vec<String> = keys
            .iter()
            .map(|&key| "x".repeat(if key < 5 { 1000 } else { 10 }))
            .collect();
        let batch = RecordBatch::try_from_iter(vec![
            ("key", Arc::new(Int32Array::from(keys)) as ArrayRef),
            ("value", Arc::new(StringArray::from(values)) as ArrayRef),
        ])?;
        let expressions = LexOrdering::new(vec![PhysicalSortExpr::new_default(col(
            "key",
            &batch.schema(),
        )?)])
        .unwrap();

        let chunk_lens = |iter: IncrementalSortIterator| -> Result<Vec<usize>> {
            let mut next_key = 0;
            iter.map(|chunk| {
                let chunk = chunk?;
                let keys = chunk.column(0).as_primitive::<Int32Type>();
                for key in keys.values() {
                    assert_eq!(*key, next_key, "rows must stay sorted");
                    next_key += 1;
                }
                Ok(chunk.num_rows())
            })
            .collect()
        };

        let iter = IncrementalSortIterator::new(batch.clone(), expressions.clone(), 50);
        assert_eq!(chunk_lens(iter)?, vec![50, 50, 1]);

        // Two large rows fit in 2500 bytes. The last large row leaves room for
        // many small rows, up to 50 rows per batch.
        let iter = IncrementalSortIterator::new(batch.clone(), expressions.clone(), 50)
            .with_max_batch_bytes(2500);
        assert_eq!(chunk_lens(iter)?, vec![2, 2, 50, 47]);

        // Without the values, every row takes the 4 bytes of its key
        let keys = batch.project(&[0])?;
        let iter =
            IncrementalSortIterator::new(keys, expressions, 50).with_max_batch_bytes(100);
        assert_eq!(chunk_lens(iter)?, vec![25, 25, 25, 25, 1]);
        Ok(())
    }

    #[test]
    fn incremental_sort_iterator_compacts_unique_dictionaries() -> Result<()> {
        // Keys 99 down to 0, each with its own 100 byte value in `unique`, and
        // one of four values, each of 25 keys, in `shared`
        let keys: Vec<i32> = (0..100).rev().collect();
        let values: Vec<String> = keys.iter().map(|key| format!("{key:0>100}")).collect();
        let unique: DictionaryArray<Int32Type> =
            values.iter().map(String::as_str).collect();
        let shared: DictionaryArray<Int32Type> = keys
            .iter()
            .map(|key| ["a", "b", "c", "d"][*key as usize / 25])
            .collect();
        let shared_values = shared.values().to_data();
        let batch = RecordBatch::try_from_iter(vec![
            ("key", Arc::new(Int32Array::from(keys)) as ArrayRef),
            ("unique", Arc::new(unique) as ArrayRef),
            ("shared", Arc::new(shared) as ArrayRef),
        ])?;
        let expressions = LexOrdering::new(vec![PhysicalSortExpr::new_default(col(
            "key",
            &batch.schema(),
        )?)])
        .unwrap();

        // A row takes 4 bytes of key and 4 of `shared` key, plus a 4 byte key,
        // a 4 byte offset and 100 bytes of value in `unique`, so 10 rows fit
        // in 1200 bytes
        let chunks = IncrementalSortIterator::new(batch, expressions, 50)
            .with_max_batch_bytes(1200)
            .collect::<Result<Vec<_>>>()?;
        assert_eq!(chunks.len(), 10);
        for chunk in &chunks {
            // Each chunk holds the unique values of its own rows, and shares
            // the values of the other dictionary
            let unique = chunk.column(1).as_any_dictionary();
            assert_eq!(unique.values().len(), chunk.num_rows());
            let shared = chunk.column(2).as_any_dictionary();
            assert!(shared.values().to_data().ptr_eq(&shared_values));
        }
        Ok(())
    }

    fn assert_iterator_size_hint(iter: &IncrementalSortIterator, expected_len: usize) {
        assert_eq!(iter.size_hint(), (expected_len, Some(expected_len)));
    }

    #[test]
    fn incremental_sort_iterator_report_correct_len() -> Result<()> {
        let original_len = 10;
        let batch_size = 3;

        let (mut iterator, _) =
            create_incremental_sort_iter_on(original_len, batch_size)?;

        assert_iterator_size_hint(&iterator, 4);

        let batch = iterator.next().unwrap()?;
        assert_eq!(batch.num_rows(), batch_size);

        assert_iterator_size_hint(&iterator, 3);

        let batch = iterator.next().unwrap()?;
        assert_eq!(batch.num_rows(), batch_size);

        assert_iterator_size_hint(&iterator, 2);

        let batch = iterator.next().unwrap()?;
        assert_eq!(batch.num_rows(), batch_size);

        assert_iterator_size_hint(&iterator, 1);

        let batch = iterator.next().unwrap()?;
        // left over
        assert_eq!(batch.num_rows(), 1);

        assert_iterator_size_hint(&iterator, 0);

        assert!(iterator.next().is_none());

        Ok(())
    }

    /// Drives a `RowCursorStream` over several partitions and reports the pool
    /// reservation, so the tests below can watch it move.
    struct RowCursorHarness {
        stream: RowCursorStream,
        pool: Arc<dyn MemoryPool>,
        schema: SchemaRef,
        /// `(rows, str_width)` of each batch, per partition.
        shapes: Vec<Vec<(usize, usize)>>,
    }

    /// The converted `Rows` size depends only on `rows` and `str_width`.
    fn make_batch(
        schema: &SchemaRef,
        seq: usize,
        rows: usize,
        str_width: usize,
    ) -> RecordBatch {
        let base = (seq * rows) as i32;
        let a = Int32Array::from_iter_values((0..rows as i32).map(|i| base + i));
        let b = StringArray::from_iter_values((0..rows).map(|_| "x".repeat(str_width)));
        RecordBatch::try_new(Arc::clone(schema), vec![Arc::new(a), Arc::new(b)]).unwrap()
    }

    impl RowCursorHarness {
        /// `batches_per_partition` batches of `rows` rows each, per partition.
        /// The sort key spans two columns so this takes the `Rows` path rather
        /// than the specialized single-column `FieldCursorStream`.
        fn new(
            partitions: usize,
            batches_per_partition: usize,
            rows: usize,
            str_width: usize,
        ) -> Result<Self> {
            Self::with_shapes(vec![
                vec![(rows, str_width); batches_per_partition];
                partitions
            ])
        }

        /// One partition per entry, one `(rows, str_width)` batch per element.
        fn with_shapes(shapes: Vec<Vec<(usize, usize)>>) -> Result<Self> {
            let schema: SchemaRef = Arc::new(Schema::new(vec![
                Field::new("a", DataType::Int32, false),
                Field::new("b", DataType::Utf8, false),
            ]));

            let streams: Vec<SendableRecordBatchStream> = shapes
                .iter()
                .map(|partition| {
                    let batches: Vec<RecordBatch> = partition
                        .iter()
                        .enumerate()
                        .map(|(seq, &(rows, str_width))| {
                            make_batch(&schema, seq, rows, str_width)
                        })
                        .collect();
                    Box::pin(
                        MemoryStream::try_new(batches, Arc::clone(&schema), None)
                            .unwrap(),
                    ) as SendableRecordBatchStream
                })
                .collect();

            let expressions = LexOrdering::new(vec![
                PhysicalSortExpr::new_default(col("a", &schema)?),
                PhysicalSortExpr::new_default(col("b", &schema)?),
            ])
            .unwrap();

            // Generous limit: this measures what is reserved, not what is refused.
            let pool: Arc<dyn MemoryPool> =
                Arc::new(GreedyMemoryPool::new(256 * 1024 * 1024));
            let reservation = MemoryConsumer::new("test").register(&pool);
            let stream =
                RowCursorStream::try_new(&schema, &expressions, streams, reservation)?;

            Ok(Self {
                stream,
                pool,
                schema,
                shapes,
            })
        }

        fn reserved(&self) -> usize {
            self.pool.reserved()
        }

        fn converter(&self) -> Result<RowConverter> {
            Ok(RowConverter::new(vec![
                SortField::new(DataType::Int32),
                SortField::new(DataType::Utf8),
            ])?)
        }

        /// `(converter size, retained Rows size)` when all batches share a shape.
        fn expected_sizes(&self) -> Result<(usize, usize)> {
            let converter = self.converter()?;
            Ok((converter.size(), self.expected_retained_sizes(0)?[0]))
        }

        /// `Rows::size()` after each of `stream_idx`'s batches, reusing one
        /// buffer like the stream does.
        fn expected_retained_sizes(&self, stream_idx: usize) -> Result<Vec<usize>> {
            let converter = self.converter()?;
            let mut rows = converter.empty_rows(0, 0);
            self.shapes[stream_idx]
                .iter()
                .enumerate()
                .map(|(seq, &(num_rows, str_width))| {
                    let batch = make_batch(&self.schema, seq, num_rows, str_width);
                    rows.clear();
                    converter.append(&mut rows, batch.columns())?;
                    Ok(rows.size())
                })
                .collect()
        }

        /// Polls `stream_idx`, handing back the cursor so the caller controls when
        /// it is dropped. `None` once the partition is finished.
        fn poll_cursor(&mut self, stream_idx: usize) -> Result<Option<RowValues>> {
            let waker = futures::task::noop_waker();
            let mut cx = Context::from_waker(&waker);
            match self.stream.poll_next(&mut cx, stream_idx) {
                Poll::Ready(Some(Ok((values, _batch)))) => Ok(Some(values)),
                Poll::Ready(Some(Err(e))) => Err(e),
                Poll::Ready(None) => Ok(None),
                Poll::Pending => unreachable!("MemoryStream is never pending"),
            }
        }

        /// Polls `stream_idx` and immediately drops the returned cursor, which is
        /// what the merge does once a cursor is exhausted. Returns `false` once
        /// the partition is finished.
        fn poll_and_drop_cursor(&mut self, stream_idx: usize) -> Result<bool> {
            let waker = futures::task::noop_waker();
            let mut cx = Context::from_waker(&waker);
            match self.stream.poll_next(&mut cx, stream_idx) {
                Poll::Ready(Some(Ok((values, _batch)))) => {
                    drop(values);
                    Ok(true)
                }
                Poll::Ready(Some(Err(e))) => Err(e),
                Poll::Ready(None) => Ok(false),
                Poll::Pending => unreachable!("MemoryStream is never pending"),
            }
        }
    }

    // `RowCursorStream` keeps one `Rows` buffer per partition alive between
    // polls so the allocation can be reused. That buffer is real memory, and it
    // outlives the cursor handed to the consumer: the merge drops a cursor as
    // soon as it is exhausted, but the buffer behind it stays cached.
    //
    // So dropping the cursor must not change what the pool reports. If it does,
    // the bytes still held by the cache have gone off the books and the pool is
    // under-counting a live allocation.
    #[test]
    fn dropping_a_cursor_does_not_unaccount_its_retained_buffer() -> Result<()> {
        let mut harness = RowCursorHarness::new(1, 4, 512, 64)?;
        let (converter_size, rows_size) = harness.expected_sizes()?;
        assert_eq!(harness.reserved(), 0);

        let cursor = harness.poll_cursor(0)?.expect("first batch");
        assert_eq!(harness.reserved(), converter_size + rows_size);

        // The cached `Rows` buffer outlives the cursor, so dropping the cursor
        // must not release its bytes.
        drop(cursor);
        assert_eq!(harness.reserved(), converter_size + rows_size);

        Ok(())
    }

    // The retained bytes are per partition, so what the pool reports has to
    // scale with partition count rather than staying flat at the size of
    // whichever batch happens to be in flight.
    #[test]
    fn retained_row_buffer_reservation_scales_with_partitions() -> Result<()> {
        for partitions in [2, 16] {
            let mut harness = RowCursorHarness::new(partitions, 4, 512, 64)?;
            let (converter_size, rows_size) = harness.expected_sizes()?;
            for stream_idx in 0..partitions {
                assert!(harness.poll_and_drop_cursor(stream_idx)?);
            }
            // One shared converter, plus one cached buffer per partition.
            assert_eq!(
                harness.reserved(),
                converter_size + partitions * rows_size,
                "{partitions} partitions"
            );
        }

        Ok(())
    }

    // The flip side: a partition that will never be polled again must hand its
    // buffer back. Otherwise the reservation only ever grows and a long merge
    // holds every partition's high-water mark until the whole stream drops.
    #[test]
    fn exhausted_partitions_release_their_retained_buffers() -> Result<()> {
        let partitions = 8;
        let batches_per_partition = 3;
        let mut harness =
            RowCursorHarness::new(partitions, batches_per_partition, 512, 64)?;
        let (converter_size, rows_size) = harness.expected_sizes()?;
        assert_eq!(harness.reserved(), 0);

        for stream_idx in 0..partitions {
            for _ in 0..batches_per_partition {
                assert!(harness.poll_and_drop_cursor(stream_idx)?);
            }
        }
        // Reusing a buffer for later batches of the same shape does not grow it.
        assert_eq!(harness.reserved(), converter_size + partitions * rows_size);

        // Poll each partition once more so it reports exhaustion, releasing
        // one buffer at a time.
        for stream_idx in 0..partitions {
            assert!(!harness.poll_and_drop_cursor(stream_idx)?);
            let still_retained = partitions - stream_idx - 1;
            assert_eq!(
                harness.reserved(),
                converter_size + still_retained * rows_size
            );
        }

        // Only the converter is left.
        assert_eq!(harness.reserved(), converter_size);

        Ok(())
    }

    // A reused buffer keeps its capacity, so the reservation should track each
    // partition's high-water mark and release it on exhaustion only.
    #[test]
    fn retained_buffer_reservation_tracks_high_water_mark() -> Result<()> {
        let small = (64, 8);
        let large = (2048, 128);
        let mut harness =
            RowCursorHarness::with_shapes(vec![vec![small, large, small], vec![small]])?;
        let converter_size = harness.converter()?.size();
        let growing = harness.expected_retained_sizes(0)?;
        let cached = harness.expected_retained_sizes(1)?[0];

        // The large batch grows the buffer; the next small one doesn't shrink it.
        assert!(growing[1] > growing[0]);
        assert_eq!(growing[2], growing[1]);

        // Partition 1 keeps its buffer cached throughout.
        assert!(harness.poll_and_drop_cursor(1)?);
        assert_eq!(harness.reserved(), converter_size + cached);

        for (seq, retained) in growing.iter().enumerate() {
            assert!(harness.poll_and_drop_cursor(0)?);
            assert_eq!(
                harness.reserved(),
                converter_size + cached + retained,
                "after batch {seq}"
            );
        }

        // Releasing partition 0 leaves partition 1 accounted for.
        assert!(!harness.poll_and_drop_cursor(0)?);
        assert_eq!(harness.reserved(), converter_size + cached);

        assert!(!harness.poll_and_drop_cursor(1)?);
        assert_eq!(harness.reserved(), converter_size);

        Ok(())
    }

    // The buffer has already been taken out of the cache when its reservation fails
    // to grow. Cleanup must still release its previous charge.
    #[test]
    fn failed_buffer_growth_releases_only_its_stream_reservation() -> Result<()> {
        let small = (64, 8);
        let large = (2048, 128);
        let mut harness =
            RowCursorHarness::with_shapes(vec![vec![small, large], vec![small]])?;

        // Cache stream 1's buffer and record the reservation that must survive.
        assert!(harness.poll_and_drop_cursor(1)?);
        let expected_remaining = harness.reserved();
        assert!(harness.poll_and_drop_cursor(0)?);

        // Leave no space for stream 0's larger batch.
        let MemoryLimit::Finite(limit) = harness.pool.memory_limit() else {
            unreachable!("the harness uses a bounded memory pool");
        };
        let competitor = MemoryConsumer::new("competitor").register(&harness.pool);
        competitor.try_grow(limit - harness.reserved())?;

        assert!(matches!(
            harness.poll_cursor(0),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        drop(competitor);

        // Only stream 1's buffer and the shared converter remain reserved.
        assert_eq!(harness.reserved(), expected_remaining);
        Ok(())
    }
}