vortex_array/data/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use std::borrow::Cow;
use std::fmt::{Display, Formatter};
use std::sync::{Arc, RwLock};

use itertools::Itertools;
use owned::OwnedArrayData;
use viewed::ViewedArrayData;
use vortex_buffer::ByteBuffer;
use vortex_dtype::DType;
use vortex_error::{vortex_err, VortexError, VortexExpect, VortexResult};
use vortex_flatbuffers::FlatBuffer;
use vortex_scalar::Scalar;

use crate::array::{
    BoolEncoding, ChunkedArray, ExtensionEncoding, NullEncoding, PrimitiveEncoding, StructEncoding,
    VarBinEncoding, VarBinViewEncoding,
};
use crate::compute::scalar_at;
use crate::encoding::{Encoding, EncodingId, EncodingRef, EncodingVTable};
use crate::iter::{ArrayIterator, ArrayIteratorAdapter};
use crate::stats::{ArrayStatistics, Stat, Statistics, StatsSet};
use crate::stream::{ArrayStream, ArrayStreamAdapter};
use crate::validity::{ArrayValidity, LogicalValidity, ValidityVTable};
use crate::{
    ArrayChildrenIterator, ArrayDType, ArrayLen, ArrayMetadata, ChildrenCollector, ContextRef,
    NamedChildrenCollector, TryDeserializeArrayMetadata,
};

mod owned;
mod statistics;
mod viewed;

/// A central type for all Vortex arrays, which are known length sequences of typed and possibly compressed data.
///
/// This is the main entrypoint for working with in-memory Vortex data, and dispatches work over the underlying encoding or memory representations.
#[derive(Debug, Clone)]
pub struct ArrayData(InnerArrayData);

#[derive(Debug, Clone)]
enum InnerArrayData {
    /// Owned [`ArrayData`] with serialized metadata, backed by heap-allocated memory.
    Owned(Arc<OwnedArrayData>),
    /// Zero-copy view over flatbuffer-encoded [`ArrayData`] data, created without eager serialization.
    Viewed(ViewedArrayData),
}

impl From<OwnedArrayData> for ArrayData {
    fn from(data: OwnedArrayData) -> Self {
        ArrayData(InnerArrayData::Owned(Arc::new(data)))
    }
}

impl From<ViewedArrayData> for ArrayData {
    fn from(data: ViewedArrayData) -> Self {
        ArrayData(InnerArrayData::Viewed(data))
    }
}

impl ArrayData {
    pub fn try_new_owned(
        encoding: EncodingRef,
        dtype: DType,
        len: usize,
        metadata: Arc<dyn ArrayMetadata>,
        buffers: Option<Box<[ByteBuffer]>>,
        children: Option<Box<[ArrayData]>>,
        statistics: StatsSet,
    ) -> VortexResult<Self> {
        Self::try_new(InnerArrayData::Owned(Arc::new(OwnedArrayData {
            encoding,
            dtype,
            len,
            metadata,
            buffers,
            children,
            stats_set: RwLock::new(statistics),
            #[cfg(feature = "canonical_counter")]
            canonical_counter: std::sync::atomic::AtomicUsize::new(0),
        })))
    }

    pub fn try_new_viewed<F>(
        ctx: ContextRef,
        dtype: DType,
        len: usize,
        flatbuffer: FlatBuffer,
        flatbuffer_init: F,
        buffers: Vec<ByteBuffer>,
    ) -> VortexResult<Self>
    where
        F: FnOnce(&[u8]) -> VortexResult<crate::flatbuffers::Array>,
    {
        let array = flatbuffer_init(flatbuffer.as_ref())?;
        let flatbuffer_loc = array._tab.loc();

        let encoding = ctx.lookup_encoding(array.encoding()).ok_or_else(
            || {
                let pretty_known_encodings = ctx.encodings()
                    .format_with("\n", |e, f| f(&format_args!("- {}", e.id())));
                vortex_err!(InvalidSerde: "Unknown encoding with ID {:#02x}. Known encodings:\n{pretty_known_encodings}", array.encoding())
            },
        )?;

        // Parse the array metadata
        let metadata = encoding.load_metadata(array.metadata().map(|v| v.bytes()))?;

        let view = ViewedArrayData {
            encoding,
            dtype,
            len,
            metadata,
            flatbuffer,
            flatbuffer_loc,
            buffers: buffers.into(),
            ctx,
            #[cfg(feature = "canonical_counter")]
            canonical_counter: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        };

        Self::try_new(InnerArrayData::Viewed(view))
    }

