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::array_slots;
26use vortex_array::arrays::Primitive;
27use vortex_array::arrays::PrimitiveArray;
28use vortex_array::buffer::BufferHandle;
29use vortex_array::dtype::DType;
30use vortex_array::dtype::Nullability;
31use vortex_array::dtype::PType;
32use vortex_array::patches::PatchSlotIndices;
33use vortex_array::patches::Patches;
34use vortex_array::patches::PatchesData;
35use vortex_array::patches::PatchesMetadata;
36use vortex_array::require_child;
37use vortex_array::require_patches;
38use vortex_array::serde::ArrayChildren;
39use vortex_array::smallvec::smallvec;
40use vortex_array::validity::Validity;
41use vortex_array::vtable::VTable;
42use vortex_array::vtable::ValidityChild;
43use vortex_array::vtable::ValidityVTableFromChild;
44use vortex_buffer::Buffer;
45use vortex_error::VortexExpect;
46use vortex_error::VortexResult;
47use vortex_error::vortex_bail;
48use vortex_error::vortex_ensure;
49use vortex_error::vortex_err;
50use vortex_error::vortex_panic;
51use vortex_session::VortexSession;
52use vortex_session::registry::CachedId;
53
54use crate::alp_rd::rules::RULES;
55use crate::alp_rd_decode;
56
57/// A [`ALPRD`]-encoded Vortex array.
58pub type ALPRDArray = Array<ALPRD>;
59
60#[derive(Clone, prost::Message)]
61pub struct ALPRDMetadata {
62    #[prost(uint32, tag = "1")]
63    right_bit_width: u32,
64    #[prost(uint32, tag = "2")]
65    dict_len: u32,
66    #[prost(uint32, repeated, tag = "3")]
67    dict: Vec<u32>,
68    #[prost(enumeration = "PType", tag = "4")]
69    left_parts_ptype: i32,
70    #[prost(message, tag = "5")]
71    patches: Option<PatchesMetadata>,
72}
73
74impl ArrayHash for ALPRDData {
75    fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: EqMode) {
76        self.left_parts_dictionary.array_hash(state, accuracy);
77        self.right_bit_width.hash(state);
78        self.patches_data.hash(state);
79    }
80}
81
82impl ArrayEq for ALPRDData {
83    fn array_eq(&self, other: &Self, accuracy: EqMode) -> bool {
84        self.left_parts_dictionary
85            .array_eq(&other.left_parts_dictionary, accuracy)
86            && self.right_bit_width == other.right_bit_width
87            && self.patches_data == other.patches_data
88    }
89}
90
91impl VTable for ALPRD {
92    type TypedArrayData = ALPRDData;
93
94    type OperationsVTable = Self;
95    type ValidityVTable = ValidityVTableFromChild;
96
97    fn id(&self) -> ArrayId {
98        static ID: CachedId = CachedId::new("vortex.alprd");
99        *ID
100    }
101
102    fn validate(
103        &self,
104        data: &ALPRDData,
105        dtype: &DType,
106        len: usize,
107        slots: &[Option<ArrayRef>],
108    ) -> VortexResult<()> {
109        let alprd_slots = ALPRDSlotsView::from_slots(slots);
110        validate_parts(
111            dtype,
112            len,
113            alprd_slots.left_parts,
114            alprd_slots.right_parts,
115            patches_from_slots(slots, data.patches_data.as_ref(), len).as_ref(),
116        )
117    }
118
119    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
120        0
121    }
122
123    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
124        vortex_panic!("ALPRDArray buffer index {idx} out of bounds")
125    }
126
127    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
128        None
129    }
130
131    fn with_buffers(
132        &self,
133        array: ArrayView<'_, Self>,
134        buffers: &[BufferHandle],
135    ) -> VortexResult<ArrayParts<Self>> {
136        vortex_array::vtable::with_empty_buffers(self, array, buffers)
137    }
138
139    fn serialize(
140        array: ArrayView<'_, Self>,
141        _session: &VortexSession,
142    ) -> VortexResult<Option<Vec<u8>>> {
143        let dict = array
144            .left_parts_dictionary()
145            .iter()
146            .map(|&i| i as u32)
147            .collect::<Vec<_>>();
148
149        Ok(Some(
150            ALPRDMetadata {
151                right_bit_width: array.right_bit_width() as u32,
152                dict_len: array.left_parts_dictionary().len() as u32,
153                dict,
154                left_parts_ptype: array.left_parts().dtype().as_ptype() as i32,
155                patches: array
156                    .left_parts_patches()
157                    .map(|p| p.to_metadata(array.len(), p.dtype()))
158                    .transpose()?,
159            }
160            .encode_to_vec(),
161        ))
162    }
163
164    #[allow(clippy::disallowed_methods)]
165    fn deserialize(
166        &self,
167        dtype: &DType,
168        len: usize,
169        metadata: &[u8],
170        _buffers: &[BufferHandle],
171        children: &dyn ArrayChildren,
172        _session: &VortexSession,
173    ) -> VortexResult<ArrayParts<Self>> {
174        let metadata = ALPRDMetadata::decode(metadata)?;
175        if children.len() < 2 {
176            vortex_bail!(
177                "Expected at least 2 children for ALPRD encoding, found {}",
178                children.len()
179            );
180        }
181
182        let left_parts_dtype = DType::Primitive(metadata.left_parts_ptype(), dtype.nullability());
183        let left_parts = children.get(0, &left_parts_dtype, len)?;
184        let left_parts_dictionary: Buffer<u16> = metadata.dict.as_slice()
185            [0..metadata.dict_len as usize]
186            .iter()
187            .map(|&i| {
188                u16::try_from(i)
189                    .map_err(|_| vortex_err!("left_parts_dictionary code {i} does not fit in u16"))
190            })
191            .try_collect()?;
192
193        let right_parts_dtype = match &dtype {
194            DType::Primitive(PType::F32, _) => {
195                DType::Primitive(PType::U32, Nullability::NonNullable)
196            }
197            DType::Primitive(PType::F64, _) => {
198                DType::Primitive(PType::U64, Nullability::NonNullable)
199            }
200            _ => vortex_bail!("Expected f32 or f64 dtype, got {:?}", dtype),
201        };
202        let right_parts = children.get(1, &right_parts_dtype, len)?;
203
204        let left_parts_patches = metadata
205            .patches
206            .map(|p| {
207                let indices = children.get(2, &p.indices_dtype()?, p.len()?)?;
208                let values = children.get(3, &left_parts_dtype.as_nonnullable(), p.len()?)?;
209
210                Patches::new(
211                    len,
212                    p.offset()?,
213                    indices,
214                    values,
215                    // TODO(0ax1): handle chunk offsets
216                    None,
217                )
218            })
219            .transpose()?;
220        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
221        let data = ALPRDData::new(
222            left_parts_dictionary,
223            u8::try_from(metadata.right_bit_width).map_err(|_| {
224                vortex_err!(
225                    "right_bit_width {} out of u8 range",
226                    metadata.right_bit_width
227                )
228            })?,
229            left_parts_patches,
230        );
231        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
232    }
233
234    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
235        ALPRDSlots::NAMES[idx].to_string()
236    }
237
238    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
239        let array = require_child!(array, array.left_parts(), ALPRDSlots::LEFT_PARTS => Primitive);
240        let array =
241            require_child!(array, array.right_parts(), ALPRDSlots::RIGHT_PARTS => Primitive);
242        require_patches!(
243            array,
244            ALPRDSlots::PATCH_INDICES,
245            ALPRDSlots::PATCH_VALUES,
246            ALPRDSlots::PATCH_CHUNK_OFFSETS
247        );
248
249        let dtype = array.dtype().clone();
250        let right_bit_width = array.right_bit_width();
251        let ALPRDDataParts {
252            left_parts,
253            right_parts,
254            left_parts_dictionary,
255            left_parts_patches,
256        } = ALPRDArrayOwnedExt::into_data_parts(array);
257        let ptype = dtype.as_ptype();
258
259        let left_parts = left_parts
260            .try_downcast::<Primitive>()
261            .ok()
262            .vortex_expect("ALPRD execute: left_parts is primitive");
263        let right_parts = right_parts
264            .try_downcast::<Primitive>()
265            .ok()
266            .vortex_expect("ALPRD execute: right_parts is primitive");
267
268        // Decode the left_parts using our builtin dictionary.
269        let left_parts_dict = left_parts_dictionary;
270        let validity = left_parts
271            .as_ref()
272            .validity()?
273            .execute_mask(left_parts.as_ref().len(), ctx)?;
274
275        let decoded_array = if ptype == PType::F32 {
276            PrimitiveArray::new(
277                alp_rd_decode::<f32>(
278                    left_parts.into_buffer_mut::<u16>(),
279                    &left_parts_dict,
280                    right_bit_width,
281                    right_parts.into_buffer_mut::<u32>(),
282                    left_parts_patches,
283                    ctx,
284                )?,
285                Validity::from_mask(validity, dtype.nullability()),
286            )
287        } else {
288            PrimitiveArray::new(
289                alp_rd_decode::<f64>(
290                    left_parts.into_buffer_mut::<u16>(),
291                    &left_parts_dict,
292                    right_bit_width,
293                    right_parts.into_buffer_mut::<u64>(),
294                    left_parts_patches,
295                    ctx,
296                )?,
297                Validity::from_mask(validity, dtype.nullability()),
298            )
299        };
300
301        Ok(ExecutionResult::done(decoded_array.into_array()))
302    }
303
304    fn reduce_parent(
305        array: ArrayView<'_, Self>,
306        parent: &ArrayRef,
307        child_idx: usize,
308    ) -> VortexResult<Option<ArrayRef>> {
309        RULES.evaluate(array, parent, child_idx)
310    }
311}
312
313#[array_slots(ALPRD)]
314pub struct ALPRDSlots {
315    /// The left (most significant) parts of the real-double encoded values.
316    pub left_parts: ArrayRef,
317    /// The right (least significant) parts of the real-double encoded values.
318    pub right_parts: ArrayRef,
319    /// The indices of left-parts exception values that could not be dictionary-encoded.
320    pub patch_indices: Option<ArrayRef>,
321    /// The exception values for left-parts that could not be dictionary-encoded.
322    pub patch_values: Option<ArrayRef>,
323    /// Chunk offsets for the left-parts patch indices/values.
324    pub patch_chunk_offsets: Option<ArrayRef>,
325}
326
327const LP_PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices {
328    indices: ALPRDSlots::PATCH_INDICES,
329    values: ALPRDSlots::PATCH_VALUES,
330    chunk_offsets: ALPRDSlots::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 patches_from_slots(
454    slots: &[Option<ArrayRef>],
455    patches_data: Option<&PatchesData>,
456    len: usize,
457) -> Option<Patches> {
458    PatchesData::patches_from_slots(patches_data, len, slots, LP_PATCH_SLOTS)
459}
460
461#[allow(clippy::disallowed_methods)]
462fn validate_parts(
463    dtype: &DType,
464    len: usize,
465    left_parts: &ArrayRef,
466    right_parts: &ArrayRef,
467    left_parts_patches: Option<&Patches>,
468) -> VortexResult<()> {
469    if !dtype.is_float() {
470        vortex_bail!("ALPRDArray given invalid DType ({dtype})");
471    }
472
473    vortex_ensure!(
474        left_parts.len() == len,
475        "left_parts len {} != outer len {len}",
476        left_parts.len(),
477    );
478    vortex_ensure!(
479        right_parts.len() == len,
480        "right_parts len {} != outer len {len}",
481        right_parts.len(),
482    );
483
484    if !left_parts.dtype().is_unsigned_int() {
485        vortex_bail!("left_parts dtype must be uint");
486    }
487    if dtype.is_nullable() != left_parts.dtype().is_nullable() {
488        vortex_bail!(
489            "ALPRDArray dtype nullability ({}) must match left_parts dtype nullability ({})",
490            dtype,
491            left_parts.dtype()
492        );
493    }
494
495    let expected_right_parts_dtype = match dtype {
496        DType::Primitive(PType::F32, _) => DType::Primitive(PType::U32, Nullability::NonNullable),
497        DType::Primitive(PType::F64, _) => DType::Primitive(PType::U64, Nullability::NonNullable),
498        _ => vortex_bail!("Expected f32 or f64 dtype, got {:?}", dtype),
499    };
500    vortex_ensure!(
501        right_parts.dtype() == &expected_right_parts_dtype,
502        "right_parts dtype {} does not match expected {}",
503        right_parts.dtype(),
504        expected_right_parts_dtype,
505    );
506
507    if let Some(patches) = left_parts_patches {
508        vortex_ensure!(
509            patches.array_len() == len,
510            "patches array_len {} != outer len {len}",
511            patches.array_len(),
512        );
513        // Left-parts exceptions are always all-valid and are stored as the non-nullable left-parts
514        // dtype. Requiring that exact dtype (rather than ignoring nullability) means each
515        // construction path must produce correct patches, removing the need to normalize them.
516        // Non-nullable also implies all-valid, so no separate validity check is required.
517        let expected = left_parts.dtype().as_nonnullable();
518        vortex_ensure!(
519            patches.dtype() == &expected,
520            "patches dtype {} must be the non-nullable left_parts dtype {}",
521            patches.dtype(),
522            expected,
523        );
524    }
525
526    Ok(())
527}
528
529pub trait ALPRDArrayExt: ALPRDArraySlotsExt {
530    fn right_bit_width(&self) -> u8 {
531        ALPRDData::right_bit_width(self)
532    }
533
534    fn left_parts_patches(&self) -> Option<Patches> {
535        patches_from_slots(
536            self.as_ref().slots(),
537            self.patches_data.as_ref(),
538            self.as_ref().len(),
539        )
540    }
541
542    fn left_parts_dictionary(&self) -> &Buffer<u16> {
543        ALPRDData::left_parts_dictionary(self)
544    }
545}
546impl<T: TypedArrayRef<ALPRD>> ALPRDArrayExt for T {}
547
548pub trait ALPRDArrayOwnedExt {
549    fn into_data_parts(self) -> ALPRDDataParts;
550}
551
552impl ALPRDArrayOwnedExt for Array<ALPRD> {
553    fn into_data_parts(self) -> ALPRDDataParts {
554        let left_parts_patches = self.left_parts_patches();
555        let left_parts = self.left_parts().clone();
556        let right_parts = self.right_parts().clone();
557        let mut parts = ALPRDDataParts {
558            left_parts,
559            left_parts_patches: None,
560            left_parts_dictionary: self.left_parts_dictionary().clone(),
561            right_parts,
562        };
563        parts.left_parts_patches = left_parts_patches;
564        parts
565    }
566}
567
568impl ValidityChild<ALPRD> for ALPRD {
569    fn validity_child(array: ArrayView<'_, ALPRD>) -> ArrayRef {
570        array.left_parts().clone()
571    }
572}
573
574#[cfg(test)]
575mod test {
576    use std::sync::LazyLock;
577
578    use prost::Message;
579    use rstest::rstest;
580    use vortex_array::VortexSessionExecute;
581    use vortex_array::arrays::PrimitiveArray;
582    use vortex_array::assert_arrays_eq;
583    use vortex_array::dtype::PType;
584    use vortex_array::patches::PatchesMetadata;
585    use vortex_array::test_harness::check_metadata;
586    use vortex_session::VortexSession;
587
588    use super::ALPRDMetadata;
589    use crate::ALPRDFloat;
590    use crate::alp_rd;
591
592    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
593        let session = vortex_array::array_session();
594        crate::initialize(&session);
595        session
596    });
597
598    #[rstest]
599    #[case(vec![0.1f32.next_up(); 1024], 1.123_848_f32)]
600    #[case(vec![0.1f64.next_up(); 1024], 1.123_848_591_110_992_f64)]
601    fn test_array_encode_with_nulls_and_patches<T: ALPRDFloat>(
602        #[case] reals: Vec<T>,
603        #[case] seed: T,
604    ) {
605        let mut ctx = SESSION.create_execution_ctx();
606        assert_eq!(reals.len(), 1024, "test expects 1024-length fixture");
607        // Null out some of the values.
608        let mut reals: Vec<Option<T>> = reals.into_iter().map(Some).collect();
609        reals[1] = None;
610        reals[5] = None;
611        reals[900] = None;
612
613        // Create a new array from this.
614        let real_array = PrimitiveArray::from_option_iter(reals.iter().cloned());
615
616        // Pick a seed that we know will trigger lots of patches.
617        let encoder: alp_rd::RDEncoder = alp_rd::RDEncoder::new(&[seed.powi(-2)]);
618
619        let rd_array = encoder.encode(real_array.as_view());
620
621        let decoded = rd_array
622            .as_array()
623            .clone()
624            .execute::<PrimitiveArray>(&mut ctx)
625            .unwrap();
626
627        assert_arrays_eq!(decoded, PrimitiveArray::from_option_iter(reals), &mut ctx);
628    }
629
630    #[cfg_attr(miri, ignore)]
631    #[test]
632    fn test_alprd_metadata() {
633        check_metadata(
634            "alprd.metadata",
635            &ALPRDMetadata {
636                right_bit_width: u32::MAX,
637                patches: Some(PatchesMetadata::new(
638                    usize::MAX,
639                    usize::MAX,
640                    PType::U64,
641                    None,
642                    None,
643                    None,
644                )),
645                dict: Vec::new(),
646                left_parts_ptype: PType::U64 as i32,
647                dict_len: 8,
648            }
649            .encode_to_vec(),
650        );
651    }
652}