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

//! Presents several `RecordBatch` values as one logical row sequence.
//!
//! `BatchCollection` supports collection-wide row indices, retained batch views,
//! and scattered-row gathering without first concatenating every input column.

use super::bound_columns::{BoundBatchColumns, BoundBatchRow};
use crate::execution::common::memory::{reserved_vec, try_reserve_accounted};
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::datatypes::{FieldRef, Schema, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::heap_size::{DFHeapSize, DFHeapSizeCtx};
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
use std::mem::size_of;
use std::ops::Range;

/// Ordered record batches accessed through one collection-wide row index.
#[derive(Debug)]
pub struct BatchCollection {
    /// Populated only on selected match-aware heads with bound row operands.
    bound: Vec<BoundBatchColumns>,
    /// The batches in order
    batches: Vec<RecordBatch>,
    /// Cumulative row counts: `cumulative_rows[i]` = total rows in batches `0..=i`
    cumulative_rows: Vec<usize>,
    /// Schema (shared across all batches)
    schema: SchemaRef,
}

pub(in crate::execution) fn gather_size_overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE history gather memory size exceeds usize".into(),
    )
}

pub(crate) fn gathered_schema_bytes(schema: &Schema) -> Result<usize> {
    // The projected Schema and Fields slice own their Arc allocations and
    // field handles. Field contents and schema metadata remain shared with
    // the source schema; account for referenced metadata conservatively.
    size_of::<Schema>()
        .checked_add(4 * size_of::<usize>())
        .and_then(|bytes| {
            schema
                .fields()
                .len()
                .checked_mul(size_of::<FieldRef>())
                .and_then(|handles| bytes.checked_add(handles))
        })
        .and_then(|bytes| {
            bytes.checked_add(schema.metadata().heap_size(&mut DFHeapSizeCtx::default()))
        })
        .ok_or_else(gather_size_overflow)
}

/// Exact history replay assembled while its source remains unchanged.
#[derive(Debug)]
pub(crate) struct PreparingReplayCollection {
    collection: BatchCollection,
    key_rows: Vec<crate::execution::matching::PartitionKeyRows>,
    batches: Range<usize>,
    batch_offset: usize,
    last_batch_end: usize,
    expected_rows: usize,
    history_bounds: (usize, usize),
    // Release the lease after the collection's vectors and sliced handles.
    memory: MemoryReservation,
}

impl PreparingReplayCollection {
    pub(crate) fn try_new(
        history: &SharedHistoryBuffer,
        start: usize,
        end_exclusive: usize,
        schema: SchemaRef,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let mut collection = BatchCollection::empty(schema);
        let expected_rows = end_exclusive.checked_sub(start).ok_or_else(|| {
            DataFusionError::Internal(
                "MATCH_RECOGNIZE history replay range has reversed bounds".into(),
            )
        })?;
        let history_bounds = (history.head_index(), history.end_index());
        if start < history_bounds.0 {
            return internal_err!(
                "Required history range {start}..{end_exclusive} was already pruned; retained history starts at {}",
                history_bounds.0
            );
        }
        if end_exclusive > history_bounds.1 {
            return internal_err!(
                "Required history range {start}..{end_exclusive} extends past appended history end {}",
                history_bounds.1
            );
        }
        if &collection.schema != history.schema() {
            return internal_err!(
                "MATCH_RECOGNIZE history replay schema differs from its source"
            );
        }
        let (batches, batch_offset, last_batch_end) = if expected_rows == 0 {
            (0..0, 0, 0)
        } else {
            let (first, offset) = history.locate(start)?;
            let (last, last_offset) = history.locate(end_exclusive - 1)?;
            (first..last + 1, offset, last_offset + 1)
        };

        let batch_count = batches.len();
        let handles = batch_count
            .checked_mul(collection.schema.fields().len())
            .and_then(|count| count.checked_mul(size_of::<ArrayRef>()))
            .ok_or_else(replay_metadata_overflow)?;
        memory.try_resize(
            memory
                .size()
                .checked_add(handles)
                .ok_or_else(replay_metadata_overflow)?,
        )?;
        collection.batches = reserved_vec(batch_count, &memory, "replay metadata")?;
        collection.cumulative_rows =
            reserved_vec(batch_count, &memory, "replay metadata")?;
        let key_rows = reserved_vec(batch_count, &memory, "replay metadata")?;
        Ok(Self {
            collection,
            key_rows,
            batches,
            batch_offset,
            last_batch_end,
            expected_rows,
            history_bounds,
            memory,
        })
    }

