vortex-array 0.94.0

Vortex in memory columnar data format
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::hash::Hasher;

use itertools::Itertools;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_ensure_eq;
use vortex_error::vortex_panic;
use vortex_session::registry::CachedId;

use crate::ArrayEq;
use crate::ArrayHash;
use crate::ArrayRef;
use crate::Canonical;
use crate::EqMode;
use crate::ExecutionCtx;
use crate::ExecutionResult;
use crate::IntoArray;
use crate::array::Array;
use crate::array::ArrayId;
use crate::array::ArrayParts;
use crate::array::ArrayView;
use crate::array::VTable;
use crate::array::with_empty_buffers;
use crate::arrays::FixedSizeList;
use crate::arrays::Struct;
use crate::arrays::Variant;
use crate::arrays::chunked::ChunkedArrayExt;
use crate::arrays::chunked::ChunkedData;
use crate::arrays::chunked::array::ChunkedSlots;
use crate::arrays::chunked::compute::rules::RULES;
use crate::arrays::chunked::vtable::canonical::ListChunks;
use crate::arrays::chunked::vtable::canonical::swizzle;
use crate::arrays::chunked::vtable::canonical::swizzle_fixed_size_list;
use crate::arrays::chunked::vtable::canonical::swizzle_list;
use crate::arrays::chunked::vtable::canonical::swizzle_struct;
use crate::arrays::chunked::vtable::canonical::swizzle_variant;
use crate::buffer::BufferHandle;
use crate::builders::ArrayBuilder;
use crate::dtype::DType;
use crate::dtype::Nullability;
use crate::dtype::PType;
mod canonical;
mod operations;
mod plugin;
mod validity;

/// A [`Chunked`]-encoded Vortex array.
pub type ChunkedArray = Array<Chunked>;

#[derive(Clone, Debug)]
pub struct Chunked;

impl ArrayHash for ChunkedData {
    fn array_hash<H: Hasher>(&self, _state: &mut H, _accuracy: EqMode) {
        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
        // and ArrayData hashing includes every slot before TypedArrayData.
    }
}

impl ArrayEq for ChunkedData {
    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
        // Chunk offsets are cached derived data. Slot 0 already stores the logical offsets array,
        // and ArrayData equality compares every slot before TypedArrayData.
        true
    }
}

impl VTable for Chunked {
    type TypedArrayData = ChunkedData;

    type OperationsVTable = Self;
    type ValidityVTable = Self;
    fn id(&self) -> ArrayId {
        static ID: CachedId = CachedId::new("vortex.chunked");
        *ID
    }

    fn validate(
        &self,
        data: &ChunkedData,
        dtype: &DType,
        len: usize,
        slots: &[Option<ArrayRef>],
    ) -> VortexResult<()> {
        vortex_ensure!(
            !slots.is_empty(),
            "ChunkedArray must have at least a chunk offsets slot"
        );
        let chunk_offsets = slots[ChunkedSlots::CHUNK_OFFSETS]
            .as_ref()
            .vortex_expect("validated chunk offsets slot");
        vortex_ensure_eq!(
            chunk_offsets.dtype(),
            &DType::Primitive(PType::U64, Nullability::NonNullable),
            "ChunkedArray chunk offsets must be non-nullable u64",
        );
        vortex_ensure_eq!(
            chunk_offsets.len(),
            data.chunk_offsets.len(),
            "ChunkedArray chunk offsets slot length does not match cached offsets length",
        );
        vortex_ensure_eq!(
            data.chunk_offsets.len(),
            slots.len() - ChunkedSlots::CHUNKS_OFFSET + 1,
            "ChunkedArray must have one more chunk offset than chunks",
        );
        vortex_ensure_eq!(
            data.chunk_offsets
                .last()
                .copied()
                .vortex_expect("chunked arrays always have a leading 0 offset"),
            len,
            "ChunkedArray length does not match outer length",
        );
        for (idx, (start, end)) in data
            .chunk_offsets
            .iter()
            .copied()
            .tuple_windows()
            .enumerate()
        {
            let chunk = slots[ChunkedSlots::CHUNKS_OFFSET + idx]
                .as_ref()
                .vortex_expect("validated chunk slot");
            vortex_ensure_eq!(
                chunk.dtype(),
                dtype,
                "ChunkedArray chunk dtype does not match outer dtype",
            );
            vortex_ensure_eq!(
                chunk.len(),
                end - start,
                "ChunkedArray chunk {idx} len does not match offsets span",
            );
        }
        Ok(())
    }

    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
        0
    }

    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
        vortex_panic!("ChunkedArray buffer index {idx} out of bounds")
    }

    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
        vortex_panic!("ChunkedArray buffer_name index {idx} out of bounds")
    }

    fn with_buffers(
        &self,
        array: ArrayView<'_, Self>,
        buffers: &[BufferHandle],
    ) -> VortexResult<ArrayParts<Self>> {
        with_empty_buffers(self, array, buffers)
    }

    fn append_to_builder(
        array: ArrayView<'_, Self>,
        builder: &mut dyn ArrayBuilder,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<()> {
        // The builder is about to receive one array per chunk, so let any chunk lists it keeps
        // grow once rather than on the way through.
        builder.reserve_chunks(array.nchunks());
        for chunk in array.iter_chunks() {
            chunk.append_to_builder(builder, ctx)?;
        }
        Ok(())
    }

    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
        match idx {
            ChunkedSlots::CHUNK_OFFSETS => "chunk_offsets".to_string(),
            n => format!("chunks[{}]", n - ChunkedSlots::CHUNKS_OFFSET),
        }
    }

    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
        match array.dtype() {
            DType::Union(..) => {
                vortex_bail!(
                    "TODO(connor)[Union]: canonicalize chunked Union arrays by packing type IDs \
                     and every sparse child along identical chunk boundaries"
                )
            }
            DType::FixedSizeList(..) => swizzle::<FixedSizeList>(array, swizzle_fixed_size_list),
            DType::Struct(..) => swizzle::<Struct>(array, swizzle_struct),
            DType::List(..) => swizzle::<ListChunks>(array, |array| swizzle_list(array, ctx)),
            DType::Variant(..) => swizzle::<Variant>(array, |array| swizzle_variant(array, ctx)),
            // For all other types, use the builder path via AppendChild.
            _ => {
                let slot_idx = array.next_child_slot.max(ChunkedSlots::CHUNKS_OFFSET);
                if slot_idx < array.slots().len() {
                    Ok(ExecutionResult::append_child(
                        array.with_next_child_slot(slot_idx + 1),
                        slot_idx,
                    ))
                } else if slot_idx == ChunkedSlots::CHUNKS_OFFSET {
                    // No chunks at all, so nothing was ever appended and the executor holds no
                    // builder to finish. This array really is empty.
                    Ok(ExecutionResult::done(
                        Canonical::empty(array.dtype()).into_array(),
                    ))
                } else {
                    // Every chunk has gone to the builder, which is what the executor will finish.
                    Ok(ExecutionResult::done_into_builder(array))
                }
            }
        }
    }

    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
        Ok(match array.nchunks() {
            // Variant has no empty canonical form; canonicalization handles empty variant chunks.
            0 if matches!(array.dtype(), DType::Variant(_)) => None,
            0 => Some(Canonical::empty(array.dtype()).into_array()),
            1 => Some(array.chunk(0).clone()),
            _ => return RULES.evaluate(array),
        })
    }
}