vortex-layout 0.84.0

Vortex layouts provide a way to perform lazy push-down scans over abstract storage
Documentation
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::any::Any;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::ops::Deref;
use std::sync::Arc;

use itertools::Itertools;
use vortex_array::SerializeMetadata;
use vortex_array::dtype::DType;
use vortex_array::dtype::FieldName;
use vortex_error::VortexExpect;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use vortex_session::registry::Id;

use crate::LayoutReaderContext;
use crate::LayoutReaderRef;
use crate::children::LayoutChildren;
use crate::display::DisplayLayoutTree;
use crate::display::display_tree_with_segment_sizes;
use crate::segments::SegmentId;
use crate::segments::SegmentSource;
use crate::vtable::LayoutRef;
use crate::vtable::VTable;

/// A unique identifier for a layout encoding.
pub type LayoutId = Id;

/// Pieces used to construct a typed layout.
pub struct LayoutParts<V: VTable> {
    vtable: V,
    dtype: DType,
    row_count: u64,
    segment_ids: Vec<SegmentId>,
    children: Arc<dyn LayoutChildren>,
    data: V::LayoutData,
}

impl<V: VTable> LayoutParts<V> {
    /// Create layout parts from common fields and vtable-specific data.
    pub fn new(
        vtable: V,
        dtype: DType,
        row_count: u64,
        segment_ids: Vec<SegmentId>,
        children: Arc<dyn LayoutChildren>,
        data: V::LayoutData,
    ) -> Self {
        Self {
            vtable,
            dtype,
            row_count,
            segment_ids,
            children,
            data,
        }
    }

    /// Convert these parts into a typed layout.
    pub fn into_typed(self) -> Layout<V> {
        Layout::from_parts(self)
    }

    /// Erase these parts into a layout reference.
    pub fn into_layout(self) -> LayoutRef {
        self.into_typed().into_layout()
    }
}

/// A typed layout node.
pub struct Layout<V: VTable> {
    inner: Arc<LayoutInner<V>>,
}

struct LayoutInner<V: VTable> {
    vtable: V,
    dtype: DType,
    row_count: u64,
    segment_ids: Vec<SegmentId>,
    children: Arc<dyn LayoutChildren>,
    data: V::LayoutData,
}

impl<V: VTable> Layout<V> {
    /// Construct a layout from explicit parts.
    pub fn from_parts(parts: LayoutParts<V>) -> Self {
        Self {
            inner: Arc::new(LayoutInner {
                vtable: parts.vtable,
                dtype: parts.dtype,
                row_count: parts.row_count,
                segment_ids: parts.segment_ids,
                children: parts.children,
                data: parts.data,
            }),
        }
    }

    /// Returns the vtable.
    pub fn vtable(&self) -> &V {
        &self.inner.vtable
    }

    /// Returns layout-specific data.
    pub fn data(&self) -> &V::LayoutData {
        &self.inner.data
    }

    /// Returns the logical dtype.
    pub fn dtype(&self) -> &DType {
        &self.inner.dtype
    }

    /// Returns the number of rows.
    pub fn row_count(&self) -> u64 {
        self.inner.row_count
    }

    /// Returns directly referenced segment IDs.
    pub fn segment_ids(&self) -> &[SegmentId] {
        &self.inner.segment_ids
    }

    /// Returns the child adapter.
    pub fn children(&self) -> &Arc<dyn LayoutChildren> {
        &self.inner.children
    }

    /// Returns the number of serialized (present) children.
    pub fn nchildren(&self) -> usize {
        self.inner.children.nchildren()
    }

    /// Returns the number of logical child slots, including any that are absent.
    pub fn nslots(&self) -> usize {
        V::nslots(self)
    }

    /// Maps a logical `slot` to the index of its serialized child, or `None` if absent.
    pub fn slot_to_child(&self, slot: usize) -> Option<usize> {
        V::slot_to_child(self, slot)
    }

    /// Materialize the child in logical `slot`, or `None` if the slot is absent.
    pub fn slot(&self, slot: usize) -> VortexResult<Option<LayoutRef>> {
        match V::slot_to_child(self, slot) {
            Some(idx) => self
                .inner
                .children
                .child(idx, &V::child_dtype(self, slot)?)
                .map(Some),
            None => Ok(None),
        }
    }

