Skip to main content

vortex_array/arrays/patched/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use crate::ArrayEq;
5use crate::ArrayHash;
6mod kernels;
7mod operations;
8mod plugin;
9mod slice;
10
11use std::hash::Hash;
12use std::hash::Hasher;
13
14use vortex_buffer::Buffer;
15use vortex_error::VortexExpect;
16use vortex_error::VortexResult;
17use vortex_error::vortex_panic;
18use vortex_session::VortexSession;
19use vortex_session::registry::CachedId;
20
21use crate::ArrayRef;
22use crate::Canonical;
23use crate::EqMode;
24use crate::ExecutionCtx;
25use crate::ExecutionResult;
26use crate::IntoArray;
27use crate::array::Array;
28use crate::array::ArrayId;
29use crate::array::ArrayParts;
30use crate::array::ArrayView;
31use crate::array::VTable;
32use crate::array::ValidityChild;
33use crate::array::ValidityVTableFromChild;
34use crate::array::with_empty_buffers;
35use crate::arrays::Primitive;
36use crate::arrays::PrimitiveArray;
37use crate::arrays::patched::PatchedArrayExt;
38use crate::arrays::patched::PatchedArraySlotsExt;
39use crate::arrays::patched::PatchedData;
40use crate::arrays::patched::PatchedSlots;
41use crate::arrays::patched::PatchedSlotsView;
42use crate::arrays::primitive::PrimitiveDataParts;
43use crate::buffer::BufferHandle;
44use crate::builders::ArrayBuilder;
45use crate::builders::PrimitiveBuilder;
46use crate::dtype::DType;
47use crate::dtype::NativePType;
48use crate::match_each_native_ptype;
49use crate::require_child;
50
51/// A [`Patched`]-encoded Vortex array.
52pub type PatchedArray = Array<Patched>;
53
54pub(crate) fn initialize(session: &VortexSession) {
55    kernels::initialize(session);
56}
57
58#[derive(Clone, Debug)]
59pub struct Patched;
60
61impl ValidityChild<Patched> for Patched {
62    fn validity_child(array: ArrayView<'_, Patched>) -> ArrayRef {
63        array.inner().clone()
64    }
65}
66
67#[derive(Clone, prost::Message)]
68pub struct PatchedMetadata {
69    /// The total number of patches, and the length of the indices and values child arrays.
70    #[prost(uint32, tag = "1")]
71    pub(crate) n_patches: u32,
72
73    /// The number of lanes used for patch indexing. Must be a power of two between 1 and 128.
74    #[prost(uint32, tag = "2")]
75    pub(crate) n_lanes: u32,
76
77    /// An offset into the first chunk's patches that should be considered in-view.
78    ///
79    /// Always between 0 and 1023.
80    #[prost(uint32, tag = "3")]
81    pub(crate) offset: u32,
82}
83
84impl ArrayHash for PatchedData {
85    fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
86        self.offset.hash(state);
87        self.n_lanes.hash(state);
88    }
89}
90
91impl ArrayEq for PatchedData {
92    fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
93        self.offset == other.offset && self.n_lanes == other.n_lanes
94    }
95}
96
97impl VTable for Patched {
98    type TypedArrayData = PatchedData;
99    type OperationsVTable = Self;
100    type ValidityVTable = ValidityVTableFromChild;
101
102    fn id(&self) -> ArrayId {
103        static ID: CachedId = CachedId::new("vortex.patched");
104        *ID
105    }
106
107    fn validate(
108        &self,
109        data: &PatchedData,
110        dtype: &DType,
111        len: usize,
112        slots: &[Option<ArrayRef>],
113    ) -> VortexResult<()> {
114        data.validate(dtype, len, &PatchedSlotsView::from_slots(slots))
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!("invalid buffer index for PatchedArray: {idx}");
123    }
124
125    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
126        vortex_panic!("invalid buffer index for PatchedArray: {idx}");
127    }
128
129    fn with_buffers(
130        &self,
131        array: ArrayView<'_, Self>,
132        buffers: &[BufferHandle],
133    ) -> VortexResult<ArrayParts<Self>> {
134        with_empty_buffers(self, array, buffers)
135    }
136
137    fn append_to_builder(
138        array: ArrayView<'_, Self>,
139        builder: &mut dyn ArrayBuilder,
140        ctx: &mut ExecutionCtx,
141    ) -> VortexResult<()> {
142        let dtype = array.array().dtype();
143
144        if !dtype.is_primitive() {
145            // Default pathway: canonicalize and propagate.
146            let canonical = array
147                .array()
148                .clone()
149                .execute::<Canonical>(ctx)?
150                .into_array();
151            return canonical.append_to_builder(builder, ctx);
152        }
153
154        let ptype = dtype.as_ptype();
155
156        let len = array.len();
157
158        array.inner().append_to_builder(builder, ctx)?;
159
160        let offset = array.offset();
161        let lane_offsets = array
162            .lane_offsets()
163            .clone()
164            .execute::<PrimitiveArray>(ctx)?;
165        let indices = array
166            .patch_indices()
167            .clone()
168            .execute::<PrimitiveArray>(ctx)?;
169        let values = array
170            .patch_values()
171            .clone()
172            .execute::<PrimitiveArray>(ctx)?;
173
174        match_each_native_ptype!(ptype, |V| {
175            let typed_builder = builder
176                .as_any_mut()
177                .downcast_mut::<PrimitiveBuilder<V>>()
178                .vortex_expect("correctly typed builder");
179
180            // Overwrite the last `len` elements of the builder. These would have been
181            // populated by the inner.append_to_builder() call above.
182            let output = typed_builder.values_mut();
183            let trailer = output.len() - len;
184
185            apply_patches_primitive::<V>(
186                &mut output[trailer..],
187                offset,
188                len,
189                array.n_lanes(),
190                lane_offsets.as_slice::<u32>(),
191                indices.as_slice::<u16>(),
192                values.as_slice::<V>(),
193            );
194        });
195
196        Ok(())
197    }
198
199    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
200        PatchedSlots::NAMES[idx].to_string()
201    }
202
203    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
204        let array = require_child!(array, array.inner(), PatchedSlots::INNER => Primitive);
205        let array =
206            require_child!(array, array.lane_offsets(), PatchedSlots::LANE_OFFSETS => Primitive);
207        let array =
208            require_child!(array, array.patch_indices(), PatchedSlots::PATCH_INDICES => Primitive);
209        let array =
210            require_child!(array, array.patch_values(), PatchedSlots::PATCH_VALUES => Primitive);
211
212        let len = array.len();
213
214        let n_lanes = array.n_lanes;
215        let offset = array.offset;
216        let slots = match array.try_into_parts() {
217            Ok(parts) => PatchedSlots::from_slots(parts.slots),
218            Err(array) => array.slots_view().to_owned(),
219        };
220
221        // TODO(joe): use iterative execution
222        let PrimitiveDataParts {
223            buffer,
224            ptype,
225            validity,
226        } = slots.inner.downcast::<Primitive>().into_data_parts();
227
228        let values = slots.patch_values.downcast::<Primitive>();
229        let lane_offsets = slots.lane_offsets.downcast::<Primitive>();
230        let patch_indices = slots.patch_indices.downcast::<Primitive>();
231
232        let patched_values = match_each_native_ptype!(values.ptype(), |V| {
233            let mut output = Buffer::<V>::from_byte_buffer(buffer.unwrap_host()).into_mut();
234
235            apply_patches_primitive::<V>(
236                &mut output,
237                offset,
238                len,
239                n_lanes,
240                lane_offsets.as_slice::<u32>(),
241                patch_indices.as_slice::<u16>(),
242                values.as_slice::<V>(),
243            );
244
245            let output = output.freeze();
246
247            PrimitiveArray::from_byte_buffer(output.into_byte_buffer(), ptype, validity)
248        });
249
250        Ok(ExecutionResult::done(patched_values.into_array()))
251    }
252}
253
254/// Apply patches on top of the existing value types.
255fn apply_patches_primitive<V: NativePType>(
256    output: &mut [V],
257    offset: usize,
258    len: usize,
259    n_lanes: usize,
260    lane_offsets: &[u32],
261    indices: &[u16],
262    values: &[V],
263) {
264    let n_chunks = (offset + len).div_ceil(1024);
265    for chunk in 0..n_chunks {
266        let start = lane_offsets[chunk * n_lanes] as usize;
267        let stop = lane_offsets[chunk * n_lanes + n_lanes] as usize;
268
269        for idx in start..stop {
270            // the indices slice is measured as an offset into the 1024-value chunk.
271            let index = chunk * 1024 + indices[idx] as usize;
272            if index < offset || index >= offset + len {
273                continue;
274            }
275
276            let value = values[idx];
277            output[index - offset] = value;
278        }
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use std::sync::LazyLock;
285
286    use rstest::rstest;
287    use vortex_buffer::ByteBufferMut;
288    use vortex_buffer::buffer;
289    use vortex_buffer::buffer_mut;
290    use vortex_error::VortexResult;
291    use vortex_session::VortexSession;
292    use vortex_session::registry::ReadContext;
293
294    use crate::Array;
295    use crate::ArrayContext;
296    use crate::ArrayParts;
297    use crate::ArraySlots;
298    use crate::IntoArray;
299    use crate::VortexSessionExecute;
300    use crate::arrays::Patched;
301    use crate::arrays::PatchedArray;
302    use crate::arrays::PrimitiveArray;
303    use crate::arrays::patched::PatchedArrayExt;
304    use crate::arrays::patched::PatchedArraySlotsExt;
305    use crate::arrays::patched::PatchedData;
306    use crate::arrays::patched::PatchedSlots;
307    use crate::arrays::patched::PatchedSlotsView;
308    use crate::assert_arrays_eq;
309    use crate::builders::builder_with_capacity_in;
310    use crate::optimizer::ArrayOptimizer;
311    use crate::patches::Patches;
312    use crate::serde::SerializeOptions;
313    use crate::serde::SerializedArray;
314    use crate::session::ArraySessionExt;
315    use crate::validity::Validity;
316
317    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
318
319    #[test]
320    fn test_execute() {
321        let mut ctx = SESSION.create_execution_ctx();
322        let values = buffer![0u16; 1024].into_array();
323        let patches = Patches::new(
324            1024,
325            0,
326            buffer![1u32, 2, 3].into_array(),
327            buffer![1u16; 3].into_array(),
328            None,
329            &mut ctx,
330        )
331        .unwrap();
332
333        let mut ctx = SESSION.create_execution_ctx();
334
335        let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
336            .unwrap()
337            .into_array();
338
339        let mut expected = buffer_mut![0u16; 1024];
340        expected[1] = 1;
341        expected[2] = 1;
342        expected[3] = 1;
343
344        assert_arrays_eq!(array, expected.into_array(), &mut ctx);
345    }
346
347    #[test]
348    fn test_execute_sliced() {
349        let mut ctx = SESSION.create_execution_ctx();
350        let values = buffer![0u16; 1024].into_array();
351        let patches = Patches::new(
352            1024,
353            0,
354            buffer![1u32, 2, 3].into_array(),
355            buffer![1u16; 3].into_array(),
356            None,
357            &mut ctx,
358        )
359        .unwrap();
360
361        let mut ctx = SESSION.create_execution_ctx();
362
363        let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
364            .unwrap()
365            .into_array()
366            .slice(3..1024)
367            .unwrap();
368
369        let mut expected = buffer_mut![0u16; 1021];
370        expected[0] = 1;
371
372        assert_arrays_eq!(array, expected.into_array(), &mut ctx);
373    }
374
375    #[test]
376    fn test_append_to_builder_non_nullable() {
377        let mut ctx = SESSION.create_execution_ctx();
378        let values = PrimitiveArray::new(buffer![0u16; 1024], Validity::NonNullable).into_array();
379        let patches = Patches::new(
380            1024,
381            0,
382            buffer![1u32, 2, 3].into_array(),
383            buffer![10u16, 20, 30].into_array(),
384            None,
385            &mut ctx,
386        )
387        .unwrap();
388
389        let mut ctx = SESSION.create_execution_ctx();
390
391        let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
392            .unwrap()
393            .into_array();
394
395        let mut builder = builder_with_capacity_in(
396            array.dtype(),
397            array.len(),
398            vortex_buffer::BufferAllocatorRef::static_ref(),
399        );
400        array.append_to_builder(builder.as_mut(), &mut ctx).unwrap();
401
402        let result = builder.finish();
403
404        let mut expected = buffer_mut![0u16; 1024];
405        expected[1] = 10;
406        expected[2] = 20;
407        expected[3] = 30;
408        let expected = expected.into_array();
409
410        assert_arrays_eq!(result, expected, &mut ctx);
411    }
412
413    #[test]
414    fn test_append_to_builder_sliced() {
415        let mut ctx = SESSION.create_execution_ctx();
416        let values = PrimitiveArray::new(buffer![0u16; 1024], Validity::NonNullable).into_array();
417        let patches = Patches::new(
418            1024,
419            0,
420            buffer![1u32, 2, 3].into_array(),
421            buffer![10u16, 20, 30].into_array(),
422            None,
423            &mut ctx,
424        )
425        .unwrap();
426
427        let mut ctx = SESSION.create_execution_ctx();
428
429        let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
430            .unwrap()
431            .into_array()
432            .slice(3..1024)
433            .unwrap();
434
435        let mut builder = builder_with_capacity_in(
436            array.dtype(),
437            array.len(),
438            vortex_buffer::BufferAllocatorRef::static_ref(),
439        );
440        array.append_to_builder(builder.as_mut(), &mut ctx).unwrap();
441
442        let result = builder.finish();
443
444        let mut expected = buffer_mut![0u16; 1021];
445        expected[0] = 30;
446        let expected = expected.into_array();
447
448        assert_arrays_eq!(result, expected, &mut ctx);
449    }
450
451    #[test]
452    fn test_append_to_builder_with_validity() {
453        let mut ctx = SESSION.create_execution_ctx();
454        // Create inner array with nulls at indices 0 and 5.
455        let validity = Validity::from_iter((0..10).map(|i| i != 0 && i != 5));
456        let values = PrimitiveArray::new(buffer![0u16; 10], validity).into_array();
457
458        // Apply patches at indices 1, 2, 3.
459        let patches = Patches::new(
460            10,
461            0,
462            buffer![1u32, 2, 3].into_array(),
463            buffer![10u16, 20, 30].into_array(),
464            None,
465            &mut ctx,
466        )
467        .unwrap();
468
469        let mut ctx = SESSION.create_execution_ctx();
470
471        let array = Patched::from_array_and_patches(values, &patches, &mut ctx)
472            .unwrap()
473            .into_array();
474
475        let mut builder = builder_with_capacity_in(
476            array.dtype(),
477            array.len(),
478            vortex_buffer::BufferAllocatorRef::static_ref(),
479        );
480        array.append_to_builder(builder.as_mut(), &mut ctx).unwrap();
481
482        let result = builder.finish();
483
484        // Expected: null at 0, patched 10/20/30 at 1/2/3, zero at 4, null at 5, zeros at 6-9.
485        let expected = PrimitiveArray::from_option_iter([
486            None,
487            Some(10u16),
488            Some(20),
489            Some(30),
490            Some(0),
491            None,
492            Some(0),
493            Some(0),
494            Some(0),
495            Some(0),
496        ])
497        .into_array();
498
499        assert_arrays_eq!(result, expected, &mut ctx);
500    }
501
502    fn make_patched_array(
503        inner: impl IntoIterator<Item = u16>,
504        patch_indices: &[u32],
505        patch_values: &[u16],
506    ) -> VortexResult<PatchedArray> {
507        let mut ctx = SESSION.create_execution_ctx();
508        let values: Vec<u16> = inner.into_iter().collect();
509        let len = values.len();
510        let array = PrimitiveArray::from_iter(values).into_array();
511
512        let indices = PrimitiveArray::from_iter(patch_indices.iter().copied()).into_array();
513        let patch_vals = PrimitiveArray::from_iter(patch_values.iter().copied()).into_array();
514
515        let patches = Patches::new(len, 0, indices, patch_vals, None, &mut ctx)?;
516
517        let mut ctx = SESSION.create_execution_ctx();
518
519        Patched::from_array_and_patches(array, &patches, &mut ctx)
520    }
521
522    #[rstest]
523    #[case::basic(
524        make_patched_array(vec![0u16; 1024], &[1, 2, 3], &[10, 20, 30]).unwrap().into_array(),
525        (0..1024).map(|i| match i { 1 => 10u16, 2 => 20, 3 => 30, _ => 0 }).collect::<Vec<_>>()
526    )]
527    #[case::multi_chunk(
528        make_patched_array(vec![0u16; 4096], &[100, 1500, 2500, 3500], &[11, 22, 33, 44]).unwrap().into_array(),
529        (0..4096).map(|i| match i { 100 => 11u16, 1500 => 22, 2500 => 33, 3500 => 44, _ => 0 }).collect::<Vec<_>>()
530    )]
531    #[case::sliced({
532        let arr = make_patched_array(vec![0u16; 1024], &[1, 2, 3], &[10, 20, 30]).unwrap();
533        arr.into_array().slice(2..1024).unwrap().optimize_ctx(&SESSION).unwrap()
534    }, (2..1024).map(|i| match i { 2 => 20u16, 3 => 30, _ => 0 }).collect::<Vec<_>>())]
535    fn test_serde_roundtrip(#[case] array: crate::ArrayRef, #[case] expected: Vec<u16>) {
536        let dtype = array.dtype().clone();
537        let len = array.len();
538
539        let session = VortexSession::empty();
540        session.arrays().register(Patched);
541
542        let ctx = ArrayContext::empty().with_allowed_ids(
543            session
544                .arrays()
545                .registry()
546                .read(|map| map.keys().copied().collect()),
547        );
548        let serialized = array
549            .serialize(&ctx, &session, &SerializeOptions::default())
550            .unwrap();
551
552        // Concat into a single buffer.
553        let mut concat = ByteBufferMut::empty();
554        for buf in serialized {
555            concat.extend_from_slice(buf.as_ref());
556        }
557        let concat = concat.freeze();
558
559        let parts = SerializedArray::try_from(concat).unwrap();
560        let decoded = parts
561            .decode(&dtype, len, &ReadContext::new(ctx.to_ids()), &session)
562            .unwrap();
563
564        assert!(decoded.is::<Patched>());
565        let expected = PrimitiveArray::from_iter(expected);
566        let mut exec_ctx = session.create_execution_ctx();
567        assert_arrays_eq!(array, &expected, &mut exec_ctx);
568        assert_arrays_eq!(decoded, expected, &mut exec_ctx);
569    }
570
571    #[test]
572    fn test_with_slots_basic() -> VortexResult<()> {
573        let array = make_patched_array(vec![0u16; 1024], &[1, 2, 3], &[10, 20, 30])?;
574
575        // Get original children via accessor methods
576        let slots = PatchedSlots::from_slots(
577            array
578                .as_array()
579                .slots()
580                .iter()
581                .cloned()
582                .collect::<ArraySlots>(),
583        );
584        let view = PatchedSlotsView::from_slots(array.as_array().slots());
585        assert_eq!(view.inner.len(), array.inner().len());
586
587        // Create new PatchedArray with same children using with_slots
588        let array_ref = array.into_array();
589        // SAFETY: the replacement slots are the original children, preserving logical values and
590        // parent statistics.
591        let new_array = unsafe { array_ref.clone().with_slots(slots.into_slots()) }?;
592
593        assert!(new_array.is::<Patched>());
594        assert_eq!(array_ref.len(), new_array.len());
595        assert_eq!(array_ref.dtype(), new_array.dtype());
596
597        let mut ctx = SESSION.create_execution_ctx();
598
599        let expected = PrimitiveArray::from_iter((0..1024).map(|i| match i {
600            1 => 10u16,
601            2 => 20,
602            3 => 30,
603            _ => 0,
604        }));
605        assert_arrays_eq!(new_array, expected, &mut ctx);
606
607        Ok(())
608    }
609
610    #[test]
611    fn test_rebuild_modified_inner_from_parts() -> VortexResult<()> {
612        let array = make_patched_array(vec![0u16; 10], &[1, 2, 3], &[10, 20, 30])?;
613
614        // Create a different inner array (all 5s instead of 0s)
615        let new_inner = PrimitiveArray::from_iter(vec![5u16; 10]).into_array();
616        let slots = PatchedSlots {
617            inner: new_inner,
618            lane_offsets: array.lane_offsets().clone(),
619            patch_indices: array.patch_indices().clone(),
620            patch_values: array.patch_values().clone(),
621        };
622
623        let data = PatchedData {
624            n_lanes: array.n_lanes(),
625            offset: array.offset(),
626        };
627        let new_array = Array::try_from_parts(ArrayParts::new(
628            Patched,
629            array.dtype().clone(),
630            array.len(),
631            data,
632            slots.into_slots(),
633        ))?
634        .into_array();
635
636        // Execute and verify the inner values changed (except at patch positions)
637        let mut ctx = SESSION.create_execution_ctx();
638
639        // Expected: all 5s except indices 1, 2, 3 which are patched to 10, 20, 30
640        let expected = PrimitiveArray::from_iter([5u16, 10, 20, 30, 5, 5, 5, 5, 5, 5]);
641        assert_arrays_eq!(new_array, expected, &mut ctx);
642
643        Ok(())
644    }
645}