    /// Append at most 256 native batch views before a resumable boundary.
    pub(crate) fn advance_chunk(
        &mut self,
        history: &SharedHistoryBuffer,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if self.history_bounds != (history.head_index(), history.end_index()) {
            return internal_err!(
                "MATCH_RECOGNIZE history changed during replay preparation"
            );
        }
        let mut work = CoarseWorkBatch::new(completed);
        let result = (|| {
            let stop = self.batches.start.saturating_add(256).min(self.batches.end);
            while self.batches.start < stop {
                let batch = history.batch(self.batches.start);
                let end = if self.batches.start + 1 == self.batches.end {
                    self.last_batch_end
                } else {
                    batch.num_rows()
                };
                let len = end.checked_sub(self.batch_offset).ok_or_else(|| {
                    DataFusionError::Internal(
                        "MATCH_RECOGNIZE replay batch has reversed bounds".into(),
                    )
                })?;
                let cumulative =
                    self.collection.num_rows().checked_add(len).ok_or_else(|| {
                        DataFusionError::ResourcesExhausted(
                            "MATCH_RECOGNIZE replay row count exceeds usize".into(),
                        )
                    })?;
                self.collection.batches.push(
                    if self.batch_offset == 0 && end == batch.num_rows() {
                        batch.clone()
                    } else {
                        batch.slice(self.batch_offset, len)
                    },
                );
                self.collection.cumulative_rows.push(cumulative);
                self.key_rows.push(
                    history
                        .key_rows(self.batches.start)
                        .slice(self.batch_offset, len)?,
                );
                self.batches.start += 1;
                self.batch_offset = 0;
                work.complete_one()?;
            }
            let complete = self.batches.is_empty();
            if complete && self.collection.num_rows() != self.expected_rows {
                return internal_err!(
                    "MATCH_RECOGNIZE history replay contains {} rows, expected {}",
                    self.collection.num_rows(),
                    self.expected_rows
                );
            }
            Ok(complete)
        })();
        work.finish_result(result)
    }

    pub(crate) fn into_parts(
        self,
    ) -> (
        BatchCollection,
        Vec<crate::execution::matching::PartitionKeyRows>,
        MemoryReservation,
    ) {
        debug_assert!(self.batches.is_empty());
        debug_assert_eq!(self.collection.num_rows(), self.expected_rows);
        (self.collection, self.key_rows, self.memory)
    }
}

fn replay_metadata_overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE replay collection metadata exceeds usize".into(),
    )
}

impl BatchCollection {
    #[inline]
    pub(crate) fn bound_batch(&self, batch: usize) -> Option<&BoundBatchColumns> {
        self.bound.get(batch)
    }