    /// Shared constructor that performs common array validation.
    fn try_new(inner: InnerArrayData) -> VortexResult<Self> {
        let array = ArrayData(inner);

        // Sanity check that the encoding implements the correct array trait
        debug_assert!(
            match array.dtype() {
                DType::Null => array.as_null_array().is_some(),
                DType::Bool(_) => array.as_bool_array().is_some(),
                DType::Primitive(..) => array.as_primitive_array().is_some(),
                DType::Utf8(_) => array.as_utf8_array().is_some(),
                DType::Binary(_) => array.as_binary_array().is_some(),
                DType::Struct(..) => array.as_struct_array().is_some(),
                DType::List(..) => array.as_list_array().is_some(),
                DType::Extension(..) => array.as_extension_array().is_some(),
            },
            "Encoding {} does not implement the variant trait for {}",
            array.encoding().id(),
            array.dtype()
        );

        // Invoke the encoding's validate function to ensure that we pass basic checks.
        // This is called for both Owned and Viewed array data since there are public functions
        // for constructing an ArrayData, e.g. `try_new_owned`.
        array.encoding().validate(&array)?;

        Ok(array)
    }

    /// Return the array's encoding
    pub fn encoding(&self) -> EncodingRef {
        match &self.0 {
            InnerArrayData::Owned(d) => d.encoding,
            InnerArrayData::Viewed(v) => v.encoding,
        }
    }

    /// Returns the number of logical elements in the array.
    #[allow(clippy::same_name_method)]
    pub fn len(&self) -> usize {
        match &self.0 {
            InnerArrayData::Owned(d) => d.len,
            InnerArrayData::Viewed(v) => v.len,
        }
    }

    /// Check whether the array has any data
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Whether the array is of a canonical encoding.
    pub fn is_canonical(&self) -> bool {
        self.is_encoding(NullEncoding.id())
            || self.is_encoding(BoolEncoding.id())
            || self.is_encoding(PrimitiveEncoding.id())
            || self.is_encoding(StructEncoding.id())
            || self.is_encoding(VarBinViewEncoding.id())
            || self.is_encoding(ExtensionEncoding.id())
    }

    /// Whether the array is fully zero-copy to Arrow (including children).
    /// This means any nested types, like Structs, Lists, and Extensions are not present.
    pub fn is_arrow(&self) -> bool {
        self.is_encoding(NullEncoding.id())
            || self.is_encoding(BoolEncoding.id())
            || self.is_encoding(PrimitiveEncoding.id())
            || self.is_encoding(VarBinEncoding.id())
            || self.is_encoding(VarBinViewEncoding.id())
    }

    /// Return whether the array is constant.
    pub fn is_constant(&self) -> bool {
        self.statistics()
            .compute_as::<bool>(Stat::IsConstant)
            .unwrap_or(false)
    }

    /// Return scalar value of this array if the array is constant
    pub fn as_constant(&self) -> Option<Scalar> {
        self.is_constant()
            // This is safe to unwrap as long as empty arrays aren't constant
            .then(|| scalar_at(self, 0).vortex_expect("expected a scalar value"))
    }