    /// Returns the relationship of the child in logical `slot` to this layout, or `None` if the
    /// slot is absent.
    pub fn slot_type(&self, slot: usize) -> Option<LayoutChildType> {
        V::slot_to_child(self, slot).map(|_| V::child_type(self, slot))
    }

    /// Returns a child's serialized row count without materializing it.
    pub fn child_row_count(&self, idx: usize) -> u64 {
        self.inner.children.child_row_count(idx)
    }

    /// Erase this typed layout into a shared layout reference.
    pub fn to_layout(&self) -> LayoutRef {
        self.clone().into_layout()
    }

    /// Erase this typed layout into a shared layout reference.
    pub fn into_layout(self) -> LayoutRef {
        Arc::new(self)
    }

    /// Construct a reader for this layout.
    pub fn new_reader(
        &self,
        name: Arc<str>,
        segment_source: Arc<dyn SegmentSource>,
        session: &VortexSession,
        ctx: &LayoutReaderContext,
    ) -> VortexResult<LayoutReaderRef> {
        V::new_reader(self, name, segment_source, session, ctx)
    }
}

impl<V: VTable> Clone for Layout<V> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<V: VTable> Debug for Layout<V> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Layout")
            .field("encoding_id", &self.vtable().id())
            .field("dtype", &self.inner.dtype)
            .field("row_count", &self.inner.row_count)
            .field("segment_ids", &self.inner.segment_ids)
            .field("data", &self.inner.data)
            .finish()
    }
}

impl<V: VTable> Deref for Layout<V> {
    type Target = V::LayoutData;

    fn deref(&self) -> &Self::Target {
        self.data()
    }
}

impl<V: VTable> From<Layout<V>> for LayoutRef {
    fn from(value: Layout<V>) -> Self {
        value.into_layout()
    }
}

/// Erased layout behavior used by [`LayoutRef`].
pub trait DynLayout: 'static + Send + Sync + Debug {
    /// Returns this layout as [`Any`] for downcasting.
    fn as_any(&self) -> &dyn Any;

    /// Clone this layout as an erased reference.
    fn dyn_to_layout(&self) -> LayoutRef;

    /// Returns the layout ID.
    fn dyn_encoding_id(&self) -> LayoutId;

    /// Returns the row count.
    fn dyn_row_count(&self) -> u64;

    /// Returns the logical dtype.
    fn dyn_dtype(&self) -> &DType;

    /// Returns the number of serialized (present) children.
    fn dyn_nchildren(&self) -> usize;

    /// Returns the number of logical child slots, including any that are absent.
    fn dyn_nslots(&self) -> usize;

    /// Materializes the child in logical `slot`, or `None` if the slot is absent.
    fn dyn_slot(&self, slot: usize) -> VortexResult<Option<LayoutRef>>;

    /// Returns the relationship of the child in logical `slot`, or `None` if the slot is absent.
    fn dyn_slot_type(&self, slot: usize) -> Option<LayoutChildType>;

    /// Serializes layout-specific metadata.
    fn dyn_metadata(&self) -> Vec<u8>;

    /// Returns directly referenced segment IDs.
    fn dyn_segment_ids(&self) -> Vec<SegmentId>;

    /// Constructs a reader.
    fn dyn_new_reader(
        &self,
        name: Arc<str>,
        segment_source: Arc<dyn SegmentSource>,
        session: &VortexSession,
        ctx: &LayoutReaderContext,
    ) -> VortexResult<LayoutReaderRef>;

    /// Returns `true` if this layout is indivisible: its readers never register natural split
    /// boundaries strictly inside their row range (see [`crate::VTable::is_indivisible`]).
    fn dyn_is_indivisible(&self) -> bool {
        false
    }
}

impl<V: VTable> DynLayout for Layout<V> {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn dyn_to_layout(&self) -> LayoutRef {
        Layout::to_layout(self)
    }

    fn dyn_encoding_id(&self) -> LayoutId {
        self.vtable().id()
    }

