vortex-array 0.62.0

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

use kernel::PARENT_KERNELS;
use vortex_buffer::Alignment;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_ensure;
use vortex_error::vortex_panic;
use vortex_session::VortexSession;

use crate::ArrayRef;
use crate::DeserializeMetadata;
use crate::ExecutionCtx;
use crate::ExecutionStep;
use crate::IntoArray;
use crate::ProstMetadata;
use crate::SerializeMetadata;
use crate::arrays::DecimalArray;
use crate::buffer::BufferHandle;
use crate::dtype::DType;
use crate::dtype::DecimalType;
use crate::dtype::NativeDecimalType;
use crate::match_each_decimal_value_type;
use crate::serde::ArrayChildren;
use crate::validity::Validity;
use crate::vtable;
use crate::vtable::VTable;
use crate::vtable::ValidityVTableFromValidityHelper;
use crate::vtable::validity_nchildren;
use crate::vtable::validity_to_child;
mod kernel;
mod operations;
mod validity;

use std::hash::Hash;

use crate::Precision;
use crate::arrays::decimal::compute::rules::RULES;
use crate::hash::ArrayEq;
use crate::hash::ArrayHash;
use crate::stats::StatsSetRef;
use crate::vtable::ArrayId;
vtable!(Decimal);

// The type of the values can be determined by looking at the type info...right?
#[derive(prost::Message)]
pub struct DecimalMetadata {
    #[prost(enumeration = "DecimalType", tag = "1")]
    pub(super) values_type: i32,
}

impl VTable for DecimalVTable {
    type Array = DecimalArray;

    type Metadata = ProstMetadata<DecimalMetadata>;
    type OperationsVTable = Self;
    type ValidityVTable = ValidityVTableFromValidityHelper;

    fn id(_array: &Self::Array) -> ArrayId {
        Self::ID
    }

    fn len(array: &DecimalArray) -> usize {
        let divisor = match array.values_type {
            DecimalType::I8 => 1,
            DecimalType::I16 => 2,
            DecimalType::I32 => 4,
            DecimalType::I64 => 8,
            DecimalType::I128 => 16,
            DecimalType::I256 => 32,
        };
        array.values.len() / divisor
    }

    fn dtype(array: &DecimalArray) -> &DType {
        &array.dtype
    }