    #[inline]
    pub(crate) fn bound_row(
        &self,
        batch: usize,
        local: usize,
    ) -> Option<BoundBatchRow<'_>> {
        self.bound_batch(batch)?.row(local)
    }

    pub(crate) fn bind_input_chunk(
        &mut self,
        index: usize,
        slots: &[usize],
        memory: &MemoryReservation,
        work: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if self.bound.is_empty() {
            self.bound = reserved_vec(self.batches.len(), memory, "bound input columns")?;
        }
        let batch = &self.batches[index];
        let width = slots
            .last()
            .map_or(0, |last| last + 1)
            .min(batch.num_columns());
        if self.bound.len() == index {
            self.bound
                .push(BoundBatchColumns::new(width, batch.num_rows(), memory)?);
        }
        let columns = &mut self.bound[index];
        let advanced = columns.bind_chunk(batch, slots, width);
        work(advanced.max(1))?;
        Ok(columns.width() == width)
    }

    pub(crate) fn into_batches(self) -> Vec<RecordBatch> {
        self.batches
    }

    /// Keep bound column handles alive until the governed retirement loop.
    pub(crate) fn into_retirement_parts(
        self,
    ) -> (Vec<RecordBatch>, Vec<BoundBatchColumns>) {
        (self.batches, self.bound)
    }

    /// Finish a preparation cursor that has checked every cumulative row count.
    pub(super) fn from_prepared_parts(
        batches: Vec<RecordBatch>,
        cumulative_rows: Vec<usize>,
        schema: SchemaRef,
    ) -> Self {
        debug_assert_eq!(batches.len(), cumulative_rows.len());
        Self {
            bound: Vec::new(),
            batches,
            cumulative_rows,
            schema,
        }
    }

    /// Construct a collection over batches that all share the same schema.
    ///
    /// Returns a resource error if their cumulative row count exceeds `usize`.
    #[cfg(test)]
    pub fn try_new(batches: Vec<RecordBatch>, schema: SchemaRef) -> Result<Self> {
        let mut cum = 0usize;
        let mut cumulative_rows = Vec::new();
        cumulative_rows.try_reserve(batches.len()).map_err(|error| {
            DataFusionError::ResourcesExhausted(format!(
                "MATCH_RECOGNIZE collection could not reserve {} cumulative batch rows: {error}",
                batches.len()
            ))
        })?;
        for batch in &batches {
            let batch_rows = batch.num_rows();
            cum = cum.checked_add(batch_rows).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE collection row count exceeds usize: {cum} existing rows plus {batch_rows} batch rows"
                ))
            })?;
            cumulative_rows.push(cum);
        }

        Ok(Self {
            bound: Vec::new(),
            batches,
            cumulative_rows,
            schema,
        })
    }

    /// Create an empty collection with the given schema.
    pub fn empty(schema: SchemaRef) -> Self {
        Self {
            bound: Vec::new(),
            batches: Vec::new(),
            cumulative_rows: Vec::new(),
            schema,
        }
    }

    /// Total number of rows across all batches.
    #[inline]
    pub fn num_rows(&self) -> usize {
        self.cumulative_rows.last().copied().unwrap_or(0)
    }

    /// Number of batches in the collection.
    #[inline]
    pub fn num_batches(&self) -> usize {
        self.batches.len()
    }

    /// Whether the collection contains no `RecordBatch` values.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.batches.is_empty()
    }

    /// Get the schema shared by the collection's batches.
    #[inline]
    pub(in crate::execution) fn schema(&self) -> &SchemaRef {
        &self.schema
    }

    /// Map a collection-wide row index to `(batch_index, row_in_batch)`.
    ///
    /// `global_row` must be less than `self.num_rows()`. Debug builds assert
    /// this precondition.
    #[inline]
    pub fn locate(&self, global_row: usize) -> (usize, usize) {
        debug_assert!(
            global_row < self.num_rows(),
            "BatchCollection::locate: global_row {} >= num_rows {}. Batches: {}",
            global_row,
            self.num_rows(),
            self.batches.len()
        );

        if self.batches.len() == 1 {
            return (0, global_row);
        }
        let batch_idx = self
            .cumulative_rows
            .partition_point(|&end| end <= global_row);
        debug_assert_eq!(self.batches[batch_idx].schema(), self.schema);
        let batch_start = if batch_idx == 0 {
            0
        } else {
            self.cumulative_rows[batch_idx - 1]
        };
        (batch_idx, global_row - batch_start)
    }

    /// Locate one retained input row while reporting a complete lookup's work.
    pub(crate) fn locate_with_work(
        &self,
        global_row: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<(usize, usize)> {
        if global_row >= self.num_rows() {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE collection row {global_row} is outside {} rows",
                self.num_rows()
            );
        }
        let location = self.locate(global_row);
        completed(1)?;
        Ok(location)
    }

    /// Get a reference to a specific batch.
    #[inline]
    pub fn batch(&self, idx: usize) -> &RecordBatch {
        &self.batches[idx]
    }

    /// Restore the working schema using an owned batch's existing Arrow handles.
    pub(crate) fn replace_input_columns(
        batch: RecordBatch,
        schema: &SchemaRef,
        replacements: &mut Vec<(usize, ArrayRef)>,
        memory: &MemoryReservation,
    ) -> Result<RecordBatch> {
        use datafusion::arrow::record_batch::RecordBatchOptions;
        let (_, mut columns, rows) = batch.into_parts();
        let width = schema.fields().len();
        if width > columns.len() {
            // Admit the widened handle vector before reallocating the owned raw prefix.
            memory.try_grow(
                width
                    .checked_mul(size_of::<ArrayRef>())
                    .ok_or_else(gather_size_overflow)?,
            )?;
            columns
                .try_reserve_exact(width - columns.len())
                .map_err(|e| {
                    DataFusionError::ResourcesExhausted(format!(
                        "MATCH_RECOGNIZE working batch columns: {e}"
                    ))
                })?;
            replacements.sort_unstable_by_key(|(slot, _)| *slot);
        }
        for (slot, value) in replacements.drain(..) {
            if slot >= width {
                return internal_err!(
                    "MATCH_RECOGNIZE working column {slot} exceeds schema width {width}"
                );
            }
            if slot == columns.len() {
                columns.push(value);
            } else if let Some(col) = columns.get_mut(slot) {
                *col = value;
            } else {
                return internal_err!(
                    "MATCH_RECOGNIZE missing working column before slot {slot}"
                );
            }
        }
        let options = RecordBatchOptions::new().with_row_count(Some(rows));
        Ok(RecordBatch::try_new_with_options(
            schema.clone(),
            columns,
            &options,
        )?)
    }

    pub(crate) fn push_input_view(
        &mut self,
        batch: RecordBatch,
        memory: &MemoryReservation,
    ) -> Result<()> {
        try_reserve_accounted(&mut self.batches, memory, 1, "input view metadata")?;
        try_reserve_accounted(
            &mut self.cumulative_rows,
            memory,
            1,
            "input view metadata",
        )?;
        self.cumulative_rows.push(
            self.num_rows()
                .checked_add(batch.num_rows())
                .ok_or_else(gather_size_overflow)?,
        );
        self.batches.push(batch);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
    use datafusion::arrow::array::{Array, Int32Array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };
    use std::sync::Arc;

    fn make_batch(start: i32, count: i32) -> RecordBatch {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let values: Vec<i32> = (start..start + count).collect();
        RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(values))]).unwrap()
    }

    #[test]
    fn test_locate() {
        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
        let batches = vec![make_batch(0, 10), make_batch(10, 20), make_batch(30, 5)];

        let coll = BatchCollection::try_new(batches, schema).unwrap();

        assert_eq!(coll.num_rows(), 35);
        assert_eq!(coll.locate(0), (0, 0));
        assert_eq!(coll.locate(9), (0, 9));
        assert_eq!(coll.locate(10), (1, 0));
        assert_eq!(coll.locate(29), (1, 19));
        assert_eq!(coll.locate(30), (2, 0));
        assert_eq!(coll.locate(34), (2, 4));
    }

    #[test]
    fn single_batch_lookup_checks_bounds_and_reports_one_completed_unit() {
        let batch = make_batch(10, 3);
        let collection =
            BatchCollection::try_new(vec![batch.clone()], batch.schema()).unwrap();
        let mut charged = 0;
        let mut completed = |n| {
            charged += n;
            Ok(())
        };
        assert_eq!(
            collection.locate_with_work(2, &mut completed).unwrap(),
            (0, 2)
        );
        assert!(collection.locate_with_work(3, &mut completed).is_err());
        assert_eq!(charged, 1);
        assert!(
            collection
                .locate_with_work(0, &mut |_| {
                    internal_err!("cancelled single-batch lookup")
                })
                .is_err()
        );
    }

    fn get_values(coll: &BatchCollection) -> Vec<i32> {
        let mut values = Vec::new();
        for batch in &coll.batches {
            let col = batch
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap();
            values.extend(col.values().iter().copied());
        }
        values
    }

    fn injected_work_failure(target_report: usize) -> impl FnMut(usize) -> Result<()> {
        let mut reports = 0usize;
        move |units| {
            assert!(units <= COARSE_WORK_BATCH_SIZE);
            reports += 1;
            if reports == target_report {
                Err(DataFusionError::Execution(
                    "injected collection work failure".to_string(),
                ))
            } else {
                Ok(())
            }
        }
    }

    #[test]
    fn replay_chunks_retain_admitted_metadata_until_release() -> Result<()> {
        let limit = 1024 * 1024;
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
        let template = MemoryConsumer::new("replay-test").register(&pool);
        let schema = make_batch(0, 1).schema();
        let mut history =
            SharedHistoryBuffer::new(Arc::clone(&schema), template.new_empty());
        for batch in 0..258 {
            history.append(make_batch(batch * 2, 2))?;
        }
        let history_bytes = pool.reserved();
        let blocker = template.new_empty();
        blocker.try_grow(limit - history_bytes)?;
        let error = PreparingReplayCollection::try_new(
            &history,
            3,
            515,
            Arc::clone(&schema),
            template.new_empty(),
        )
        .expect_err("replay metadata must be admitted before retaining slices");
        assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
        assert_eq!(pool.reserved(), limit);
        assert_eq!((history.head_index(), history.end_index()), (0, 516));
        drop(blocker);
        assert_eq!(pool.reserved(), history_bytes);

        let mut pending = PreparingReplayCollection::try_new(
            &history,
            3,
            515,
            Arc::clone(&schema),
            template.new_empty(),
        )?;
        let admitted = pending.memory.size();
        assert!(admitted > 0);
        assert_eq!(pool.reserved(), history_bytes + admitted);
        let mut work = 0;
        assert!(!pending.advance_chunk(&history, &mut |units| {
            assert!(units <= COARSE_WORK_BATCH_SIZE);
            work += units;
            Ok(())
        })?);
        assert_eq!(work, 256);
        assert_eq!(pending.collection.num_batches(), 256);
        assert_eq!(pending.collection.num_rows(), 511);
        assert_eq!(pending.memory.size(), admitted);
        assert_eq!(pool.reserved(), history_bytes + admitted);
        drop(pending);
        assert_eq!(pool.reserved(), history_bytes);

        let mut pending = PreparingReplayCollection::try_new(
            &history,
            3,
            515,
            schema,
            template.new_empty(),
        )?;
        pending
            .advance_chunk(&history, &mut injected_work_failure(1))
            .expect_err("cancellation must preserve the last completed slice cursor");
        assert_eq!(pending.collection.num_batches(), COARSE_WORK_BATCH_SIZE);
        while !pending.advance_chunk(&history, &mut |_| Ok(()))? {}
        let (collection, key_rows, memory) = pending.into_parts();
        assert_eq!(get_values(&collection), (3..515).collect::<Vec<_>>());
        assert_eq!(collection.num_batches(), 257);
        assert_eq!(collection.batch(0).num_rows(), 1);
        assert_eq!(collection.batch(256).num_rows(), 1);
        let key_bytes = key_rows.capacity()
            * size_of::<crate::execution::matching::PartitionKeyRows>();
        assert!(memory.size() > 0);
        drop(key_rows);
        memory.try_shrink(key_bytes)?;

        // The previous end cuts through a source batch. A new replay can
        // select only its newly readable remainder while the old view stays intact.
        let mut remainder = PreparingReplayCollection::try_new(
            &history,
            515,
            516,
            collection.schema().clone(),
            template.new_empty(),
        )?;
        let mut work = 0;
        assert!(remainder.advance_chunk(&history, &mut |units| {
            work += units;
            Ok(())
        })?);
        assert_eq!(work, 1);
        let (remainder, keys, remainder_memory) = remainder.into_parts();
        assert_eq!(keys.len(), 1);
        assert_eq!(get_values(&remainder), [515]);
        assert_eq!(get_values(&collection), (3..515).collect::<Vec<_>>());
        assert_eq!(remainder.num_batches(), 1);
        assert_eq!(remainder.batch(0).num_rows(), 1);
        assert!(remainder_memory.size() > 0);
        assert_eq!(
            pool.reserved(),
            history_bytes + memory.size() + remainder_memory.size()
        );
        drop(remainder);
        drop(keys);
        drop(remainder_memory);
        assert_eq!(pool.reserved(), history_bytes + memory.size());
        drop(collection);
        drop(memory);
        assert_eq!(pool.reserved(), history_bytes);
        drop(history);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }
}