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_eq;
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(
232            self.clone(),
233            dtype.clone(),
234            len,
235            data,
236            slots,
237        ))
238    }
239
240    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
241        ALPRDSlots::NAMES[idx].to_string()
242    }
243
244    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
245        let array = require_child!(array, array.left_parts(), ALPRDSlots::LEFT_PARTS => Primitive);
246        let array =
247            require_child!(array, array.right_parts(), ALPRDSlots::RIGHT_PARTS => Primitive);
248        require_patches!(
249            array,
250            ALPRDSlots::PATCH_INDICES,
251            ALPRDSlots::PATCH_VALUES,
252            ALPRDSlots::PATCH_CHUNK_OFFSETS
253        );
254
255        let dtype = array.dtype().clone();
256        let right_bit_width = array.right_bit_width();
257        let ALPRDDataParts {
258            left_parts,
259            right_parts,
260            left_parts_dictionary,
261            left_parts_patches,
262        } = ALPRDArrayOwnedExt::into_data_parts(array);
263        let ptype = dtype.as_ptype();
264
265        let left_parts = left_parts
266            .try_downcast::<Primitive>()
267            .ok()
268            .vortex_expect("ALPRD execute: left_parts is primitive");
269        let right_parts = right_parts
270            .try_downcast::<Primitive>()
271            .ok()
272            .vortex_expect("ALPRD execute: right_parts is primitive");
273
274        // Decode the left_parts using our builtin dictionary.
275        let left_parts_dict = left_parts_dictionary;
276        let validity = left_parts
277            .as_ref()
278            .validity()?
279            .execute_mask(left_parts.as_ref().len(), ctx)?;
280
281        let decoded_array = if ptype == PType::F32 {
282            PrimitiveArray::new(
283                alp_rd_decode::<f32>(
284                    left_parts.into_buffer_mut::<u16>(),
285                    &left_parts_dict,
286                    right_bit_width,
287                    right_parts.into_buffer_mut::<u32>(),
288                    left_parts_patches,
289                    ctx,
290                )?,
291                Validity::from_mask(validity, dtype.nullability()),
292            )
293        } else {
294            PrimitiveArray::new(
295                alp_rd_decode::<f64>(
296                    left_parts.into_buffer_mut::<u16>(),
297                    &left_parts_dict,
298                    right_bit_width,
299                    right_parts.into_buffer_mut::<u64>(),
300                    left_parts_patches,
301                    ctx,
302                )?,
303                Validity::from_mask(validity, dtype.nullability()),
304            )
305        };
306
307        Ok(ExecutionResult::done(decoded_array.into_array()))
308    }
309
310    fn reduce_parent(
311        array: ArrayView<'_, Self>,
312        parent: &ArrayRef,
313        child_idx: usize,
314    ) -> VortexResult<Option<ArrayRef>> {
315        RULES.evaluate(array, parent, child_idx)
316    }
317}
318
319#[array_slots(ALPRD)]
320pub struct ALPRDSlots {
321    /// The left (most significant) parts of the real-double encoded values.
322    #[slot(0)]
323    pub left_parts: ArrayRef,
324    /// The right (least significant) parts of the real-double encoded values.
325    #[slot(1)]
326    pub right_parts: ArrayRef,
327    /// The indices of left-parts exception values that could not be dictionary-encoded.
328    #[slot(2)]
329    pub patch_indices: Option<ArrayRef>,
330    /// The exception values for left-parts that could not be dictionary-encoded.
331    #[slot(3)]
332    pub patch_values: Option<ArrayRef>,
333    /// Chunk offsets for the left-parts patch indices/values.
334    #[slot(4)]
335    pub patch_chunk_offsets: Option<ArrayRef>,
336}
337
338const LP_PATCH_SLOTS: PatchSlotIndices = PatchSlotIndices {
339    indices: ALPRDSlots::PATCH_INDICES,
340    values: ALPRDSlots::PATCH_VALUES,
341    chunk_offsets: ALPRDSlots::PATCH_CHUNK_OFFSETS,
342};
343
344#[derive(Clone, Debug)]
345pub struct ALPRDData {
346    patches_data: Option<PatchesData>,
347    left_parts_dictionary: Buffer<u16>,
348    right_bit_width: u8,
349}
350
351impl Display for ALPRDData {
352    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
353        write!(f, "right_bit_width: {}", self.right_bit_width)?;
354        if let Some(pd) = &self.patches_data {
355            write!(f, ", patch_offset: {}", pd.offset())?;
356        }
357        Ok(())
358    }
359}
360
361#[derive(Clone, Debug)]
362pub struct ALPRDDataParts {
363    pub left_parts: ArrayRef,
364    pub left_parts_patches: Option<Patches>,
365    pub left_parts_dictionary: Buffer<u16>,
366    pub right_parts: ArrayRef,
367}
368
369#[derive(Clone, Debug)]
370pub struct ALPRD;
371
372impl ALPRD {
373    pub fn try_new(
374        dtype: DType,
375        left_parts: ArrayRef,
376        left_parts_dictionary: Buffer<u16>,
377        right_parts: ArrayRef,
378        right_bit_width: u8,
379        left_parts_patches: Option<Patches>,
380    ) -> VortexResult<ALPRDArray> {
381        let len = left_parts.len();
382        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
383        let data = ALPRDData::new(left_parts_dictionary, right_bit_width, left_parts_patches);
384        Array::try_from_parts(ArrayParts::new(ALPRD, dtype, len, data, slots))
385    }
386
387    /// # Safety
388    /// See [`ALPRD::try_new`] for preconditions.
389    pub unsafe fn new_unchecked(
390        dtype: DType,
391        left_parts: ArrayRef,
392        left_parts_dictionary: Buffer<u16>,
393        right_parts: ArrayRef,
394        right_bit_width: u8,
395        left_parts_patches: Option<Patches>,
396    ) -> ALPRDArray {
397        let len = left_parts.len();
398        let slots = ALPRDData::make_slots(&left_parts, &right_parts, left_parts_patches.as_ref());
399        let data = unsafe {
400            ALPRDData::new_unchecked(left_parts_dictionary, right_bit_width, left_parts_patches)
401        };
402        unsafe { Array::from_parts_unchecked(ArrayParts::new(ALPRD, dtype, len, data, slots)) }
403    }
404}
405
406impl ALPRDData {
407    /// Build a new `ALPRDArray` from components.
408    pub fn new(
409        left_parts_dictionary: Buffer<u16>,
410        right_bit_width: u8,
411        left_parts_patches: Option<Patches>,
412    ) -> Self {
413        Self {
414            patches_data: left_parts_patches.as_ref().map(PatchesData::from_patches),
415            left_parts_dictionary,
416            right_bit_width,
417        }
418    }
419
420    /// Build a new `ALPRDArray` from components. This does not perform any validation, and instead
421    /// it constructs it from parts.
422    pub(crate) unsafe fn new_unchecked(
423        left_parts_dictionary: Buffer<u16>,
424        right_bit_width: u8,
425        left_parts_patches: Option<Patches>,
426    ) -> Self {
427        Self::new(left_parts_dictionary, right_bit_width, left_parts_patches)
428    }
429
430    fn make_slots(
431        left_parts: &ArrayRef,
432        right_parts: &ArrayRef,
433        patches: Option<&Patches>,
434    ) -> ArraySlots {
435        let mut slots: ArraySlots = smallvec![Some(left_parts.clone()), Some(right_parts.clone())];
436        PatchesData::push_slots(&mut slots, patches);
437        slots
438    }
439
440    /// Return all the owned parts of the array
441    pub fn into_parts(self, left_parts: ArrayRef, right_parts: ArrayRef) -> ALPRDDataParts {
442        ALPRDDataParts {
443            left_parts,
444            left_parts_patches: None,
445            left_parts_dictionary: self.left_parts_dictionary,
446            right_parts,
447        }
448    }
449
450    #[inline]
451    pub fn right_bit_width(&self) -> u8 {
452        self.right_bit_width
453    }
454
455    /// The dictionary that maps the codes in `left_parts` into bit patterns.
456    #[inline]
457    pub fn left_parts_dictionary(&self) -> &Buffer<u16> {
458        &self.left_parts_dictionary
459    }
460}
461
462fn patches_from_slots(
463    slots: &[Option<ArrayRef>],
464    patches_data: Option<&PatchesData>,
465    len: usize,
466) -> Option<Patches> {
467    PatchesData::patches_from_slots(patches_data, len, slots, LP_PATCH_SLOTS)
468}
469
470#[allow(clippy::disallowed_methods)]
471fn validate_parts(
472    dtype: &DType,
473    len: usize,
474    left_parts: &ArrayRef,
475    right_parts: &ArrayRef,
476    left_parts_patches: Option<&Patches>,
477) -> VortexResult<()> {
478    if !dtype.is_float() {
479        vortex_bail!("ALPRDArray given invalid DType ({dtype})");
480    }
481
482    vortex_ensure_eq!(left_parts.len(), len);
483    vortex_ensure_eq!(right_parts.len(), len);
484
485    if !left_parts.dtype().is_unsigned_int() {
486        vortex_bail!("left_parts dtype must be uint");
487    }
488    if dtype.is_nullable() != left_parts.dtype().is_nullable() {
489        vortex_bail!(
490            "ALPRDArray dtype nullability ({}) must match left_parts dtype nullability ({})",
491            dtype,
492            left_parts.dtype()
493        );
494    }
495
496    let expected_right_parts_dtype = match dtype {
497        DType::Primitive(PType::F32, _) => DType::Primitive(PType::U32, Nullability::NonNullable),
498        DType::Primitive(PType::F64, _) => DType::Primitive(PType::U64, Nullability::NonNullable),
499        _ => vortex_bail!("Expected f32 or f64 dtype, got {:?}", dtype),
500    };
501    vortex_ensure_eq!(right_parts.dtype(), &expected_right_parts_dtype);
502
503    if let Some(patches) = left_parts_patches {
504        vortex_ensure_eq!(patches.array_len(), len);
505        // Left-parts exceptions are always all-valid and are stored as the non-nullable left-parts
506        // dtype. Requiring that exact dtype (rather than ignoring nullability) means each
507        // construction path must produce correct patches, removing the need to normalize them.
508        // Non-nullable also implies all-valid, so no separate validity check is required.
509        let expected = left_parts.dtype().as_nonnullable();
510        vortex_ensure_eq!(
511            patches.dtype(),
512            &expected,
513            "patches dtype must be the non-nullable left_parts dtype"
514        );
515    }
516
517    Ok(())
518}
519
520pub trait ALPRDArrayExt: ALPRDArraySlotsExt {
521    fn right_bit_width(&self) -> u8 {
522        ALPRDData::right_bit_width(self)
523    }
524
525    fn left_parts_patches(&self) -> Option<Patches> {
526        patches_from_slots(self.slots(), self.patches_data.as_ref(), self.len())
527    }
528
529    fn left_parts_dictionary(&self) -> &Buffer<u16> {
530        ALPRDData::left_parts_dictionary(self)
531    }
532}
533impl<T: TypedArrayRef<ALPRD>> ALPRDArrayExt for T {}
534
535pub trait ALPRDArrayOwnedExt {
536    fn into_data_parts(self) -> ALPRDDataParts;
537}
538
539impl ALPRDArrayOwnedExt for Array<ALPRD> {
540    fn into_data_parts(self) -> ALPRDDataParts {
541        let left_parts_patches = self.left_parts_patches();
542        let left_parts = self.left_parts().clone();
543        let right_parts = self.right_parts().clone();
544        let mut parts = ALPRDDataParts {
545            left_parts,
546            left_parts_patches: None,
547            left_parts_dictionary: self.left_parts_dictionary().clone(),
548            right_parts,
549        };
550        parts.left_parts_patches = left_parts_patches;
551        parts
552    }
553}
554
555impl ValidityChild<ALPRD> for ALPRD {
556    fn validity_child(array: ArrayView<'_, ALPRD>) -> ArrayRef {
557        array.left_parts().clone()
558    }
559}
560
561#[cfg(test)]
562mod test {
563    use std::sync::LazyLock;
564
565    use prost::Message;
566    use rstest::rstest;
567    use vortex_array::VortexSessionExecute;
568    use vortex_array::arrays::PrimitiveArray;
569    use vortex_array::assert_arrays_eq;
570    use vortex_array::dtype::NativePType;
571    use vortex_array::dtype::PType;
572    use vortex_array::patches::PatchesMetadata;
573    use vortex_array::test_harness::check_metadata;
574    use vortex_session::VortexSession;
575
576    use super::ALPRDMetadata;
577    use crate::ALPRDFloat;
578    use crate::RDEncoderExt;
579    use crate::alp_rd;
580
581    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
582        let session = vortex_array::array_session();
583        crate::initialize(&session);
584        session
585    });
586
587    #[rstest]
588    #[case(vec![0.1f32.next_up(); 1024], 1.123_848_f32)]
589    #[case(vec![0.1f64.next_up(); 1024], 1.123_848_591_110_992_f64)]
590    fn test_array_encode_with_nulls_and_patches<T: ALPRDFloat + NativePType>(
591        #[case] reals: Vec<T>,
592        #[case] seed: T,
593    ) {
594        let mut ctx = SESSION.create_execution_ctx();
595        assert_eq!(reals.len(), 1024, "test expects 1024-length fixture");
596        // Null out some of the values.
597        let mut reals: Vec<Option<T>> = reals.into_iter().map(Some).collect();
598        reals[1] = None;
599        reals[5] = None;
600        reals[900] = None;
601
602        // Create a new array from this.
603        let real_array = PrimitiveArray::from_option_iter(reals.iter().cloned());
604
605        // Pick a seed that we know will trigger lots of patches.
606        let encoder: alp_rd::RDEncoder = alp_rd::RDEncoder::new(&[seed.powi(-2)]);
607
608        let rd_array = encoder.encode(real_array.as_view());
609
610        assert_arrays_eq!(rd_array, PrimitiveArray::from_option_iter(reals), &mut ctx);
611    }
612
613    #[cfg_attr(miri, ignore)]
614    #[test]
615    fn test_alprd_metadata() {
616        check_metadata(
617            "alprd.metadata",
618            &ALPRDMetadata {
619                right_bit_width: u32::MAX,
620                patches: Some(PatchesMetadata::new(
621                    usize::MAX,
622                    usize::MAX,
623                    PType::U64,
624                    None,
625                    None,
626                    None,
627                )),
628                dict: Vec::new(),
629                left_parts_ptype: PType::U64 as i32,
630                dict_len: 8,
631            }
632            .encode_to_vec(),
633        );
634    }
635}