Skip to main content

vortex_alp/alp_rd/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::hash::Hash;
8use std::hash::Hasher;
9
10use itertools::Itertools;
11use prost::Message;
12use vortex_array::Array;
13use vortex_array::ArrayEq;
14use vortex_array::ArrayHash;
15use vortex_array::ArrayId;
16use vortex_array::ArrayParts;
17use vortex_array::ArrayRef;
18use vortex_array::ArraySlots;
19use vortex_array::ArrayView;
20use vortex_array::EqMode;
21use vortex_array::ExecutionCtx;
22use vortex_array::ExecutionResult;
23use vortex_array::IntoArray;
24use vortex_array::TypedArrayRef;
25use vortex_array::arrays::Primitive;
26use vortex_array::arrays::PrimitiveArray;
27use vortex_array::buffer::BufferHandle;
28use vortex_array::dtype::DType;
29use vortex_array::dtype::Nullability;
30use vortex_array::dtype::PType;
31use vortex_array::patches::PatchSlotIndices;
32use vortex_array::patches::Patches;
33use vortex_array::patches::PatchesData;
34use vortex_array::patches::PatchesMetadata;
35use vortex_array::require_child;
36use vortex_array::require_patches;
37use vortex_array::serde::ArrayChildren;
38use vortex_array::smallvec::smallvec;
39use vortex_array::validity::Validity;
40use vortex_array::vtable::VTable;
41use vortex_array::vtable::ValidityChild;
42use vortex_array::vtable::ValidityVTableFromChild;
43use vortex_buffer::Buffer;
44use vortex_error::VortexExpect;
45use vortex_error::VortexResult;
46use vortex_error::vortex_bail;
47use vortex_error::vortex_ensure;
48use vortex_error::vortex_err;
49use vortex_error::vortex_panic;
50use vortex_session::VortexSession;
51use vortex_session::registry::CachedId;
52
53use crate::alp_rd::rules::RULES;
54use crate::alp_rd_decode;
55
56/// A [`ALPRD`]-encoded Vortex array.
57pub type ALPRDArray = Array<ALPRD>;
58
59#[derive(Clone, prost::Message)]
60pub struct ALPRDMetadata {
61    #[prost(uint32, tag = "1")]
62    right_bit_width: u32,
63    #[prost(uint32, tag = "2")]
64    dict_len: u32,
65    #[prost(uint32, repeated, tag = "3")]
66    dict: Vec<u32>,
67    #[prost(enumeration = "PType", tag = "4")]
68    left_parts_ptype: i32,
69    #[prost(message, tag = "5")]
70    patches: Option<PatchesMetadata>,
71}
72
73impl ArrayHash for ALPRDData {
74    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
75        self.left_parts_dictionary.array_hash(state, accuracy);
76        self.right_bit_width.hash(state);
77        self.patches_data.hash(state);
78    }
79}
80
81impl ArrayEq for ALPRDData {
82    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
83        self.left_parts_dictionary
84            .array_eq(&other.left_parts_dictionary, accuracy)
85            && self.right_bit_width == other.right_bit_width
86            && self.patches_data == other.patches_data
87    }
88}
89
90impl VTable for ALPRD {
91    type TypedArrayData = ALPRDData;
92
93    type OperationsVTable = Self;
94    type ValidityVTable = ValidityVTableFromChild;
95
96    fn id(&self) -> ArrayId {
97        static ID: CachedId = CachedId::new("vortex.alprd");
98        *ID
99    }
100
101    fn validate(
102        &self,
103        data: &ALPRDData,
104        dtype: &DType,
105        len: usize,
106        slots: &[Option<ArrayRef>],
107    ) -> VortexResult<()> {
108        validate_parts(
109            dtype,
110            len,
111            left_parts_from_slots(slots),
112            right_parts_from_slots(slots),
113            patches_from_slots(slots, data.patches_data.as_ref(), len).as_ref(),
114        )
115    }
116
117    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
118        0
119    }
120
121    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
122        vortex_panic!("ALPRDArray buffer index {idx} out of bounds")
123    }
124
125    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
126        None
127    }
128
129    fn with_buffers(
130        &self,
131        array: ArrayView<'_, Self>,
132        buffers: &[BufferHandle],
133    ) -> VortexResult<ArrayParts<Self>> {
134        vortex_array::vtable::with_empty_buffers(self, array, buffers)
135    }
136
137    fn serialize(
138        array: ArrayView<'_, Self>,
139        _session: &VortexSession,
140    ) -> VortexResult<Option<Vec<u8>>> {
141        let dict = array
142            .left_parts_dictionary()
143            .iter()
144            .map(|&i| i as u32)
145            .collect::<Vec<_>>();
146
147        Ok(Some(
148            ALPRDMetadata {
149                right_bit_width: array.right_bit_width() as u32,
150                dict_len: array.left_parts_dictionary().len() as u32,
151                dict,
152                left_parts_ptype: array.left_parts().dtype().as_ptype() as i32,
153                patches: array
154                    .left_parts_patches()
155                    .map(|p| p.to_metadata(array.len(), p.dtype()))
156                    .transpose()?,
157            }
158            .encode_to_vec(),
159        ))
160    }
161
162    fn deserialize(
163        &self,
164        dtype: &DType,
165        len: usize,
166        metadata: &[u8],
167        _buffers: &[BufferHandle],
168        children: &dyn ArrayChildren,
169        _session: &VortexSession,
170    ) -> VortexResult<ArrayParts<Self>> {
171        let metadata = ALPRDMetadata::decode(metadata)?;
172        if children.len() < 2 {
173            vortex_bail!(
174                "Expected at least 2 children for ALPRD encoding, found {}",
175                children.len()
176            );
177        }
178
179        let left_parts_dtype = DType::Primitive(metadata.left_parts_ptype(), dtype.nullability());
180        let left_parts = children.get(0, &left_parts_dtype, len)?;
181        let left_parts_dictionary: Buffer<u16> = metadata.dict.as_slice()
182            [0..metadata.dict_len as usize]
183            .iter()
184            .map(|&i| {
185                u16::try_from(i)
186                    .map_err(|_| vortex_err!("left_parts_dictionary code {i} does not fit in u16"))
187            })
188            .try_collect()?;
189
190        let right_parts_dtype = match &dtype {
191            DType::Primitive(PType::F32, _) => {
192                DType::Primitive(PType::U32, Nullability::NonNullable)
193            }
194            DType::Primitive(PType::F64, _) => {
195                DType::Primitive(PType::U64, Nullability::NonNullable)
196            }
197            _ => vortex_bail!("Expected f32 or f64 dtype, got {:?}", dtype),
198        };
199        let right_parts = children.get(1, &right_parts_dtype, len)?;
200
201        let left_parts_patches = metadata
202            .patches
203            .map(|p| {
204                let indices = children.get(2, &p.indices_dtype()?, p.len()?)?;
205                let values = children.get(3, &left_parts_dtype.as_nonnullable(), p.len()?)?;
206
207                Patches::new(
208                    len,
209                    p.offset()?,
210                    indices,
211                    values,
212                    // TODO(0ax1): handle chunk offsets
213                    None,
214                )
215            })
216            .transpose()?;
217        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
218        let data = ALPRDData::new(
219            left_parts_dictionary,
220            u8::try_from(metadata.right_bit_width).map_err(|_| {
221                vortex_err!(
222                    "right_bit_width {} out of u8 range",
223                    metadata.right_bit_width
224                )
225            })?,
226            left_parts_patches,
227        );
228        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
229    }
230
231    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
232        SLOT_NAMES[idx].to_string()
233    }
234
235    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
236        let array = require_child!(array, array.left_parts(), 0 => Primitive);
237        let array = require_child!(array, array.right_parts(), 1 => Primitive);
238        require_patches!(
239            array,
240            LP_PATCH_INDICES_SLOT,
241            LP_PATCH_VALUES_SLOT,
242            LP_PATCH_CHUNK_OFFSETS_SLOT
243        );
244
245        let dtype = array.dtype().clone();
246        let right_bit_width = array.right_bit_width();
247        let ALPRDDataParts {
248            left_parts,
249            right_parts,
250            left_parts_dictionary,
251            left_parts_patches,
252        } = ALPRDArrayOwnedExt::into_data_parts(array);
253        let ptype = dtype.as_ptype();
254
255        let left_parts = left_parts
256            .try_downcast::<Primitive>()
257            .ok()
258            .vortex_expect("ALPRD execute: left_parts is primitive");
259        let right_parts = right_parts
260            .try_downcast::<Primitive>()
261            .ok()
262            .vortex_expect("ALPRD execute: right_parts is primitive");
263
264        // Decode the left_parts using our builtin dictionary.
265        let left_parts_dict = left_parts_dictionary;
266        let validity = left_parts
267            .as_ref()
268            .validity()?
269            .execute_mask(left_parts.as_ref().len(), ctx)?;
270
271        let decoded_array = if ptype == PType::F32 {
272            PrimitiveArray::new(
273                alp_rd_decode::<f32>(
274                    left_parts.into_buffer_mut::<u16>(),
275                    &left_parts_dict,
276                    right_bit_width,
277                    right_parts.into_buffer_mut::<u32>(),
278                    left_parts_patches,
279                    ctx,
280                )?,
281                Validity::from_mask(validity, dtype.nullability()),
282            )
283        } else {
284            PrimitiveArray::new(
285                alp_rd_decode::<f64>(
286                    left_parts.into_buffer_mut::<u16>(),
287                    &left_parts_dict,
288                    right_bit_width,
289                    right_parts.into_buffer_mut::<u64>(),
290                    left_parts_patches,
291                    ctx,
292                )?,
293                Validity::from_mask(validity, dtype.nullability()),
294            )
295        };
296
297        Ok(ExecutionResult::done(decoded_array.into_array()))
298    }
299
300    fn reduce_parent(
301        array: ArrayView<'_, Self>,
302        parent: &ArrayRef,
303        child_idx: usize,
304    ) -> VortexResult<Option<ArrayRef>> {
305        RULES.evaluate(array, parent, child_idx)
306    }
307}
308
309/// The left (most significant) parts of the real-double encoded values.
310pub(super) const LEFT_PARTS_SLOT: usize = 0;
311/// The right (least significant) parts of the real-double encoded values.
312pub(super) const RIGHT_PARTS_SLOT: usize = 1;
313/// The indices of left-parts exception values that could not be dictionary-encoded.
314pub(super) const LP_PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices {
315    indices: LP_PATCH_INDICES_SLOT,
316    values: LP_PATCH_VALUES_SLOT,
317    chunk_offsets: LP_PATCH_CHUNK_OFFSETS_SLOT,
318};
319pub(super) const LP_PATCH_INDICES_SLOT: usize = 2;
320/// The exception values for left-parts that could not be dictionary-encoded.
321pub(super) const LP_PATCH_VALUES_SLOT: usize = 3;
322/// Chunk offsets for the left-parts patch indices/values.
323pub(super) const LP_PATCH_CHUNK_OFFSETS_SLOT: usize = 4;
324pub(super) const NUM_SLOTS: usize = 5;
325pub(super) const SLOT_NAMES: [&str; NUM_SLOTS] = [
326    "left_parts",
327    "right_parts",
328    "patch_indices",
329    "patch_values",
330    "patch_chunk_offsets",
331];
332
333#[derive(Clone, Debug)]
334pub struct ALPRDData {
335    patches_data: Option<PatchesData>,
336    left_parts_dictionary: Buffer<u16>,
337    right_bit_width: u8,
338}
339
340impl Display for ALPRDData {
341    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
342        write!(f, "right_bit_width: {}", self.right_bit_width)?;
343        if let Some(pd) = &self.patches_data {
344            write!(f, ", patch_offset: {}", pd.offset())?;
345        }
346        Ok(())
347    }
348}
349
350#[derive(Clone, Debug)]
351pub struct ALPRDDataParts {
352    pub left_parts: ArrayRef,
353    pub left_parts_patches: Option<Patches>,
354    pub left_parts_dictionary: Buffer<u16>,
355    pub right_parts: ArrayRef,
356}
357
358#[derive(Clone, Debug)]
359pub struct ALPRD;
360
361impl ALPRD {
362    pub fn try_new(
363        dtype: DType,
364        left_parts: ArrayRef,
365        left_parts_dictionary: Buffer<u16>,
366        right_parts: ArrayRef,
367        right_bit_width: u8,
368        left_parts_patches: Option<Patches>,
369    ) -> VortexResult<ALPRDArray> {
370        let len = left_parts.len();
371        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
372        let data = ALPRDData::new(left_parts_dictionary, right_bit_width, left_parts_patches);
373        Array::try_from_parts(ArrayParts::new(ALPRD, dtype, len, data).with_slots(slots))
374    }
375
376    /// # Safety
377    /// See [`ALPRD::try_new`] for preconditions.
378    pub unsafe fn new_unchecked(
379        dtype: DType,
380        left_parts: ArrayRef,
381        left_parts_dictionary: Buffer<u16>,
382        right_parts: ArrayRef,
383        right_bit_width: u8,
384        left_parts_patches: Option<Patches>,
385    ) -> ALPRDArray {
386        let len = left_parts.len();
387        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
388        let data = unsafe {
389            ALPRDData::new_unchecked(left_parts_dictionary, right_bit_width, left_parts_patches)
390        };
391        unsafe {
392            Array::from_parts_unchecked(ArrayParts::new(ALPRD, dtype, len, data).with_slots(slots))
393        }
394    }
395}
396
397impl ALPRDData {
398    /// Build a new `ALPRDArray` from components.
399    pub fn new(
400        left_parts_dictionary: Buffer<u16>,
401        right_bit_width: u8,
402        left_parts_patches: Option<Patches>,
403    ) -> Self {
404        Self {
405            patches_data: left_parts_patches.as_ref().map(PatchesData::from_patches),
406            left_parts_dictionary,
407            right_bit_width,
408        }
409    }
410
411    /// Build a new `ALPRDArray` from components. This does not perform any validation, and instead
412    /// it constructs it from parts.
413    pub(crate) unsafe fn new_unchecked(
414        left_parts_dictionary: Buffer<u16>,
415        right_bit_width: u8,
416        left_parts_patches: Option<Patches>,
417    ) -> Self {
418        Self::new(left_parts_dictionary, right_bit_width, left_parts_patches)
419    }
420
421    fn make_slots(
422        left_parts: &ArrayRef,
423        right_parts: &ArrayRef,
424        patches: Option<&Patches>,
425    ) -> ArraySlots {
426        let mut slots: ArraySlots = smallvec![Some(left_parts.clone()), Some(right_parts.clone())];
427        PatchesData::push_slots(&mut slots, patches);
428        slots
429    }
430
431    /// Return all the owned parts of the array
432    pub fn into_parts(self, left_parts: ArrayRef, right_parts: ArrayRef) -> ALPRDDataParts {
433        ALPRDDataParts {
434            left_parts,
435            left_parts_patches: None,
436            left_parts_dictionary: self.left_parts_dictionary,
437            right_parts,
438        }
439    }
440
441    #[inline]
442    pub fn right_bit_width(&self) -> u8 {
443        self.right_bit_width
444    }
445
446    /// The dictionary that maps the codes in `left_parts` into bit patterns.
447    #[inline]
448    pub fn left_parts_dictionary(&self) -> &Buffer<u16> {
449        &self.left_parts_dictionary
450    }
451}
452
453fn left_parts_from_slots(slots: &[Option<ArrayRef>]) -> &ArrayRef {
454    slots[LEFT_PARTS_SLOT]
455        .as_ref()
456        .vortex_expect("ALPRDArray left_parts slot")
457}
458
459fn right_parts_from_slots(slots: &[Option<ArrayRef>]) -> &ArrayRef {
460    slots[RIGHT_PARTS_SLOT]
461        .as_ref()
462        .vortex_expect("ALPRDArray right_parts slot")
463}
464
465fn patches_from_slots(
466    slots: &[Option<ArrayRef>],
467    patches_data: Option<&PatchesData>,
468    len: usize,
469) -> Option<Patches> {
470    PatchesData::patches_from_slots(patches_data, len, slots, LP_PATCH_SLOTS)
471}
472
473fn validate_parts(
474    dtype: &DType,
475    len: usize,
476    left_parts: &ArrayRef,
477    right_parts: &ArrayRef,
478    left_parts_patches: Option<&Patches>,
479) -> VortexResult<()> {
480    if !dtype.is_float() {
481        vortex_bail!("ALPRDArray given invalid DType ({dtype})");
482    }
483
484    vortex_ensure!(
485        left_parts.len() == len,
486        "left_parts len {} != outer len {len}",
487        left_parts.len(),
488    );
489    vortex_ensure!(
490        right_parts.len() == len,
491        "right_parts len {} != outer len {len}",
492        right_parts.len(),
493    );
494
495    if !left_parts.dtype().is_unsigned_int() {
496        vortex_bail!("left_parts dtype must be uint");
497    }
498    if dtype.is_nullable() != left_parts.dtype().is_nullable() {
499        vortex_bail!(
500            "ALPRDArray dtype nullability ({}) must match left_parts dtype nullability ({})",
501            dtype,
502            left_parts.dtype()
503        );
504    }
505
506    let expected_right_parts_dtype = match dtype {
507        DType::Primitive(PType::F32, _) => DType::Primitive(PType::U32, Nullability::NonNullable),
508        DType::Primitive(PType::F64, _) => DType::Primitive(PType::U64, Nullability::NonNullable),
509        _ => vortex_bail!("Expected f32 or f64 dtype, got {:?}", dtype),
510    };
511    vortex_ensure!(
512        right_parts.dtype() == &expected_right_parts_dtype,
513        "right_parts dtype {} does not match expected {}",
514        right_parts.dtype(),
515        expected_right_parts_dtype,
516    );
517
518    if let Some(patches) = left_parts_patches {
519        vortex_ensure!(
520            patches.array_len() == len,
521            "patches array_len {} != outer len {len}",
522            patches.array_len(),
523        );
524        // Left-parts exceptions are always all-valid and are stored as the non-nullable left-parts
525        // dtype. Requiring that exact dtype (rather than ignoring nullability) means each
526        // construction path must produce correct patches, removing the need to normalize them.
527        // Non-nullable also implies all-valid, so no separate validity check is required.
528        let expected = left_parts.dtype().as_nonnullable();
529        vortex_ensure!(
530            patches.dtype() == &expected,
531            "patches dtype {} must be the non-nullable left_parts dtype {}",
532            patches.dtype(),
533            expected,
534        );
535    }
536
537    Ok(())
538}
539
540pub trait ALPRDArrayExt: TypedArrayRef<ALPRD> {
541    fn left_parts(&self) -> &ArrayRef {
542        left_parts_from_slots(self.as_ref().slots())
543    }
544
545    fn right_parts(&self) -> &ArrayRef {
546        right_parts_from_slots(self.as_ref().slots())
547    }
548
549    fn right_bit_width(&self) -> u8 {
550        ALPRDData::right_bit_width(self)
551    }
552
553    fn left_parts_patches(&self) -> Option<Patches> {
554        patches_from_slots(
555            self.as_ref().slots(),
556            self.patches_data.as_ref(),
557            self.as_ref().len(),
558        )
559    }
560
561    fn left_parts_dictionary(&self) -> &Buffer<u16> {
562        ALPRDData::left_parts_dictionary(self)
563    }
564}
565impl<T: TypedArrayRef<ALPRD>> ALPRDArrayExt for T {}
566
567pub trait ALPRDArrayOwnedExt {
568    fn into_data_parts(self) -> ALPRDDataParts;
569}
570
571impl ALPRDArrayOwnedExt for Array<ALPRD> {
572    fn into_data_parts(self) -> ALPRDDataParts {
573        let left_parts_patches = self.left_parts_patches();
574        let left_parts = self.left_parts().clone();
575        let right_parts = self.right_parts().clone();
576        let mut parts = ALPRDDataParts {
577            left_parts,
578            left_parts_patches: None,
579            left_parts_dictionary: self.left_parts_dictionary().clone(),
580            right_parts,
581        };
582        parts.left_parts_patches = left_parts_patches;
583        parts
584    }
585}
586
587impl ValidityChild<ALPRD> for ALPRD {
588    fn validity_child(array: ArrayView<'_, ALPRD>) -> ArrayRef {
589        array.left_parts().clone()
590    }
591}
592
593#[cfg(test)]
594mod test {
595    use std::sync::LazyLock;
596
597    use prost::Message;
598    use rstest::rstest;
599    use vortex_array::VortexSessionExecute;
600    use vortex_array::arrays::PrimitiveArray;
601    use vortex_array::assert_arrays_eq;
602    use vortex_array::dtype::PType;
603    use vortex_array::patches::PatchesMetadata;
604    use vortex_array::test_harness::check_metadata;
605    use vortex_session::VortexSession;
606
607    use super::ALPRDMetadata;
608    use crate::ALPRDFloat;
609    use crate::alp_rd;
610
611    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
612        let session = vortex_array::array_session();
613        crate::initialize(&session);
614        session
615    });
616
617    #[rstest]
618    #[case(vec![0.1f32.next_up(); 1024], 1.123_848_f32)]
619    #[case(vec![0.1f64.next_up(); 1024], 1.123_848_591_110_992_f64)]
620    fn test_array_encode_with_nulls_and_patches<T: ALPRDFloat>(
621        #[case] reals: Vec<T>,
622        #[case] seed: T,
623    ) {
624        let mut ctx = SESSION.create_execution_ctx();
625        assert_eq!(reals.len(), 1024, "test expects 1024-length fixture");
626        // Null out some of the values.
627        let mut reals: Vec<Option<T>> = reals.into_iter().map(Some).collect();
628        reals[1] = None;
629        reals[5] = None;
630        reals[900] = None;
631
632        // Create a new array from this.
633        let real_array = PrimitiveArray::from_option_iter(reals.iter().cloned());
634
635        // Pick a seed that we know will trigger lots of patches.
636        let encoder: alp_rd::RDEncoder = alp_rd::RDEncoder::new(&[seed.powi(-2)]);
637
638        let rd_array = encoder.encode(real_array.as_view());
639
640        let decoded = rd_array
641            .as_array()
642            .clone()
643            .execute::<PrimitiveArray>(&mut ctx)
644            .unwrap();
645
646        assert_arrays_eq!(decoded, PrimitiveArray::from_option_iter(reals), &mut ctx);
647    }
648
649    #[cfg_attr(miri, ignore)]
650    #[test]
651    fn test_alprd_metadata() {
652        check_metadata(
653            "alprd.metadata",
654            &ALPRDMetadata {
655                right_bit_width: u32::MAX,
656                patches: Some(PatchesMetadata::new(
657                    usize::MAX,
658                    usize::MAX,
659                    PType::U64,
660                    None,
661                    None,
662                    None,
663                )),
664                dict: Vec::new(),
665                left_parts_ptype: PType::U64 as i32,
666                dict_len: 8,
667            }
668            .encode_to_vec(),
669        );
670    }
671}