vortex_file/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4#![expect(clippy::cast_possible_truncation)]
5#![doc(html_logo_url = "/vortex/docs/_static/vortex_spiral_logo.svg")]
6//! Read and write Vortex layouts, a serialization of Vortex arrays.
7//!
8//! A Vortex file stores a root [`Layout`](vortex_layout::Layout), the byte segments referenced by
9//! that layout, an optional file-level [`DType`](vortex_array::dtype::DType) and statistics, and
10//! enough footer metadata to deserialize the tree. Layouts are recursive, so a file may organize
11//! data by row groups, columns, dictionaries, statistics, or other writer-chosen structures without
12//! changing the logical dtype seen by readers. The built-in layouts are:
13//!
14//! - [`FlatLayout`](vortex_layout::layouts::flat::FlatLayout): a single contiguously serialized
15//! array of buffers with a specific in-memory [`Alignment`](vortex_buffer::Alignment).
16//! - [`StructLayout`](vortex_layout::layouts::struct_::StructLayout): each column laid out at known
17//! offsets, permitting a subset of columns to be read in linear time with constant-time random
18//! access to any column.
19//! - [`ChunkedLayout`](vortex_layout::layouts::chunked::ChunkedLayout): each chunk laid out at known
20//! offsets; locating the chunks covering a row range is an `N log(N)` search of the offsets.
21//! - [`DictLayout`](vortex_layout::layouts::dict::DictLayout): a shared dictionary of values with a
22//! child layout holding indices.
23//! - [`ZonedLayout`](vortex_layout::layouts::zoned::ZonedLayout): a zone-map of statistics used for
24//! filter pruning.
25//!
26//! A layout alone is _not_ a standalone Vortex file: it is not self-describing, so the file pairs it
27//! with the dtype and footer metadata needed to deserialize it. This crate owns the file
28//! reader/writer APIs; the byte-level format is described under [File Format](#file-format) below
29//! and specified in full in the docs: <https://docs.vortex.dev/specs/file-format.html>.
30//!
31//! # Reading
32//!
33//! Use [`OpenOptionsSessionExt::open_options`] to create [`VortexOpenOptions`] from a session.
34//! Opening reads or accepts a footer, builds a segment source, and returns [`VortexFile`]. Scans are
35//! configured from [`VortexFile::scan`] with projection/filter expressions, row ranges,
36//! [`Selection`](vortex_scan::selection::Selection), split strategy, and concurrency settings from
37//! `vortex-layout`.
38//!
39//! Supplying known metadata can reduce open-time IO:
40//!
41//! - [`VortexOpenOptions::with_file_size`] avoids a size request.
42//! - [`VortexOpenOptions::with_dtype`] is required for files written without an embedded dtype.
43//! - [`VortexOpenOptions::with_footer`] can open a file without reading footer bytes.
44//! - [`VortexOpenOptions::with_segment_cache`] reuses segment buffers across scans.
45//!
46//! # Writing
47//!
48//! Use [`WriteOptionsSessionExt::write_options`] or [`VortexWriteOptions::new`] to write an
49//! [`ArrayStream`](vortex_array::stream::ArrayStream). The default [`WriteStrategyBuilder`]
50//! repartitions rows, builds statistics layouts, dictionary-encodes suitable columns, compresses
51//! chunks with the BtrBlocks-style compressor, and writes flat leaf layouts. Advanced users can
52//! replace the whole strategy or override individual fields.
53//!
54//! # File Format
55//!
56//! A Vortex file begins and ends with the 4-byte magic `VTXF`. Data segments are written first, in
57//! writer-chosen order, followed by the footer flatbuffers, a postscript, and an 8-byte
58//! end-of-file marker:
59//!
60//! ```text
61//! ┌────────────────────────────┐
62//! │ Magic bytes 'VTXF' │ 4 bytes
63//! ├────────────────────────────┤
64//! │ Segments │ serialized array chunks and per-column
65//! │ (data & statistics) │ statistics, in writer-chosen order
66//! ├────────────────────────────┤
67//! │ User-metadata segments │ optional; opaque values keyed by the postscript
68//! ├────────────────────────────┤
69//! │ DType flatbuffer │ optional; omitted via `exclude_dtype`
70//! ├────────────────────────────┤
71//! │ Layout flatbuffer │ required; the root Layout tree
72//! ├────────────────────────────┤
73//! │ Statistics flatbuffer │ optional; file-level per-field statistics
74//! ├────────────────────────────┤
75//! │ Footer flatbuffer │ required; dictionary-encoded segment map
76//! │ │ and array/layout/compression/encryption specs
77//! ├────────────────────────────┤
78//! │ Postscript │ locators for the footer and user-metadata segments;
79//! │ │ at most 65528 bytes
80//! ├────────────────────────────┤
81//! │ 8-byte End of File │ u16 version, u16 postscript length,
82//! │ │ 4 magic bytes 'VTXF'
83//! └────────────────────────────┘
84//! ```
85//!
86//! The postscript records the offset, length, and alignment of the dtype, layout, statistics, and
87//! footer segments, plus any user-defined metadata segments keyed by string, so a single read of the
88//! file tail (defaulting to 64KiB) is enough to locate and parse the footer and metadata locators.
89//! User-metadata values live in their own segments; opening a file reads none of them by default.
90//! [`VortexOpenOptions::include_metadata`] eagerly resolves every locator through the cache-backed
91//! segment source, issuing targeted reads only for values not already covered by the initial read.
92//! The byte-level format is specified in full at
93//! <https://docs.vortex.dev/specs/file-format.html>.
94//!
95//! A Parquet-style file is realized by nesting a chunked layout of struct layouts of chunked layouts
96//! of flat layouts: the outer chunked layout models row groups and the inner one models pages.
97//! Layouts are adaptive, so the writer is free to build arbitrarily complex layouts to trade off
98//! locality and parallelism, or to elide statistics entirely when an external index supplies them.
99//!
100//! # Footer Deserialization
101//!
102//! [`FooterDeserializer`] supports incremental footer reads. It returns [`DeserializeStep`] values
103//! when it needs more bytes or a file size, and returns [`Footer`] once all required footer segments
104//! are available. [`VortexOpenOptions`] drives this state machine for ordinary file opens.
105
106mod counting;
107mod file;
108mod footer;
109pub mod multi;
110mod open;
111mod pruning;
112mod read;
113/// Segment sources, caches, and sinks used by file readers and writers.
114pub mod segments;
115mod strategy;
116#[cfg(test)]
117mod tests;
118/// Compatibility readers for newer file-statistics layout behavior.
119pub mod v2;
120mod writer;
121
122pub use counting::CountingVortexWrite;
123pub use file::*;
124pub use footer::*;
125pub use forever_constant::*;
126pub use open::*;
127pub use strategy::*;
128use vortex_array::arrays::Patched;
129use vortex_array::arrays::patched::use_experimental_patches;
130use vortex_array::session::ArraySessionExt;
131use vortex_pco::Pco;
132use vortex_session::VortexSession;
133pub use writer::*;
134
135/// The current version of the Vortex file format
136pub const VERSION: u16 = 1;
137/// The size of the footer in bytes in Vortex version 1
138pub const V1_FOOTER_FBS_SIZE: usize = 32;
139
140/// Constants that will never change (i.e., doing so would break backwards compatibility)
141mod forever_constant {
142 /// The extension for Vortex files
143 pub const VORTEX_FILE_EXTENSION: &str = "vortex";
144
145 /// The maximum length of a Vortex postscript in bytes
146 pub const MAX_POSTSCRIPT_SIZE: u16 = u16::MAX - 8;
147 /// The magic bytes for a Vortex file
148 pub const MAGIC_BYTES: [u8; 4] = *b"VTXF";
149 /// The size of the EOF marker in bytes
150 pub const EOF_SIZE: usize = 8;
151
152 #[cfg(test)]
153 mod test {
154 use crate::*;
155
156 #[test]
157 fn never_change_these_constants() {
158 assert_eq!(V1_FOOTER_FBS_SIZE, 32);
159 assert_eq!(MAX_POSTSCRIPT_SIZE, 65527);
160 assert_eq!(MAGIC_BYTES, *b"VTXF");
161 assert_eq!(EOF_SIZE, 8);
162 }
163 }
164}
165
166/// Register the default encodings use in Vortex files with the provided session.
167///
168/// Registration covers reading: a session can decode every encoding registered here. The
169/// writer is gated separately by the editions enabled on its session.
170pub fn register_default_encodings(session: &VortexSession) {
171 vortex_bytebool::initialize(session);
172 vortex_fsst::initialize(session);
173 vortex_onpair::initialize(session);
174 vortex_zigzag::initialize(session);
175 #[cfg(feature = "zstd")]
176 vortex_zstd::initialize(session);
177
178 {
179 let arrays = session.arrays();
180 arrays.register(Pco);
181 if use_experimental_patches() {
182 arrays.register(Patched);
183 }
184 }
185
186 vortex_alp::initialize(session);
187 vortex_datetime_parts::initialize(session);
188 vortex_decimal_byte_parts::initialize(session);
189 vortex_fastlanes::initialize(session);
190 vortex_runend::initialize(session);
191 vortex_sequence::initialize(session);
192 vortex_sparse::initialize(session);
193
194 #[cfg(feature = "tensor")]
195 vortex_tensor::initialize(session);
196}
197
198#[cfg(test)]
199pub(crate) fn enable_all_registered_array_encodings(session: &VortexSession) {
200 use vortex_array::dtype::session::DTypeSessionExt;
201 use vortex_edition::ComponentKind;
202 use vortex_edition::Edition;
203 use vortex_edition::EditionId;
204 use vortex_edition::EditionInclusion;
205 use vortex_edition::EditionSessionExt;
206 use vortex_error::VortexExpect;
207 use vortex_error::vortex_err;
208 use vortex_layout::session::LayoutSessionExt;
209
210 const TEST_EDITION: EditionId = EditionId::new("test", 2026, 7, 0);
211
212 let editions = session.editions();
213 editions
214 .declare_edition(Edition {
215 id: TEST_EDITION,
216 min_library_version: None,
217 })
218 .map_err(|error| vortex_err!("{error}"))
219 .vortex_expect("test edition is valid");
220 let component_ids = [
221 (
222 ComponentKind::Array,
223 session
224 .arrays()
225 .registry()
226 .read(|map| map.keys().copied().collect::<Vec<_>>()),
227 ),
228 (
229 ComponentKind::Layout,
230 session
231 .layouts()
232 .registry()
233 .read(|map| map.keys().copied().collect::<Vec<_>>()),
234 ),
235 (
236 ComponentKind::DType,
237 session
238 .dtypes()
239 .registry()
240 .read(|map| map.keys().copied().collect::<Vec<_>>()),
241 ),
242 ];
243 for (kind, ids) in component_ids {
244 for id in ids {
245 editions
246 .declare_inclusion(EditionInclusion::new(kind, &id, TEST_EDITION))
247 .map_err(|error| vortex_err!("{error}"))
248 .vortex_expect("registered component has one test-edition inclusion");
249 }
250 }
251 for id in [
252 "vortex.bounded_max",
253 "vortex.bounded_min",
254 "vortex.max",
255 "vortex.min",
256 "vortex.nan_count",
257 "vortex.null_count",
258 ] {
259 editions
260 .declare_inclusion(EditionInclusion::new(
261 ComponentKind::Aggregate,
262 id,
263 TEST_EDITION,
264 ))
265 .map_err(|error| vortex_err!("{error}"))
266 .vortex_expect("default aggregate has one test-edition inclusion");
267 }
268 session
269 .enable_edition(TEST_EDITION)
270 .map_err(|error| vortex_err!("{error}"))
271 .vortex_expect("test edition is registered");
272}
273
274#[cfg(test)]
275mod default_encoding_tests {
276 use vortex_array::VTable as _;
277 use vortex_array::array_session;
278 use vortex_array::arrays::Filter;
279 use vortex_array::optimizer::kernels::ArrayKernelsExt as _;
280 use vortex_array::session::ArraySessionExt as _;
281 use vortex_fsst::FSST;
282 use vortex_onpair::OnPair;
283
284 use crate::register_default_encodings;
285
286 #[test]
287 fn register_default_encodings_registers_external_execute_parent_kernels() {
288 let session = array_session();
289
290 assert!(!session.arrays().registry().contains_key(&FSST.id()));
291 assert!(!session.kernels().has_execute_parent(Filter.id(), FSST.id()));
292
293 register_default_encodings(&session);
294
295 assert!(session.arrays().registry().contains_key(&FSST.id()));
296 assert!(session.kernels().has_execute_parent(Filter.id(), FSST.id()));
297 assert!(session.arrays().registry().contains_key(&OnPair.id()));
298 assert!(
299 session
300 .kernels()
301 .has_execute_parent(Filter.id(), OnPair.id())
302 );
303 }
304}