adriangb commented on code in PR #12184:
URL: https://github.com/apache/arrow-rs/pull/12184#discussion_r4722411012
##########
arrow-select/src/minify.rs:
##########
@@ -0,0 +1,2608 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! [`minify`]: Copy an array into buffers that hold only the data its rows
reference
+//!
+//! Arrays often keep memory alive that their visible rows do not use:
+//!
+//! * A sliced array shares the buffers of the original, unsliced array.
+//! * A sliced list, map or byte array shares the full child array or value
buffer.
+//! * A view array can reference a small part of large data buffers.
+//! * A dictionary can hold values that no key references.
+//! * A dense union can hold child rows that no row references.
+//!
+//! [`minify`] returns a logically equal array without this unused memory.
+//!
+//! # Reuse policy
+//!
+//! [`minify`] copies a buffer only when its allocation is larger than the
+//! visible data needs (rounded up to 64 bytes). Otherwise it reuses the buffer
+//! without a copy. This makes `minify` cheap on an array that is already
+//! minimal, and calling it twice copies nothing the second time.
+//!
+//! A buffer that other arrays share counts as too large when its allocation
+//! is larger than the visible data. `minify` copies it, so the total memory in
+//! use can grow until the other arrays drop the shared buffer.
+//!
+//! A buffer can also appear more than once inside `array`, for example in
+//! two struct columns over the same array, or in two dictionaries over the
+//! same values. Struct columns over the same rows of the same buffers share
+//! one minified column. In other cases `minify` can copy the buffer once per
+//! reference. If the result then uses more memory than `array` (beyond 64
+//! bytes per allocation), `minify` returns `array` unchanged.
+//!
+//! # Null rows
+//!
+//! `minify` gives every null row of a byte, list, map or list view array an
+//! empty value range, and every null row of a byte view array an empty view.
+//! The child array or value buffers then hold only the data of valid rows.
+//!
+//! An O(rows) check over the offsets and the null bitmap finds out if any null
+//! row has a non-empty range. If none has, `minify` copies or slices the
+//! referenced range in one piece. Otherwise it copies the ranges of each run
of
+//! valid rows.
+//!
+//! # Limitations
+//!
+//! * `minify` does not deduplicate dictionary values or merge equal runs.
+//! * Null rows of a struct or fixed size list array keep their child data.
+//! The child rows stay at the same positions, so `minify` cannot drop them.
+//! * The rows of a sparse union keep the data of all children, also of the
+//! children that their type ids do not select.
+
+use std::collections::HashSet;
+use std::ops::Range;
+use std::sync::Arc;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::*;
+use arrow_array::*;
+use arrow_buffer::{
+ ArrowNativeType, BooleanBuffer, BooleanBufferBuilder, Buffer, NullBuffer,
OffsetBuffer,
+ ScalarBuffer, bit_util,
+};
+use arrow_data::transform::{Capacities, MutableArrayData};
+use arrow_data::{ArrayData, ByteView, MAX_INLINE_VIEW_LEN};
+use arrow_schema::{
+ ArrowError, DataType, FieldRef, IntervalUnit, TimeUnit, UnionFields,
UnionMode,
+};
+
+use crate::take::take;
+
+/// Returns an array that is logically equal to `array` and whose buffers hold
+/// only the data that its rows reference.
+///
+/// The result has an offset of zero, except when `minify` returns `array`
+/// unchanged because aliased buffers would make the result larger (see the
+/// [module documentation](self)). `minify` applies itself recursively to
+/// child arrays, dictionary values and run-end encoded values.
+///
+/// See the [module documentation](self) for the policy on when `minify`
+/// reuses a buffer instead of copying it.
+///
+/// # Example
+///
+/// ```
+/// # use arrow_array::{Array, Int32Array};
+/// # use arrow_select::minify::minify;
+/// let array = Int32Array::from_iter_values(0..1024);
+/// let sliced = array.slice(10, 4);
+/// // The slice keeps the whole 4 KiB buffer alive
+/// assert_eq!(sliced.get_buffer_memory_size(), 4096);
+///
+/// let minified = minify(&sliced).unwrap();
+/// assert_eq!(minified.as_ref(), &sliced as &dyn Array);
+/// assert_eq!(minified.get_buffer_memory_size(), 64);
+/// ```
+///
+/// # Errors
+///
+/// `minify` returns `InvalidArgumentError` for a time type with an invalid
+/// unit, a dictionary with an invalid key type and a run-end encoded array
+/// with an invalid run end type. It also returns the error of an array
+/// constructor that rejects the minified parts.
+pub fn minify(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
+ let minified = minify_inner(array)?;
+ // Buffers that `array` references more than once can be copied once per
+ // reference. Then `array` itself uses less memory. The slack of 64 bytes
+ // per allocation ignores the rounding of small allocations.
+ let (after, allocations) = allocated_memory(&minified.to_data());
+ let (before, _) = allocated_memory(&array.to_data());
+ if grew(before, after, allocations) {
+ return Ok(make_array(array.to_data()));
+ }
+ Ok(minified)
+}
+
+/// Returns `true` if `after` bytes in `allocations` allocations exceed
+/// `before` bytes by more than 64 bytes per allocation.
+fn grew(before: usize, after: usize, allocations: usize) -> bool {
+ after > before + 64 * allocations
+}
+
+/// Returns the capacity and the number of all distinct allocations that
+/// `data` and its children reference.
+fn allocated_memory(data: &ArrayData) -> (usize, usize) {
+ fn visit(data: &ArrayData, seen: &mut HashSet<*const u8>, total: &mut
usize) {
+ let buffers = data
+ .buffers()
+ .iter()
+ .chain(data.nulls().map(|n| n.buffer()));
+ for b in buffers {
+ if seen.insert(b.data_ptr().as_ptr()) {
+ *total += b.capacity();
+ }
+ }
+ data.child_data().iter().for_each(|c| visit(c, seen, total));
+ }
+ let mut total = 0;
+ let mut seen = HashSet::new();
+ visit(data, &mut seen, &mut total);
+ (total, seen.len())
+}
+
+/// Returns `true` if `a` and `b` describe the same rows of the same buffers.
+fn same_data(a: &ArrayData, b: &ArrayData) -> bool {
+ let same_buffer = |x: &Buffer, y: &Buffer| x.as_ptr() == y.as_ptr() &&
x.len() == y.len();
+ let same_nulls = match (a.nulls(), b.nulls()) {
+ (None, None) => true,
+ (Some(x), Some(y)) => {
+ x.offset() == y.offset() && x.len() == y.len() &&
same_buffer(x.buffer(), y.buffer())
+ }
+ _ => false,
+ };
+ a.data_type() == b.data_type()
+ && a.len() == b.len()
+ && a.offset() == b.offset()
+ && same_nulls
+ && a.buffers().len() == b.buffers().len()
+ && a.buffers()
+ .iter()
+ .zip(b.buffers())
+ .all(|(x, y)| same_buffer(x, y))
+ && a.child_data().len() == b.child_data().len()
+ && a.child_data()
+ .iter()
+ .zip(b.child_data())
+ .all(|(x, y)| same_data(x, y))
+}
+
+fn minify_inner(array: &dyn Array) -> Result<ArrayRef, ArrowError> {
+ macro_rules! primitive {
+ ($t:ty) => {
+ Ok(Arc::new(minify_primitive(array.as_primitive::<$t>())))
+ };
+ }
+ match array.data_type() {
+ DataType::Null => Ok(Arc::new(NullArray::new(array.len()))),
+ DataType::Int8 => primitive!(Int8Type),
+ DataType::Int16 => primitive!(Int16Type),
+ DataType::Int32 => primitive!(Int32Type),
+ DataType::Int64 => primitive!(Int64Type),
+ DataType::UInt8 => primitive!(UInt8Type),
+ DataType::UInt16 => primitive!(UInt16Type),
+ DataType::UInt32 => primitive!(UInt32Type),
+ DataType::UInt64 => primitive!(UInt64Type),
+ DataType::Float16 => primitive!(Float16Type),
+ DataType::Float32 => primitive!(Float32Type),
+ DataType::Float64 => primitive!(Float64Type),
+ DataType::Decimal32(_, _) => primitive!(Decimal32Type),
+ DataType::Decimal64(_, _) => primitive!(Decimal64Type),
+ DataType::Decimal128(_, _) => primitive!(Decimal128Type),
+ DataType::Decimal256(_, _) => primitive!(Decimal256Type),
+ DataType::Date32 => primitive!(Date32Type),
+ DataType::Date64 => primitive!(Date64Type),
+ DataType::Time32(TimeUnit::Second) => primitive!(Time32SecondType),
+ DataType::Time32(TimeUnit::Millisecond) =>
primitive!(Time32MillisecondType),
+ DataType::Time64(TimeUnit::Microsecond) =>
primitive!(Time64MicrosecondType),
+ DataType::Time64(TimeUnit::Nanosecond) =>
primitive!(Time64NanosecondType),
+ t @ (DataType::Time32(TimeUnit::Microsecond | TimeUnit::Nanosecond)
+ | DataType::Time64(TimeUnit::Second | TimeUnit::Millisecond)) => Err(
+ ArrowError::InvalidArgumentError(format!("invalid time unit in
{t}")),
+ ),
+ DataType::Timestamp(TimeUnit::Second, _) =>
primitive!(TimestampSecondType),
+ DataType::Timestamp(TimeUnit::Millisecond, _) =>
primitive!(TimestampMillisecondType),
+ DataType::Timestamp(TimeUnit::Microsecond, _) =>
primitive!(TimestampMicrosecondType),
+ DataType::Timestamp(TimeUnit::Nanosecond, _) =>
primitive!(TimestampNanosecondType),
+ DataType::Duration(TimeUnit::Second) => primitive!(DurationSecondType),
+ DataType::Duration(TimeUnit::Millisecond) =>
primitive!(DurationMillisecondType),
+ DataType::Duration(TimeUnit::Microsecond) =>
primitive!(DurationMicrosecondType),
+ DataType::Duration(TimeUnit::Nanosecond) =>
primitive!(DurationNanosecondType),
+ DataType::Interval(IntervalUnit::YearMonth) =>
primitive!(IntervalYearMonthType),
+ DataType::Interval(IntervalUnit::DayTime) =>
primitive!(IntervalDayTimeType),
+ DataType::Interval(IntervalUnit::MonthDayNano) =>
primitive!(IntervalMonthDayNanoType),
+ DataType::Boolean => {
+ let array = array.as_boolean();
+ let values = minify_bool_buffer(array.values());
+ Ok(Arc::new(BooleanArray::new(
+ values,
+ minify_nulls(array.nulls()),
+ )))
+ }
+ DataType::Utf8 =>
Ok(Arc::new(minify_bytes(array.as_bytes::<Utf8Type>()))),
+ DataType::LargeUtf8 =>
Ok(Arc::new(minify_bytes(array.as_bytes::<LargeUtf8Type>()))),
+ DataType::Binary =>
Ok(Arc::new(minify_bytes(array.as_bytes::<BinaryType>()))),
+ DataType::LargeBinary =>
Ok(Arc::new(minify_bytes(array.as_bytes::<LargeBinaryType>()))),
+ DataType::Utf8View => Ok(Arc::new(minify_byte_view(
+ array.as_byte_view::<StringViewType>(),
+ ))),
+ DataType::BinaryView => Ok(Arc::new(minify_byte_view(
+ array.as_byte_view::<BinaryViewType>(),
+ ))),
+ DataType::FixedSizeBinary(size) => {
+ let array = array.as_fixed_size_binary();
+ let values = minify_buffer(array.values());
+ Ok(Arc::new(FixedSizeBinaryArray::try_new_with_len(
+ *size,
+ values,
+ minify_nulls(array.nulls()),
+ array.len(),
+ )?))
+ }
+ DataType::List(field) => minify_list(array.as_list::<i32>(), field),
+ DataType::LargeList(field) => minify_list(array.as_list::<i64>(),
field),
+ DataType::ListView(field) =>
minify_list_view(array.as_list_view::<i32>(), field),
+ DataType::LargeListView(field) =>
minify_list_view(array.as_list_view::<i64>(), field),
+ DataType::FixedSizeList(field, size) => {
+ let array = array.as_fixed_size_list();
+ // `FixedSizeListArray::slice` already slices the child array
+ let values = minify_inner(array.values().as_ref())?;
+ Ok(Arc::new(FixedSizeListArray::try_new_with_length(
+ Arc::clone(field),
+ *size,
+ values,
+ minify_nulls(array.nulls()),
+ array.len(),
+ )?))
+ }
+ DataType::Map(field, ordered) => {
+ let array = array.as_map();
+ let (offsets, entries) =
+ minify_list_child(array.offsets(), array.entries(),
array.nulls())?;
+ Ok(Arc::new(MapArray::try_new(
+ Arc::clone(field),
+ offsets,
+ entries.as_struct().clone(),
+ minify_nulls(array.nulls()),
+ *ordered,
+ )?))
+ }
+ DataType::Struct(fields) => {
+ let array = array.as_struct();
+ // `StructArray::slice` already slices the child arrays
+ // Columns over the same data share one minified column
+ let mut done: Vec<(ArrayData, ArrayRef)> = vec![];
+ let mut columns = Vec::with_capacity(array.num_columns());
+ for c in array.columns() {
+ let data = c.to_data();
+ let column = match done.iter().find(|(d, _)| same_data(d,
&data)) {
+ Some((_, m)) => Arc::clone(m),
+ None => {
+ let m = minify_inner(c.as_ref())?;
+ done.push((data, Arc::clone(&m)));
+ m
+ }
+ };
+ columns.push(column);
+ }
+ Ok(Arc::new(StructArray::try_new_with_length(
+ fields.clone(),
+ columns,
+ minify_nulls(array.nulls()),
+ array.len(),
+ )?))
+ }
+ DataType::Union(fields, mode) => minify_union(array.as_union(),
fields, *mode),
+ DataType::Dictionary(key, _) => match key.as_ref() {
+ DataType::Int8 =>
minify_dictionary(array.as_dictionary::<Int8Type>()),
+ DataType::Int16 =>
minify_dictionary(array.as_dictionary::<Int16Type>()),
+ DataType::Int32 =>
minify_dictionary(array.as_dictionary::<Int32Type>()),
+ DataType::Int64 =>
minify_dictionary(array.as_dictionary::<Int64Type>()),
+ DataType::UInt8 =>
minify_dictionary(array.as_dictionary::<UInt8Type>()),
+ DataType::UInt16 =>
minify_dictionary(array.as_dictionary::<UInt16Type>()),
+ DataType::UInt32 =>
minify_dictionary(array.as_dictionary::<UInt32Type>()),
+ DataType::UInt64 =>
minify_dictionary(array.as_dictionary::<UInt64Type>()),
+ t => Err(ArrowError::InvalidArgumentError(format!(
+ "invalid dictionary key type {t}"
+ ))),
+ },
+ DataType::RunEndEncoded(run_ends, _) => match run_ends.data_type() {
+ DataType::Int16 => minify_run(array.as_run::<Int16Type>()),
+ DataType::Int32 => minify_run(array.as_run::<Int32Type>()),
+ DataType::Int64 => minify_run(array.as_run::<Int64Type>()),
+ t => Err(ArrowError::InvalidArgumentError(format!(
+ "invalid run end type {t}"
+ ))),
+ },
+ }
+}
+
+/// Returns `true` if `buffer` owns an allocation that is larger than its
+/// length (rounded up to 64 bytes).
+fn is_oversized(buffer: &Buffer) -> bool {
+ buffer.capacity() > bit_util::round_upto_multiple_of_64(buffer.len())
+}
+
+/// Returns `buffer`, or a copy of `buffer` if its allocation is oversized.
+fn minify_buffer(buffer: &Buffer) -> Buffer {
+ if is_oversized(buffer) {
+ Buffer::from_slice_ref(buffer.as_slice())
+ } else {
+ buffer.clone()
+ }
+}
+
+fn minify_scalar_buffer<T: ArrowNativeType>(buffer: &ScalarBuffer<T>) ->
ScalarBuffer<T> {
+ ScalarBuffer::new(minify_buffer(buffer.inner()), 0, buffer.len())
+}
+
+fn minify_bool_buffer(buffer: &BooleanBuffer) -> BooleanBuffer {
+ // `sliced` copies the bits when the offset is not a multiple of 8.
+ // Otherwise it returns a zero-copy slice, which `minify_buffer` checks.
+ BooleanBuffer::new(minify_buffer(&buffer.sliced()), 0, buffer.len())
+}
+
+/// Copies the null buffer if needed, and drops it if it has no nulls.
+fn minify_nulls(nulls: Option<&NullBuffer>) -> Option<NullBuffer> {
+ let nulls = nulls.filter(|n| n.null_count() > 0)?;
+ let buffer = minify_bool_buffer(nulls.inner());
+ // SAFETY: the bits and so the null count do not change
+ Some(unsafe { NullBuffer::new_unchecked(buffer, nulls.null_count()) })
+}
+
+/// Returns offsets that start at zero, plus the start and end of the child
+/// range that the original offsets reference.
+fn rebase_offsets<O: OffsetSizeTrait>(
+ offsets: &OffsetBuffer<O>,
+) -> (OffsetBuffer<O>, usize, usize) {
+ let start = offsets[0];
+ let end = offsets[offsets.len() - 1];
+ let values = if start == O::zero() {
+ minify_scalar_buffer(offsets.inner())
+ } else {
+ offsets.iter().map(|o| *o - start).collect()
Review Comment:
Good call, switched to `subtract`. It still allocates since the array holds
the buffer, but benchmarks are unchanged and it reads nicer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]