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

//! Bounded reuse of single-row Arrow arrays during fallback expression evaluation.

use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash, Hasher};
use std::mem::size_of;

use datafusion::arrow::array::{Array, ArrayRef};
use datafusion::arrow::datatypes::DataType;
use datafusion::scalar::ScalarValue;
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::memory_pool::MemoryReservation;
use hashbrown::{Equivalent, HashTable};

use crate::config::{
    DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES, DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES,
    MAX_SINGLE_ROW_ARRAY_CACHE_BYTES, MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES,
};
use crate::execution::common::progress::CoarseWorkCounter;

/// Charge the materialized array until the caller releases its last reference.
fn materialize_scalar(
    value: &ScalarValue,
    memory: &MemoryReservation,
) -> Result<ArrayRef> {
    let array = value.to_array_of_size(1)?;
    memory.try_grow(array.get_array_memory_size())?;
    Ok(array)
}

/// Validated bound for one scan-local dynamic array cache.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SingleRowArrayArenaPolicy {
    max_dynamic_entries: usize,
    max_dynamic_bytes: usize,
}

impl SingleRowArrayArenaPolicy {
    /// Validate public session limits before fallback evaluation begins.
    pub(crate) fn try_from_configured(
        max_dynamic_entries: usize,
        max_dynamic_bytes: usize,
    ) -> std::result::Result<Self, String> {
        if max_dynamic_entries > MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES {
            return Err(format!(
                "match_recognize.limits.single_row_array_cache_max_entries must not exceed {MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES}"
            ));
        }
        if max_dynamic_bytes > MAX_SINGLE_ROW_ARRAY_CACHE_BYTES {
            return Err(format!(
                "match_recognize.limits.single_row_array_cache_max_bytes must not exceed {MAX_SINGLE_ROW_ARRAY_CACHE_BYTES}"
            ));
        }
        Ok(Self {
            max_dynamic_entries,
            max_dynamic_bytes,
        })
    }
}

impl Default for SingleRowArrayArenaPolicy {
    fn default() -> Self {
        Self {
            max_dynamic_entries: DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_ENTRIES,
            max_dynamic_bytes: DEFAULT_SINGLE_ROW_ARRAY_CACHE_MAX_BYTES,
        }
    }
}

#[derive(Debug)]
struct DynamicEntry {
    key: DynamicKey,
    array: ArrayRef,
    retained_bytes: usize,
    prev: Option<usize>,
    next: Option<usize>,
}

/// Expected O(1) intrusive LRU map backed by `hashbrown::HashTable` with zero
/// extra crate dependencies or duplicate key storage.
#[derive(Debug, Default)]
struct DynamicLru {
    hasher: RandomState,
    index: HashTable<usize>,
    slots: Vec<Option<DynamicEntry>>,
    free: Vec<usize>,
    head: Option<usize>,
    tail: Option<usize>,
}

impl DynamicLru {
    fn len(&self) -> usize {
        self.index.len()
    }

    #[cfg(test)]
    fn is_empty(&self) -> bool {
        self.index.is_empty()
    }

    fn slot(&self, idx: usize) -> &DynamicEntry {
        self.slots[idx].as_ref().expect("live LRU slot")
    }

    fn slot_mut(&mut self, idx: usize) -> &mut DynamicEntry {
        self.slots[idx].as_mut().expect("live LRU slot")
    }

    fn touch_get(&mut self, key: &DynamicKeyRef<'_>) -> Option<ArrayRef> {
        let hash = self.hasher.hash_one(key.value);
        let idx = *self
            .index
            .find(hash, |&idx| key.equivalent(&self.slot(idx).key))?;
        self.move_to_back(idx);
        Some(self.slot(idx).array.clone())
    }

    fn move_to_back(&mut self, idx: usize) {
        if self.tail == Some(idx) {
            return;
        }
        let (prev, next) = {
            let entry = self.slot_mut(idx);
            (entry.prev.take(), entry.next.take())
        };
        match prev {
            Some(p) => self.slot_mut(p).next = next,
            None => self.head = next,
        }
        if let Some(n) = next {
            self.slot_mut(n).prev = prev;
        }
        self.link_back(idx);
    }

