datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
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
// Licensed 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.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Owns accepted nonempty input batches and their DataFusion memory charge
//! until committed work and every live consumer have advanced far enough to
//! release each whole batch.

use std::collections::VecDeque;
use std::sync::Arc;

use crate::compat::memory::RecordBatchMemoryCounter;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;

use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::matching::{
    PartitionKeyBatch, PartitionKeyRows, key_memory_overflow,
};

/// Whole input batches retained with absolute row coordinates and memory
/// accounting.
pub struct SharedHistoryBuffer {
    /// Schema shared by every buffered batch.
    schema: SchemaRef,
    /// Batches and their absolute starting row indices.
    batches: VecDeque<HistoryBatch>,
    /// Total rows appended since stream start. This never decreases.
    total_rows_appended: usize,
    /// Accounts retained slot capacity and serves as the consumer template for
    /// per-batch reservations.
    reservation: MemoryReservation,
}

struct HistoryBatch {
    batch: RecordBatch,
    /// Absolute start index in the input stream.
    start_row: usize,
    /// Absolute end-exclusive index in the input stream.
    end_row: usize,
    keys: Arc<PartitionKeyBatch>,
    /// Releases this batch's Arrow memory charge when the batch is dropped.
    _reservation: MemoryReservation,
    /// One lease shared by every zero-copy chunk of an oversized input batch.
    _shared_backing: Option<Arc<MemoryReservation>>,
}

impl SharedHistoryBuffer {
    /// Create a new shared history buffer.
    pub fn new(schema: SchemaRef, reservation: MemoryReservation) -> Self {
        Self {
            schema,
            batches: VecDeque::new(),
            total_rows_appended: 0,
            reservation,
        }
    }

    /// Append an accepted batch after reserving its Arrow array memory.
    ///
    /// Empty batches are ignored; nonempty batches must use the buffer schema.
    #[cfg(test)]
    pub fn append(&mut self, batch: RecordBatch) -> Result<()> {
        if batch.num_rows() == 0 {
            return Ok(());
        }
        let memory = self.admit_input(&batch, false)?;
        let keys = RecordBatch::try_new_with_options(
            Arc::new(datafusion::arrow::datatypes::Schema::empty()),
            Vec::new(),
            &datafusion::arrow::record_batch::RecordBatchOptions::new()
                .with_row_count(Some(batch.num_rows())),
        )?;
        let key_memory = memory.new_empty();
        let keys = PartitionKeyBatch::new(keys, key_memory);
        self.append_admitted(batch, keys, memory, None)?;
        Ok(())
    }

    pub(crate) fn validate_batch_schema(
        expected: &SchemaRef,
        actual: &SchemaRef,
    ) -> Result<()> {
        // File partition literals may narrow top-level nullability. Keep types
        // and metadata exact: replacing a schema does not retype nested arrays.
        if actual != expected
            && (!expected.contains(actual)
                || expected.metadata() != actual.metadata()
                || expected.fields().iter().zip(actual.fields().iter()).any(
                    |(expected, actual)| {
                        expected.data_type() != actual.data_type()
                            || expected.metadata() != actual.metadata()
                    },
                ))
        {
            return internal_err!(
                "MATCH_RECOGNIZE history batch has schema {actual}, expected {expected}"
            );
        }
        Ok(())
    }

    pub(crate) fn memory(&self) -> &MemoryReservation {
        &self.reservation
    }