    fn stats(array: &DecimalArray) -> StatsSetRef<'_> {
        array.stats_set.to_ref(array.as_ref())
    }

    fn array_hash<H: std::hash::Hasher>(array: &DecimalArray, state: &mut H, precision: Precision) {
        array.dtype.hash(state);
        array.values.array_hash(state, precision);
        std::mem::discriminant(&array.values_type).hash(state);
        array.validity.array_hash(state, precision);
    }

    fn array_eq(array: &DecimalArray, other: &DecimalArray, precision: Precision) -> bool {
        array.dtype == other.dtype
            && array.values.array_eq(&other.values, precision)
            && array.values_type == other.values_type
            && array.validity.array_eq(&other.validity, precision)
    }

    fn nbuffers(_array: &DecimalArray) -> usize {
        1
    }

    fn buffer(array: &DecimalArray, idx: usize) -> BufferHandle {
        match idx {
            0 => array.values.clone(),
            _ => vortex_panic!("DecimalArray buffer index {idx} out of bounds"),
        }
    }

    fn buffer_name(_array: &DecimalArray, idx: usize) -> Option<String> {
        match idx {
            0 => Some("values".to_string()),
            _ => None,
        }
    }

    fn nchildren(array: &DecimalArray) -> usize {
        validity_nchildren(&array.validity)
    }

    fn child(array: &DecimalArray, idx: usize) -> ArrayRef {
        match idx {
            0 => validity_to_child(&array.validity, array.len())
                .vortex_expect("DecimalArray child index out of bounds"),
            _ => vortex_panic!("DecimalArray child index {idx} out of bounds"),
        }
    }

    fn child_name(_array: &DecimalArray, _idx: usize) -> String {
        "validity".to_string()
    }

    fn metadata(array: &DecimalArray) -> VortexResult<Self::Metadata> {
        Ok(ProstMetadata(DecimalMetadata {
            values_type: array.values_type() as i32,
        }))
    }

    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
        Ok(Some(metadata.serialize()))
    }

    fn deserialize(
        bytes: &[u8],
        _dtype: &DType,
        _len: usize,
        _buffers: &[BufferHandle],
        _session: &VortexSession,
    ) -> VortexResult<Self::Metadata> {
        let metadata = ProstMetadata::<DecimalMetadata>::deserialize(bytes)?;
        Ok(ProstMetadata(metadata))
    }

    fn build(
        dtype: &DType,
        len: usize,
        metadata: &Self::Metadata,
        buffers: &[BufferHandle],
        children: &dyn ArrayChildren,
    ) -> VortexResult<DecimalArray> {
        if buffers.len() != 1 {
            vortex_bail!("Expected 1 buffer, got {}", buffers.len());
        }
        let values = buffers[0].clone();

        let validity = if children.is_empty() {
            Validity::from(dtype.nullability())
        } else if children.len() == 1 {
            let validity = children.get(0, &Validity::DTYPE, len)?;
            Validity::Array(validity)
        } else {
            vortex_bail!("Expected 0 or 1 child, got {}", children.len());
        };

        let Some(decimal_dtype) = dtype.as_decimal_opt() else {
            vortex_bail!("Expected Decimal dtype, got {:?}", dtype)
        };

        match_each_decimal_value_type!(metadata.values_type(), |D| {
            // Check and reinterpret-cast the buffer
            vortex_ensure!(
                values.is_aligned_to(Alignment::of::<D>()),
                "DecimalArray buffer not aligned for values type {:?}",
                D::DECIMAL_TYPE
            );
            DecimalArray::try_new_handle(values, metadata.values_type(), *decimal_dtype, validity)
        })
    }

    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
        vortex_ensure!(
            children.len() <= 1,
            "DecimalArray expects 0 or 1 child (validity), got {}",
            children.len()
        );

        if children.is_empty() {
            array.validity = Validity::from(array.dtype.nullability());
        } else {
            array.validity = Validity::Array(
                children
                    .into_iter()
                    .next()
                    .vortex_expect("children length already validated"),
            );
        }
        Ok(())
    }

    fn execute(array: &Self::Array, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionStep> {
        Ok(ExecutionStep::Done(array.clone().into_array()))
    }

    fn reduce_parent(
        array: &Self::Array,
        parent: &ArrayRef,
        child_idx: usize,
    ) -> VortexResult<Option<ArrayRef>> {
        RULES.evaluate(array, parent, child_idx)
    }

    fn execute_parent(
        array: &Self::Array,
        parent: &ArrayRef,
        child_idx: usize,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<Option<ArrayRef>> {
        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
    }
}

#[derive(Debug)]
pub struct DecimalVTable;

impl DecimalVTable {
    pub const ID: ArrayId = ArrayId::new_ref("vortex.decimal");
}

#[cfg(test)]
mod tests {
    use vortex_buffer::ByteBufferMut;
    use vortex_buffer::buffer;
    use vortex_session::registry::ReadContext;

    use crate::ArrayContext;
    use crate::IntoArray;
    use crate::LEGACY_SESSION;
    use crate::arrays::DecimalArray;
    use crate::arrays::DecimalVTable;
    use crate::dtype::DecimalDType;
    use crate::serde::ArrayParts;
    use crate::serde::SerializeOptions;
    use crate::validity::Validity;

    #[test]
    fn test_array_serde() {
        let array = DecimalArray::new(
            buffer![100i128, 200i128, 300i128, 400i128, 500i128],
            DecimalDType::new(10, 2),
            Validity::NonNullable,
        );
        let dtype = array.dtype().clone();

        let ctx = ArrayContext::empty();
        let out = array
            .into_array()
            .serialize(&ctx, &SerializeOptions::default())
            .unwrap();
        // Concat into a single buffer
        let mut concat = ByteBufferMut::empty();
        for buf in out {
            concat.extend_from_slice(buf.as_ref());
        }

        let concat = concat.freeze();

        let parts = ArrayParts::try_from(concat).unwrap();
        let decoded = parts
            .decode(&dtype, 5, &ReadContext::new(ctx.to_ids()), &LEGACY_SESSION)
            .unwrap();
        assert!(decoded.is::<DecimalVTable>());
    }
}