    pub fn child<'a>(&'a self, idx: usize, dtype: &'a DType, len: usize) -> VortexResult<Self> {
        match &self.0 {
            InnerArrayData::Owned(d) => d.child(idx, dtype, len).cloned(),
            InnerArrayData::Viewed(v) => v
                .child(idx, dtype, len)
                .map(|view| ArrayData(InnerArrayData::Viewed(view))),
        }
    }

    /// Returns a Vec of Arrays with all the array's child arrays.
    // TODO(ngates): deprecate this function and return impl Iterator
    pub fn children(&self) -> Vec<ArrayData> {
        match &self.0 {
            InnerArrayData::Owned(d) => d.children.as_ref().map(|c| c.to_vec()).unwrap_or_default(),
            InnerArrayData::Viewed(_) => {
                let mut collector = ChildrenCollector::default();
                self.encoding()
                    .accept(self, &mut collector)
                    .vortex_expect("Failed to get children");
                collector.children()
            }
        }
    }

    /// Returns a Vec of Arrays with all the array's child arrays.
    pub fn named_children(&self) -> Vec<(String, ArrayData)> {
        let mut collector = NamedChildrenCollector::default();
        self.encoding()
            .accept(&self.clone(), &mut collector)
            .vortex_expect("Failed to get children");
        collector.children()
    }

    /// Returns the number of child arrays
    pub fn nchildren(&self) -> usize {
        match &self.0 {
            InnerArrayData::Owned(d) => d.nchildren(),
            InnerArrayData::Viewed(v) => v.nchildren(),
        }
    }

    pub fn depth_first_traversal(&self) -> ArrayChildrenIterator {
        ArrayChildrenIterator::new(self.clone())
    }

    /// Count the number of cumulative buffers encoded by self.
    pub fn cumulative_nbuffers(&self) -> usize {
        self.children()
            .iter()
            .map(|child| child.cumulative_nbuffers())
            .sum::<usize>()
            + self.nbuffers()
    }

    /// Return the buffer offsets and the total length of all buffers, assuming the given alignment.
    /// This includes all child buffers.
    pub fn all_buffer_offsets(&self, alignment: usize) -> Vec<u64> {
        let mut offsets = vec![];
        let mut offset = 0;

        for col_data in self.depth_first_traversal() {
            for buffer in col_data.byte_buffers() {
                offsets.push(offset as u64);

                let buffer_size = buffer.len();
                let aligned_size = (buffer_size + (alignment - 1)) & !(alignment - 1);
                offset += aligned_size;
            }
        }
        offsets.push(offset as u64);

        offsets
    }

    pub fn array_metadata(&self) -> &dyn ArrayMetadata {
        match &self.0 {
            InnerArrayData::Owned(d) => &*d.metadata,
            InnerArrayData::Viewed(v) => &*v.metadata,
        }
    }

    pub fn metadata<M: ArrayMetadata + Clone + for<'m> TryDeserializeArrayMetadata<'m>>(
        &self,
    ) -> VortexResult<&M> {
        match &self.0 {
            InnerArrayData::Owned(d) => &d.metadata,
            InnerArrayData::Viewed(v) => &v.metadata,
        }
        .as_any()
        .downcast_ref::<M>()
        .ok_or_else(|| {
            vortex_err!(
                "Failed to downcast metadata to {}",
                std::any::type_name::<M>()
            )
        })
    }

    /// Get back the (possibly owned) metadata for the array.
    ///
    /// View arrays will return a reference to their bytes, while heap-backed arrays
    /// must first serialize their metadata, returning an owned byte array to the caller.
    pub fn metadata_bytes(&self) -> VortexResult<Cow<[u8]>> {
        match &self.0 {
            InnerArrayData::Owned(array_data) => {
                // Heap-backed arrays must first try and serialize the metadata.
                let owned_meta: Vec<u8> = array_data
                    .metadata()
                    .try_serialize_metadata()?
                    .as_ref()
                    .to_owned();

                Ok(Cow::Owned(owned_meta))
            }
            InnerArrayData::Viewed(array_view) => {
                // View arrays have direct access to metadata bytes.
                array_view
                    .metadata_bytes()
                    .ok_or_else(|| vortex_err!("things"))
                    .map(Cow::Borrowed)
            }
        }
    }

    pub fn nbuffers(&self) -> usize {
        match &self.0 {
            InnerArrayData::Owned(o) => o.buffers.as_ref().map_or(0, |b| b.len()),
            InnerArrayData::Viewed(v) => v.nbuffers(),
        }
    }

    pub fn byte_buffer(&self, index: usize) -> Option<&ByteBuffer> {
        match &self.0 {
            InnerArrayData::Owned(d) => d.byte_buffer(index),
            InnerArrayData::Viewed(v) => v.buffer(index),
        }
    }

    pub fn byte_buffers(&self) -> impl Iterator<Item = ByteBuffer> + '_ {
        (0..self.nbuffers())
            .map(|i| self.byte_buffer(i).vortex_expect("missing declared buffer"))
            .cloned()
    }

    pub fn into_byte_buffer(self, index: usize) -> Option<ByteBuffer> {
        // NOTE(ngates): we can't really into_inner an Arc, so instead we clone the buffer out,
        //  but we still consume self by value such that the ref-count drops at the end of this
        //  function.
        match &self.0 {
            InnerArrayData::Owned(d) => d.byte_buffer(index).cloned(),
            InnerArrayData::Viewed(v) => v.buffer(index).cloned(),
        }
    }

    pub fn into_array_iterator(self) -> impl ArrayIterator {
        let dtype = self.dtype().clone();
        let iter = ChunkedArray::maybe_from(self.clone())
            .map(|chunked| ArrayDataIterator::Chunked(chunked, 0))
            .unwrap_or_else(|| ArrayDataIterator::Single(Some(self)));
        ArrayIteratorAdapter::new(dtype, iter)
    }

    pub fn into_array_stream(self) -> impl ArrayStream {
        ArrayStreamAdapter::new(
            self.dtype().clone(),
            futures_util::stream::iter(self.into_array_iterator()),
        )
    }

    /// Checks whether array is of a given encoding.
    pub fn is_encoding(&self, id: EncodingId) -> bool {
        self.encoding().id() == id
    }

    #[cfg(feature = "canonical_counter")]
    pub(crate) fn inc_canonical_counter(&self) {
        let prev = match &self.0 {
            InnerArrayData::Owned(o) => o
                .canonical_counter
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            InnerArrayData::Viewed(v) => v
                .canonical_counter
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed),
        };
        if prev >= 1 {
            log::warn!(
                "ArrayData::into_canonical called {} times on array",
                prev + 1,
            );
        }
        if prev >= 2 {
            let bt = backtrace::Backtrace::new();
            log::warn!("{:?}", bt);
        }
    }

    pub fn try_downcast_ref<E: Encoding>(&self) -> VortexResult<(&E::Array, &E)>
    where
        for<'a> &'a E::Array: TryFrom<&'a ArrayData, Error = VortexError>,
    {
        let array_ref = <&E::Array>::try_from(self)?;
        let encoding = self
            .encoding()
            .as_any()
            .downcast_ref::<E>()
            .ok_or_else(|| vortex_err!("Mismatched encoding"))?;
        Ok((array_ref, encoding))
    }
}