    pub(crate) fn admit_input(
        &self,
        batch: &RecordBatch,
        shared: bool,
    ) -> Result<MemoryReservation> {
        Self::validate_batch_schema(&self.schema, batch.schema_ref())?;

        self.total_rows_appended
            .checked_add(batch.num_rows())
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE absolute history row count exceeds usize"
                        .to_string(),
                )
            })?;
        let memory = self.reservation.new_empty();
        Self::resize_input_admission(batch, &memory, shared)?;
        Ok(memory)
    }

    pub(crate) fn resize_input_admission(
        batch: &RecordBatch,
        memory: &MemoryReservation,
        shared: bool,
    ) -> Result<()> {
        let handles = batch
            .num_columns()
            .checked_mul(size_of::<datafusion::arrow::array::ArrayRef>())
            .ok_or_else(key_memory_overflow)?;
        let mut counter = RecordBatchMemoryCounter::new();
        let array_bytes = if shared {
            // The shared lease owns buffers; each slice owns new Array objects.
            batch.columns().iter().try_fold(0usize, |bytes, column| {
                bytes
                    .checked_add(
                        column
                            .get_array_memory_size()
                            .saturating_sub(column.get_buffer_memory_size()),
                    )
                    .ok_or_else(key_memory_overflow)
            })?
        } else {
            counter.count_batch_with_array_overhead(batch)
        };
        memory.try_resize(
            array_bytes
                .checked_add(handles)
                .ok_or_else(key_memory_overflow)?,
        )
    }

    pub(crate) fn append_admitted(
        &mut self,
        batch: RecordBatch,
        keys: Arc<PartitionKeyBatch>,
        memory: MemoryReservation,
        shared_backing: Option<Arc<MemoryReservation>>,
    ) -> Result<(RecordBatch, usize)> {
        // Establish field drop order before any fallible operation: arrays and
        // keys must retire before the reservations that account for them.
        let mut entry = HistoryBatch {
            batch,
            start_row: self.total_rows_appended,
            end_row: self.total_rows_appended,
            keys,
            _reservation: memory,
            _shared_backing: shared_backing,
        };
        if entry.batch.schema() != self.schema {
            entry.batch = entry.batch.with_schema(Arc::clone(&self.schema))?;
        }
        entry.end_row = self
            .total_rows_appended
            .checked_add(entry.batch.num_rows())
            .ok_or_else(key_memory_overflow)?;
        if entry.keys.rows() != entry.batch.num_rows() {
            return internal_err!(
                "MATCH_RECOGNIZE cached partition keys do not cover their input batch"
            );
        }
        let moved = if self.batches.len() == self.batches.capacity() {
            let target_capacity = self
                .batches
                .len()
                .checked_add(1)
                .and_then(usize::checked_next_power_of_two)
                .ok_or_else(key_memory_overflow)?;
            let growth = target_capacity
                .checked_sub(self.batches.capacity())
                .and_then(|slots| slots.checked_mul(size_of::<HistoryBatch>()))
                .ok_or_else(key_memory_overflow)?;
            self.reservation.try_grow(growth)?;
            if let Err(error) = self
                .batches
                .try_reserve_exact(target_capacity - self.batches.len())
            {
                self.reservation.shrink(growth);
                return Err(DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE history metadata allocation failed: {error}"
                )));
            }
            self.reservation
                .resize(self.batches.capacity() * size_of::<HistoryBatch>());
            self.batches.len()
        } else {
            0
        };
        let batch = entry.batch.clone();
        self.total_rows_appended = entry.end_row;
        self.batches.push_back(entry);
        Ok((batch, moved))
    }

    /// Get the absolute start row of the oldest row currently in the buffer.
    pub fn head_index(&self) -> usize {
        self.batches
            .front()
            .map(|b| b.start_row)
            .unwrap_or(self.total_rows_appended)
    }

    pub(crate) fn end_index(&self) -> usize {
        self.total_rows_appended
    }

    pub(super) fn schema(&self) -> &SchemaRef {
        &self.schema
    }

    /// Locate a retained absolute row without cloning unrelated batch columns.
    pub(crate) fn locate(&self, row: usize) -> Result<(usize, usize)> {
        let start = self.head_index();
        if row < start {
            return internal_err!(
                "Required history row {row} was already pruned; retained history starts at {start}"
            );
        }
        if row >= self.total_rows_appended {
            return internal_err!(
                "Required history row {row} extends past appended history end {}",
                self.total_rows_appended
            );
        }
        if self.batches.len() == 1 {
            return Ok((0, row - start));
        }
        let index = self.batches.partition_point(|batch| batch.end_row <= row);
        let batch = &self.batches[index];
        Ok((index, row - batch.start_row))
    }

    pub(crate) fn batch(&self, index: usize) -> &RecordBatch {
        &self.batches[index].batch
    }

    pub(crate) fn group_bounds(
        &self,
        batch: usize,
        row: usize,
    ) -> Option<(usize, Option<usize>)> {
        self.batches[batch]
            .keys
            .grouped
            .as_ref()
            .map(|groups| groups.bounds_at(row))
    }

    pub(crate) fn key_rows(&self, index: usize) -> PartitionKeyRows {
        PartitionKeyRows::full(Arc::clone(&self.batches[index].keys))
    }

    /// Find a partition end in retained lookahead. A later fragment can close
    /// an open group even when its last row still belongs to the anchor.
    pub(crate) fn partition_end(
        &self,
        anchor: usize,
        unchecked: std::ops::Range<usize>,
        keyed: bool,
    ) -> Result<Option<usize>> {
        let (batch, row) = self.locate(anchor)?;
        let group = self.group_bounds(batch, row);
        if let Some((_, Some(end))) = group {
            return Ok(Some(end));
        }
        if unchecked.is_empty() || (!keyed && group.is_none()) {
            return Ok(None);
        }
        let last = unchecked.end - 1;
        let (b, i) = self.locate(last)?;
        if let Some((start, _)) = group
            && let Some((other, Some(end))) = self.group_bounds(b, i)
            && start == other
        {
            return Ok(Some(end));
        }
        let key = group
            .is_none()
            .then(|| self.key_rows(batch).key(row))
            .transpose()?;
        let equal = |b, i| -> Result<bool> {
            if let Some((start, _)) = group {
                Ok(self
                    .group_bounds(b, i)
                    .is_some_and(|(other, _)| start == other))
            } else {
                key.as_ref()
                    .expect("ordered key")
                    .same_values(self.key_rows(b).key(i)?.as_ref())
            }
        };
        if equal(b, i)? {
            return Ok(None);
        }
        let (mut lo, mut hi) = (unchecked.start, last);
        while lo < hi {
            let mid = lo + (hi - lo) / 2;
            let (b, i) = self.locate(mid)?;
            if equal(b, i)? {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        Ok(Some(lo))
    }

    /// Prune whole batches that end at or before `min_retained_row`.
    ///
    /// The caller computes this lower bound from unpublished accumulator input,
    /// unfinalized row presence, and every current or suspended scan including
    /// navigation lookbehind.
    #[cfg(test)]
    pub fn prune(&mut self, min_retained_row: usize) {
        let mut completed = |_| Ok(());
        while !self
            .prune_chunk(min_retained_row, &mut completed)
            .expect("infallible history pruning callback must succeed")
        {}
    }

    /// Release a bounded prefix of whole batches below a fixed retained floor.
    ///
    /// Comparisons are reported before mutation; released batches are reported
    /// afterward. A later callback failure does not restore released history.
    /// The caller must keep input and consumers quiescent until this returns true.
    pub(crate) fn prune_chunk(
        &mut self,
        min_retained_row: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if self.batches.is_empty() {
            return Ok(true);
        }

        let (front, back) = self.batches.as_slices();
        let first = if front.is_empty() { back } else { front };
        // Input and key schemas are fixed. Keep native batch drops atomic,
        // but bound their enclosing loop by the column handles they release.
        let batch_work = first[0]
            .batch
            .num_columns()
            .saturating_add(first[0].keys.values.num_columns())
            .max(1);
        let limit = first
            .len()
            .min((COARSE_WORK_BATCH_SIZE / batch_work).max(1));
        let mut comparisons = 0;
        let prune_count = first[..limit].partition_point(|batch| {
            comparisons += 1;
            batch.end_row <= min_retained_row
        });
        completed(comparisons)?;
        drop(self.batches.drain(..prune_count));
        if self.batches.is_empty() {
            self.batches = VecDeque::new();
            self.reservation.free();
        }
        if prune_count != 0 {
            completed(prune_count * batch_work)?;
        }
        Ok(prune_count < limit || self.batches.is_empty())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::storage::collection::PreparingReplayCollection;
    use datafusion::arrow::array::{ArrayRef, Int32Array, new_null_array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use std::ops::Range;
    use std::sync::Arc;

    fn setup() -> (SchemaRef, SharedHistoryBuffer, Arc<GreedyMemoryPool>) {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let pool = Arc::new(GreedyMemoryPool::new(1024 * 1024));
        let reservation = MemoryConsumer::new("history-test")
            .register(&(Arc::clone(&pool) as Arc<dyn MemoryPool>));
        let buffer = SharedHistoryBuffer::new(Arc::clone(&schema), reservation);
        (schema, buffer, pool)
    }

    fn make_batch(schema: &SchemaRef, rows: Range<i32>) -> RecordBatch {
        RecordBatch::try_new(
            Arc::clone(schema),
            vec![Arc::new(Int32Array::from_iter_values(rows))],
        )
        .unwrap()
    }

    #[test]
    fn admission_errors_leave_history_and_memory_unchanged() {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let other = Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, false)]));
        let nullable = Field::new("a", DataType::Int32, true);
        let nullable_schema = Arc::new(Schema::new(vec![nullable.clone()]));
        let metadata = std::collections::HashMap::from([("tag".into(), "value".into())]);
        let nested_type =
            DataType::Struct(vec![Field::new("n", DataType::Int32, false)].into());
        let nested_schema = Arc::new(Schema::new(vec![Field::new(
            "a",
            nested_type.clone(),
            true,
        )]));
        let nested_batch =
            RecordBatch::try_new(nested_schema, vec![new_null_array(&nested_type, 1)])
                .unwrap();
        let widened_nested = Arc::new(Schema::new(vec![Field::new(
            "a",
            DataType::Struct(vec![Field::new("n", DataType::Int32, true)].into()),
            true,
        )]));
        for (history_schema, batch, end, limit, resource_error) in [
            (
                Arc::clone(&schema),
                make_batch(&other, 0..1),
                0,
                usize::MAX,
                false,
            ),
            (
                Arc::clone(&schema),
                make_batch(&schema, 0..1),
                usize::MAX,
                usize::MAX,
                true,
            ),
            (Arc::clone(&schema), make_batch(&schema, 0..1), 0, 0, true),
            (
                Arc::clone(&schema),
                make_batch(&nullable_schema, 0..1),
                0,
                usize::MAX,
                false,
            ),
            (
                Arc::new(Schema::new_with_metadata(
                    vec![nullable.clone()],
                    metadata.clone(),
                )),
                make_batch(&schema, 0..1),
                0,
                usize::MAX,
                false,
            ),
            (
                Arc::new(Schema::new(vec![nullable.with_metadata(metadata)])),
                make_batch(&schema, 0..1),
                0,
                usize::MAX,
                false,
            ),
            (widened_nested, nested_batch, 0, usize::MAX, false),
        ] {
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
            let memory = MemoryConsumer::new("history-admission-test").register(&pool);
            let mut history = SharedHistoryBuffer::new(history_schema, memory);
            history.total_rows_appended = end;
            let error = history.admit_input(&batch, false).unwrap_err();
            assert_eq!(
                matches!(error, DataFusionError::ResourcesExhausted(_)),
                resource_error
            );
            assert!(matches!(
                error,
                DataFusionError::Internal(_) | DataFusionError::ResourcesExhausted(_)
            ));
            assert!(history.batches.is_empty());
            assert_eq!(history.end_index(), end);
            assert_eq!(history.reservation.size(), 0);
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn append_errors_release_admission_without_publishing_history() -> Result<()> {
        for failure in ["schema", "rows", "keys", "metadata"] {
            let schema =
                Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
            let batch = make_batch(&schema, 0..2);
            let source = Arc::downgrade(batch.column(0));
            let bytes = batch.get_array_memory_size() + size_of::<ArrayRef>();
            let pool: Arc<dyn MemoryPool> =
                Arc::new(GreedyMemoryPool::new(if failure == "metadata" {
                    bytes
                } else {
                    1024 * 1024
                }));
            let memory = MemoryConsumer::new("append failure").register(&pool);
            let mut history = SharedHistoryBuffer::new(schema, memory);
            let admitted = history.admit_input(&batch, false)?;
            let values = RecordBatch::try_new_with_options(
                Arc::new(Schema::empty()),
                vec![],
                &datafusion::arrow::record_batch::RecordBatchOptions::new()
                    .with_row_count(Some(if failure == "keys" { 1 } else { 2 })),
            )?;
            let keys = PartitionKeyBatch::new(values, admitted.new_empty());
            if failure == "schema" {
                history.schema =
                    Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, false)]));
            } else if failure == "rows" {
                history.total_rows_appended = usize::MAX;
            }
            let end = history.end_index();
            assert!(
                history
                    .append_admitted(batch, keys, admitted, None)
                    .is_err(),
                "{failure}"
            );
            assert!(source.upgrade().is_none());
            assert!(history.batches.is_empty());
            assert_eq!(history.end_index(), end);
            assert_eq!(pool.reserved(), 0, "{failure}");
        }
        Ok(())
    }

    #[test]
    fn narrowed_input_nullability_uses_the_history_schema_without_copying() -> Result<()>
    {
        let (source_schema, _, pool) = setup();
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, true)]));
        let memory = MemoryConsumer::new("history-nullability-test")
            .register(&(Arc::clone(&pool) as Arc<dyn MemoryPool>));
        let mut history = SharedHistoryBuffer::new(Arc::clone(&schema), memory);
        let batch = make_batch(&source_schema, 0..3);
        let values = Arc::clone(batch.column(0));
        history.append(batch)?;
        history.append(RecordBatch::try_new(
            Arc::clone(&schema),
            vec![Arc::new(Int32Array::from(vec![None, Some(4)]))],
        )?)?;
        for index in 0..2 {
            assert!(Arc::ptr_eq(history.batch(index).schema_ref(), &schema));
        }
        assert!(Arc::ptr_eq(history.batch(0).column(0), &values));
        assert_eq!(history.end_index(), 5);
        assert_eq!(history.batch(1).column(0).null_count(), 1);
        drop(history);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn history_reservations_follow_whole_batch_lifetimes() -> Result<()> {
        let (schema, mut history, pool) = setup();
        let first = make_batch(&schema, 0..3);
        let second = make_batch(&schema, 3..5);
        let first_bytes = first.get_array_memory_size();
        let second_bytes = second.get_array_memory_size();
        let owner_bytes = size_of::<ArrayRef>();
        history.append(first)?;
        history.append(second)?;
        let both =
            first_bytes + second_bytes + 2 * owner_bytes + history.reservation.size();
        assert_eq!(pool.reserved(), both);
        history.prune(2); // A required row inside the first batch retains the whole batch.
        assert_eq!(history.head_index(), 0);
        assert_eq!(pool.reserved(), both);
        history.prune(3);
        assert_eq!(history.head_index(), 3);
        assert_eq!(
            pool.reserved(),
            second_bytes + owner_bytes + history.reservation.size()
        );
        drop(history);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn replay_and_lookup_obey_retained_absolute_bounds() -> Result<()> {
        let (schema, mut history, _) = setup();
        history.append(make_batch(&schema, 0..3))?;
        history.append(make_batch(&schema, 3..6))?;
        for (start, end, expected) in [(1, 5, vec![1, 2, 3, 4]), (6, 6, vec![])] {
            let mut replay = PreparingReplayCollection::try_new(
                &history,
                start,
                end,
                Arc::clone(&schema),
                history.reservation.new_empty(),
            )?;
            while !replay.advance_chunk(&history, &mut |_| Ok(()))? {}
            let (collection, _key_rows, _memory) = replay.into_parts();
            let actual = (0..collection.num_batches())
                .flat_map(|index| {
                    collection
                        .batch(index)
                        .column(0)
                        .as_any()
                        .downcast_ref::<Int32Array>()
                        .unwrap()
                        .values()
                        .to_vec()
                })
                .collect::<Vec<_>>();
            assert_eq!(actual, expected);
        }
        for (start, end, diagnostic) in [
            (0, 7, "extends past"),
            (7, 7, "extends past"),
            (4, 3, "reversed"),
        ] {
            let error = PreparingReplayCollection::try_new(
                &history,
                start,
                end,
                Arc::clone(&schema),
                history.reservation.new_empty(),
            )
            .unwrap_err();
            assert!(error.to_string().contains(diagnostic), "{error}");
        }
        history.prune(3);
        let error = PreparingReplayCollection::try_new(
            &history,
            2,
            4,
            schema,
            history.reservation.new_empty(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("already pruned"), "{error}");
        assert_eq!(history.locate(3)?, (0, 0));
        assert_eq!(history.locate(5)?, (0, 2));
        assert!(
            history
                .locate(2)
                .unwrap_err()
                .to_string()
                .contains("already pruned")
        );
        assert!(
            history
                .locate(6)
                .unwrap_err()
                .to_string()
                .contains("extends past")
        );
        Ok(())
    }

    #[test]
    fn pruning_cancellation_distinguishes_preparation_from_committed_release()
    -> Result<()> {
        let (schema, mut history, pool) = setup();
        for row in 0..65 {
            history.append(make_batch(&schema, row..row + 1))?;
        }
        let reserved = pool.reserved();
        let error = history
            .prune_chunk(65, &mut |_| {
                Err(DataFusionError::Execution("before release".into()))
            })
            .unwrap_err();
        assert!(error.to_string().contains("before release"));
        assert_eq!((history.head_index(), history.batches.len()), (0, 65));
        assert_eq!(pool.reserved(), reserved);

        let mut reports = 0;
        let error = history
            .prune_chunk(65, &mut |units| {
                assert!(units <= COARSE_WORK_BATCH_SIZE);
                reports += 1;
                if reports == 2 {
                    Err(DataFusionError::Execution("after release".into()))
                } else {
                    Ok(())
                }
            })
            .unwrap_err();
        assert!(error.to_string().contains("after release"));
        assert_eq!((history.head_index(), history.batches.len()), (64, 1));
        assert_eq!(history.locate(64)?, (0, 0));
        assert!(pool.reserved() < reserved);
        assert!(history.prune_chunk(65, &mut |_| Ok(()))?);
        assert_eq!(history.head_index(), 65);
        assert!(history.batches.is_empty());
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn pruning_wrapped_history_keeps_the_absolute_row_sequence() -> Result<()> {
        let (schema, mut history, pool) = setup();
        for row in 0..8 {
            history.append(make_batch(&schema, row..row + 1))?;
        }
        history.prune(6);
        for row in 8..12 {
            history.append(make_batch(&schema, row..row + 1))?;
        }
        assert!(
            !history.batches.as_slices().1.is_empty(),
            "test_case must cross the deque boundary"
        );
        history.prune(10);
        assert_eq!((history.head_index(), history.batches.len()), (10, 2));
        for (index, expected) in [(0, 10), (1, 11)] {
            let values = history
                .batch(index)
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap();
            assert_eq!(values.values(), &[expected]);
        }
        history.prune(12);
        assert!(history.batches.is_empty());
        assert_eq!(history.head_index(), 12);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn admit_input_deduplicates_shared_column_buffers() -> Result<()> {
        use datafusion::arrow::buffer::{Buffer, ScalarBuffer};

        let schema = Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int64, false),
            Field::new("b", DataType::Int64, false),
            Field::new("c", DataType::Int64, false),
            Field::new("d", DataType::Int64, false),
        ]));
        let shared = Buffer::from_vec(vec![0_u128; 512]);
        let shared_cap = shared.capacity();
        let cols: Vec<ArrayRef> = (0..4)
            .map(|_| {
                Arc::new(datafusion::arrow::array::Int64Array::new(
                    ScalarBuffer::new(shared.clone(), 0, 1024),
                    None,
                )) as ArrayRef
            })
            .collect();
        let batch = RecordBatch::try_new(Arc::clone(&schema), cols)?;
        assert!(
            batch.get_array_memory_size() >= 4 * shared_cap,
            "get_array_memory_size overcounts shared buffers across columns"
        );

        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
        let memory = MemoryConsumer::new("history-shared-buf-test").register(&pool);
        let history = SharedHistoryBuffer::new(schema, memory);
        let admitted = history.admit_input(&batch, false)?;
        assert!(
            admitted.size() < 2 * shared_cap,
            "admit_input should count shared buffer once, got {} vs 4 * {}",
            admitted.size(),
            shared_cap
        );
        drop(admitted);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }
}