datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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
// 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.

//! Collection setup, batch projection, and scan-context preparation.

use super::*;
use crate::config::CancellationPolicy;
use crate::execution::matching::row_loop::state::{
    CollectionWindow, PendingCollectionSetup,
};

impl PatternMatcher {
    pub(super) fn prepare_collection_setup_windowed<'a>(
        &mut self,
        scan_ctx: &mut ScanContext,
        input: &mut ProcessRowsInput<'a>,
        read_end_row: usize,
    ) -> Result<Option<(CollectionSetup<'a>, NextMatchCursor)>> {
        let batches = input.batches;
        let start_row = input.start_row;
        let total_rows_in_collection = batches.num_rows();
        let final_flush = input.final_flush;
        let history_buffer = input.history_buffer;
        let global_offset = input.global_offset;

        let n_states = self.automaton().nfa().state_count();
        let n_symbols = self.automaton().id_to_symbol().len();
        let provider_origin = global_offset.checked_add(start_row).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE Boolean provider origin exceeds usize".to_string(),
            )
        })?;

        let read_len = read_end_row.checked_sub(start_row).ok_or_else(|| {
            DataFusionError::Internal(format!(
                "MATCH_RECOGNIZE collection read end {read_end_row} precedes start {start_row}"
            ))
        })?;
        let total_rows = read_len.checked_add(1).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE collection scan extent exceeds usize".to_string(),
            )
        })?;
        let absolute_read_end =
            global_offset.checked_add(read_end_row).ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE provider end exceeds usize".to_string(),
                )
            })?;

        let cancellation_policy = CancellationPolicy::try_from_configured(
            self.program.config().cancellation_poll_interval,
            self.program.config().execution_deadline_millis,
        )?;
        let array_arena_policy = crate::execution::matching::row_loop::arena::SingleRowArrayArenaPolicy::try_from_configured(
            self.program.config().single_row_array_cache_max_entries,
            self.program.config().single_row_array_cache_max_bytes,
        )
        .map_err(DataFusionError::Configuration)?;

        let window = CollectionWindow {
            head_generation: input.head_generation,
            provider_origin,
            provider_end: absolute_read_end,
            has_virtual_end: final_flush,
            backing_start: start_row,
            candidate_end_row: input.end_row,
        };
        scan_ctx.collection.validate_not_poisoned("step")?;
        scan_ctx.validate_execution_identity(
            self.execution_partition_id,
            self.program_id(),
        )?;

        scan_ctx.validate_logical_partition(input.partition_id)?;
        scan_ctx.collection.validate_pending_setup(
            scan_ctx,
            window,
            input.bool_columns,
        )?;
        scan_ctx
            .aggregation
            .scratch
            .array_arena
            .configure(array_arena_policy)?;
        scan_ctx
            .scan_state
            .governor
            .bind_cancellation_policy(cancellation_policy)?;
        let preparing = scan_ctx.collection.is_preparing();
        let fresh = scan_ctx.collection.is_idle();
        let starting = fresh || preparing;
        let retained_backing = if fresh {
            scan_ctx.validate_collection_start(input.partition_id)?;
            None
        } else if preparing {
            scan_ctx.collection.pending_backing()
        } else {
            scan_ctx.validate_collection_resume(input.partition_id, window)?
        };

        // Logical views share the physical head's immutable native columns.
        let reused_provider = retained_backing.is_some();
        let backing = if let Some(backing) = retained_backing {
            if !Arc::ptr_eq(&backing, input.bool_columns) {
                return internal_err!(
                    "MATCH_RECOGNIZE same-head Boolean backing changed"
                );
            }
            backing
        } else {
            scan_ctx
                .scan_state
                .governor
                .record_completed(1, || self.is_aborted())?;
            Arc::clone(input.bool_columns)
        };
        let provider =
            MultiBatchBoolColumns::for_range(backing, start_row, read_end_row)?;

        scan_ctx.ensure_capacity(n_states, n_symbols)?;

        // An idle Start derives absence facts. A Resume continues either the
        // private preparation or the bound variant.
        if fresh
            && self.should_prune_absent_symbols(
                final_flush,
                start_row,
                read_end_row,
                total_rows_in_collection,
            )
        {
            let memory = scan_ctx.thread_store.state_memory().new_empty();
            let preparation = self.prepare_absent_symbol_pruning(read_len, &memory);
            scan_ctx.collection.begin_setup(PendingCollectionSetup {
                identity: scan_ctx.required_partition_identity("pattern preparation")?,
                window,
                backing: provider.backing(),
                preparation,
            });
        }
        let variant = if scan_ctx.collection.is_preparing() {
            let Some(variant) =
                scan_ctx.advance_collection_setup(self, &provider, input.yield_policy)?
            else {
                return Ok(None);
            };
            ActiveVariant::from_pruned(variant, self.program.base_variant())
        } else if !fresh {
            scan_ctx.active_variant.clone().ok_or_else(|| {
                DataFusionError::Internal(
                    "MATCH_RECOGNIZE collection setup did not bind an active executable variant"
                        .to_string(),
                )
            })?
        } else {
            ActiveVariant::base(self.program.base_variant())
        };

        if !reused_provider || starting {
            if starting {
                scan_ctx.prepare_collection_start(provider_origin);
                scan_ctx.install_active_variant(variant.clone())?;
                if !variant.is_base()
                    && let Some(metrics) = &self.services.metrics
                {
                    metrics.static_absence_pruned_partitions.add(1);
                }
            }
            let binding =
                scan_ctx.prepare_collection_binding(window, provider.backing())?;
            if !starting && scan_ctx.has_live_continuation() {
                scan_ctx.bind_continuation_head(
                    provider_origin,
                    absolute_read_end,
                    final_flush,
                )?;
            }
            scan_ctx.collection.commit_binding(binding);
        }
        scan_ctx.partition.global_row_offset = global_offset;
        scan_ctx.partition.partition_start_row = start_row;
        scan_ctx.partition.partition_end_row = read_end_row;

        log::debug!(
            target: "datafusion_match_recognize::execution::matching::collection",
            event = "prepare_collection",
            partition_start_row = scan_ctx.partition.partition_start_row,
            partition_end_row = scan_ctx.partition.partition_end_row,
            global_offset = scan_ctx.partition.global_row_offset,
            fresh;
            "prepare_collection: partition_start_row={}, partition_end_row={}, global_offset={}, fresh={}",
            scan_ctx.partition.partition_start_row,
            scan_ctx.partition.partition_end_row,
            scan_ctx.partition.global_row_offset,
            fresh
        );

        let cursor = if starting {
            NextMatchCursor {
                row_idx: provider_origin,
            }
        } else {
            scan_ctx.cursor
        };
        Ok(Some((
            CollectionSetup {
                provider_origin,
                absolute_read_end,
                provider,
                total_rows,
                variant,
                input_buffer: batches,
                final_flush,
                history_buffer,
            },
            cursor,
        )))
    }

    pub(super) fn run_windowed_collection<'a>(
        &mut self,
        scan_ctx: &mut ScanContext,
        input: &mut ProcessRowsInput<'a>,
        read_end_row: usize,
    ) -> Result<(ComputeStep, bool)> {
        // Tiny fresh segments can stay entirely in the inline driver. A
        // segment that may compile an absence variant keeps the clock check.
        let inline_only = scan_ctx.collection.is_idle()
            && (input.start_row != 0 || read_end_row != input.batches.num_rows())
            && !self.should_prune_absent_symbols(
                input.final_flush,
                input.start_row,
                read_end_row,
                input.batches.num_rows(),
            );
        let Some((setup, cursor)) =
            self.prepare_collection_setup_windowed(scan_ctx, input, read_end_row)?
        else {
            return Ok((ComputeStep::Yield, false));
        };

        let end_row = input.end_row;
        let out = &mut *input.out;
        let pending_output = &mut *input.pending_output;
        let metrics = input.metrics;
        let yield_policy = input.yield_policy;
        let global_offset = scan_ctx.partition.global_row_offset;
        let end_row = global_offset.checked_add(end_row).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE collection end cannot be represented as usize".into(),
            )
        })?;
        let read_end_row = setup.absolute_read_end;
        let resolved_variant = setup.variant.resolve(self.program.base_variant());
        let min_match_rows = resolved_variant.automaton().min_match_rows();
        let max_match_rows = resolved_variant.automaton().max_match_rows();
        let anchored_at_end = resolved_variant.automaton().anchored_at_end();

        MatchAwareCandidates {
            anchor_head: input
                .candidate_end_row
                .is_none()
                .then_some((input.partition_id, input.head_generation)),
            lane: lane_scan::LaneCollection::new(),
            starts: Default::default(),
            matcher: self,
            setup,
            end_row,
            read_end_row,
            out,
            stop_on_output: input.stop_on_output,
            pending_output_at_start: pending_output.len(),
            pending_output,
            metrics,
            yield_policy,
            row_idx: cursor.row_idx,
            min_match_rows,
            max_match_rows,
            anchored_at_end,
            candidate_cleanup_finalized: false,
            inline_only,
            skip_direct: input.skip_direct,
            batched_base_routes: input.batched_base_routes.as_deref_mut(),
            scan_ctx,
        }
        .run()
    }

    pub(crate) fn begin_physical_bool_columns(
        &self,
        rows: usize,
        memory: datafusion_execution::memory_pool::MemoryReservation,
    ) -> Result<crate::execution::matching::PreparingPhysicalBoolColumns> {
        let base = self.program.base_variant();
        let prechecks = base.symbol_execution_plan();
        crate::execution::matching::PreparingPhysicalBoolColumns::try_new(
            self.automaton().id_to_symbol().len(),
            base.active_symbol_columns().columns().len(),
            prechecks.static_precheck_columns().len(),
            Arc::clone(prechecks.static_precheck_slots()),
            rows,
            memory,
        )
    }

    pub(crate) fn advance_physical_bool_columns(
        &self,
        pending: &mut crate::execution::matching::PreparingPhysicalBoolColumns,
        batches: &BatchCollection,
    ) -> Result<bool> {
        let base = self.program.base_variant();
        pending.advance(
            batches,
            base.active_symbol_columns().columns(),
            base.symbol_execution_plan().static_precheck_columns(),
        )
    }

    #[cfg(test)]
    pub(crate) fn physical_bool_columns_for_test(
        &self,
        batches: &BatchCollection,
    ) -> Result<
        Arc<crate::execution::matching::symbol_columns::MultiBatchBoolColumnsBacking>,
    > {
        let mut pending = self.begin_physical_bool_columns(
            batches.num_rows(),
            crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
        )?;
        while !self.advance_physical_bool_columns(&mut pending, batches)? {}
        pending.finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{MatchRecognizeConfig, YieldPolicy};

    use crate::core::{NormalizedPattern, Pattern, RowsPerMatch, Symbol, SymbolId};
    use crate::execution::common::progress::ComputeStep;
    use crate::execution::matching::symbol_columns::MultiBatchBoolColumnsBacking;
    use crate::execution::matching::symbols::BoolColumnProvider;
    use crate::execution::matching::{CollectionTestDriver, test_output_program};
    use crate::nfa::CompiledAutomaton;
    use datafusion::arrow::array::{ArrayRef, BooleanArray, UInt32Array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::arrow::record_batch::RecordBatch;
    use datafusion::scalar::ScalarValue;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    fn setup_batch(values: Vec<bool>) -> RecordBatch {
        let rows = values.len();
        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::UInt32, false),
            Field::new("__mr_symbol_a", DataType::Boolean, false),
        ]));
        RecordBatch::try_new(
            schema,
            vec![
                Arc::new(UInt32Array::from_iter_values(0..rows as u32)) as ArrayRef,
                Arc::new(BooleanArray::from(values)) as ArrayRef,
            ],
        )
        .unwrap()
    }

    fn setup_driver(
        batch: RecordBatch,
        config: &MatchRecognizeConfig,
    ) -> CollectionTestDriver {
        let normalized_pattern =
            NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
        let compiled = Arc::new(
            CompiledAutomaton::compile(&normalized_pattern, &["A".into()]).unwrap(),
        );
        let output_spec =
            test_output_program(&batch, &compiled, vec![], RowsPerMatch::OneRow);
        CollectionTestDriver::try_new(
            batch,
            normalized_pattern,
            compiled,
            config,
            128,
            output_spec,
            |_| {},
        )
        .unwrap()
    }

    fn prepare_driver(
        driver: &mut CollectionTestDriver,
    ) -> Result<(Arc<MultiBatchBoolColumnsBacking>, bool)> {
        let read_end_row = driver.end_row;
        let scratch = driver.scratch.as_mut().expect("driver owns the partition");
        let mut input = ProcessRowsInput {
            stop_on_output: false,
            batches: &driver.collection,
            bool_columns: &driver.bool_columns,
            start_row: driver.start_row,
            end_row: driver.candidate_end_row.unwrap_or(driver.end_row),
            candidate_end_row: None,
            out: &mut driver.accumulator,
            pending_output: &mut driver.pending_output,
            history_buffer: None,
            metrics: &driver.metrics,
            yield_policy: YieldPolicy::Disabled,
            partition_id: driver.partition_id,
            head_generation: driver.head_generation,
            final_flush: driver.final_flush,
            global_offset: driver.global_offset,
            skip_direct: SkipDirect::None,
            batched_base_routes: None,
        };
        let prepared = driver.matcher.prepare_collection_setup_windowed(
            scratch,
            &mut input,
            read_end_row,
        );
        let (setup, cursor) = prepared?.expect("disabled yielding completes setup");
        // The full candidate driver resumes from the cursor returned by setup.
        scratch.cursor = cursor;
        let symbol = SymbolId::try_new(
            1,
            setup
                .variant
                .resolve(driver.matcher.program.base_variant())
                .automaton()
                .id_to_symbol()
                .len(),
        )
        .expect("test program must contain symbol A");
        let first_row_matches = setup
            .provider
            .locate(0)
            .is_some_and(|loc| setup.provider.get_bool_with_loc(symbol, loc));
        Ok((setup.provider.backing(), first_row_matches))
    }

    #[test]
    fn bound_slice_rejects_wrong_owner_cap_and_replayed_local_rows_before_commit() {
        let mut config = MatchRecognizeConfig::default();
        config.diagnostics.disable_pattern_optimizer = true;
        let mut driver = setup_driver(setup_batch(vec![false, true, false]), &config);
        driver.global_offset = 100;
        driver.start_row = 1;
        driver.end_row = 3;
        driver.candidate_end_row = Some(2);
        let (original, _) = prepare_driver(&mut driver).unwrap();
        let original_partition = driver.partition_id;
        driver.partition_id = MatchPartitionId::new(original_partition.get() + 1);
        let error = prepare_driver(&mut driver).unwrap_err();
        assert!(error.to_string().contains("partition mismatch"), "{error}");
        driver.partition_id = original_partition;
        driver.candidate_end_row = None;
        let error = prepare_driver(&mut driver).unwrap_err();
        assert!(
            error.to_string().contains("collection head 1 changed"),
            "{error}"
        );
        // Identical absolute extents and owned end, different rows in the same backing.
        driver.global_offset = 101;
        driver.start_row = 0;
        driver.end_row = 2;
        driver.candidate_end_row = Some(1);
        let error = prepare_driver(&mut driver).unwrap_err();
        assert!(
            error.to_string().contains("collection head 1 changed"),
            "{error}"
        );
        driver.global_offset = 100;
        driver.start_row = 1;
        driver.end_row = 3;
        driver.candidate_end_row = Some(2);
        let mut other = setup_driver(setup_batch(vec![false, true, false]), &config);
        std::mem::swap(&mut other.matcher, &mut driver.matcher);
        let error = prepare_driver(&mut driver).unwrap_err();
        assert!(
            error.to_string().contains("scan context program changed"),
            "{error}"
        );
        std::mem::swap(&mut other.matcher, &mut driver.matcher);
        let (retry, _) = prepare_driver(&mut driver).unwrap();
        assert!(Arc::ptr_eq(&original, &retry));
        assert!(driver.pending_output.is_empty());
    }

    #[test]
    fn absence_scan_yields_before_publishing_the_collection() {
        const ROWS: usize = 1_024;
        let mut values = vec![false; ROWS];
        values[ROWS - 1] = true;
        let mut driver =
            setup_driver(setup_batch(values), &MatchRecognizeConfig::default());

        assert_eq!(
            driver.step(YieldPolicy::from_test_budget(1), None).unwrap(),
            ComputeStep::Yield
        );
        let scan = driver.scratch.as_ref().unwrap();
        assert!(scan.collection.is_preparing());
        assert!(scan.active_variant.is_none());
        assert!(scan.collection.provider_backing().is_none());
        assert!(Arc::ptr_eq(
            &scan.collection.pending_backing().unwrap(),
            &driver.bool_columns
        ));
        assert!(
            scan.scan_state.governor.progress_epoch_for_observation() < ROWS as u64,
            "yield must happen before the absence scan reaches the last row"
        );

        driver.assert_bound_head();
        assert_eq!(
            driver.step(YieldPolicy::Disabled, None).unwrap(),
            ComputeStep::Complete
        );
        driver.flush_output(ROWS, true, None).unwrap();
        let output = driver.concat_output();
        let ids = output
            .column(0)
            .as_any()
            .downcast_ref::<UInt32Array>()
            .unwrap();
        assert_eq!(ids.values().as_ref(), &[(ROWS - 1) as u32]);
    }

    #[test]
    fn same_head_resume_reuses_backing_work_and_canonical_empty_partition_key() {
        let mut config = MatchRecognizeConfig::default();
        config.diagnostics.disable_pattern_optimizer = true;
        let singleton = crate::execution::matching::shared_empty_partition_key();
        for supplied in [None, Some(Arc::clone(&singleton))] {
            let mut driver = setup_driver(setup_batch(vec![false, false, true]), &config);
            driver.enable_matcher_metrics();
            driver.configure_initial_partition_key(supplied).unwrap();
            assert_eq!(
                driver.step(YieldPolicy::from_test_budget(1), None).unwrap(),
                ComputeStep::Yield
            );
            let scan = driver.scratch.as_ref().unwrap();
            let original = scan.collection.provider_backing().unwrap();
            let epoch = scan.scan_state.governor.progress_epoch_for_observation();
            assert!(Arc::ptr_eq(
                scan.partition.logical().unwrap().key.canonical().unwrap(),
                &singleton
            ));
            driver.assert_bound_head();
            let (resumed, _) = prepare_driver(&mut driver).unwrap();
            assert!(Arc::ptr_eq(&original, &resumed));
            let scan = driver.scratch.as_ref().unwrap();
            assert!(Arc::ptr_eq(
                scan.partition.logical().unwrap().key.canonical().unwrap(),
                &singleton
            ));
            assert_eq!(
                scan.scan_state.governor.progress_epoch_for_observation(),
                epoch
            );
        }
    }

    #[test]
    fn newer_head_failure_is_atomic_and_retry_observes_owned_slice() {
        let mut config = MatchRecognizeConfig::default();
        config.diagnostics.disable_pattern_optimizer = true;
        config.limits.cancellation_poll_interval = 1;
        let mut driver = setup_driver(setup_batch(vec![false; 20]), &config);
        driver.enable_matcher_metrics();
        driver.global_offset = 100;
        driver.end_row = 20;
        driver.final_flush = false;
        let canonical_key = crate::execution::matching::owned_partition_key(vec![
            ScalarValue::Utf8(Some("wide-partition-key".repeat(8))),
            ScalarValue::Decimal128(Some(12_345), 20, 4),
        ]);
        driver
            .configure_initial_partition_key(Some(Arc::clone(&canonical_key)))
            .unwrap();
        driver.head_generation = CollectionHeadGeneration::new(4);

        let (old_backing, old_value) = prepare_driver(&mut driver).unwrap();
        assert!(!old_value);
        let scan = driver.scratch.as_ref().unwrap();
        let old_variant = Arc::clone(
            scan.active_variant
                .as_ref()
                .unwrap()
                .resolve(driver.matcher.program.base_variant()),
        );
        assert!(Arc::ptr_eq(
            scan.partition.logical().unwrap().key.canonical().unwrap(),
            &canonical_key
        ));
        driver.scratch.as_mut().unwrap().cursor.row_idx = 110;

        let mut new_values = vec![false; 30];
        new_values[8] = true;
        let new_batch = setup_batch(new_values);
        driver
            .replace_collection(
                BatchCollection::try_new(vec![new_batch.clone()], new_batch.schema())
                    .unwrap(),
            )
            .unwrap();
        driver.start_row = 8;
        driver.end_row = 30;
        driver.head_generation = CollectionHeadGeneration::new(5);

        let abort = Arc::new(AtomicBool::new(true));
        driver.matcher.services.abort_signal = Some(Arc::clone(&abort));
        let error = prepare_driver(&mut driver).unwrap_err();
        assert!(error.to_string().contains("cancelled"), "{error}");
        let scan = driver.scratch.as_ref().unwrap();
        assert_eq!(
            scan.collection.head_generation(),
            Some(CollectionHeadGeneration::new(4))
        );
        assert!(!scan.collection.is_preparing());
        assert!(Arc::ptr_eq(
            &old_backing,
            &scan.collection.provider_backing().unwrap()
        ));
        assert!(Arc::ptr_eq(
            scan.partition.logical().unwrap().key.canonical().unwrap(),
            &canonical_key
        ));

        abort.store(false, Ordering::Relaxed);
        let (new_backing, new_value) = prepare_driver(&mut driver).unwrap();
        assert!(new_value);
        assert!(!Arc::ptr_eq(&old_backing, &new_backing));
        let old_slots = &old_backing.pre_check_slots;
        assert!(Arc::ptr_eq(old_slots, &new_backing.pre_check_slots));
        let scan = driver.scratch.as_ref().unwrap();
        assert!(Arc::ptr_eq(
            &old_variant,
            scan.active_variant
                .as_ref()
                .unwrap()
                .resolve(driver.matcher.program.base_variant())
        ));
        assert!(Arc::ptr_eq(
            scan.partition.logical().unwrap().key.canonical().unwrap(),
            &canonical_key
        ));

        drop(driver);
        let symbol = SymbolId::try_new(1, 2).unwrap();
        let old_provider = MultiBatchBoolColumns::from_backing(old_backing);
        let old_location = old_provider.locate(0).unwrap();
        assert!(!old_provider.get_bool_with_loc(symbol, old_location));
        let new_provider = MultiBatchBoolColumns::for_range(new_backing, 8, 30).unwrap();
        let new_location = new_provider.locate(0).unwrap();
        assert!(new_provider.get_bool_with_loc(symbol, new_location));
    }
}