impl Display for ArrayData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let prefix = match &self.0 {
            InnerArrayData::Owned(_) => "",
            InnerArrayData::Viewed(_) => "$",
        };
        write!(
            f,
            "{}{}({}, len={})",
            prefix,
            self.encoding().id(),
            self.dtype(),
            self.len()
        )
    }
}

impl<T: AsRef<ArrayData>> ArrayDType for T {
    fn dtype(&self) -> &DType {
        match &self.as_ref().0 {
            InnerArrayData::Owned(d) => &d.dtype,
            InnerArrayData::Viewed(v) => &v.dtype,
        }
    }
}

impl<T: AsRef<ArrayData>> ArrayLen for T {
    fn len(&self) -> usize {
        self.as_ref().len()
    }

    fn is_empty(&self) -> bool {
        self.as_ref().is_empty()
    }
}

impl<A: AsRef<ArrayData>> ArrayValidity for A {
    /// Return whether the element at the given index is valid (true) or null (false).
    fn is_valid(&self, index: usize) -> bool {
        ValidityVTable::<ArrayData>::is_valid(self.as_ref().encoding(), self.as_ref(), index)
    }

    /// Return the logical validity of the array.
    fn logical_validity(&self) -> LogicalValidity {
        ValidityVTable::<ArrayData>::logical_validity(self.as_ref().encoding(), self.as_ref())
    }
}

impl<T: AsRef<ArrayData>> ArrayStatistics for T {
    fn statistics(&self) -> &(dyn Statistics + '_) {
        self.as_ref()
    }

    // FIXME(ngates): this is really slow...
    fn inherit_statistics(&self, parent: &dyn Statistics) {
        let stats = self.statistics();
        // The to_set call performs a slow clone of the stats
        for (stat, scalar) in parent.to_set() {
            stats.set(stat, scalar);
        }
    }
}

/// We define a single iterator that can handle both chunked and non-chunked arrays.
/// This avoids the need to create boxed static iterators for the two chunked and non-chunked cases.
enum ArrayDataIterator {
    Single(Option<ArrayData>),
    Chunked(ChunkedArray, usize),
}

impl Iterator for ArrayDataIterator {
    type Item = VortexResult<ArrayData>;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            ArrayDataIterator::Single(array) => array.take().map(Ok),
            ArrayDataIterator::Chunked(chunked, idx) => (*idx < chunked.nchunks()).then(|| {
                let chunk = chunked.chunk(*idx);
                *idx += 1;
                chunk
            }),
        }
    }
}