    fn link_back(&mut self, idx: usize) {
        let old_tail = self.tail.replace(idx);
        let entry = self.slot_mut(idx);
        entry.prev = old_tail;
        entry.next = None;
        match old_tail {
            Some(t) => self.slot_mut(t).next = Some(idx),
            None => self.head = Some(idx),
        }
    }

    fn pop_front(&mut self) {
        let Some(idx) = self.head else {
            return;
        };
        let entry = self.slots[idx].take().expect("head slot is live");
        self.head = entry.next;
        match entry.next {
            Some(n) => self.slot_mut(n).prev = None,
            None => self.tail = None,
        }
        let hash = self.hasher.hash_one(&entry.key);
        if let Ok(found) = self.index.find_entry(hash, |&slot| slot == idx) {
            found.remove();
        }
        self.free.push(idx);
    }

    fn insert(&mut self, key: DynamicKey, array: ArrayRef, retained_bytes: usize) {
        let hash = self.hasher.hash_one(&key);
        let entry = DynamicEntry {
            key,
            array,
            retained_bytes,
            prev: None,
            next: None,
        };
        let idx = if let Some(slot) = self.free.pop() {
            self.slots[slot] = Some(entry);
            slot
        } else {
            let slot = self.slots.len();
            self.slots.push(Some(entry));
            slot
        };
        self.link_back(idx);
        let hasher = &self.hasher;
        let slots = &self.slots;
        self.index.insert_unique(hash, idx, |&existing| {
            hasher.hash_one(&slots[existing].as_ref().expect("live LRU slot").key)
        });
    }

    #[cfg(test)]
    fn contains(&self, key: &DynamicKeyRef<'_>) -> bool {
        let hash = self.hasher.hash_one(key.value);
        self.index
            .find(hash, |&idx| key.equivalent(&self.slot(idx).key))
            .is_some()
    }
}

#[derive(Debug, PartialEq, Eq)]
struct DynamicKey {
    data_type: DataType,
    value: ScalarValue,
}

impl Hash for DynamicKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Scalar hashes select buckets; exact type equality resolves metadata
        // collisions without hashing the Arrow type on every lookup.
        self.value.hash(state);
    }
}

/// Borrow the scalar payload while requiring exact Arrow type identity.
/// Scalar equality alone ignores fixed-binary widths and timestamp timezones.
struct DynamicKeyRef<'a> {
    data_type: DataType,
    value: &'a ScalarValue,
}

impl Equivalent<DynamicKey> for DynamicKeyRef<'_> {
    fn equivalent(&self, key: &DynamicKey) -> bool {
        self.data_type == key.data_type && self.value == &key.value
    }
}

#[derive(Debug, Default)]
struct CommonArrays {
    null: Option<ArrayRef>,
    booleans: [Option<ArrayRef>; 3],
    int64: [Option<ArrayRef>; 18],
    uint64: [Option<ArrayRef>; 17],
}

impl CommonArrays {
    fn slot(&mut self, value: &ScalarValue) -> Option<&mut Option<ArrayRef>> {
        Some(match value {
            ScalarValue::Null => &mut self.null,
            ScalarValue::Boolean(value) => {
                &mut self.booleans[value.map_or(0, |v| 1 + usize::from(v))]
            }
            ScalarValue::Int64(Some(v @ -1..=16)) => &mut self.int64[(v + 1) as usize],
            ScalarValue::UInt64(Some(v @ 0..=16)) => &mut self.uint64[*v as usize],
            _ => return None,
        })
    }
}

/// Cache from fallback `ScalarValue`s to one-row Arrow arrays.
///
/// Common scalars use fixed slots. Dynamic entries are ordered oldest first
/// and bounded by both count and estimated key, array and entry bytes.
#[derive(Debug)]
pub struct SingleRowArrayArena {
    common: CommonArrays,
    dynamic: DynamicLru,
    policy: SingleRowArrayArenaPolicy,
    dynamic_bytes: usize,
    peak_entries: usize,
    reservation: MemoryReservation,
}

impl Default for SingleRowArrayArena {
    fn default() -> Self {
        let state_memory = super::state_growth::new_unbounded_state_memory();
        Self::with_reservation(state_memory.new_empty(), Default::default())
    }
}

