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