    fn dyn_row_count(&self) -> u64 {
        Layout::row_count(self)
    }

    fn dyn_dtype(&self) -> &DType {
        Layout::dtype(self)
    }

    fn dyn_nchildren(&self) -> usize {
        Layout::nchildren(self)
    }

    fn dyn_nslots(&self) -> usize {
        Layout::nslots(self)
    }

    fn dyn_slot(&self, slot: usize) -> VortexResult<Option<LayoutRef>> {
        Layout::slot(self, slot)
    }

    fn dyn_slot_type(&self, slot: usize) -> Option<LayoutChildType> {
        Layout::slot_type(self, slot)
    }

    fn dyn_metadata(&self) -> Vec<u8> {
        V::metadata(self).serialize()
    }

    fn dyn_segment_ids(&self) -> Vec<SegmentId> {
        self.inner.segment_ids.clone()
    }

    fn dyn_new_reader(
        &self,
        name: Arc<str>,
        segment_source: Arc<dyn SegmentSource>,
        session: &VortexSession,
        ctx: &LayoutReaderContext,
    ) -> VortexResult<LayoutReaderRef> {
        Layout::new_reader(self, name, segment_source, session, ctx)
    }

    fn dyn_is_indivisible(&self) -> bool {
        self.vtable().is_indivisible()
    }
}

/// Identifies how a layout child relates to its parent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LayoutChildType {
    /// A child retaining the parent's schema and row offset.
    Transparent(Arc<str>),
    /// Auxiliary data, such as dictionary values or zone maps.
    Auxiliary(Arc<str>),
    /// A row-based chunk with its relative row offset.
    Chunk((usize, u64)),
    /// A single field of a struct.
    Field(FieldName),
}

impl LayoutChildType {
    /// Returns the child name.
    pub fn name(&self) -> Arc<str> {
        match self {
            Self::Chunk((idx, _)) => format!("[{idx}]").into(),
            Self::Auxiliary(name) | Self::Transparent(name) => Arc::clone(name),
            Self::Field(name) => name.clone().into(),
        }
    }

    /// Returns the relative row offset, or `None` for auxiliary children.
    pub fn row_offset(&self) -> Option<u64> {
        match self {
            Self::Chunk((_, offset)) => Some(*offset),
            Self::Auxiliary(_) => None,
            Self::Transparent(_) | Self::Field(_) => Some(0),
        }
    }
}

