Skip to main content

vortex_layout/layouts/flat/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod reader;
5pub mod writer;
6
7use std::env;
8use std::sync::Arc;
9
10use vortex_array::DeserializeMetadata;
11use vortex_array::ProstMetadata;
12use vortex_array::dtype::DType;
13use vortex_buffer::ByteBuffer;
14use vortex_error::VortexResult;
15use vortex_error::vortex_bail;
16use vortex_error::vortex_panic;
17use vortex_session::VortexSession;
18use vortex_session::registry::ReadContext;
19
20use crate::LayoutChildType;
21use crate::LayoutEncodingRef;
22use crate::LayoutId;
23use crate::LayoutReaderRef;
24use crate::LayoutRef;
25use crate::VTable;
26use crate::children::LayoutChildren;
27use crate::layouts::flat::reader::FlatReader;
28use crate::segments::SegmentId;
29use crate::segments::SegmentSource;
30use crate::vtable;
31
32/// Check if inline array node is enabled.
33/// This checks the env var each time to allow tests to toggle the behavior.
34pub(super) fn flat_layout_inline_array_node() -> bool {
35    env::var("FLAT_LAYOUT_INLINE_ARRAY_NODE").is_ok()
36}
37
38vtable!(Flat);
39
40impl VTable for Flat {
41    type Layout = FlatLayout;
42    type Encoding = FlatLayoutEncoding;
43    type Metadata = ProstMetadata<FlatLayoutMetadata>;
44
45    fn id(_encoding: &Self::Encoding) -> LayoutId {
46        LayoutId::new_ref("vortex.flat")
47    }
48
49    fn encoding(_layout: &Self::Layout) -> LayoutEncodingRef {
50        LayoutEncodingRef::new_ref(FlatLayoutEncoding.as_ref())
51    }
52
53    fn row_count(layout: &Self::Layout) -> u64 {
54        layout.row_count
55    }
56
57    fn dtype(layout: &Self::Layout) -> &DType {
58        &layout.dtype
59    }
60
61    fn metadata(layout: &Self::Layout) -> Self::Metadata {
62        ProstMetadata(FlatLayoutMetadata {
63            array_encoding_tree: layout.array_tree.as_ref().map(|bytes| bytes.to_vec()),
64        })
65    }
66
67    fn segment_ids(layout: &Self::Layout) -> Vec<SegmentId> {
68        vec![layout.segment_id]
69    }
70
71    fn nchildren(_layout: &Self::Layout) -> usize {
72        0
73    }
74
75    fn child(_layout: &Self::Layout, _idx: usize) -> VortexResult<LayoutRef> {
76        vortex_bail!("Flat layout has no children");
77    }
78
79    fn child_type(_layout: &Self::Layout, _idx: usize) -> LayoutChildType {
80        vortex_panic!("Flat layout has no children");
81    }
82
83    fn new_reader(
84        layout: &Self::Layout,
85        name: Arc<str>,
86        segment_source: Arc<dyn SegmentSource>,
87        session: &VortexSession,
88    ) -> VortexResult<LayoutReaderRef> {
89        Ok(Arc::new(FlatReader::new(
90            layout.clone(),
91            name,
92            segment_source,
93            session.clone(),
94        )))
95    }
96
97    fn build(
98        _encoding: &Self::Encoding,
99        dtype: &DType,
100        row_count: u64,
101        metadata: &<Self::Metadata as DeserializeMetadata>::Output,
102        segment_ids: Vec<SegmentId>,
103        _children: &dyn LayoutChildren,
104        ctx: &ReadContext,
105    ) -> VortexResult<Self::Layout> {
106        if segment_ids.len() != 1 {
107            vortex_bail!("Flat layout must have exactly one segment ID");
108        }
109        Ok(FlatLayout::new_with_metadata(
110            row_count,
111            dtype.clone(),
112            segment_ids[0],
113            ctx.clone(),
114            metadata
115                .array_encoding_tree
116                .as_ref()
117                .map(|v| ByteBuffer::from(v.clone())),
118        ))
119    }
120
121    fn with_children(_layout: &mut Self::Layout, children: Vec<LayoutRef>) -> VortexResult<()> {
122        if !children.is_empty() {
123            vortex_bail!("Flat layout has no children, got {}", children.len());
124        }
125        Ok(())
126    }
127}
128
129#[derive(Debug)]
130pub struct FlatLayoutEncoding;
131
132/// The terminal node of a layout tree. Stores a single chunk of array data as one serialized
133/// segment on disk.
134#[derive(Clone, Debug)]
135pub struct FlatLayout {
136    row_count: u64,
137    dtype: DType,
138    segment_id: SegmentId,
139    ctx: ReadContext,
140    array_tree: Option<ByteBuffer>,
141}
142
143impl FlatLayout {
144    pub fn new(row_count: u64, dtype: DType, segment_id: SegmentId, ctx: ReadContext) -> Self {
145        Self {
146            row_count,
147            dtype,
148            segment_id,
149            ctx,
150            array_tree: None,
151        }
152    }
153
154    pub fn new_with_metadata(
155        row_count: u64,
156        dtype: DType,
157        segment_id: SegmentId,
158        ctx: ReadContext,
159        metadata: Option<ByteBuffer>,
160    ) -> Self {
161        Self {
162            row_count,
163            dtype,
164            segment_id,
165            ctx,
166            array_tree: metadata,
167        }
168    }
169
170    #[inline]
171    pub fn segment_id(&self) -> SegmentId {
172        self.segment_id
173    }
174
175    #[inline]
176    pub fn array_ctx(&self) -> &ReadContext {
177        &self.ctx
178    }
179
180    #[inline]
181    pub fn array_tree(&self) -> Option<&ByteBuffer> {
182        self.array_tree.as_ref()
183    }
184}
185
186#[derive(prost::Message)]
187pub struct FlatLayoutMetadata {
188    // We can optionally store the array encoding tree here to avoid needing to fetch the segment
189    // to plan array deserialization.
190    // This will be a `ArrayNode`.
191    #[prost(optional, bytes, tag = "1")]
192    pub array_encoding_tree: Option<Vec<u8>>,
193}