Skip to main content

datafusion_common/utils/
memory.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! This module provides a function to estimate the memory size of a HashTable prior to allocation
6
7use crate::error::_exec_datafusion_err;
8use crate::hash_map::Entry;
9use crate::{HashMap, HashSet, Result};
10use arrow::array::types::{
11    ByteArrayType, ByteViewType, Int8Type, Int16Type, Int32Type, Int64Type,
12    RunEndIndexType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
13};
14use arrow::array::{
15    Array, ArrayRef, AsArray, GenericByteArray, GenericByteViewArray, GenericListArray,
16    GenericListViewArray, RunArray,
17};
18use arrow::buffer::Buffer;
19use arrow::datatypes::DataType;
20use arrow::downcast_primitive_array;
21use arrow::record_batch::RecordBatch;
22use std::mem::size_of;
23use std::num::NonZero;
24use std::sync::Arc;
25
26/// Maximum number of distinct buffer IDs retained inline before promotion to
27/// a heap-allocated map. Sixteen keeps small buffer sets allocation-free while
28/// limiting linear lookup and inline storage to 16 entries.
29/// This is a performance heuristic, not a semantic limit.
30const INLINE_BUFFER_IDS: usize = 16;
31
32/// Estimates the memory size required for a hash table prior to allocation.
33///
34/// # Parameters
35/// - `num_elements`: The number of elements expected in the hash table.
36/// - `fixed_size`: A fixed overhead size associated with the collection
37///   (e.g., HashSet or HashTable).
38/// - `T`: The type of elements stored in the hash table.
39///
40/// # Details
41/// This function calculates the estimated memory size by considering:
42/// - An overestimation of buckets to keep approximately 1/8 of them empty.
43/// - The total memory size is computed as:
44///   - The size of each entry (`T`) multiplied by the estimated number of
45///     buckets.
46///   - One byte overhead for each bucket.
47///   - The fixed size overhead of the collection.
48/// - If the estimation overflows, we return a [`crate::error::DataFusionError`]
49///
50/// # Examples
51/// ---
52///
53/// ## From within a struct
54///
55/// ```rust
56/// # use datafusion_common::utils::memory::estimate_memory_size;
57/// # use datafusion_common::Result;
58///
59/// struct MyStruct<T> {
60///     values: Vec<T>,
61///     other_data: usize,
62/// }
63///
64/// impl<T> MyStruct<T> {
65///     fn size(&self) -> Result<usize> {
66///         let num_elements = self.values.len();
67///         let fixed_size =
68///             std::mem::size_of_val(self) + std::mem::size_of_val(&self.values);
69///
70///         estimate_memory_size::<T>(num_elements, fixed_size)
71///     }
72/// }
73/// ```
74/// ---
75/// ## With a simple collection
76///
77/// ```rust
78/// # use datafusion_common::utils::memory::estimate_memory_size;
79/// # use std::collections::HashMap;
80///
81/// let num_rows = 100;
82/// let fixed_size = std::mem::size_of::<HashMap<u64, u64>>();
83/// let estimated_hashtable_size =
84///     estimate_memory_size::<(u64, u64)>(num_rows, fixed_size)
85///         .expect("Size estimation failed");
86/// ```
87pub fn estimate_memory_size<T>(num_elements: usize, fixed_size: usize) -> Result<usize> {
88    // For the majority of cases hashbrown overestimates the bucket quantity
89    // to keep ~1/8 of them empty. We take this factor into account by
90    // multiplying the number of elements with a fixed ratio of 8/7 (~1.14).
91    // This formula leads to over-allocation for small tables (< 8 elements)
92    // but should be fine overall.
93    num_elements
94        .checked_mul(8)
95        .and_then(|overestimate| {
96            let estimated_buckets = (overestimate / 7).next_power_of_two();
97            // + size of entry * number of buckets
98            // + 1 byte for each bucket
99            // + fixed size of collection (HashSet/HashTable)
100            size_of::<T>()
101                .checked_mul(estimated_buckets)?
102                .checked_add(estimated_buckets)?
103                .checked_add(fixed_size)
104        })
105        .ok_or_else(|| {
106            _exec_datafusion_err!("usize overflow while estimating the number of buckets")
107        })
108}
109
110/// Calculate total used memory of this batch.
111///
112/// This function is used to estimate the physical memory usage of the `RecordBatch`.
113/// It only counts the memory of large data `Buffer`s, and ignores metadata like
114/// types and pointers.
115/// The implementation will add up all unique `Buffer`'s memory
116/// size, due to:
117/// - The data pointer inside `Buffer` are memory regions returned by global memory
118///   allocator, those regions can't have overlap.
119/// - The actual used range of `ArrayRef`s inside `RecordBatch` can have overlap
120///   or reuse the same `Buffer`. For example: taking a slice from `Array`.
121///
122/// Example:
123/// For a `RecordBatch` with two columns: `col1` and `col2`, two columns are pointing
124/// to a sub-region of the same buffer.
125///
126/// ```text
127/// {xxxxxxxxxxxxxxxxxxx} <--- buffer
128///       ^    ^  ^    ^
129///       |    |  |    |
130/// col1->{    }  |    |
131/// col2--------->{    }
132/// ```
133///
134/// In the above case, `get_record_batch_memory_size` will return the size of
135/// the buffer, instead of the sum of `col1` and `col2`'s actual memory size.
136///
137/// Note: [`RecordBatch::get_array_memory_size`] double counts the buffer
138/// memory size if multiple arrays within the batch are sharing the same
139/// `Buffer`, while this function counts each `Buffer` exactly once.
140pub fn get_record_batch_memory_size(batch: &RecordBatch) -> usize {
141    RecordBatchMemoryCounter::new().count_batch(batch)
142}
143
144/// Tracks the memory used by a sequence of [`RecordBatch`]es that may share
145/// underlying buffers, counting each buffer exactly once.
146///
147/// Use this instead of [`get_record_batch_memory_size`] to account for the
148/// total memory of a sequence of batches, e.g. when buffering the batches of
149/// an input stream. Such batches can share buffers (for example, operators
150/// like aggregates emit one large batch as multiple zero-copy slices), and
151/// calling [`get_record_batch_memory_size`] per batch counts the shared
152/// buffers once per batch, while this counter counts them exactly once. A
153/// batch's buffers are kept alive by the batch even when only a sub-range is
154/// referenced, so counting unique buffers in full reflects the memory the
155/// batches actually retain.
156///
157/// This counter only adds. Use [`RecordBatchMemoryTracker`] when batches are
158/// dropped one at a time and their memory must be released.
159#[derive(Debug, Default)]
160pub struct RecordBatchMemoryCounter {
161    /// Start addresses of `Buffer`s that have already been counted (instead of
162    /// actual used data region's pointer represented by current `Array`)
163    counted_buffers: BufferIdSet,
164    /// Array objects already counted by [`Self::count_batch_with_array_overhead`]
165    counted_arrays: HashSet<usize>,
166    /// Total memory of all counted allocations
167    memory_usage: usize,
168}
169
170impl RecordBatchMemoryCounter {
171    pub fn new() -> Self {
172        Self::default()
173    }
174
175    /// Count `batch`, returning the memory used by its buffers that have not
176    /// been counted before.
177    pub fn count_batch(&mut self, batch: &RecordBatch) -> usize {
178        let previous_memory_usage = self.memory_usage;
179
180        for array in batch.columns() {
181            self.count_array_memory_size(array.as_ref());
182        }
183
184        self.memory_usage - previous_memory_usage
185    }
186
187    /// Count `array`, returning the memory used by its buffers that have not
188    /// been counted before.
189    pub fn count_array(&mut self, array: &dyn Array) -> usize {
190        let previous_memory_usage = self.memory_usage;
191        self.count_array_memory_size(array);
192        self.memory_usage - previous_memory_usage
193    }
194
195    /// Counts unique buffers and Array objects retained by `batch`.
196    ///
197    /// This is useful for accounting a sequence of batches at an operator
198    /// boundary. It counts buffers once, including buffers shared by multiple
199    /// batches. Array-object overhead is deduplicated recursively when a shared
200    /// child has the same `ArrayRef` identity; Arrow constructors that rebuild
201    /// child array objects may conservatively count their object overhead again.
202    pub fn count_batch_with_array_overhead(&mut self, batch: &RecordBatch) -> usize {
203        let mut total_size = self.count_batch(batch);
204        let mut array_overhead = 0;
205
206        for array in batch.columns() {
207            array_overhead += count_unique_array_object_memory_size(array, &mut |id| {
208                self.counted_arrays.insert(id)
209            });
210        }
211
212        total_size += array_overhead;
213        self.memory_usage += array_overhead;
214        total_size
215    }
216
217    /// Total memory of all counted allocations.
218    pub fn memory_usage(&self) -> usize {
219        self.memory_usage
220    }
221
222    /// Count the memory usage of `array` and its children recursively.
223    fn count_array_memory_size(&mut self, array: &dyn Array) {
224        visit_array_buffers(array, self);
225    }
226}
227
228impl BufferVisitor for RecordBatchMemoryCounter {
229    fn visit(&mut self, buffer: &Buffer) {
230        self.memory_usage += self
231            .counted_buffers
232            .insert(buffer.data_ptr().addr(), buffer.capacity());
233    }
234}
235
236/// Like [`RecordBatchMemoryCounter`], but batches can also be released.
237///
238/// Operators that retain batches incrementally and drop them later (sort,
239/// window, sort-merge join, TopK) count a batch when they retain it and
240/// [`Self::uncount_batch`] it when they drop it. The tracker keeps a reference
241/// count per buffer: it is charged the largest capacity seen while its count
242/// is positive, and released when its count returns to 0.
243///
244/// **Contract**: a batch must be uncounted *before* its buffers are dropped.
245/// The tracker identifies buffers by their data-pointer address and does not
246/// keep them alive.
247///
248/// ```text
249/// ───────────────────────┬────────────────────────────
250/// step                   │ memory_usage()
251/// ───────────────────────┼────────────────────────────
252/// count_batch(slice1)    │ 4 MB (parent buffer counted)
253/// count_batch(slice2)    │ 4 MB (already counted)
254/// uncount_batch(slice1)  │ 4 MB (slice2 still uses it)
255/// uncount_batch(slice2)  │ 0
256/// ───────────────────────┴────────────────────────────
257/// ```
258#[derive(Debug, Default)]
259pub struct RecordBatchMemoryTracker {
260    /// Reference count of each retained buffer, keyed by its start address
261    counted_buffers: BufferIdMap,
262    /// Reference count of each Array object counted by
263    /// [`Self::count_batch_with_array_overhead`]
264    counted_arrays: HashMap<usize, u32>,
265    /// Total memory of all retained allocations
266    memory_usage: usize,
267}
268
269impl RecordBatchMemoryTracker {
270    pub fn new() -> Self {
271        Self::default()
272    }
273
274    /// Count `batch`, returning the memory used by its buffers that were not
275    /// already retained.
276    pub fn count_batch(&mut self, batch: &RecordBatch) -> usize {
277        let previous_memory_usage = self.memory_usage;
278        for array in batch.columns() {
279            self.count_array_memory_size(array.as_ref());
280        }
281        self.memory_usage - previous_memory_usage
282    }
283
284    /// Count `array`, returning the memory used by its buffers that were not
285    /// already retained.
286    pub fn count_array(&mut self, array: &dyn Array) -> usize {
287        let previous_memory_usage = self.memory_usage;
288        self.count_array_memory_size(array);
289        self.memory_usage - previous_memory_usage
290    }
291
292    /// Like [`RecordBatchMemoryCounter::count_batch_with_array_overhead`].
293    pub fn count_batch_with_array_overhead(&mut self, batch: &RecordBatch) -> usize {
294        let mut total_size = self.count_batch(batch);
295        let mut array_overhead = 0;
296
297        for array in batch.columns() {
298            array_overhead += count_unique_array_object_memory_size(array, &mut |id| {
299                let count = self.counted_arrays.entry(id).or_insert(0);
300                *count += 1;
301                *count == 1
302            });
303        }
304
305        total_size += array_overhead;
306        self.memory_usage += array_overhead;
307        total_size
308    }
309
310    /// Release the buffers of `batch`, returning the bytes freed: the sizes of
311    /// buffers no other counted batch retains. Buffers that were never
312    /// counted are ignored.
313    pub fn uncount_batch(&mut self, batch: &RecordBatch) -> usize {
314        let previous_memory_usage = self.memory_usage;
315        for array in batch.columns() {
316            self.uncount_array_memory_size(array.as_ref());
317        }
318        previous_memory_usage - self.memory_usage
319    }
320
321    /// Release the buffers of `array`, returning the bytes freed.
322    ///
323    /// See [`Self::uncount_batch`] for semantics.
324    pub fn uncount_array(&mut self, array: &dyn Array) -> usize {
325        let previous_memory_usage = self.memory_usage;
326        self.uncount_array_memory_size(array);
327        previous_memory_usage - self.memory_usage
328    }
329
330    /// Inverse of [`Self::count_batch_with_array_overhead`].
331    pub fn uncount_batch_with_array_overhead(&mut self, batch: &RecordBatch) -> usize {
332        let mut total_released = self.uncount_batch(batch);
333        let mut array_overhead = 0;
334
335        for array in batch.columns() {
336            // Releases the overhead of each array object no other counted
337            // batch still holds
338            array_overhead +=
339                count_unique_array_object_memory_size(array, &mut |id| match self
340                    .counted_arrays
341                    .get_mut(&id)
342                {
343                    Some(count) if *count > 1 => {
344                        *count -= 1;
345                        false
346                    }
347                    Some(_) => {
348                        self.counted_arrays.remove(&id);
349                        true
350                    }
351                    None => false,
352                });
353        }
354
355        total_released += array_overhead;
356        self.memory_usage -= array_overhead;
357        total_released
358    }
359
360    /// Total memory of all retained allocations.
361    pub fn memory_usage(&self) -> usize {
362        self.memory_usage
363    }
364
365    fn count_array_memory_size(&mut self, array: &dyn Array) {
366        visit_array_buffers(array, self);
367    }
368
369    fn uncount_array_memory_size(&mut self, array: &dyn Array) {
370        visit_array_buffers(array, &mut Uncount(self));
371    }
372}
373
374/// Counting visitor: retains each buffer once more.
375impl BufferVisitor for RecordBatchMemoryTracker {
376    fn visit(&mut self, buffer: &Buffer) {
377        self.memory_usage += self
378            .counted_buffers
379            .increment(buffer.data_ptr().addr(), buffer.capacity());
380    }
381}
382
383/// Releasing visitor for [`RecordBatchMemoryTracker::uncount_array_memory_size`].
384struct Uncount<'a>(&'a mut RecordBatchMemoryTracker);
385
386impl BufferVisitor for Uncount<'_> {
387    fn visit(&mut self, buffer: &Buffer) {
388        self.0.memory_usage -= self.0.counted_buffers.decrement(buffer.data_ptr().addr());
389    }
390}
391
392/// Receives each buffer found by [`visit_array_buffers`].
393trait BufferVisitor {
394    fn visit(&mut self, buffer: &Buffer);
395}
396
397/// Calls `visitor` on every buffer of `array` and its children, recursively.
398fn visit_array_buffers(array: &dyn Array, visitor: &mut impl BufferVisitor) {
399    if let Some(nulls) = array.nulls() {
400        visitor.visit(nulls.buffer());
401    }
402
403    downcast_primitive_array! {
404        array => visitor.visit(array.values().inner()),
405        DataType::Null => {}
406        DataType::Boolean => visitor.visit(array.as_boolean().values().inner()),
407        DataType::Binary => visit_byte_array_buffers(array.as_binary::<i32>(), visitor),
408        DataType::LargeBinary => visit_byte_array_buffers(array.as_binary::<i64>(), visitor),
409        DataType::Utf8 => visit_byte_array_buffers(array.as_string::<i32>(), visitor),
410        DataType::LargeUtf8 => visit_byte_array_buffers(array.as_string::<i64>(), visitor),
411        DataType::BinaryView => {
412            visit_byte_view_array_buffers(array.as_binary_view(), visitor)
413        }
414        DataType::Utf8View => visit_byte_view_array_buffers(array.as_string_view(), visitor),
415        DataType::FixedSizeBinary(_) => visitor.visit(array.as_fixed_size_binary().values()),
416        DataType::List(_) => visit_list_array_buffers(array.as_list::<i32>(), visitor),
417        DataType::LargeList(_) => visit_list_array_buffers(array.as_list::<i64>(), visitor),
418        DataType::ListView(_) => {
419            visit_list_view_array_buffers(array.as_list_view::<i32>(), visitor)
420        }
421        DataType::LargeListView(_) => {
422            visit_list_view_array_buffers(array.as_list_view::<i64>(), visitor)
423        }
424        DataType::FixedSizeList(_, _) => {
425            visit_array_buffers(array.as_fixed_size_list().values().as_ref(), visitor)
426        }
427        DataType::Struct(_) => {
428            for child in array.as_struct().columns() {
429                visit_array_buffers(child.as_ref(), visitor);
430            }
431        }
432        DataType::Union(_, _) => {
433            let array = array.as_union();
434            visitor.visit(array.type_ids().inner());
435            if let Some(offsets) = array.offsets() {
436                visitor.visit(offsets.inner());
437            }
438            for (type_id, _) in array.fields().iter() {
439                visit_array_buffers(array.child(type_id).as_ref(), visitor);
440            }
441        }
442        DataType::Dictionary(_, _) => {
443            let array = array.as_any_dictionary();
444            visit_array_buffers(array.keys(), visitor);
445            visit_array_buffers(array.values().as_ref(), visitor);
446        }
447        DataType::Map(_, _) => {
448            let array = array.as_map();
449            visitor.visit(array.offsets().inner().inner());
450            visit_array_buffers(array.entries(), visitor);
451        }
452        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
453            DataType::Int16 => visit_run_array_buffers::<Int16Type>(array, visitor),
454            DataType::Int32 => visit_run_array_buffers::<Int32Type>(array, visitor),
455            DataType::Int64 => visit_run_array_buffers::<Int64Type>(array, visitor),
456            _ => visit_array_data_buffers(&array.to_data(), visitor),
457        },
458        _ => visit_array_data_buffers(&array.to_data(), visitor),
459    }
460}
461
462fn visit_byte_array_buffers<T: ByteArrayType>(
463    array: &GenericByteArray<T>,
464    visitor: &mut impl BufferVisitor,
465) {
466    visitor.visit(array.offsets().inner().inner());
467    visitor.visit(array.values());
468}
469
470fn visit_byte_view_array_buffers<T: ByteViewType>(
471    array: &GenericByteViewArray<T>,
472    visitor: &mut impl BufferVisitor,
473) {
474    visitor.visit(array.views().inner());
475    for buffer in array.data_buffers().iter() {
476        visitor.visit(buffer);
477    }
478}
479
480fn visit_list_array_buffers<O: arrow::array::OffsetSizeTrait>(
481    array: &GenericListArray<O>,
482    visitor: &mut impl BufferVisitor,
483) {
484    visitor.visit(array.offsets().inner().inner());
485    visit_array_buffers(array.values().as_ref(), visitor);
486}
487
488fn visit_list_view_array_buffers<O: arrow::array::OffsetSizeTrait>(
489    array: &GenericListViewArray<O>,
490    visitor: &mut impl BufferVisitor,
491) {
492    visitor.visit(array.offsets().inner());
493    visitor.visit(array.sizes().inner());
494    visit_array_buffers(array.values().as_ref(), visitor);
495}
496
497fn visit_run_array_buffers<R: RunEndIndexType>(
498    array: &dyn Array,
499    visitor: &mut impl BufferVisitor,
500) {
501    if let Some(array) = array.as_any().downcast_ref::<RunArray<R>>() {
502        visitor.visit(array.run_ends().inner().inner());
503        visit_array_buffers(array.values().as_ref(), visitor);
504    } else {
505        visit_array_data_buffers(&array.to_data(), visitor);
506    }
507}
508
509fn visit_array_data_buffers(
510    array_data: &arrow::array::ArrayData,
511    visitor: &mut impl BufferVisitor,
512) {
513    for buffer in array_data.buffers() {
514        visitor.visit(buffer);
515    }
516    if let Some(nulls) = array_data.nulls() {
517        visitor.visit(nulls.buffer());
518    }
519    for child in array_data.child_data() {
520        visit_array_data_buffers(child, visitor);
521    }
522}
523
524/// Counts the Array object memory of `array` and its children whose identity
525/// `first_seen` reports as new; children of an already seen array are skipped.
526fn count_unique_array_object_memory_size(
527    array: &ArrayRef,
528    first_seen: &mut impl FnMut(usize) -> bool,
529) -> usize {
530    let array_ptr = Arc::as_ptr(array).cast::<()>() as usize;
531    if !first_seen(array_ptr) {
532        return 0;
533    }
534
535    let children = array_children(array);
536    let children_overhead: usize = children
537        .iter()
538        .map(|child| child.get_array_memory_size() - child.get_buffer_memory_size())
539        .sum();
540    let own_overhead = array.get_array_memory_size()
541        - array.get_buffer_memory_size()
542        - children_overhead;
543
544    own_overhead
545        + children
546            .into_iter()
547            .map(|child| count_unique_array_object_memory_size(child, first_seen))
548            .sum::<usize>()
549}
550
551/// Returns the `ArrayRef` children whose object allocations may be shared.
552fn array_children(array: &ArrayRef) -> Vec<&ArrayRef> {
553    match array.data_type() {
554        DataType::Struct(_) => array.as_struct().columns().iter().collect(),
555        DataType::List(_) => vec![array.as_list::<i32>().values()],
556        DataType::LargeList(_) => vec![array.as_list::<i64>().values()],
557        DataType::ListView(_) => vec![array.as_list_view::<i32>().values()],
558        DataType::LargeListView(_) => vec![array.as_list_view::<i64>().values()],
559        DataType::FixedSizeList(_, _) => vec![array.as_fixed_size_list().values()],
560        DataType::Map(_, _) => {
561            let map = array.as_map();
562            vec![map.keys(), map.values()]
563        }
564        DataType::Union(_, _) => {
565            let union = array.as_union();
566            union
567                .fields()
568                .iter()
569                .map(|(type_id, _)| union.child(type_id))
570                .collect()
571        }
572        DataType::Dictionary(key_type, _) => match key_type.as_ref() {
573            DataType::Int8 => vec![array.as_dictionary::<Int8Type>().values()],
574            DataType::Int16 => vec![array.as_dictionary::<Int16Type>().values()],
575            DataType::Int32 => vec![array.as_dictionary::<Int32Type>().values()],
576            DataType::Int64 => vec![array.as_dictionary::<Int64Type>().values()],
577            DataType::UInt8 => vec![array.as_dictionary::<UInt8Type>().values()],
578            DataType::UInt16 => vec![array.as_dictionary::<UInt16Type>().values()],
579            DataType::UInt32 => vec![array.as_dictionary::<UInt32Type>().values()],
580            DataType::UInt64 => vec![array.as_dictionary::<UInt64Type>().values()],
581            _ => unreachable!("invalid dictionary key type: {key_type}"),
582        },
583        DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
584            DataType::Int16 => array
585                .as_any()
586                .downcast_ref::<RunArray<Int16Type>>()
587                .map(|array| vec![array.values()])
588                .unwrap_or_default(),
589            DataType::Int32 => array
590                .as_any()
591                .downcast_ref::<RunArray<Int32Type>>()
592                .map(|array| vec![array.values()])
593                .unwrap_or_default(),
594            DataType::Int64 => array
595                .as_any()
596                .downcast_ref::<RunArray<Int64Type>>()
597                .map(|array| vec![array.values()])
598                .unwrap_or_default(),
599            _ => vec![],
600        },
601        _ => vec![],
602    }
603}
604
605/// Tracks a small number of buffers inline, avoiding a heap allocation for
606/// typical batches, and promotes to a hash map when more buffers are seen.
607///
608/// Keeps the largest capacity seen per address: buffers built with
609/// `Buffer::from_custom_allocation`, such as FFI imports, can share an address
610/// while reporting different capacities.
611#[derive(Debug)]
612struct BufferIdSet {
613    inline: [Option<NonZero<usize>>; INLINE_BUFFER_IDS],
614    /// Counted capacity of each inline buffer, parallel to `inline`.
615    capacities: [usize; INLINE_BUFFER_IDS],
616    len: usize,
617    overflow: Option<HashMap<NonZero<usize>, usize>>,
618}
619
620impl Default for BufferIdSet {
621    fn default() -> Self {
622        Self {
623            inline: [None; INLINE_BUFFER_IDS],
624            capacities: [0; INLINE_BUFFER_IDS],
625            len: 0,
626            overflow: None,
627        }
628    }
629}
630
631impl BufferIdSet {
632    /// Returns the bytes of `capacity` not already counted for `buffer_id`.
633    fn insert(&mut self, buffer_id: NonZero<usize>, capacity: usize) -> usize {
634        if let Some(overflow) = &mut self.overflow {
635            let counted = overflow.entry(buffer_id).or_insert(0);
636            return grow_counted_capacity(counted, capacity);
637        }
638
639        for i in 0..self.len {
640            if self.inline[i] == Some(buffer_id) {
641                return grow_counted_capacity(&mut self.capacities[i], capacity);
642            }
643        }
644
645        if self.len < INLINE_BUFFER_IDS {
646            self.inline[self.len] = Some(buffer_id);
647            self.capacities[self.len] = capacity;
648            self.len += 1;
649            return capacity;
650        }
651
652        let mut overflow = HashMap::with_capacity(INLINE_BUFFER_IDS + 1);
653        overflow.extend(self.inline.iter().flatten().copied().zip(self.capacities));
654        overflow.insert(buffer_id, capacity);
655        self.overflow = Some(overflow);
656        capacity
657    }
658}
659
660/// Raises `counted` to `capacity` if that is larger, returning the growth.
661#[inline(always)]
662fn grow_counted_capacity(counted: &mut usize, capacity: usize) -> usize {
663    let growth = capacity.saturating_sub(*counted);
664    *counted += growth;
665    growth
666}
667
668/// Reference-counted buffer tracker with an inline fast path.
669///
670/// Tracks buffer addresses with their reference counts and counted capacities
671/// (the largest seen, as in [`BufferIdSet`]). The first [`INLINE_BUFFER_IDS`]
672/// distinct buffers are stored in fixed-size inline arrays to avoid heap
673/// allocation for typical batches. When more buffers are encountered, the
674/// tracker promotes to a heap-allocated `HashMap`.
675///
676/// The inline path stores addresses, counts and capacities in **separate**
677/// arrays so that the hot scan over addresses touches a contiguous
678/// `[Option<NonZero<usize>>; 16]` (128 bytes, two cache lines) without
679/// interleaved count words.
680#[derive(Debug)]
681struct BufferIdMap {
682    /// Inline storage: buffer addresses (None = empty slot).
683    ids: [Option<NonZero<usize>>; INLINE_BUFFER_IDS],
684    /// Inline storage: per-slot reference counts, parallel to `ids`.
685    counts: [u32; INLINE_BUFFER_IDS],
686    /// Inline storage: per-slot counted capacities, parallel to `ids`.
687    capacities: [usize; INLINE_BUFFER_IDS],
688    /// Number of occupied inline slots.
689    len: usize,
690    /// Overflow storage used when more than `INLINE_BUFFER_IDS` distinct
691    /// buffers are tracked: (reference count, counted capacity).
692    overflow: Option<HashMap<NonZero<usize>, (u32, usize)>>,
693}
694
695impl Default for BufferIdMap {
696    fn default() -> Self {
697        Self {
698            ids: [None; INLINE_BUFFER_IDS],
699            counts: [0; INLINE_BUFFER_IDS],
700            capacities: [0; INLINE_BUFFER_IDS],
701            len: 0,
702            overflow: None,
703        }
704    }
705}
706
707impl BufferIdMap {
708    /// Increment the reference count for `buffer_id`, returning the bytes of
709    /// `capacity` not already counted for it.
710    #[inline(always)]
711    fn increment(&mut self, buffer_id: NonZero<usize>, capacity: usize) -> usize {
712        if let Some(overflow) = &mut self.overflow {
713            let (count, counted) = overflow.entry(buffer_id).or_insert((0, 0));
714            *count += 1;
715            return grow_counted_capacity(counted, capacity);
716        }
717
718        // Search inline slots.
719        for i in 0..self.len {
720            if self.ids[i] == Some(buffer_id) {
721                self.counts[i] += 1;
722                return grow_counted_capacity(&mut self.capacities[i], capacity);
723            }
724        }
725
726        // New buffer: try inline first.
727        if self.len < INLINE_BUFFER_IDS {
728            self.ids[self.len] = Some(buffer_id);
729            self.counts[self.len] = 1;
730            self.capacities[self.len] = capacity;
731            self.len += 1;
732            return capacity;
733        }
734
735        // Promote to overflow.
736        let mut overflow = HashMap::with_capacity(INLINE_BUFFER_IDS + 1);
737        for i in 0..self.len {
738            if let Some(id) = self.ids[i] {
739                overflow.insert(id, (self.counts[i], self.capacities[i]));
740            }
741        }
742        overflow.insert(buffer_id, (1, capacity));
743        self.overflow = Some(overflow);
744        capacity
745    }
746
747    /// Decrement the reference count for `buffer_id`, returning its counted
748    /// capacity when the count reaches zero and 0 otherwise.
749    fn decrement(&mut self, buffer_id: NonZero<usize>) -> usize {
750        if let Some(overflow) = &mut self.overflow {
751            let Entry::Occupied(mut entry) = overflow.entry(buffer_id) else {
752                return 0;
753            };
754            let (count, _) = entry.get_mut();
755            *count -= 1;
756            return if *count == 0 { entry.remove().1 } else { 0 };
757        }
758
759        // Search inline slots.
760        let target = Some(buffer_id);
761        for i in 0..self.len {
762            if self.ids[i] == target {
763                self.counts[i] -= 1;
764                if self.counts[i] == 0 {
765                    let counted = self.capacities[i];
766                    // Swap-remove: move last entry here.
767                    self.len -= 1;
768                    if i < self.len {
769                        self.ids[i] = self.ids[self.len];
770                        self.counts[i] = self.counts[self.len];
771                        self.capacities[i] = self.capacities[self.len];
772                    }
773                    self.ids[self.len] = None;
774                    return counted;
775                }
776                return 0;
777            }
778        }
779
780        0
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use std::{collections::HashSet, mem::size_of};
787
788    use super::estimate_memory_size;
789
790    #[test]
791    fn test_estimate_memory() {
792        // size (bytes): 48
793        let fixed_size = size_of::<HashSet<u32>>();
794
795        // estimated buckets: 16 = (8 * 8 / 7).next_power_of_two()
796        let num_elements = 8;
797        // size (bytes): 128 = 16 * 4 + 16 + 48
798        let estimated = estimate_memory_size::<u32>(num_elements, fixed_size).unwrap();
799        assert_eq!(estimated, 128);
800
801        // estimated buckets: 64 = (40 * 8 / 7).next_power_of_two()
802        let num_elements = 40;
803        // size (bytes): 368 = 64 * 4 + 64 + 48
804        let estimated = estimate_memory_size::<u32>(num_elements, fixed_size).unwrap();
805        assert_eq!(estimated, 368);
806    }
807
808    #[test]
809    fn test_estimate_memory_overflow() {
810        let num_elements = usize::MAX;
811        let fixed_size = size_of::<HashSet<u32>>();
812        let estimated = estimate_memory_size::<u32>(num_elements, fixed_size);
813
814        assert!(estimated.is_err());
815    }
816}
817
818#[cfg(test)]
819mod record_batch_tests {
820    use super::*;
821    use arrow::array::{
822        ArrayData, ArrayRef, BinaryViewArray, BooleanArray, DictionaryArray,
823        Float64Array, Int16Array, Int32Array, Int64Array, LargeListViewArray, ListArray,
824        ListViewArray, MapArray, RunArray, StringArray, StringViewArray, StructArray,
825        UnionArray, new_null_array,
826    };
827    use arrow::buffer::OffsetBuffer;
828    use arrow::datatypes::{
829        DataType, Field, Fields, Int16Type, Int32Type, Int64Type, Schema, UnionFields,
830        UnionMode,
831    };
832    use std::sync::Arc;
833
834    fn array_data_memory_size(array: &dyn Array) -> usize {
835        fn count(
836            array_data: &ArrayData,
837            counted_buffers: &mut HashSet<NonZero<usize>>,
838            total_size: &mut usize,
839        ) {
840            for buffer in array_data.buffers() {
841                if counted_buffers.insert(buffer.data_ptr().addr()) {
842                    *total_size += buffer.capacity();
843                }
844            }
845            if let Some(nulls) = array_data.nulls() {
846                let buffer = nulls.inner().inner();
847                if counted_buffers.insert(buffer.data_ptr().addr()) {
848                    *total_size += buffer.capacity();
849                }
850            }
851            for child in array_data.child_data() {
852                count(child, counted_buffers, total_size);
853            }
854        }
855
856        let mut total_size = 0;
857        count(&array.to_data(), &mut HashSet::default(), &mut total_size);
858        total_size
859    }
860
861    fn assert_array_memory_size_matches(array: &dyn Array) {
862        let counted = RecordBatchMemoryCounter::new().count_array(array);
863        assert_eq!(counted, array_data_memory_size(array));
864        // The tracker counts the same, and uncounting releases everything.
865        let mut tracker = RecordBatchMemoryTracker::new();
866        assert_eq!(tracker.count_array(array), counted);
867        assert_eq!(tracker.uncount_array(array), counted);
868        assert_eq!(tracker.memory_usage(), 0);
869    }
870
871    #[test]
872    fn test_count_array_counts_shared_buffers_once() {
873        let array = Int32Array::from(vec![1, 2, 3, 4, 5]);
874        let size = array_data_memory_size(&array);
875
876        let mut counter = RecordBatchMemoryCounter::new();
877        assert_eq!(counter.count_array(&array), size);
878        // A slice shares the buffer that is already counted
879        assert_eq!(counter.count_array(&array.slice(1, 2)), 0);
880        assert_eq!(counter.memory_usage(), size);
881    }
882
883    #[test]
884    fn test_get_record_batch_memory_size() {
885        let schema = Arc::new(Schema::new(vec![
886            Field::new("ints", DataType::Int32, true),
887            Field::new("float64", DataType::Float64, false),
888        ]));
889
890        let int_array =
891            Int32Array::from(vec![Some(1), Some(2), Some(3), Some(4), Some(5)]);
892        let float64_array = Float64Array::from(vec![1.0, 2.0, 3.0, 4.0, 5.0]);
893
894        let batch = RecordBatch::try_new(
895            schema,
896            vec![Arc::new(int_array), Arc::new(float64_array)],
897        )
898        .unwrap();
899
900        let size = get_record_batch_memory_size(&batch);
901        assert_eq!(size, 60);
902    }
903
904    #[test]
905    fn test_get_record_batch_memory_size_with_null() {
906        let schema = Arc::new(Schema::new(vec![
907            Field::new("ints", DataType::Int32, true),
908            Field::new("float64", DataType::Float64, false),
909        ]));
910
911        let int_array = Int32Array::from(vec![None, Some(2), Some(3)]);
912        let float64_array = Float64Array::from(vec![1.0, 2.0, 3.0]);
913
914        let batch = RecordBatch::try_new(
915            schema,
916            vec![Arc::new(int_array), Arc::new(float64_array)],
917        )
918        .unwrap();
919
920        let size = get_record_batch_memory_size(&batch);
921        assert_eq!(size, 100);
922    }
923
924    #[test]
925    fn test_get_record_batch_memory_size_empty() {
926        let schema = Arc::new(Schema::new(vec![Field::new(
927            "ints",
928            DataType::Int32,
929            false,
930        )]));
931
932        let int_array: Int32Array = Int32Array::from(vec![] as Vec<i32>);
933        let batch = RecordBatch::try_new(schema, vec![Arc::new(int_array)]).unwrap();
934
935        let size = get_record_batch_memory_size(&batch);
936        assert_eq!(size, 0, "Empty batch should have 0 memory size");
937    }
938
939    #[test]
940    fn test_get_record_batch_memory_size_shared_buffer() {
941        let original = Int32Array::from(vec![1, 2, 3, 4, 5]);
942        let slice1 = original.slice(0, 3);
943        let slice2 = original.slice(2, 3);
944
945        let schema_origin = Arc::new(Schema::new(vec![Field::new(
946            "origin_col",
947            DataType::Int32,
948            false,
949        )]));
950        let batch_origin =
951            RecordBatch::try_new(schema_origin, vec![Arc::new(original)]).unwrap();
952
953        let schema = Arc::new(Schema::new(vec![
954            Field::new("slice1", DataType::Int32, false),
955            Field::new("slice2", DataType::Int32, false),
956        ]));
957
958        let batch_sliced =
959            RecordBatch::try_new(schema, vec![Arc::new(slice1), Arc::new(slice2)])
960                .unwrap();
961
962        let size_origin = get_record_batch_memory_size(&batch_origin);
963        let size_sliced = get_record_batch_memory_size(&batch_sliced);
964
965        assert_eq!(size_origin, size_sliced);
966    }
967
968    #[test]
969    fn test_record_batch_memory_counter_array_overhead_shared_across_batches() {
970        let schema = Arc::new(Schema::new(vec![
971            Field::new("ints", DataType::Int32, false),
972            Field::new("floats", DataType::Float64, false),
973        ]));
974        let batch = RecordBatch::try_new(
975            schema,
976            vec![
977                Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 6])),
978                Arc::new(Float64Array::from(vec![1., 2., 3., 4., 5., 6.])),
979            ],
980        )
981        .unwrap();
982
983        let mut counter = RecordBatchMemoryCounter::new();
984        assert_eq!(
985            counter.count_batch_with_array_overhead(&batch),
986            batch.get_array_memory_size()
987        );
988        assert_eq!(counter.count_batch_with_array_overhead(&batch), 0);
989        assert_eq!(counter.memory_usage(), batch.get_array_memory_size());
990    }
991
992    #[test]
993    fn test_record_batch_memory_counter_deduplicates_shared_nested_array_overhead() {
994        let shared_child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
995        let fields =
996            Fields::from(vec![Arc::new(Field::new("value", DataType::Int32, false))]);
997        let first = Arc::new(StructArray::new(
998            fields.clone(),
999            vec![Arc::clone(&shared_child)],
1000            None,
1001        )) as _;
1002        let second = Arc::new(StructArray::new(
1003            fields,
1004            vec![Arc::clone(&shared_child)],
1005            None,
1006        )) as _;
1007        let batch =
1008            RecordBatch::try_from_iter(vec![("first", first), ("second", second)])
1009                .unwrap();
1010
1011        let mut counter = RecordBatchMemoryCounter::new();
1012        counter.count_batch_with_array_overhead(&batch);
1013
1014        assert_eq!(
1015            counter.memory_usage(),
1016            batch.get_array_memory_size() - shared_child.get_array_memory_size()
1017        );
1018    }
1019
1020    fn assert_recursive_shared_child_memory(
1021        name: &str,
1022        first: ArrayRef,
1023        second: ArrayRef,
1024        shared_memory: usize,
1025    ) {
1026        let first_memory = first.get_array_memory_size();
1027        let second_memory = second.get_array_memory_size();
1028        let first_batch = RecordBatch::try_from_iter(vec![(name, first)]).unwrap();
1029        let second_batch = RecordBatch::try_from_iter(vec![(name, second)]).unwrap();
1030        let mut counter = RecordBatchMemoryCounter::new();
1031
1032        assert_eq!(
1033            counter.count_batch_with_array_overhead(&first_batch),
1034            first_memory,
1035            "{name}: first batch"
1036        );
1037        assert_eq!(
1038            counter.count_batch_with_array_overhead(&second_batch),
1039            second_memory - shared_memory,
1040            "{name}: shared child"
1041        );
1042    }
1043
1044    #[test]
1045    fn test_record_batch_memory_counter_deduplicates_shared_list_child() {
1046        let shared_child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1047        let list_field = Arc::new(Field::new_list_field(DataType::Int32, false));
1048
1049        let first = Arc::new(ListArray::new(
1050            Arc::clone(&list_field),
1051            OffsetBuffer::new(vec![0, 3].into()),
1052            Arc::clone(&shared_child),
1053            None,
1054        ));
1055        let second = Arc::new(ListArray::new(
1056            list_field,
1057            OffsetBuffer::new(vec![0, 3].into()),
1058            Arc::clone(&shared_child),
1059            None,
1060        ));
1061
1062        assert_recursive_shared_child_memory(
1063            "list",
1064            first,
1065            second,
1066            shared_child.get_array_memory_size(),
1067        );
1068    }
1069
1070    fn map_with_shared_children(
1071        fields: &Fields,
1072        shared_key: &ArrayRef,
1073        shared_value: &ArrayRef,
1074    ) -> ArrayRef {
1075        Arc::new(
1076            MapArray::try_new(
1077                Arc::new(Field::new(
1078                    "entries",
1079                    DataType::Struct(fields.clone()),
1080                    false,
1081                )),
1082                OffsetBuffer::new(vec![0, 3].into()),
1083                StructArray::new(
1084                    fields.clone(),
1085                    vec![Arc::clone(shared_key), Arc::clone(shared_value)],
1086                    None,
1087                ),
1088                None,
1089                false,
1090            )
1091            .unwrap(),
1092        )
1093    }
1094
1095    #[test]
1096    fn test_record_batch_memory_counter_deduplicates_shared_map_children() {
1097        let shared_key: ArrayRef = Arc::new(Int32Array::from(vec![4, 5, 6]));
1098        let shared_value: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1099        let fields = Fields::from(vec![
1100            Arc::new(Field::new("key", DataType::Int32, false)),
1101            Arc::new(Field::new("value", DataType::Int32, false)),
1102        ]);
1103
1104        let first = map_with_shared_children(&fields, &shared_key, &shared_value);
1105        let second = map_with_shared_children(&fields, &shared_key, &shared_value);
1106
1107        assert_recursive_shared_child_memory(
1108            "map",
1109            first,
1110            second,
1111            shared_key.get_array_memory_size() + shared_value.get_array_memory_size(),
1112        );
1113    }
1114
1115    #[test]
1116    fn test_record_batch_memory_counter_deduplicates_union_slice_child_overhead() {
1117        let shared_child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1118        let fields: UnionFields =
1119            std::iter::once((0, Arc::new(Field::new("value", DataType::Int32, false))))
1120                .collect();
1121        let first = Arc::new(
1122            UnionArray::try_new(
1123                fields,
1124                vec![0, 0, 0].into(),
1125                Some(vec![0, 1, 2].into()),
1126                vec![Arc::clone(&shared_child)],
1127            )
1128            .unwrap(),
1129        ) as ArrayRef;
1130        let second = Arc::new(first.as_union().slice(1, 2)) as ArrayRef;
1131        let first_batch =
1132            RecordBatch::try_from_iter(vec![("union", Arc::clone(&first))]).unwrap();
1133        let second_batch =
1134            RecordBatch::try_from_iter(vec![("union", Arc::clone(&second))]).unwrap();
1135        let child_overhead =
1136            shared_child.get_array_memory_size() - shared_child.get_buffer_memory_size();
1137        let second_parent_overhead = second.get_array_memory_size()
1138            - second.get_buffer_memory_size()
1139            - child_overhead;
1140        let mut counter = RecordBatchMemoryCounter::new();
1141
1142        assert_eq!(
1143            counter.count_batch_with_array_overhead(&first_batch),
1144            first.get_array_memory_size()
1145        );
1146        assert_eq!(
1147            counter.count_batch_with_array_overhead(&second_batch),
1148            second_parent_overhead
1149        );
1150    }
1151
1152    #[test]
1153    fn test_record_batch_memory_counter_deduplicates_run_end_slice_child_overhead() {
1154        let values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1155        let first = Arc::new(
1156            RunArray::<Int32Type>::try_new(
1157                &Int32Array::from(vec![1, 2, 3]),
1158                values.as_ref(),
1159            )
1160            .unwrap(),
1161        ) as ArrayRef;
1162        let second = Arc::new(
1163            first
1164                .as_any()
1165                .downcast_ref::<RunArray<Int32Type>>()
1166                .unwrap()
1167                .slice(1, 2),
1168        ) as ArrayRef;
1169        let first_batch =
1170            RecordBatch::try_from_iter(vec![("run", Arc::clone(&first))]).unwrap();
1171        let second_batch =
1172            RecordBatch::try_from_iter(vec![("run", Arc::clone(&second))]).unwrap();
1173        let child_overhead =
1174            values.get_array_memory_size() - values.get_buffer_memory_size();
1175        let second_parent_overhead = second.get_array_memory_size()
1176            - second.get_buffer_memory_size()
1177            - child_overhead;
1178        let mut counter = RecordBatchMemoryCounter::new();
1179
1180        assert_eq!(
1181            counter.count_batch_with_array_overhead(&first_batch),
1182            first.get_array_memory_size()
1183        );
1184        assert_eq!(
1185            counter.count_batch_with_array_overhead(&second_batch),
1186            second_parent_overhead
1187        );
1188    }
1189
1190    #[test]
1191    fn test_record_batch_memory_counter_deduplicates_shared_dictionary_child() {
1192        let shared_child: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1193        let make_dictionary = || {
1194            Arc::new(
1195                DictionaryArray::<Int32Type>::try_new(
1196                    Int32Array::from(vec![0, 1, 2]),
1197                    Arc::clone(&shared_child),
1198                )
1199                .unwrap(),
1200            ) as ArrayRef
1201        };
1202
1203        assert_recursive_shared_child_memory(
1204            "dictionary",
1205            make_dictionary(),
1206            make_dictionary(),
1207            shared_child.get_array_memory_size(),
1208        );
1209    }
1210
1211    #[test]
1212    fn test_record_batch_memory_counter_buffer_shared_across_batches() {
1213        let schema = Arc::new(Schema::new(vec![Field::new(
1214            "ints",
1215            DataType::Int32,
1216            false,
1217        )]));
1218
1219        let int_array = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
1220        let batch = RecordBatch::try_new(schema, vec![Arc::new(int_array)]).unwrap();
1221        let slices = [batch.slice(0, 2), batch.slice(2, 2), batch.slice(4, 2)];
1222
1223        // Counting each slice individually counts the shared buffer once per slice
1224        let summed: usize = slices.iter().map(get_record_batch_memory_size).sum();
1225        assert_eq!(summed, 3 * get_record_batch_memory_size(&batch));
1226
1227        // A counter shared across the batches counts it exactly once
1228        let mut counter = RecordBatchMemoryCounter::new();
1229        let deduped: usize = slices.iter().map(|slice| counter.count_batch(slice)).sum();
1230        assert_eq!(deduped, get_record_batch_memory_size(&batch));
1231        assert_eq!(counter.memory_usage(), get_record_batch_memory_size(&batch));
1232    }
1233
1234    #[test]
1235    fn test_record_batch_memory_counter_promotes_buffer_set() {
1236        let fields = (0..=INLINE_BUFFER_IDS)
1237            .map(|index| Field::new(format!("col_{index}"), DataType::Int32, false))
1238            .collect::<Vec<_>>();
1239        let columns = (0..=INLINE_BUFFER_IDS)
1240            .map(|value| Arc::new(Int32Array::from(vec![value as i32])) as _)
1241            .collect::<Vec<_>>();
1242        let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
1243
1244        let mut counter = RecordBatchMemoryCounter::new();
1245        assert_eq!(
1246            counter.count_batch(&batch),
1247            (INLINE_BUFFER_IDS + 1) * size_of::<i32>()
1248        );
1249        assert!(counter.counted_buffers.overflow.is_some());
1250        assert_eq!(counter.count_batch(&batch), 0);
1251    }
1252
1253    /// Arrays over one allocation with different capacities, as
1254    /// `arrow::ffi::from_ffi` imports slices of one batch.
1255    fn custom_allocation_arrays(lens: &[usize]) -> Vec<ArrayRef> {
1256        use arrow::buffer::ScalarBuffer;
1257        use std::ptr::NonNull;
1258
1259        let max_len = lens.iter().copied().max().unwrap_or(0);
1260        let owner: Arc<Vec<i32>> = Arc::new((0..max_len as i32).collect());
1261        let ptr = NonNull::new(owner.as_ptr().cast::<u8>().cast_mut()).unwrap();
1262        lens.iter()
1263            .map(|&len| {
1264                // SAFETY: `owner` holds `len` values at `ptr`; the buffer keeps it alive.
1265                let buffer = unsafe {
1266                    Buffer::from_custom_allocation(
1267                        ptr,
1268                        len * size_of::<i32>(),
1269                        Arc::clone(&owner) as _,
1270                    )
1271                };
1272                Arc::new(Int32Array::new(ScalarBuffer::new(buffer, 0, len), None))
1273                    as ArrayRef
1274            })
1275            .collect()
1276    }
1277
1278    /// Arrays that fill the inline slots, so the next buffer promotes to overflow.
1279    fn inline_filler_arrays() -> Vec<ArrayRef> {
1280        (0..INLINE_BUFFER_IDS)
1281            .map(|i| Arc::new(Int32Array::from(vec![i as i32])) as ArrayRef)
1282            .collect()
1283    }
1284
1285    #[test]
1286    fn test_record_batch_memory_counter_counts_largest_capacity_at_address() {
1287        let (small, large) = (16 * size_of::<i32>(), 1024 * size_of::<i32>());
1288        for promote in [false, true] {
1289            for (lens, expected) in [
1290                ([16, 1024], (small, large - small)),
1291                ([1024, 16], (large, 0)),
1292            ] {
1293                let arrays = custom_allocation_arrays(&lens);
1294                let mut counter = RecordBatchMemoryCounter::new();
1295                if promote {
1296                    for array in inline_filler_arrays() {
1297                        counter.count_array(array.as_ref());
1298                    }
1299                }
1300                let base = counter.memory_usage();
1301
1302                let first = counter.count_array(arrays[0].as_ref());
1303                let second = counter.count_array(arrays[1].as_ref());
1304                assert_eq!((first, second), expected);
1305                assert_eq!(counter.memory_usage() - base, large);
1306                assert_eq!(counter.counted_buffers.overflow.is_some(), promote);
1307            }
1308        }
1309    }
1310
1311    #[test]
1312    fn test_uncount_releases_largest_capacity_at_address() {
1313        let (small, large) = (16 * size_of::<i32>(), 1024 * size_of::<i32>());
1314        for promote in [false, true] {
1315            let arrays = custom_allocation_arrays(&[16, 1024]);
1316            let mut tracker = RecordBatchMemoryTracker::new();
1317            let fillers = inline_filler_arrays();
1318            if promote {
1319                for array in &fillers {
1320                    tracker.count_array(array.as_ref());
1321                }
1322            }
1323            let base = tracker.memory_usage();
1324
1325            assert_eq!(tracker.count_array(arrays[0].as_ref()), small);
1326            assert_eq!(tracker.count_array(arrays[1].as_ref()), large - small);
1327            assert_eq!(tracker.counted_buffers.overflow.is_some(), promote);
1328            // Released at its largest capacity once the last array goes.
1329            assert_eq!(tracker.uncount_array(arrays[0].as_ref()), 0);
1330            assert_eq!(tracker.uncount_array(arrays[1].as_ref()), large);
1331            assert_eq!(tracker.memory_usage(), base);
1332
1333            for array in &fillers {
1334                tracker.uncount_array(array.as_ref());
1335            }
1336            assert_eq!(tracker.memory_usage(), 0);
1337        }
1338    }
1339
1340    #[test]
1341    fn test_array_memory_size_matches_array_data_layouts() {
1342        let list_field = Arc::new(Field::new_list_field(DataType::Int32, true));
1343        let struct_fields = vec![Field::new("value", DataType::Int32, true)].into();
1344        let union_fields = UnionFields::try_new(
1345            vec![0],
1346            vec![Field::new("value", DataType::Int32, true)],
1347        )
1348        .unwrap();
1349        let map_entries = Arc::new(Field::new(
1350            "entries",
1351            DataType::Struct(
1352                vec![
1353                    Field::new("key", DataType::Utf8, false),
1354                    Field::new("value", DataType::Int32, true),
1355                ]
1356                .into(),
1357            ),
1358            false,
1359        ));
1360        let data_types = vec![
1361            DataType::Boolean,
1362            DataType::Int32,
1363            DataType::Binary,
1364            DataType::LargeBinary,
1365            DataType::FixedSizeBinary(4),
1366            DataType::BinaryView,
1367            DataType::Utf8,
1368            DataType::LargeUtf8,
1369            DataType::Utf8View,
1370            DataType::List(Arc::clone(&list_field)),
1371            DataType::LargeList(Arc::clone(&list_field)),
1372            DataType::ListView(Arc::clone(&list_field)),
1373            DataType::LargeListView(Arc::clone(&list_field)),
1374            DataType::FixedSizeList(Arc::clone(&list_field), 2),
1375            DataType::Struct(struct_fields),
1376            DataType::Union(union_fields, UnionMode::Dense),
1377            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
1378            DataType::Map(map_entries, false),
1379        ];
1380
1381        for data_type in data_types {
1382            let array = new_null_array(&data_type, 3);
1383            assert_array_memory_size_matches(array.as_ref());
1384        }
1385
1386        // Exercise the view-specific buffers with concrete, non-empty values.
1387        let view_arrays = [
1388            Arc::new(BinaryViewArray::from_iter_values([
1389                b"short".as_slice(),
1390                b"a payload longer than twelve bytes".as_slice(),
1391            ])) as ArrayRef,
1392            Arc::new(StringViewArray::from_iter_values([
1393                "short",
1394                "a payload longer than twelve bytes",
1395            ])) as ArrayRef,
1396            Arc::new(ListViewArray::from_iter_primitive::<Int32Type, _, _>([
1397                Some(vec![Some(1), Some(2)]),
1398                None,
1399                Some(vec![Some(3)]),
1400            ])) as ArrayRef,
1401            Arc::new(LargeListViewArray::from_iter_primitive::<Int32Type, _, _>(
1402                [Some(vec![Some(1), Some(2)]), None, Some(vec![Some(3)])],
1403            )) as ArrayRef,
1404        ];
1405
1406        for array in view_arrays {
1407            assert_array_memory_size_matches(array.as_ref());
1408        }
1409
1410        let run_values = StringArray::from(vec!["alpha", "beta"]);
1411        let run_arrays = [
1412            Arc::new(
1413                RunArray::<Int16Type>::try_new(
1414                    &Int16Array::from(vec![2_i16, 5]),
1415                    &run_values,
1416                )
1417                .unwrap(),
1418            ) as ArrayRef,
1419            Arc::new(
1420                RunArray::<Int32Type>::try_new(
1421                    &Int32Array::from(vec![2_i32, 5]),
1422                    &run_values,
1423                )
1424                .unwrap(),
1425            ) as ArrayRef,
1426            Arc::new(
1427                RunArray::<Int64Type>::try_new(
1428                    &Int64Array::from(vec![2_i64, 5]),
1429                    &run_values,
1430                )
1431                .unwrap(),
1432            ) as ArrayRef,
1433        ];
1434
1435        for array in run_arrays {
1436            assert_array_memory_size_matches(array.as_ref());
1437        }
1438    }
1439
1440    #[test]
1441    fn test_get_record_batch_memory_size_nested_array() {
1442        let schema = Arc::new(Schema::new(vec![
1443            Field::new(
1444                "nested_int",
1445                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
1446                false,
1447            ),
1448            Field::new(
1449                "nested_int2",
1450                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
1451                false,
1452            ),
1453        ]));
1454
1455        let int_list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1456            Some(vec![Some(1), Some(2), Some(3)]),
1457        ]);
1458
1459        let int_list_array2 = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1460            Some(vec![Some(4), Some(5), Some(6)]),
1461        ]);
1462
1463        let batch = RecordBatch::try_new(
1464            schema,
1465            vec![Arc::new(int_list_array), Arc::new(int_list_array2)],
1466        )
1467        .unwrap();
1468
1469        let size = get_record_batch_memory_size(&batch);
1470        assert_eq!(size, 8208);
1471    }
1472
1473    // ---- RecordBatchMemoryTracker ----
1474
1475    #[test]
1476    fn test_uncount_two_slices_example_from_issue() {
1477        let array = Int32Array::from(vec![0; 1_000_000]); // 4 MB
1478        let schema =
1479            Arc::new(Schema::new(vec![Field::new("col", DataType::Int32, false)]));
1480        let batch = RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap();
1481        let slice1 = batch.slice(0, 500_000);
1482        let slice2 = batch.slice(500_000, 500_000);
1483        let buffer_size = get_record_batch_memory_size(&batch);
1484
1485        let mut tracker = RecordBatchMemoryTracker::new();
1486        assert_eq!(tracker.count_batch(&slice1), buffer_size);
1487        assert_eq!(tracker.count_batch(&slice2), 0);
1488        // slice2 still holds the buffer
1489        assert_eq!(tracker.uncount_batch(&slice1), 0);
1490        assert_eq!(tracker.memory_usage(), buffer_size);
1491        assert_eq!(tracker.uncount_batch(&slice2), buffer_size);
1492        assert_eq!(tracker.memory_usage(), 0);
1493    }
1494
1495    /// Uncounting one of two arrays that share buffers keeps exactly what the
1496    /// other one still holds.
1497    #[test]
1498    fn test_uncount_keeps_buffers_shared_with_counted_arrays() {
1499        let string_view = Arc::new(StringViewArray::from_iter_values([
1500            "short",
1501            "a payload longer than twelve bytes that spills",
1502            "another long payload that also spills to data buffers",
1503        ])) as ArrayRef;
1504        let dictionary_values: ArrayRef =
1505            Arc::new(StringArray::from(vec!["a", "b", "c"]));
1506        let dictionary = |keys: Vec<i32>| {
1507            Arc::new(
1508                DictionaryArray::<Int32Type>::try_new(
1509                    Int32Array::from(keys),
1510                    Arc::clone(&dictionary_values),
1511                )
1512                .unwrap(),
1513            ) as ArrayRef
1514        };
1515        let list_values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
1516        let list = |offsets: Vec<i32>| {
1517            Arc::new(ListArray::new(
1518                Arc::new(Field::new_list_field(DataType::Int32, false)),
1519                OffsetBuffer::new(offsets.into()),
1520                Arc::clone(&list_values),
1521                None,
1522            )) as ArrayRef
1523        };
1524
1525        let cases = [
1526            (
1527                "view data buffers",
1528                string_view.slice(0, 1),
1529                string_view.slice(1, 2),
1530            ),
1531            (
1532                "dictionary values",
1533                dictionary(vec![0, 1]),
1534                dictionary(vec![2]),
1535            ),
1536            ("list child", list(vec![0, 2]), list(vec![0, 1, 4])),
1537        ];
1538        for (name, first, second) in cases {
1539            let mut tracker = RecordBatchMemoryTracker::new();
1540            tracker.count_array(first.as_ref());
1541            tracker.count_array(second.as_ref());
1542            tracker.uncount_array(first.as_ref());
1543            assert_eq!(
1544                tracker.memory_usage(),
1545                RecordBatchMemoryCounter::new().count_array(second.as_ref()),
1546                "{name}"
1547            );
1548            tracker.uncount_array(second.as_ref());
1549            assert_eq!(tracker.memory_usage(), 0, "{name}");
1550        }
1551    }
1552
1553    #[test]
1554    fn test_uncount_with_overflow_promotion() {
1555        let arrays: Vec<ArrayRef> = (0..INLINE_BUFFER_IDS + 4)
1556            .map(|i| Arc::new(Int32Array::from(vec![i as i32])) as ArrayRef)
1557            .collect();
1558
1559        let mut tracker = RecordBatchMemoryTracker::new();
1560        let counted: usize = arrays.iter().map(|a| tracker.count_array(a)).sum();
1561        assert!(tracker.counted_buffers.overflow.is_some());
1562        let released: usize = arrays.iter().rev().map(|a| tracker.uncount_array(a)).sum();
1563        assert_eq!(released, counted);
1564        assert_eq!(tracker.memory_usage(), 0);
1565    }
1566
1567    #[test]
1568    fn test_uncount_untracked_array_releases_nothing() {
1569        let array = Int32Array::from(vec![1, 2, 3]);
1570        let mut tracker = RecordBatchMemoryTracker::new();
1571        assert_eq!(tracker.uncount_array(&array), 0);
1572
1573        tracker.count_array(&array);
1574        tracker.uncount_array(&array);
1575        assert_eq!(tracker.uncount_array(&array), 0);
1576        assert_eq!(tracker.memory_usage(), 0);
1577    }
1578
1579    /// Array overhead is released only when the last batch holding a shared
1580    /// `ArrayRef` is uncounted.
1581    #[test]
1582    fn test_uncount_array_overhead_while_still_held() {
1583        let col: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1584        let schema = Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, false)]));
1585        let b1 = RecordBatch::try_new(schema, vec![col]).unwrap();
1586        let b2 = b1.clone();
1587
1588        let mut tracker = RecordBatchMemoryTracker::new();
1589        let full = tracker.count_batch_with_array_overhead(&b1);
1590        assert_eq!(tracker.count_batch_with_array_overhead(&b2), 0);
1591        assert_eq!(tracker.uncount_batch_with_array_overhead(&b1), 0);
1592        assert_eq!(tracker.memory_usage(), full);
1593        assert_eq!(tracker.uncount_batch_with_array_overhead(&b2), full);
1594    }
1595
1596    /// A random sequence of counts and uncounts, checked against counting the
1597    /// arrays still held from scratch.
1598    #[test]
1599    fn test_randomized_count_uncount_sequence() {
1600        let int32 = Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef;
1601        let string = Arc::new(StringArray::from(vec!["a", "bc", "def"])) as ArrayRef;
1602        let string_view = Arc::new(StringViewArray::from_iter_values([
1603            "short",
1604            "another long string that also spills to data buffers for sharing",
1605        ])) as ArrayRef;
1606        let dictionary = Arc::new(
1607            DictionaryArray::<Int32Type>::try_new(
1608                Int32Array::from(vec![0, 1, 2]),
1609                Arc::new(StringArray::from(vec!["a", "b", "c"])),
1610            )
1611            .unwrap(),
1612        ) as ArrayRef;
1613        let arrays = [
1614            int32.slice(0, 2),
1615            int32.slice(1, 2),
1616            Arc::clone(&string),
1617            string.slice(1, 2),
1618            string_view.slice(0, 1),
1619            string_view.slice(1, 1),
1620            dictionary.slice(0, 2),
1621            dictionary,
1622            Arc::new(BooleanArray::from(vec![true, false])) as ArrayRef,
1623        ];
1624
1625        let mut seed: u64 = 42;
1626        let mut next_rand = || {
1627            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
1628            (seed >> 33) as usize
1629        };
1630        let mut tracker = RecordBatchMemoryTracker::new();
1631        let mut held = vec![0usize; arrays.len()];
1632        for op in 0..300 {
1633            let idx = next_rand() % arrays.len();
1634            if held[idx] > 0 && next_rand() % 2 == 0 {
1635                tracker.uncount_array(arrays[idx].as_ref());
1636                held[idx] -= 1;
1637            } else {
1638                tracker.count_array(arrays[idx].as_ref());
1639                held[idx] += 1;
1640            }
1641
1642            let mut expected = RecordBatchMemoryCounter::new();
1643            for (array, &count) in arrays.iter().zip(&held) {
1644                if count > 0 {
1645                    expected.count_array(array.as_ref());
1646                }
1647            }
1648            assert_eq!(tracker.memory_usage(), expected.memory_usage(), "op {op}");
1649        }
1650    }
1651}