Skip to main content

common_recordbatch/
recordbatch.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::mem::size_of;
17use std::slice;
18use std::sync::Arc;
19
20use datafusion::arrow::util::pretty::pretty_format_batches;
21use datafusion_common::arrow::array::ArrayRef;
22use datafusion_common::arrow::compute;
23use datafusion_common::arrow::datatypes::{DataType as ArrowDataType, SchemaRef as ArrowSchemaRef};
24use datatypes::arrow::array::{Array, AsArray, OffsetSizeTrait, RecordBatchOptions};
25use datatypes::arrow::util::bit_util;
26use datatypes::prelude::DataType;
27use datatypes::schema::SchemaRef;
28use datatypes::vectors::{Helper, VectorRef};
29use serde::ser::{Error, SerializeStruct};
30use serde::{Serialize, Serializer};
31use snafu::{OptionExt, ResultExt, ensure};
32
33use crate::DfRecordBatch;
34use crate::error::{
35    self, ArrowComputeSnafu, ColumnNotExistsSnafu, DataTypesSnafu, ProjectArrowRecordBatchSnafu,
36    Result,
37};
38
39/// A two-dimensional batch of column-oriented data with a defined schema.
40#[derive(Clone, Debug, PartialEq)]
41pub struct RecordBatch {
42    pub schema: SchemaRef,
43    df_record_batch: DfRecordBatch,
44}
45
46impl RecordBatch {
47    /// Create a new [`RecordBatch`] from `schema` and `columns`.
48    pub fn new<I: IntoIterator<Item = VectorRef>>(
49        schema: SchemaRef,
50        columns: I,
51    ) -> Result<RecordBatch> {
52        let columns: Vec<_> = columns.into_iter().collect();
53        let arrow_arrays = columns.iter().map(|v| v.to_arrow_array()).collect();
54
55        // Casting the arrays here to match the schema, is a temporary solution to support Arrow's
56        // view array types (`StringViewArray` and `BinaryViewArray`).
57        // As to "support": the arrays here are created from vectors, which do not have types
58        // corresponding to view arrays. What we can do is to only cast them.
59        // As to "temporary": we are planing to use Arrow's RecordBatch directly in the read path.
60        // the casting here will be removed in the end.
61        // TODO(LFC): Remove the casting here once `Batch` is no longer used.
62        let arrow_arrays = Self::cast_view_arrays(schema.arrow_schema(), arrow_arrays)?;
63
64        let df_record_batch = DfRecordBatch::try_new(schema.arrow_schema().clone(), arrow_arrays)
65            .context(error::NewDfRecordBatchSnafu)?;
66
67        Ok(RecordBatch {
68            schema,
69            df_record_batch,
70        })
71    }
72
73    pub fn to_df_record_batch<I: IntoIterator<Item = VectorRef>>(
74        arrow_schema: ArrowSchemaRef,
75        columns: I,
76    ) -> Result<DfRecordBatch> {
77        let columns: Vec<_> = columns.into_iter().collect();
78        let arrow_arrays = columns.iter().map(|v| v.to_arrow_array()).collect();
79
80        // Casting the arrays here to match the schema, is a temporary solution to support Arrow's
81        // view array types (`StringViewArray` and `BinaryViewArray`).
82        // As to "support": the arrays here are created from vectors, which do not have types
83        // corresponding to view arrays. What we can do is to only cast them.
84        // As to "temporary": we are planing to use Arrow's RecordBatch directly in the read path.
85        // the casting here will be removed in the end.
86        // TODO(LFC): Remove the casting here once `Batch` is no longer used.
87        let arrow_arrays = Self::cast_view_arrays(&arrow_schema, arrow_arrays)?;
88
89        let df_record_batch = DfRecordBatch::try_new(arrow_schema, arrow_arrays)
90            .context(error::NewDfRecordBatchSnafu)?;
91
92        Ok(df_record_batch)
93    }
94
95    fn cast_view_arrays(
96        schema: &ArrowSchemaRef,
97        mut arrays: Vec<ArrayRef>,
98    ) -> Result<Vec<ArrayRef>> {
99        for (f, a) in schema.fields().iter().zip(arrays.iter_mut()) {
100            let expected = f.data_type();
101            let actual = a.data_type();
102            if matches!(
103                (expected, actual),
104                (ArrowDataType::Utf8View, ArrowDataType::Utf8)
105                    | (ArrowDataType::BinaryView, ArrowDataType::Binary)
106            ) {
107                *a = compute::cast(a, expected).context(ArrowComputeSnafu)?;
108            }
109        }
110        Ok(arrays)
111    }
112
113    /// Create an empty [`RecordBatch`] from `schema`.
114    pub fn new_empty(schema: SchemaRef) -> RecordBatch {
115        let df_record_batch = DfRecordBatch::new_empty(schema.arrow_schema().clone());
116        RecordBatch {
117            schema,
118            df_record_batch,
119        }
120    }
121
122    /// Create an empty [`RecordBatch`] from `schema` with `num_rows`.
123    pub fn new_with_count(schema: SchemaRef, num_rows: usize) -> Result<Self> {
124        let df_record_batch = DfRecordBatch::try_new_with_options(
125            schema.arrow_schema().clone(),
126            vec![],
127            &RecordBatchOptions::new().with_row_count(Some(num_rows)),
128        )
129        .context(error::NewDfRecordBatchSnafu)?;
130        Ok(RecordBatch {
131            schema,
132            df_record_batch,
133        })
134    }
135
136    pub fn try_project(&self, indices: &[usize]) -> Result<Self> {
137        let schema = Arc::new(self.schema.try_project(indices).context(DataTypesSnafu)?);
138        let df_record_batch = self.df_record_batch.project(indices).with_context(|_| {
139            ProjectArrowRecordBatchSnafu {
140                schema: self.schema.clone(),
141                projection: indices.to_vec(),
142            }
143        })?;
144
145        Ok(Self {
146            schema,
147            df_record_batch,
148        })
149    }
150
151    /// Create a new [`RecordBatch`] from `schema` and `df_record_batch`.
152    ///
153    /// This method doesn't check the schema.
154    pub fn from_df_record_batch(schema: SchemaRef, df_record_batch: DfRecordBatch) -> RecordBatch {
155        RecordBatch {
156            schema,
157            df_record_batch,
158        }
159    }
160
161    #[inline]
162    pub fn df_record_batch(&self) -> &DfRecordBatch {
163        &self.df_record_batch
164    }
165
166    #[inline]
167    pub fn into_df_record_batch(self) -> DfRecordBatch {
168        self.df_record_batch
169    }
170
171    #[inline]
172    pub fn columns(&self) -> &[ArrayRef] {
173        self.df_record_batch.columns()
174    }
175
176    #[inline]
177    pub fn column(&self, idx: usize) -> &ArrayRef {
178        self.df_record_batch.column(idx)
179    }
180
181    pub fn column_by_name(&self, name: &str) -> Option<&ArrayRef> {
182        self.df_record_batch.column_by_name(name)
183    }
184
185    #[inline]
186    pub fn num_columns(&self) -> usize {
187        self.df_record_batch.num_columns()
188    }
189
190    #[inline]
191    pub fn num_rows(&self) -> usize {
192        self.df_record_batch.num_rows()
193    }
194
195    pub fn column_vectors(
196        &self,
197        table_name: &str,
198        table_schema: SchemaRef,
199    ) -> Result<HashMap<String, VectorRef>> {
200        let mut vectors = HashMap::with_capacity(self.num_columns());
201
202        // column schemas in recordbatch must match its vectors, otherwise it's corrupted
203        for (field, array) in self
204            .df_record_batch
205            .schema()
206            .fields()
207            .iter()
208            .zip(self.df_record_batch.columns().iter())
209        {
210            let column_name = field.name();
211            let column_schema =
212                table_schema
213                    .column_schema_by_name(column_name)
214                    .context(ColumnNotExistsSnafu {
215                        table_name,
216                        column_name,
217                    })?;
218            let vector = if field.data_type() != &column_schema.data_type.as_arrow_type() {
219                let array = compute::cast(array, &column_schema.data_type.as_arrow_type())
220                    .context(ArrowComputeSnafu)?;
221                Helper::try_into_vector(array).context(DataTypesSnafu)?
222            } else {
223                Helper::try_into_vector(array).context(DataTypesSnafu)?
224            };
225
226            let _ = vectors.insert(column_name.clone(), vector);
227        }
228
229        Ok(vectors)
230    }
231
232    /// Pretty display this record batch like a table
233    pub fn pretty_print(&self) -> String {
234        pretty_format_batches(slice::from_ref(&self.df_record_batch))
235            .map(|t| t.to_string())
236            .unwrap_or("failed to pretty display a record batch".to_string())
237    }
238
239    /// Return a slice record batch starts from offset, with len rows
240    pub fn slice(&self, offset: usize, len: usize) -> Result<RecordBatch> {
241        ensure!(
242            offset + len <= self.num_rows(),
243            error::RecordBatchSliceIndexOverflowSnafu {
244                size: self.num_rows(),
245                visit_index: offset + len
246            }
247        );
248        let sliced = self.df_record_batch.slice(offset, len);
249        Ok(RecordBatch::from_df_record_batch(
250            self.schema.clone(),
251            sliced,
252        ))
253    }
254
255    /// Returns the total number of bytes of memory pointed to by the arrays in this `RecordBatch`.
256    ///
257    /// The buffers store bytes in the Arrow memory format, and include the data as well as the validity map.
258    /// Note that this does not always correspond to the exact memory usage of an array,
259    /// since multiple arrays can share the same buffers or slices thereof.
260    pub fn buffer_memory_size(&self) -> usize {
261        self.df_record_batch
262            .columns()
263            .iter()
264            .map(|array| array.get_buffer_memory_size())
265            .sum()
266    }
267
268    /// Returns the logical memory size of this batch's array slices.
269    ///
270    /// This sums Arrow's logical visible slice buffers rather than the capacity of their shared
271    /// backing buffers. View out-of-line payloads and nested custom payloads are not separately
272    /// traversed or accounted. It is not an exact measure of live physical memory. If Arrow cannot
273    /// calculate a slice's size, the full buffer size is used conservatively.
274    ///
275    /// Flat columns (fixed-width primitives, timestamps, booleans, and `Utf8`/`LargeUtf8`/
276    /// `Binary`/`LargeBinary`) are measured directly from their typed arrays using Arrow's own
277    /// formula (see [`flat_slice_memory_size`]), so the scan hot path does not materialize an
278    /// `ArrayData` per column per batch. All other types use Arrow's calculation.
279    ///
280    /// Mito's current scan paths do not produce top-level View arrays. If they do in the future,
281    /// their out-of-line payload accounting must be reassessed here.
282    pub fn logical_slice_memory_size(&self) -> usize {
283        self.df_record_batch
284            .columns()
285            .iter()
286            .fold(0, |total, array| {
287                total.saturating_add(logical_column_memory_size(array))
288            })
289    }
290
291    /// Iterate the values as strings in the column at index `i`.
292    ///
293    /// Note that if the underlying array is not a valid GreptimeDB vector, an empty iterator is
294    /// returned.
295    ///
296    /// # Panics
297    /// if index `i` is out of bound.
298    pub fn iter_column_as_string(&self, i: usize) -> Box<dyn Iterator<Item = Option<String>> + '_> {
299        macro_rules! iter {
300            ($column: ident) => {
301                Box::new(
302                    (0..$column.len())
303                        .map(|i| $column.is_valid(i).then(|| $column.value(i).to_string())),
304                )
305            };
306        }
307
308        let column = self.df_record_batch.column(i);
309        match column.data_type() {
310            ArrowDataType::Utf8 => {
311                let column = column.as_string::<i32>();
312                let iter = iter!(column);
313                iter as _
314            }
315            ArrowDataType::LargeUtf8 => {
316                let column = column.as_string::<i64>();
317                iter!(column)
318            }
319            ArrowDataType::Utf8View => {
320                let column = column.as_string_view();
321                iter!(column)
322            }
323            _ => {
324                if let Ok(column) = Helper::try_into_vector(column) {
325                    Box::new(
326                        (0..column.len())
327                            .map(move |i| (!column.is_null(i)).then(|| column.get(i).to_string())),
328                    )
329                } else {
330                    Box::new(std::iter::empty())
331                }
332            }
333        }
334    }
335}
336
337/// Returns Arrow's logical slice memory size of a single column.
338///
339/// This is `array.to_data().get_slice_memory_size()`, with the full buffer size as a conservative
340/// fallback when Arrow cannot calculate the slice size. Flat columns are measured from their typed
341/// array (see [`flat_slice_memory_size`]) so that no `ArrayData` is materialized for them.
342fn logical_column_memory_size(array: &dyn Array) -> usize {
343    flat_slice_memory_size(array).unwrap_or_else(|| {
344        array
345            .to_data()
346            .get_slice_memory_size()
347            .unwrap_or_else(|_| array.get_buffer_memory_size())
348    })
349}
350
351/// Computes `array.to_data().get_slice_memory_size()` for flat arrays without building the
352/// `ArrayData`.
353///
354/// The formulas mirror Arrow's `ArrayData::get_slice_memory_size` (arrow-data 59.2.0,
355/// `get_slice_memory_size` in `arrow-data/src/data.rs`):
356///
357/// - a fixed-width value buffer costs `len * byte_width`, where the byte width is the one of the
358///   type's buffer layout, as reported by `DataType::primitive_width`,
359/// - the value bitmap of a boolean array costs `ceil(len / 8)`,
360/// - the offsets buffer of a variable-width array holds `len + 1` boundaries and costs
361///   `(len + 1) * offset_width`,
362/// - the visible value bytes of a variable-width array cost `offset[len] - offset[0]`,
363/// - the validity bitmap costs `ceil(len / 8)`, but only if the slice contains a null: converting
364///   an array to `ArrayData` drops a validity bitmap without any null (`ArrayDataBuilder::build`),
365///   so Arrow only sees one when `null_count` is non-zero.
366///
367/// Returns `None` for data types that are left to Arrow's general computation (nested, view,
368/// dictionary, union, `FixedSizeBinary`, `Null`, ...) and when the size computation overflows
369/// `usize`, which Arrow reports as an error. Callers must then fall back to Arrow.
370fn flat_slice_memory_size(array: &dyn Array) -> Option<usize> {
371    let len = array.len();
372    let validity_size = if array.null_count() != 0 {
373        bit_util::ceil(len, 8)
374    } else {
375        0
376    };
377
378    match array.data_type() {
379        ArrowDataType::Boolean => bit_util::ceil(len, 8).checked_add(validity_size),
380        ArrowDataType::Utf8 => {
381            offset_slice_memory_size(len, array.as_string::<i32>().offsets(), validity_size)
382        }
383        ArrowDataType::LargeUtf8 => {
384            offset_slice_memory_size(len, array.as_string::<i64>().offsets(), validity_size)
385        }
386        ArrowDataType::Binary => {
387            offset_slice_memory_size(len, array.as_binary::<i32>().offsets(), validity_size)
388        }
389        ArrowDataType::LargeBinary => {
390            offset_slice_memory_size(len, array.as_binary::<i64>().offsets(), validity_size)
391        }
392        data_type => data_type
393            .primitive_width()
394            .and_then(|byte_width| fixed_width_slice_memory_size(len, byte_width, validity_size)),
395    }
396}
397
398/// Returns `len * byte_width + validity_size`, or `None` on overflow.
399#[inline]
400fn fixed_width_slice_memory_size(
401    len: usize,
402    byte_width: usize,
403    validity_size: usize,
404) -> Option<usize> {
405    len.checked_mul(byte_width)?.checked_add(validity_size)
406}
407
408/// Returns `(len + 1) * offset_width + (offsets[len] - offsets[0]) + validity_size`, or `None` on
409/// overflow.
410///
411/// `offsets` are the offsets of the visible slice, so `offsets[0]` is the first visible byte and
412/// `offsets[len]` is the end of the last visible value. The offsets buffer size is checked before
413/// `offsets[len]` is read, so a `len` that cannot come from a valid offsets buffer is reported as
414/// an overflow instead of panicking.
415#[inline]
416fn offset_slice_memory_size<O: OffsetSizeTrait>(
417    len: usize,
418    offsets: &[O],
419    validity_size: usize,
420) -> Option<usize> {
421    let offsets_size = len.checked_add(1)?.checked_mul(size_of::<O>())?;
422    let values_size = (offsets[len] - offsets[0]).as_usize();
423    offsets_size
424        .checked_add(values_size)?
425        .checked_add(validity_size)
426}
427
428impl Serialize for RecordBatch {
429    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
430    where
431        S: Serializer,
432    {
433        // TODO(yingwen): arrow and arrow2's schemas have different fields, so
434        // it might be better to use our `RawSchema` as serialized field.
435        let mut s = serializer.serialize_struct("record", 2)?;
436        s.serialize_field("schema", &**self.schema.arrow_schema())?;
437
438        let columns = self.df_record_batch.columns();
439        let columns = Helper::try_into_vectors(columns).map_err(Error::custom)?;
440        let vec = columns
441            .iter()
442            .map(|c| c.serialize_to_json())
443            .collect::<std::result::Result<Vec<_>, _>>()
444            .map_err(S::Error::custom)?;
445
446        s.serialize_field("columns", &vec)?;
447        s.end()
448    }
449}
450
451/// merge multiple recordbatch into a single
452pub fn merge_record_batches(schema: SchemaRef, batches: &[RecordBatch]) -> Result<RecordBatch> {
453    let batches_len = batches.len();
454    if batches_len == 0 {
455        return Ok(RecordBatch::new_empty(schema));
456    }
457
458    let record_batch = compute::concat_batches(
459        schema.arrow_schema(),
460        batches.iter().map(|x| x.df_record_batch()),
461    )
462    .context(ArrowComputeSnafu)?;
463
464    // Create a new RecordBatch with merged columns
465    Ok(RecordBatch::from_df_record_batch(schema, record_batch))
466}
467
468#[cfg(test)]
469mod tests {
470    use std::sync::Arc;
471
472    use datatypes::arrow::array::{
473        ArrayRef, AsArray, BinaryArray, BooleanArray, DictionaryArray, FixedSizeBinaryArray,
474        Int32Array, LargeBinaryArray, LargeStringArray, ListArray, PrimitiveArray, StringArray,
475        StringViewArray, TimestampMillisecondArray, UInt32Array,
476    };
477    use datatypes::arrow::buffer::{NullBuffer, ScalarBuffer};
478    use datatypes::arrow::datatypes::{
479        ArrowNativeType, ArrowPrimitiveType, DataType, Date32Type, Date64Type, Decimal128Type,
480        Decimal256Type, DurationMicrosecondType, Field, Float32Type, Float64Type, Int8Type,
481        Int16Type, Int32Type, Int64Type, IntervalDayTimeType, IntervalMonthDayNanoType,
482        IntervalYearMonthType, Schema as ArrowSchema, Time32MillisecondType, Time64NanosecondType,
483        TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
484        TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
485    };
486    use datatypes::data_type::ConcreteDataType;
487    use datatypes::extension::json::JsonExtensionType;
488    use datatypes::schema::{ColumnSchema, Schema};
489    use datatypes::vectors::{
490        BinaryVector, BooleanVector, StringVector, UInt32Vector, UInt64Vector,
491    };
492
493    use super::*;
494
495    #[test]
496    fn test_record_batch() {
497        let arrow_schema = Arc::new(ArrowSchema::new(vec![
498            Field::new("c1", DataType::UInt32, false),
499            Field::new("c2", DataType::UInt32, false),
500        ]));
501        let schema = Arc::new(Schema::try_from(arrow_schema).unwrap());
502
503        let c1 = Arc::new(UInt32Vector::from_slice([1, 2, 3]));
504        let c2 = Arc::new(UInt32Vector::from_slice([4, 5, 6]));
505        let columns: Vec<VectorRef> = vec![c1, c2];
506
507        let expected = vec![
508            Arc::new(UInt32Array::from_iter_values([1, 2, 3])) as ArrayRef,
509            Arc::new(UInt32Array::from_iter_values([4, 5, 6])),
510        ];
511
512        let batch = RecordBatch::new(schema.clone(), columns.clone()).unwrap();
513        assert_eq!(3, batch.num_rows());
514        assert_eq!(expected, batch.df_record_batch().columns());
515        assert_eq!(schema, batch.schema);
516
517        assert_eq!(&expected[0], batch.column_by_name("c1").unwrap());
518        assert_eq!(&expected[1], batch.column_by_name("c2").unwrap());
519        assert!(batch.column_by_name("c3").is_none());
520
521        let converted = RecordBatch::from_df_record_batch(schema, batch.df_record_batch().clone());
522        assert_eq!(batch, converted);
523        assert_eq!(*batch.df_record_batch(), converted.into_df_record_batch());
524    }
525
526    #[test]
527    pub fn test_serialize_recordbatch() {
528        let column_schemas = vec![ColumnSchema::new(
529            "number",
530            ConcreteDataType::uint32_datatype(),
531            false,
532        )];
533        let schema = Arc::new(Schema::try_new(column_schemas).unwrap());
534
535        let numbers: Vec<u32> = (0..10).collect();
536        let columns = vec![Arc::new(UInt32Vector::from_slice(numbers)) as VectorRef];
537        let batch = RecordBatch::new(schema, columns).unwrap();
538
539        let output = serde_json::to_string(&batch).unwrap();
540        assert_eq!(
541            r#"{"schema":{"fields":[{"name":"number","data_type":"UInt32","nullable":false,"dict_id":0,"dict_is_ordered":false,"metadata":{}}],"metadata":{"greptime:version":"0"}},"columns":[[0,1,2,3,4,5,6,7,8,9]]}"#,
542            output
543        );
544    }
545
546    #[test]
547    fn test_record_batch_slice() {
548        let column_schemas = vec![
549            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
550            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
551        ];
552        let schema = Arc::new(Schema::new(column_schemas));
553        let columns: Vec<VectorRef> = vec![
554            Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
555            Arc::new(StringVector::from(vec![
556                None,
557                Some("hello"),
558                Some("greptime"),
559                None,
560            ])),
561        ];
562        let recordbatch = RecordBatch::new(schema, columns).unwrap();
563        let recordbatch = recordbatch.slice(1, 2).expect("recordbatch slice");
564
565        let expected = &UInt32Array::from_iter_values([2u32, 3]);
566        let array = recordbatch.column(0);
567        let actual = array.as_primitive::<UInt32Type>();
568        assert_eq!(expected, actual);
569
570        let expected = &StringArray::from(vec!["hello", "greptime"]);
571        let array = recordbatch.column(1);
572        let actual = array.as_string::<i32>();
573        assert_eq!(expected, actual);
574
575        assert!(recordbatch.slice(1, 5).is_err());
576    }
577
578    #[test]
579    fn test_logical_slice_memory_size_for_visible_primitive_string_binary_slices() {
580        let schema = Arc::new(Schema::new(vec![
581            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
582            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
583            ColumnSchema::new("binary", ConcreteDataType::binary_datatype(), true),
584        ]));
585        let numbers: Vec<_> = (0..1024).collect();
586        let strings = (0..1024)
587            .map(|value| (value % 3 != 0).then(|| format!("value-{value}")))
588            .collect::<Vec<_>>();
589        let binary = (0_u32..1024)
590            .map(|value| (value % 3 != 0).then(|| value.to_le_bytes().to_vec()))
591            .collect::<Vec<_>>();
592        let columns: Vec<VectorRef> = vec![
593            Arc::new(UInt32Vector::from_slice(numbers)),
594            Arc::new(StringVector::from(strings)),
595            Arc::new(BinaryVector::from(binary)),
596        ];
597        let batch = RecordBatch::new(schema, columns).unwrap();
598        let slice = batch.slice(511, 3).unwrap();
599
600        assert!(slice.columns().iter().any(|column| column.null_count() > 0));
601        assert!(slice.logical_slice_memory_size() < slice.buffer_memory_size());
602        assert_eq!(
603            slice.logical_slice_memory_size(),
604            slice
605                .columns()
606                .iter()
607                .map(|column| column.to_data().get_slice_memory_size().unwrap())
608                .sum::<usize>()
609        );
610    }
611
612    #[test]
613    fn test_logical_slice_memory_size_for_many_shared_buffer_slices() {
614        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
615            "strings",
616            ConcreteDataType::string_datatype(),
617            false,
618        )]));
619        let strings = (0..1024)
620            .map(|value| format!("shared-value-{value}"))
621            .collect::<Vec<_>>();
622        let backing = RecordBatch::new(
623            schema,
624            vec![Arc::new(StringVector::from(strings)) as VectorRef],
625        )
626        .unwrap();
627        let slices = (0..128)
628            .map(|index| backing.slice(index * 4, 2).unwrap())
629            .collect::<Vec<_>>();
630        let logical_total = slices
631            .iter()
632            .map(RecordBatch::logical_slice_memory_size)
633            .sum::<usize>();
634        let buffer_total = slices
635            .iter()
636            .map(RecordBatch::buffer_memory_size)
637            .sum::<usize>();
638
639        assert!(logical_total < buffer_total);
640        assert!(slices.iter().all(|slice| {
641            slice.logical_slice_memory_size()
642                == slice.column(0).to_data().get_slice_memory_size().unwrap()
643        }));
644    }
645
646    #[test]
647    fn test_logical_slice_memory_size_uses_arrow_slice_scope_for_views() {
648        let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
649            "strings",
650            ConcreteDataType::utf8_view_datatype(),
651            false,
652        )]));
653        let columns: Vec<VectorRef> =
654            vec![Arc::new(StringVector::from(StringViewArray::from(vec![
655                "unrelated backing payload",
656                "visible string view payload",
657            ])))];
658        let batch = RecordBatch::new(schema, columns)
659            .unwrap()
660            .slice(1, 1)
661            .unwrap();
662
663        assert_eq!(
664            batch.column(0).to_data().get_slice_memory_size().unwrap(),
665            batch.logical_slice_memory_size()
666        );
667    }
668
669    /// Arrow's own computation for a single array, the reference for the fast path.
670    fn arrow_slice_memory_size(array: &dyn Array) -> usize {
671        array
672            .to_data()
673            .get_slice_memory_size()
674            .unwrap_or_else(|_| array.get_buffer_memory_size())
675    }
676
677    /// Slices probed for every array: the whole array, empty slices at both ends, single element
678    /// slices, a non byte aligned range, and slices that skip a prefix or a suffix.
679    fn probe_ranges(len: usize) -> Vec<(usize, usize)> {
680        if len == 0 {
681            return vec![(0, 0)];
682        }
683
684        let mut ranges = vec![
685            (0, 0),
686            (len, 0),
687            (0, 1),
688            (len - 1, 1),
689            (1, len.saturating_sub(1)),
690            (len / 3, len / 3),
691        ];
692        if len >= 8 {
693            ranges.push((3, 5));
694        }
695        ranges
696    }
697
698    /// Asserts the fast path covers `array` and agrees with Arrow's own formula.
699    #[track_caller]
700    fn assert_fast_path_matches_arrow(name: &str, array: &dyn Array) {
701        let expected = arrow_slice_memory_size(array);
702        let Some(actual) = flat_slice_memory_size(array) else {
703            panic!("{name}: fast path must cover {:?}", array.data_type());
704        };
705
706        assert_eq!(
707            expected,
708            actual,
709            "{name}: fast path disagrees with Arrow for {:?} (len {}, null count {})",
710            array.data_type(),
711            array.len(),
712            array.null_count()
713        );
714        assert_eq!(
715            expected,
716            logical_column_memory_size(array),
717            "{name}: column size disagrees with Arrow for {:?}",
718            array.data_type()
719        );
720    }
721
722    /// Asserts the fast path agrees with Arrow for `array` and all probe slices of it.
723    fn assert_fast_path_matches_arrow_on_slices(name: &str, array: &ArrayRef) {
724        assert_fast_path_matches_arrow(name, array.as_ref());
725
726        for (offset, len) in probe_ranges(array.len()) {
727            let slice = array.slice(offset, len);
728            assert_fast_path_matches_arrow(
729                &format!("{name}[{offset}..{}]", offset + len),
730                slice.as_ref(),
731            );
732        }
733    }
734
735    /// Returns a full array, an array with a few nulls and an all-null array of `len` values.
736    fn primitive_cases<T: ArrowPrimitiveType>(len: usize) -> Vec<ArrayRef> {
737        let values = (0..len)
738            .map(|index| Some(T::Native::usize_as(index)))
739            .collect::<PrimitiveArray<T>>();
740        let with_nulls = (0..len)
741            .map(|index| (index % 3 != 0).then(|| T::Native::usize_as(index)))
742            .collect::<PrimitiveArray<T>>();
743        let all_null = (0..len)
744            .map(|_| None::<T::Native>)
745            .collect::<PrimitiveArray<T>>();
746
747        vec![
748            Arc::new(values) as ArrayRef,
749            Arc::new(with_nulls),
750            Arc::new(all_null),
751        ]
752    }
753
754    #[test]
755    fn test_flat_slice_memory_size_matches_arrow_for_fixed_width_types() {
756        macro_rules! check {
757            ($($ty:ty),* $(,)?) => {
758                $(
759                    for (index, array) in primitive_cases::<$ty>(13).into_iter().enumerate() {
760                        assert_fast_path_matches_arrow_on_slices(
761                            &format!("{}-{index}", stringify!($ty)),
762                            &array,
763                        );
764                    }
765                )*
766            };
767        }
768
769        check!(
770            Int8Type,
771            Int16Type,
772            Int32Type,
773            Int64Type,
774            UInt8Type,
775            UInt16Type,
776            UInt32Type,
777            UInt64Type,
778            Float32Type,
779            Float64Type,
780            Date32Type,
781            Date64Type,
782            Time32MillisecondType,
783            Time64NanosecondType,
784            TimestampSecondType,
785            TimestampMillisecondType,
786            TimestampMicrosecondType,
787            TimestampNanosecondType,
788            DurationMicrosecondType,
789            IntervalYearMonthType,
790            IntervalDayTimeType,
791            IntervalMonthDayNanoType,
792            Decimal128Type,
793            Decimal256Type,
794        );
795
796        // Guard against a vacuous differential test: `len` values cost `len * width`, plus one
797        // bitmap byte per 8 values when the array is nullable.
798        let len = 13;
799        let plain = Int32Array::from((0..len as i32).collect::<Vec<_>>());
800        assert_eq!(Some(len * 4), flat_slice_memory_size(&plain));
801        let nullable = Int32Array::from(
802            (0..len)
803                .map(|index| (index % 2 == 0).then_some(index as i32))
804                .collect::<Vec<_>>(),
805        );
806        assert_eq!(
807            Some(len * 4 + bit_util::ceil(len, 8)),
808            flat_slice_memory_size(&nullable)
809        );
810
811        // Timestamps with a timezone share the `Int64` layout.
812        let with_timezone =
813            Arc::new(TimestampMillisecondArray::from(vec![1_i64, 2, 3]).with_timezone_utc())
814                as ArrayRef;
815        assert_fast_path_matches_arrow_on_slices("timestamp-utc", &with_timezone);
816    }
817
818    #[test]
819    fn test_flat_slice_memory_size_matches_arrow_for_byte_arrays() {
820        // Empty, short (inline) and long (out of line) values, plus nulls.
821        let strings: Vec<Option<&str>> = vec![
822            Some(""),
823            Some("a"),
824            Some("greptime"),
825            Some("a value that is much longer than twelve bytes"),
826            None,
827            Some(""),
828            Some("z"),
829            Some("another long value that exceeds the inline limit"),
830            None,
831        ];
832        let bytes: Vec<Option<&[u8]>> = strings
833            .iter()
834            .map(|value| value.map(str::as_bytes))
835            .collect();
836
837        let cases: Vec<(&str, ArrayRef)> = vec![
838            ("utf8", Arc::new(StringArray::from(strings.clone()))),
839            (
840                "large-utf8",
841                Arc::new(LargeStringArray::from(strings.clone())),
842            ),
843            ("binary", Arc::new(BinaryArray::from(bytes.clone()))),
844            ("large-binary", Arc::new(LargeBinaryArray::from(bytes))),
845        ];
846
847        for (name, array) in cases {
848            assert_fast_path_matches_arrow_on_slices(name, &array);
849
850            // `(len + 1) * offset_width + visible value bytes`, plus the validity bitmap.
851            let len = array.len();
852            let offset_width = match array.data_type() {
853                DataType::Utf8 | DataType::Binary => 4,
854                DataType::LargeUtf8 | DataType::LargeBinary => 8,
855                other => panic!("unexpected type {other}"),
856            };
857            let visible: usize = strings.iter().map(|value| value.map_or(0, str::len)).sum();
858            let mut expected = (len + 1) * offset_width + visible;
859            if array.null_count() != 0 {
860                expected += bit_util::ceil(len, 8);
861            }
862            assert_eq!(
863                Some(expected),
864                flat_slice_memory_size(array.as_ref()),
865                "{name}"
866            );
867        }
868
869        // Zero rows keep one offset boundary per array, and nothing else.
870        let empty = Arc::new(StringArray::from(Vec::<Option<&str>>::new())) as ArrayRef;
871        assert_eq!(Some(4), flat_slice_memory_size(empty.as_ref()));
872        assert_eq!(4, arrow_slice_memory_size(empty.as_ref()));
873        assert_fast_path_matches_arrow("utf8-empty", empty.as_ref());
874
875        let empty_large = Arc::new(LargeStringArray::from(Vec::<Option<&str>>::new())) as ArrayRef;
876        assert_eq!(Some(8), flat_slice_memory_size(empty_large.as_ref()));
877        assert_fast_path_matches_arrow("large-utf8-empty", empty_large.as_ref());
878    }
879
880    #[test]
881    fn test_flat_slice_memory_size_matches_arrow_for_boolean_bitmaps() {
882        // Lengths around byte boundaries of the value bitmap.
883        for len in [0_usize, 1, 7, 8, 9, 15, 16, 17, 33] {
884            let plain =
885                BooleanArray::from((0..len).map(|index| index % 3 == 0).collect::<Vec<_>>());
886            let nullable = BooleanArray::from(
887                (0..len)
888                    .map(|index| (index % 4 != 0).then_some(index % 3 == 0))
889                    .collect::<Vec<_>>(),
890            );
891            let all_null = BooleanArray::from(vec![None::<bool>; len]);
892
893            let cases: Vec<(&str, ArrayRef)> = vec![
894                ("plain", Arc::new(plain)),
895                ("nullable", Arc::new(nullable)),
896                ("all-null", Arc::new(all_null)),
897            ];
898
899            for (kind, array) in cases {
900                let name = format!("boolean-{kind}-{len}");
901                assert_fast_path_matches_arrow_on_slices(&name, &array);
902
903                // A value bitmap, plus a validity bitmap when the slice contains a null.
904                let bitmaps = if array.null_count() != 0 { 2 } else { 1 };
905                assert_eq!(
906                    Some(bit_util::ceil(len, 8) * bitmaps),
907                    flat_slice_memory_size(array.as_ref()),
908                    "{name}"
909                );
910            }
911        }
912    }
913
914    #[test]
915    fn test_flat_slice_memory_size_ignores_null_free_validity_bitmap() {
916        // A validity bitmap without any null value is free: `ArrayDataBuilder::build` drops it, so
917        // Arrow's formula does not charge for it even though the physical buffer exists.
918        let array = Arc::new(Int32Array::new(
919            ScalarBuffer::from(vec![1_i32, 2, 3, 4, 5]),
920            Some(NullBuffer::new_valid(5)),
921        )) as ArrayRef;
922
923        assert_eq!(0, array.null_count());
924        assert!(array.nulls().is_some());
925        assert_eq!(Some(5 * 4), flat_slice_memory_size(array.as_ref()));
926        assert_fast_path_matches_arrow_on_slices("int32-validity-only", &array);
927    }
928
929    #[test]
930    fn test_flat_slice_memory_size_matches_arrow_for_zero_rows() {
931        let schema = Arc::new(Schema::new(vec![
932            ColumnSchema::new("numbers", ConcreteDataType::uint64_datatype(), true),
933            ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), true),
934            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
935            ColumnSchema::new("binary", ConcreteDataType::binary_datatype(), true),
936        ]));
937        let columns: Vec<VectorRef> = vec![
938            Arc::new(UInt64Vector::from_slice([1_u64, 2, 3])),
939            Arc::new(BooleanVector::from(vec![Some(true), None, Some(false)])),
940            Arc::new(StringVector::from(vec![Some("a"), None, Some("ccc")])),
941            Arc::new(BinaryVector::from(vec![
942                Some(vec![1_u8]),
943                None,
944                Some(vec![2_u8, 3]),
945            ])),
946        ];
947        let batch = RecordBatch::new(schema, columns).unwrap();
948        let empty = batch.slice(0, 0).unwrap();
949
950        assert_eq!(0, empty.num_rows());
951        for (index, column) in empty.columns().iter().enumerate() {
952            assert_fast_path_matches_arrow(&format!("empty-column-{index}"), column.as_ref());
953        }
954
955        let expected: usize = empty
956            .columns()
957            .iter()
958            .map(|column| arrow_slice_memory_size(column.as_ref()))
959            .sum();
960        assert_eq!(expected, empty.logical_slice_memory_size());
961        // Only the offsets of the string and binary columns survive.
962        assert_eq!(4 + 4, empty.logical_slice_memory_size());
963    }
964
965    #[test]
966    fn test_flat_slice_memory_size_for_many_slices_of_shared_backing() {
967        let schema = Arc::new(Schema::new(vec![
968            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), false),
969            ColumnSchema::new("numbers", ConcreteDataType::uint64_datatype(), false),
970            ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), false),
971        ]));
972        let strings = (0..1024)
973            .map(|value| format!("shared-value-{value}"))
974            .collect::<Vec<_>>();
975        let numbers = (0_u64..1024).collect::<Vec<_>>();
976        let flags = (0..1024).map(|value| value % 3 == 0).collect::<Vec<_>>();
977        let backing = RecordBatch::new(
978            schema,
979            vec![
980                Arc::new(StringVector::from(strings)) as VectorRef,
981                Arc::new(UInt64Vector::from_slice(numbers)),
982                Arc::new(BooleanVector::from(flags)),
983            ],
984        )
985        .unwrap();
986
987        let slices = (0..128)
988            .map(|index| backing.slice(index * 4, 3).unwrap())
989            .collect::<Vec<_>>();
990
991        for slice in &slices {
992            for column in slice.columns() {
993                assert_fast_path_matches_arrow("shared-backing", column.as_ref());
994            }
995            let expected: usize = slice
996                .columns()
997                .iter()
998                .map(|column| arrow_slice_memory_size(column.as_ref()))
999                .sum();
1000            assert_eq!(expected, slice.logical_slice_memory_size());
1001        }
1002
1003        let logical_total = slices
1004            .iter()
1005            .map(RecordBatch::logical_slice_memory_size)
1006            .sum::<usize>();
1007        let buffer_total = slices
1008            .iter()
1009            .map(RecordBatch::buffer_memory_size)
1010            .sum::<usize>();
1011        assert!(logical_total < buffer_total);
1012    }
1013
1014    #[test]
1015    fn test_logical_slice_memory_size_matches_arrow_for_mixed_slices() {
1016        let schema = Arc::new(Schema::new(vec![
1017            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
1018            ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), true),
1019            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
1020            ColumnSchema::new("binary", ConcreteDataType::binary_datatype(), true),
1021        ]));
1022        let numbers: Vec<u32> = (0..512).collect();
1023        let flags = (0..512)
1024            .map(|value| (value % 5 != 0).then_some(value % 3 == 0))
1025            .collect::<Vec<_>>();
1026        let strings = (0..512)
1027            .map(|value| (value % 4 != 0).then(|| format!("value-{value}")))
1028            .collect::<Vec<_>>();
1029        let binary = (0..512_u32)
1030            .map(|value| (value % 4 != 0).then(|| value.to_le_bytes().to_vec()))
1031            .collect::<Vec<_>>();
1032        let batch = RecordBatch::new(
1033            schema,
1034            vec![
1035                Arc::new(UInt32Vector::from_slice(numbers)) as VectorRef,
1036                Arc::new(BooleanVector::from(flags)),
1037                Arc::new(StringVector::from(strings)),
1038                Arc::new(BinaryVector::from(binary)),
1039            ],
1040        )
1041        .unwrap();
1042
1043        for (offset, len) in [(0, 512), (0, 0), (511, 1), (1, 511), (3, 5), (256, 3)] {
1044            let slice = batch.slice(offset, len).unwrap();
1045
1046            for column in slice.columns() {
1047                assert_fast_path_matches_arrow("mixed-slice", column.as_ref());
1048            }
1049            let expected: usize = slice
1050                .columns()
1051                .iter()
1052                .map(|column| arrow_slice_memory_size(column.as_ref()))
1053                .sum();
1054            assert_eq!(
1055                expected,
1056                slice.logical_slice_memory_size(),
1057                "slice({offset}, {len})"
1058            );
1059        }
1060    }
1061
1062    #[test]
1063    fn test_flat_slice_memory_size_declines_on_overflow() {
1064        // `len * byte_width` overflows `usize`, Arrow reports an error for it.
1065        assert_eq!(
1066            None,
1067            fixed_width_slice_memory_size(usize::MAX / 8 + 1, 8, 0)
1068        );
1069        // The validity bitmap pushes the total over the edge.
1070        assert_eq!(None, fixed_width_slice_memory_size(usize::MAX, 1, 8));
1071        // `(len + 1) * offset_width` overflows `usize`.
1072        assert_eq!(
1073            None,
1074            offset_slice_memory_size::<i32>(usize::MAX, &[0, 0], 0)
1075        );
1076        // The visible value bytes push the total over the edge.
1077        assert_eq!(
1078            None,
1079            offset_slice_memory_size::<i32>(1, &[0, i32::MAX], usize::MAX)
1080        );
1081        // In range sizes are still computed: `(len + 1) * 4` offsets plus `offsets[2] - offsets[0]`
1082        // visible value bytes.
1083        assert_eq!(Some(16), fixed_width_slice_memory_size(2, 8, 0));
1084        assert_eq!(
1085            Some(3 * 4 + 3),
1086            offset_slice_memory_size::<i32>(2, &[7, 9, 10], 0)
1087        );
1088    }
1089
1090    #[test]
1091    fn test_logical_column_memory_size_falls_back_for_other_types() {
1092        let view = StringViewArray::from(vec![
1093            "a short view",
1094            "a much longer string view value that is stored out of line",
1095            "",
1096        ]);
1097        let dictionary = DictionaryArray::<Int32Type>::from_iter(vec![
1098            Some("first"),
1099            None,
1100            Some("a longer dictionary value"),
1101        ]);
1102        let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
1103            Some(vec![Some(1), Some(2), None]),
1104            None,
1105            Some(vec![Some(3)]),
1106        ]);
1107        let first: [u8; 3] = [1, 2, 3];
1108        let second: [u8; 3] = [4, 5, 6];
1109        let fixed_size_binary = FixedSizeBinaryArray::try_from(vec![
1110            Some(first.as_slice()),
1111            None::<&[u8]>,
1112            Some(second.as_slice()),
1113        ])
1114        .unwrap();
1115
1116        let cases: Vec<(&str, ArrayRef)> = vec![
1117            ("utf8-view", Arc::new(view)),
1118            ("dictionary", Arc::new(dictionary)),
1119            ("list", Arc::new(list)),
1120            ("fixed-size-binary", Arc::new(fixed_size_binary)),
1121        ];
1122
1123        for (name, array) in cases {
1124            assert_eq!(
1125                None,
1126                flat_slice_memory_size(array.as_ref()),
1127                "{name}: expected Arrow's fallback for {:?}",
1128                array.data_type()
1129            );
1130
1131            for (offset, len) in probe_ranges(array.len()) {
1132                let slice = array.slice(offset, len);
1133                assert_eq!(
1134                    None,
1135                    flat_slice_memory_size(slice.as_ref()),
1136                    "{name}[{offset}..{}]: expected Arrow's fallback",
1137                    offset + len
1138                );
1139                assert_eq!(
1140                    arrow_slice_memory_size(slice.as_ref()),
1141                    logical_column_memory_size(slice.as_ref()),
1142                    "{name}[{offset}..{}]: fallback must match Arrow",
1143                    offset + len
1144                );
1145            }
1146        }
1147    }
1148
1149    #[test]
1150    fn test_merge_record_batch() {
1151        let column_schemas = vec![
1152            ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
1153            ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
1154        ];
1155        let schema = Arc::new(Schema::new(column_schemas));
1156        let columns: Vec<VectorRef> = vec![
1157            Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
1158            Arc::new(StringVector::from(vec![
1159                None,
1160                Some("hello"),
1161                Some("greptime"),
1162                None,
1163            ])),
1164        ];
1165        let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
1166
1167        let columns: Vec<VectorRef> = vec![
1168            Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
1169            Arc::new(StringVector::from(vec![
1170                None,
1171                Some("hello"),
1172                Some("greptime"),
1173                None,
1174            ])),
1175        ];
1176        let recordbatch2 = RecordBatch::new(schema.clone(), columns).unwrap();
1177
1178        let merged = merge_record_batches(schema.clone(), &[recordbatch, recordbatch2])
1179            .expect("merge recordbatch");
1180        assert_eq!(merged.num_rows(), 8);
1181    }
1182
1183    #[test]
1184    fn test_legacy_json_with_extension_does_not_align_as_structured_json() {
1185        let field = Field::new("j", DataType::Binary, true).with_extension_type(JsonExtensionType);
1186        let arrow_schema = Arc::new(ArrowSchema::new(vec![field]));
1187        let schema = Arc::new(Schema::try_from(arrow_schema).unwrap());
1188        let columns: Vec<VectorRef> = vec![Arc::new(BinaryVector::from(vec![Some(
1189            br#"{"a":1}"#.to_vec(),
1190        )]))];
1191        let batch = RecordBatch::new(schema, columns).unwrap();
1192        assert_eq!(batch.column(0).data_type(), &DataType::Binary);
1193    }
1194}