impl dyn DynLayout + '_ {
    /// Returns a cloned erased layout reference.
    pub fn to_layout(&self) -> LayoutRef {
        self.dyn_to_layout()
    }

    /// Returns the layout ID.
    pub fn encoding_id(&self) -> LayoutId {
        self.dyn_encoding_id()
    }

    /// Returns the logical dtype.
    pub fn dtype(&self) -> &DType {
        self.dyn_dtype()
    }

    /// Returns the number of rows.
    pub fn row_count(&self) -> u64 {
        self.dyn_row_count()
    }

    /// Returns the number of serialized (present) children.
    pub fn nchildren(&self) -> usize {
        self.dyn_nchildren()
    }

    /// Returns the number of logical child slots, including any that are absent.
    pub fn nslots(&self) -> usize {
        self.dyn_nslots()
    }

    /// Materializes the child in logical `slot`, or `None` if the slot is absent.
    pub fn slot(&self, slot: usize) -> VortexResult<Option<LayoutRef>> {
        self.dyn_slot(slot)
    }

    /// Returns the relationship of the child in logical `slot`, or `None` if the slot is absent.
    pub fn slot_type(&self, slot: usize) -> Option<LayoutChildType> {
        self.dyn_slot_type(slot)
    }

    /// Returns serialized layout-specific metadata.
    pub fn metadata(&self) -> Vec<u8> {
        self.dyn_metadata()
    }

    /// Returns directly referenced segment IDs.
    pub fn segment_ids(&self) -> Vec<SegmentId> {
        self.dyn_segment_ids()
    }

    /// Constructs a reader for this layout.
    pub fn new_reader(
        &self,
        name: Arc<str>,
        segment_source: Arc<dyn SegmentSource>,
        session: &VortexSession,
        ctx: &LayoutReaderContext,
    ) -> VortexResult<LayoutReaderRef> {
        self.dyn_new_reader(name, segment_source, session, ctx)
    }

    /// Returns all serialized (present) children, in slot order.
    pub fn children(&self) -> VortexResult<Vec<LayoutRef>> {
        (0..self.nslots())
            .filter_map(|slot| self.slot(slot).transpose())
            .try_collect()
    }

    /// Returns the types of all serialized (present) children, in slot order.
    pub fn child_types(&self) -> impl Iterator<Item = LayoutChildType> + '_ {
        (0..self.nslots()).filter_map(|slot| self.slot_type(slot))
    }

    /// Returns all child names.
    pub fn child_names(&self) -> impl Iterator<Item = Arc<str>> + '_ {
        self.child_types().map(|child| child.name())
    }

    /// Returns all child row offsets.
    pub fn child_row_offsets(&self) -> impl Iterator<Item = Option<u64>> + '_ {
        self.child_types().map(|child| child.row_offset())
    }

    /// Returns whether this layout uses vtable `V`.
    pub fn is<V: VTable>(&self) -> bool {
        self.as_opt::<V>().is_some()
    }

    /// Downcasts this layout to vtable `V`.
    pub fn as_<V: VTable>(&self) -> &Layout<V> {
        self.as_opt::<V>().vortex_expect("Failed to downcast")
    }

    /// Attempts to downcast this layout to vtable `V`.
    pub fn as_opt<V: VTable>(&self) -> Option<&Layout<V>> {
        self.as_any().downcast_ref()
    }

    /// Returns a depth-first pre-order traversal.
    pub fn depth_first_traversal(&self) -> impl Iterator<Item = VortexResult<LayoutRef>> {
        struct ChildrenIterator {
            stack: Vec<LayoutRef>,
        }

        impl Iterator for ChildrenIterator {
            type Item = VortexResult<LayoutRef>;

            fn next(&mut self) -> Option<Self::Item> {
                let next = self.stack.pop()?;
                let Ok(children) = next.children() else {
                    return Some(Ok(next));
                };
                self.stack.extend(children.into_iter().rev());
                Some(Ok(next))
            }
        }

        ChildrenIterator {
            stack: vec![self.to_layout()],
        }
    }

    /// Displays the layout as a tree.
    pub fn display_tree(&self) -> DisplayLayoutTree {
        DisplayLayoutTree::new(self.to_layout(), false)
    }

    /// Displays the layout as a tree with optional verbose metadata.
    pub fn display_tree_verbose(&self, verbose: bool) -> DisplayLayoutTree {
        DisplayLayoutTree::new(self.to_layout(), verbose)
    }

    /// Displays the tree after fetching segment sizes.
    pub async fn display_tree_with_segments(
        &self,
        segment_source: Arc<dyn SegmentSource>,
    ) -> VortexResult<DisplayLayoutTree> {
        display_tree_with_segment_sizes(self.to_layout(), segment_source).await
    }
}

impl Display for dyn DynLayout + '_ {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let segments = self.segment_ids();
        if segments.is_empty() {
            write!(
                f,
                "{}({}, rows={})",
                self.encoding_id(),
                self.dtype(),
                self.row_count()
            )
        } else {
            write!(
                f,
                "{}({}, rows={}, segments=[{}])",
                self.encoding_id(),
                self.dtype(),
                self.row_count(),
                segments.iter().map(|s| format!("{}", **s)).join(", ")
            )
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn layout_child_type_names_and_offsets() {
        let chunk = LayoutChildType::Chunk((5, 100));
        assert_eq!(chunk.name().as_ref(), "[5]");
        assert_eq!(chunk.row_offset(), Some(100));

        let field = LayoutChildType::Field(FieldName::from("customer_id"));
        assert_eq!(field.name().as_ref(), "customer_id");
        assert_eq!(field.row_offset(), Some(0));

        let auxiliary = LayoutChildType::Auxiliary("zone_map".into());
        assert_eq!(auxiliary.row_offset(), None);
        let transparent = LayoutChildType::Transparent("compressed".into());
        assert_eq!(transparent.row_offset(), Some(0));
    }
}