impl SingleRowArrayArena {
    pub(crate) fn with_reservation(
        reservation: MemoryReservation,
        policy: SingleRowArrayArenaPolicy,
    ) -> Self {
        Self {
            common: CommonArrays::default(),
            dynamic: DynamicLru::default(),
            policy,
            reservation,
            dynamic_bytes: 0,
            peak_entries: 0,
        }
    }

    /// Rebind an empty arena to validated limits. Live entries cannot silently
    /// change ownership or become out of policy during a resumable scan.
    pub(crate) fn configure(&mut self, policy: SingleRowArrayArenaPolicy) -> Result<()> {
        if self.policy == policy {
            return Ok(());
        }
        if self.reservation.size() != 0 {
            return Err(DataFusionError::Internal(
                "MATCH_RECOGNIZE single-row array cache policy changed while entries were retained"
                    .to_string(),
            ));
        }
        self.policy = policy;
        Ok(())
    }

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

    fn dynamic_entry_bytes(value: &ScalarValue, array: &ArrayRef) -> Result<usize> {
        value
            .size()
            .checked_add(array.data_type().size())
            .and_then(|bytes| bytes.checked_add(array.get_array_memory_size()))
            .and_then(|bytes| bytes.checked_add(size_of::<DynamicEntry>()))
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE single-row array cache entry size overflowed"
                        .to_string(),
                )
            })
    }

    fn get_single_row_array(
        &mut self,
        value: &ScalarValue,
        transient: &MemoryReservation,
        work: &mut CoarseWorkCounter,
        report: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<ArrayRef> {
        // These scalars already own a one-row array. Conversion only clones its
        // Arc, so hashing their nested contents and retaining a cache key adds work.
        if matches!(
            value,
            ScalarValue::List(_)
                | ScalarValue::LargeList(_)
                | ScalarValue::ListView(_)
                | ScalarValue::LargeListView(_)
                | ScalarValue::FixedSizeList(_)
                | ScalarValue::Struct(_)
                | ScalarValue::Map(_)
        ) {
            return materialize_scalar(value, transient);
        }

        if let Some(slot) = self.common.slot(value) {
            if let Some(array) = slot {
                transient.try_grow(array.get_array_memory_size())?;
                return Ok(array.clone());
            }
            let array = materialize_scalar(value, transient)?;
            self.reservation.try_grow(array.get_array_memory_size())?;
            *slot = Some(array.clone());
            return Ok(array);
        }

        let key = DynamicKeyRef {
            data_type: value.data_type(),
            value,
        };
        if let Some(array) = self.dynamic.touch_get(&key) {
            transient.try_grow(array.get_array_memory_size())?;
            return Ok(array);
        }

        let array = materialize_scalar(value, transient)?;
        let entry_bytes = Self::dynamic_entry_bytes(value, &array)?;
        if self.policy.max_dynamic_entries == 0
            || entry_bytes > self.policy.max_dynamic_bytes
        {
            return Ok(array);
        }

        // Inspect just the LRU prefix needed for admission. Keep it intact until
        // the pool accepts the net growth, including any reusable slot storage.
        let mut entries = self.dynamic.len() + 1;
        let mut bytes = self.dynamic_bytes + entry_bytes;
        let mut cursor = self.dynamic.head;
        while entries > self.policy.max_dynamic_entries
            || bytes > self.policy.max_dynamic_bytes
        {
            let entry = self
                .dynamic
                .slot(cursor.expect("an admissible entry fits an empty cache"));
            bytes -= entry.retained_bytes;
            entries -= 1;
            cursor = entry.next;
            work.complete_one(report)?;
        }
        if entries <= self.dynamic.len() {
            // Finish accounting for the lookup and its eviction prefix before commit.
            work.flush_result(Ok(()), report)?;
        }
        // The slot table and hash index recycle capacity after eviction. Charge
        // an approximate per-slot footprint at peak occupancy until clear frees it.
        const SLOT_BYTES: usize =
            size_of::<Option<DynamicEntry>>() + 2 * size_of::<usize>();
        let new_slots = entries.saturating_sub(self.peak_entries);
        let new_bytes = bytes + new_slots * SLOT_BYTES;
        if new_bytes > self.dynamic_bytes {
            self.reservation.try_grow(new_bytes - self.dynamic_bytes)?;
        }

        while self.dynamic.len() >= entries {
            self.dynamic.pop_front();
        }
        self.dynamic.insert(
            DynamicKey {
                data_type: key.data_type,
                value: value.clone(),
            },
            array.clone(),
            entry_bytes,
        );
        if new_bytes < self.dynamic_bytes {
            self.reservation.shrink(self.dynamic_bytes - new_bytes);
        }
        self.dynamic_bytes = bytes;
        self.peak_entries = self.peak_entries.max(entries);
        Ok(array)
    }

    /// Charge the lookup plus each planned eviction, preserving lookup errors.
    pub(crate) fn get_single_row_array_governed(
        &mut self,
        value: &ScalarValue,
        transient: &MemoryReservation,
        report_completed_work: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<ArrayRef> {
        let mut work = CoarseWorkCounter::new();
        work.complete_one(report_completed_work)?;
        let before = transient.size();
        let lookup =
            self.get_single_row_array(value, transient, &mut work, report_completed_work);
        let result = work.finish_result(lookup, report_completed_work);
        if result.is_err() {
            transient.shrink(transient.size() - before);
        }
        result
    }

    #[cfg(test)]
    pub(crate) fn reserved_bytes(&self) -> usize {
        self.reservation.size()
    }

    #[cfg(test)]
    pub(crate) fn contains(&mut self, value: &ScalarValue) -> bool {
        if let Some(slot) = self.common.slot(value) {
            return slot.is_some();
        }
        let key = DynamicKeyRef {
            data_type: value.data_type(),
            value,
        };
        self.dynamic.contains(&key)
    }

    /// Release the arrays, keys and reusable LRU storage.
    pub fn clear(&mut self) {
        if self.reservation.size() == 0 {
            return;
        }
        self.common = CommonArrays::default();
        self.dynamic = DynamicLru::default();
        self.dynamic_bytes = 0;
        self.peak_entries = 0;
        self.reservation.free();
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use datafusion::scalar::ScalarValue;
    use datafusion_common::DataFusionError;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };

    use super::{ArrayRef, SingleRowArrayArena, SingleRowArrayArenaPolicy};

    fn lookup(arena: &mut SingleRowArrayArena, value: &ScalarValue) -> ArrayRef {
        let transient = arena.memory().new_empty();
        let entries_before = arena.dynamic.len();
        let hit = arena.contains(value);
        let mut reports = Vec::new();
        let array = arena
            .get_single_row_array_governed(value, &transient, &mut |units| {
                reports.push(units);
                Ok(())
            })
            .unwrap();
        let admitted = !hit
            && arena.dynamic.contains(&super::DynamicKeyRef {
                data_type: value.data_type(),
                value,
            });
        let evicted = entries_before + usize::from(admitted) - arena.dynamic.len();
        assert_eq!(reports.iter().sum::<usize>(), 1 + evicted);
        array
    }

    fn arena_with_pool(
        capacity: usize,
        entries: usize,
        bytes: usize,
    ) -> (Arc<dyn MemoryPool>, SingleRowArrayArena) {
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(capacity));
        let reservation =
            MemoryConsumer::new("single-row-array-arena-test").register(&pool);
        let policy =
            SingleRowArrayArenaPolicy::try_from_configured(entries, bytes).unwrap();
        (
            Arc::clone(&pool),
            SingleRowArrayArena::with_reservation(reservation, policy),
        )
    }

    fn assert_distinct_typed_entries<const N: usize>(mut values: [ScalarValue; N]) {
        for _ in 0..2 {
            let (pool, mut arena) = arena_with_pool(usize::MAX, N, 64 * 1024);
            let arrays = values.each_ref().map(|v| lookup(&mut arena, v));
            let reserved = pool.reserved();
            for (value, array) in values.iter().zip(&arrays) {
                assert_eq!(array.len(), 1);
                assert_eq!(array.data_type(), &value.data_type());
                assert_eq!(&ScalarValue::try_from_array(array, 0).unwrap(), value);
                assert!(Arc::ptr_eq(array, &lookup(&mut arena, value)));
            }
            assert_eq!(arena.dynamic.len(), N);
            assert_eq!(pool.reserved(), reserved);
            arena.clear();
            assert_eq!(pool.reserved(), 0);
            values.reverse();
        }
    }

    #[test]
    fn dynamic_cache_preserves_float_bits_and_fixed_binary_null_widths() {
        assert_distinct_typed_entries(
            [0.0, -0.0, f64::NAN, f64::from_bits(f64::NAN.to_bits() + 1)]
                .map(|v| ScalarValue::Float64(Some(v))),
        );
        assert_distinct_typed_entries([
            ScalarValue::FixedSizeBinary(3, None),
            ScalarValue::FixedSizeBinary(18, None),
        ]);
    }

    #[test]
    fn dynamic_cache_preserves_timestamp_units_and_timezone_metadata() {
        for value in [None, Some(0)] {
            assert_distinct_typed_entries([
                ScalarValue::TimestampNanosecond(value, None),
                ScalarValue::TimestampNanosecond(value, Some("UTC".into())),
                ScalarValue::TimestampNanosecond(value, Some("Europe/Paris".into())),
            ]);
        }
        assert_distinct_typed_entries([
            ScalarValue::TimestampSecond(Some(0), None),
            ScalarValue::TimestampMillisecond(Some(0), None),
            ScalarValue::TimestampMicrosecond(Some(0), None),
            ScalarValue::TimestampNanosecond(Some(0), None),
        ]);
    }

    #[test]
    fn common_slots_survive_dynamic_admission_and_clear_releases_both() {
        let (pool, mut arena) = arena_with_pool(usize::MAX, 1, 16 * 1024);
        for value in [
            ScalarValue::Null,
            ScalarValue::Boolean(None),
            ScalarValue::Boolean(Some(false)),
            ScalarValue::Boolean(Some(true)),
            ScalarValue::Int64(Some(-1)),
            ScalarValue::Int64(Some(16)),
            ScalarValue::UInt64(Some(0)),
            ScalarValue::UInt64(Some(16)),
        ] {
            let first = lookup(&mut arena, &value);
            let second = lookup(&mut arena, &value);
            assert!(Arc::ptr_eq(&first, &second));
            assert_eq!(ScalarValue::try_from_array(&first, 0).unwrap(), value);
        }
        assert!(arena.dynamic.is_empty());
        let dynamic = ScalarValue::Int64(Some(17));
        let array = lookup(&mut arena, &dynamic);
        assert_eq!(ScalarValue::try_from_array(&array, 0).unwrap(), dynamic);
        assert_eq!(arena.dynamic.len(), 1);
        let new_policy = SingleRowArrayArenaPolicy::default();
        assert!(arena.configure(new_policy).is_err());
        let common = ScalarValue::Int64(Some(-1));
        let cached = lookup(&mut arena, &common);
        assert!(pool.reserved() > 0);
        arena.clear();
        arena.configure(new_policy).unwrap();
        assert_eq!(Arc::strong_count(&cached), 1);
        assert_eq!(Arc::strong_count(&array), 1);
        assert_eq!(pool.reserved(), 0);
        assert!(!Arc::ptr_eq(&cached, &lookup(&mut arena, &common)));
    }

    #[test]
    fn entry_and_byte_limits_evict_the_least_recently_used_prefix() {
        let small = [17, 18, 19].map(|v| ScalarValue::Int64(Some(v)));
        let large = ScalarValue::Utf8(Some("x".repeat(4096)));
        let bytes = |v: &ScalarValue| {
            SingleRowArrayArena::dynamic_entry_bytes(v, &v.to_array().unwrap()).unwrap()
        };
        let tight_budget = bytes(&small[0]) + bytes(&large);
        for (budget, survivors) in [(64 * 1024, 3), (tight_budget, 2)] {
            let (pool, mut arena) = arena_with_pool(usize::MAX, 3, budget);
            let arrays = small.each_ref().map(|value| lookup(&mut arena, value));
            assert!(Arc::ptr_eq(&arrays[0], &lookup(&mut arena, &small[0])));
            lookup(&mut arena, &large);
            assert_eq!(arena.dynamic.len(), survivors);
            assert!(arena.contains(&large));
            assert!(arena.contains(&small[0]));
            assert!(!arena.contains(&small[1]));
            assert_eq!(arena.contains(&small[2]), survivors == 3);
            assert_eq!(
                arena.dynamic_bytes,
                bytes(&large) + (survivors - 1) * bytes(&small[0])
            );
            assert!(pool.reserved() >= arena.dynamic_bytes);
        }
    }

    #[test]
    fn byte_eviction_reports_the_prefix_before_changing_the_cache() {
        use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;

        let count = 2 * COARSE_WORK_BATCH_SIZE;
        let large = ScalarValue::Utf8(Some("x".repeat(64 * 1024)));
        let budget =
            SingleRowArrayArena::dynamic_entry_bytes(&large, &large.to_array().unwrap())
                .unwrap();
        let (pool, mut arena) = arena_with_pool(usize::MAX, count, budget);
        let values = (0..count)
            .map(|i| ScalarValue::Int64(Some(1000 + i as i64)))
            .collect::<Vec<_>>();
        let retained = values
            .iter()
            .map(|value| lookup(&mut arena, value))
            .collect::<Vec<_>>();
        let reserved = pool.reserved();
        for cancel_at in [COARSE_WORK_BATCH_SIZE, count + 1] {
            let mut total = 0;
            let error = arena
                .get_single_row_array_governed(
                    &large,
                    &arena.memory().new_empty(),
                    &mut |units| {
                        assert!(units <= COARSE_WORK_BATCH_SIZE);
                        total += units;
                        if total == cancel_at {
                            return Err(DataFusionError::Execution("cancelled".into()));
                        }
                        Ok(())
                    },
                )
                .unwrap_err();
            assert!(error.to_string().contains("cancelled"));
            assert_eq!(total, cancel_at);
            assert_eq!(pool.reserved(), reserved);
            assert_eq!(arena.dynamic.len(), count);
            assert!(!arena.contains(&large));
            let mut cursor = arena.dynamic.head;
            for (value, array) in values.iter().zip(&retained) {
                let entry = arena.dynamic.slot(cursor.unwrap());
                assert_eq!(&entry.key.value, value);
                assert!(Arc::ptr_eq(array, &entry.array));
                cursor = entry.next;
            }
            assert!(cursor.is_none());
        }
        lookup(&mut arena, &large);
        assert_eq!(arena.dynamic.len(), 1);
        assert!(retained.iter().all(|array| Arc::strong_count(array) == 1));
    }

    #[test]
    fn oversized_entries_and_zero_limits_skip_dynamic_retention() {
        let value = ScalarValue::Utf8(Some("uncached".into()));
        for (entries, bytes) in [(4, 1), (4, 0), (0, 4096)] {
            let (pool, mut arena) = arena_with_pool(usize::MAX, entries, bytes);
            let transient = arena.memory().new_empty();
            let first = arena
                .get_single_row_array_governed(&value, &transient, &mut |_| Ok(()))
                .unwrap();
            assert!(arena.dynamic.is_empty());
            assert_eq!(arena.reserved_bytes(), 0);
            assert_eq!(pool.reserved(), first.get_array_memory_size());
            drop(first);
            drop(transient);
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn array_backed_scalars_share_arrays_without_cache_entries() {
        use datafusion::arrow::datatypes::{DataType, Field};

        let field = Arc::new(Field::new("item", DataType::Int64, true));
        let entries = Arc::new(Field::new(
            "entries",
            DataType::Struct(
                vec![
                    Field::new("key", DataType::Int64, false),
                    Field::new("value", DataType::Int64, true),
                ]
                .into(),
            ),
            false,
        ));
        for data_type in [
            DataType::List(Arc::clone(&field)),
            DataType::LargeList(Arc::clone(&field)),
            DataType::ListView(Arc::clone(&field)),
            DataType::LargeListView(Arc::clone(&field)),
            DataType::FixedSizeList(Arc::clone(&field), 2),
            DataType::Struct(vec![field].into()),
            DataType::Map(entries, false),
        ] {
            let value = ScalarValue::try_new_null(&data_type).unwrap();
            let expected = value.to_array_of_size(1).unwrap();
            let (pool, mut arena) = arena_with_pool(usize::MAX, 4, 64 * 1024);
            let transient = arena.memory().new_empty();
            let array = arena
                .get_single_row_array_governed(&value, &transient, &mut |_| Ok(()))
                .unwrap();
            assert!(Arc::ptr_eq(&array, &expected));
            assert!(arena.dynamic.is_empty());
            assert_eq!(arena.reserved_bytes(), 0);
            assert_eq!(pool.reserved(), array.get_array_memory_size());
            drop(array);
            drop(transient);
            assert_eq!(pool.reserved(), 0);
        }
    }

    #[test]
    fn failed_growth_after_planned_eviction_preserves_the_old_lru_entry() {
        let old_value = ScalarValue::Utf8(Some("old".to_string()));
        let new_value = ScalarValue::Utf8(Some("x".repeat(4096)));
        let (pool, mut arena) = arena_with_pool(64 * 1024, 1, 64 * 1024);
        let retained_old = lookup(&mut arena, &old_value);
        let reserved_before = pool.reserved();
        let blocker = MemoryConsumer::new("block-cache-growth").register(&pool);
        blocker.try_grow(64 * 1024 - reserved_before).unwrap();
        let error = arena
            .get_single_row_array_governed(
                &new_value,
                &arena.memory().new_empty(),
                &mut |_| Ok(()),
            )
            .unwrap_err();
        assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
        drop(blocker);
        assert_eq!(pool.reserved(), reserved_before);
        assert!(Arc::ptr_eq(&retained_old, &lookup(&mut arena, &old_value)));
    }

    #[test]
    fn changing_int_decimal_and_string_values_stay_within_cache_limits() {
        const ENTRIES: usize = 16;
        const VALUES: usize = 4 * ENTRIES;
        let (pool, mut arena) = arena_with_pool(usize::MAX, ENTRIES, 64 * 1024);

        for index in 0..VALUES {
            let value = match index % 3 {
                0 if index == 0 => ScalarValue::Int64(Some(i64::MIN)),
                0 if index == 3 => ScalarValue::Int64(Some(i64::MAX)),
                0 => ScalarValue::Int64(Some(index as i64 + 1_000)),
                1 => ScalarValue::Decimal128(Some(-(index as i128)), 38, 3),
                _ => ScalarValue::Utf8(Some(format!(
                    "value-{index}-{}",
                    "x".repeat(index * 2)
                ))),
            };
            lookup(&mut arena, &value);
            assert!(arena.dynamic.len() <= ENTRIES);
            assert!(arena.dynamic_bytes <= 64 * 1024);
        }

        assert_eq!(arena.dynamic.len(), ENTRIES);
        drop(arena);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn equal_sized_dynamic_replacements_keep_the_cache_reservation_constant() {
        const ENTRIES: usize = 16;
        let (pool, mut arena) = arena_with_pool(usize::MAX, ENTRIES, 64 * 1024);
        let value = |index: usize| ScalarValue::Int64(Some(1_000 + index as i64));
        for index in 0..ENTRIES {
            lookup(&mut arena, &value(index));
        }
        assert_eq!(arena.dynamic.len(), ENTRIES);
        let baseline = pool.reserved();
        assert!(baseline > 0);
        for index in ENTRIES..4 * ENTRIES {
            let next = value(index);
            lookup(&mut arena, &next);
            assert!(arena.contains(&next));
            assert_eq!(arena.dynamic.len(), ENTRIES);
            assert_eq!(pool.reserved(), baseline);
        }
        drop(arena);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn policy_enforces_exact_ceilings() {
        let entries = super::MAX_SINGLE_ROW_ARRAY_CACHE_ENTRIES;
        let bytes = super::MAX_SINGLE_ROW_ARRAY_CACHE_BYTES;
        for (entries, bytes, valid) in [
            (0, 0, true),
            (entries, bytes, true),
            (entries + 1, 1, false),
            (1, bytes + 1, false),
        ] {
            assert_eq!(
                SingleRowArrayArenaPolicy::try_from_configured(entries, bytes).is_ok(),
                valid
            );
        }
    }
}