Skip to main content

vortex_file/
strategy.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! This module defines the default layout strategy for a Vortex file.
5
6use std::sync::Arc;
7use std::sync::LazyLock;
8
9use vortex_alp::ALP;
10use vortex_alp::ALPRD;
11use vortex_array::ArrayId;
12use vortex_array::VTable;
13use vortex_array::arrays::Bool;
14use vortex_array::arrays::Chunked;
15use vortex_array::arrays::Constant;
16use vortex_array::arrays::Decimal;
17use vortex_array::arrays::Dict;
18use vortex_array::arrays::Extension;
19use vortex_array::arrays::FixedSizeList;
20use vortex_array::arrays::List;
21use vortex_array::arrays::ListView;
22use vortex_array::arrays::Masked;
23use vortex_array::arrays::Null;
24use vortex_array::arrays::Patched;
25use vortex_array::arrays::Primitive;
26use vortex_array::arrays::Struct;
27use vortex_array::arrays::VarBin;
28use vortex_array::arrays::VarBinView;
29use vortex_array::arrays::Variant;
30use vortex_array::arrays::patched::use_experimental_patches;
31use vortex_array::dtype::FieldPath;
32use vortex_btrblocks::BtrBlocksCompressorBuilder;
33use vortex_btrblocks::SchemeExt;
34use vortex_btrblocks::schemes::integer::IntDictScheme;
35use vortex_bytebool::ByteBool;
36use vortex_datetime_parts::DateTimeParts;
37use vortex_decimal_byte_parts::DecimalByteParts;
38use vortex_fastlanes::BitPacked;
39use vortex_fastlanes::Delta;
40use vortex_fastlanes::FoR;
41use vortex_fastlanes::RLE;
42use vortex_fsst::FSST;
43use vortex_layout::LayoutStrategy;
44use vortex_layout::layouts::buffered::BufferedStrategy;
45use vortex_layout::layouts::chunked::writer::ChunkedLayoutStrategy;
46use vortex_layout::layouts::collect::CollectStrategy;
47use vortex_layout::layouts::compressed::CompressingStrategy;
48use vortex_layout::layouts::compressed::CompressorPlugin;
49use vortex_layout::layouts::dict::writer::DictStrategy;
50use vortex_layout::layouts::flat::writer::FlatLayoutStrategy;
51use vortex_layout::layouts::repartition::RepartitionStrategy;
52use vortex_layout::layouts::repartition::RepartitionWriterOptions;
53use vortex_layout::layouts::table::TableStrategy;
54use vortex_layout::layouts::zoned::writer::ZonedLayoutOptions;
55use vortex_layout::layouts::zoned::writer::ZonedStrategy;
56use vortex_pco::Pco;
57use vortex_runend::RunEnd;
58use vortex_sequence::Sequence;
59use vortex_sparse::Sparse;
60use vortex_utils::aliases::hash_map::HashMap;
61use vortex_utils::aliases::hash_set::HashSet;
62use vortex_zigzag::ZigZag;
63#[cfg(feature = "zstd")]
64use vortex_zstd::Zstd;
65#[cfg(all(feature = "zstd", feature = "unstable_encodings"))]
66use vortex_zstd::ZstdBuffers;
67
68const ONE_MEG: u64 = 1 << 20;
69
70/// Static registry of all allowed array encodings for file writing.
71///
72/// This includes all canonical encodings from vortex-array plus all compressed
73/// encodings from the various encoding crates.
74pub static ALLOWED_ENCODINGS: LazyLock<HashSet<ArrayId>> = LazyLock::new(|| {
75    let mut allowed = HashSet::new();
76
77    // Canonical encodings from vortex-array
78    allowed.insert(Null.id());
79    allowed.insert(Bool.id());
80    allowed.insert(Primitive.id());
81    allowed.insert(Decimal.id());
82    allowed.insert(VarBin.id());
83    allowed.insert(VarBinView.id());
84    allowed.insert(List.id());
85    allowed.insert(ListView.id());
86    allowed.insert(FixedSizeList.id());
87    allowed.insert(Struct.id());
88    allowed.insert(Extension.id());
89    allowed.insert(Chunked.id());
90    allowed.insert(Constant.id());
91    allowed.insert(Masked.id());
92    allowed.insert(Dict.id());
93    allowed.insert(Variant.id());
94
95    // Compressed encodings from encoding crates
96    allowed.insert(ALP.id());
97    allowed.insert(ALPRD.id());
98    allowed.insert(BitPacked.id());
99    allowed.insert(ByteBool.id());
100    allowed.insert(DateTimeParts.id());
101    allowed.insert(DecimalByteParts.id());
102    allowed.insert(Delta.id());
103    allowed.insert(FoR.id());
104    allowed.insert(FSST.id());
105    allowed.insert(Pco.id());
106    allowed.insert(RLE.id());
107    allowed.insert(RunEnd.id());
108    allowed.insert(Sequence.id());
109    allowed.insert(Sparse.id());
110    allowed.insert(ZigZag.id());
111
112    // Experimental encodings
113
114    if use_experimental_patches() {
115        allowed.insert(Patched.id());
116    }
117
118    #[cfg(feature = "zstd")]
119    allowed.insert(Zstd.id());
120    #[cfg(all(feature = "zstd", feature = "unstable_encodings"))]
121    allowed.insert(ZstdBuffers.id());
122
123    allowed
124});
125
126/// How the compressor was configured on [`WriteStrategyBuilder`].
127enum CompressorConfig {
128    /// A [`BtrBlocksCompressorBuilder`] that [`WriteStrategyBuilder::build`] will finalize.
129    /// `IntDictScheme` is automatically excluded from the data compressor to prevent recursive
130    /// dictionary encoding.
131    BtrBlocks(BtrBlocksCompressorBuilder),
132    /// An opaque compressor used as-is for both data and stats compression.
133    Opaque(Arc<dyn CompressorPlugin>),
134}
135
136/// Build a new [writer strategy](LayoutStrategy) to compress and reorganize chunks of a Vortex
137/// file.
138///
139/// Vortex provides an out-of-the-box file writer that optimizes the layout of chunks on-disk,
140/// repartitioning and compressing them to strike a balance between size on-disk,
141/// bulk decoding performance, and IOPS required to perform an indexed read.
142pub struct WriteStrategyBuilder {
143    compressor: CompressorConfig,
144    row_block_size: usize,
145    field_writers: HashMap<FieldPath, Arc<dyn LayoutStrategy>>,
146    allow_encodings: Option<HashSet<ArrayId>>,
147    flat_strategy: Option<Arc<dyn LayoutStrategy>>,
148}
149
150impl Default for WriteStrategyBuilder {
151    /// Create a new empty builder. It can be further configured,
152    /// and then finally built yielding the [`LayoutStrategy`].
153    fn default() -> Self {
154        Self {
155            compressor: CompressorConfig::BtrBlocks(BtrBlocksCompressorBuilder::default()),
156            row_block_size: 8192,
157            field_writers: HashMap::new(),
158            allow_encodings: Some(ALLOWED_ENCODINGS.clone()),
159            flat_strategy: None,
160        }
161    }
162}
163
164impl WriteStrategyBuilder {
165    /// Override the row block size used to determine the zone map sizes.
166    pub fn with_row_block_size(mut self, row_block_size: usize) -> Self {
167        self.row_block_size = row_block_size;
168        self
169    }
170
171    /// Override the default write layout for a specific field somewhere in the nested
172    /// schema tree.
173    pub fn with_field_writer(
174        mut self,
175        field: impl Into<FieldPath>,
176        writer: Arc<dyn LayoutStrategy>,
177    ) -> Self {
178        self.field_writers.insert(field.into(), writer);
179        self
180    }
181
182    /// Override the allowed array encodings for normalization.
183    pub fn with_allow_encodings(mut self, allow_encodings: HashSet<ArrayId>) -> Self {
184        self.allow_encodings = Some(allow_encodings);
185        self
186    }
187
188    /// Override the flat layout strategy used for leaf chunks.
189    ///
190    /// By default, this uses [`FlatLayoutStrategy`]. This can be used to substitute a custom
191    /// layout strategy, e.g. one that inlines constant array buffers for GPU reads.
192    pub fn with_flat_strategy(mut self, flat: Arc<dyn LayoutStrategy>) -> Self {
193        self.flat_strategy = Some(flat);
194        self
195    }
196
197    /// Override the default [`BtrBlocksCompressorBuilder`] used for compression.
198    ///
199    /// The builder is finalized during [`build`](Self::build), producing two compressors: one for
200    /// data (with `IntDictScheme` excluded) and one for stats.
201    pub fn with_btrblocks_builder(mut self, builder: BtrBlocksCompressorBuilder) -> Self {
202        self.compressor = CompressorConfig::BtrBlocks(builder);
203        self
204    }
205
206    /// Set the compressor to an opaque [`CompressorPlugin`].
207    ///
208    /// The compressor is used as-is for both data and stats compression.
209    pub fn with_compressor<C: CompressorPlugin>(mut self, compressor: C) -> Self {
210        self.compressor = CompressorConfig::Opaque(Arc::new(compressor));
211        self
212    }
213
214    /// Builds the canonical [`LayoutStrategy`] implementation, with the configured overrides
215    /// applied.
216    pub fn build(self) -> Arc<dyn LayoutStrategy> {
217        let flat: Arc<dyn LayoutStrategy> = if let Some(flat) = self.flat_strategy {
218            flat
219        } else if let Some(allow_encodings) = self.allow_encodings {
220            Arc::new(FlatLayoutStrategy::default().with_allow_encodings(allow_encodings))
221        } else {
222            Arc::new(FlatLayoutStrategy::default())
223        };
224
225        // 7. for each chunk create a flat layout
226        let chunked = ChunkedLayoutStrategy::new(Arc::clone(&flat));
227        // 6. buffer chunks so they end up with closer segment ids physically
228        let buffered = BufferedStrategy::new(chunked, 2 * ONE_MEG); // 2MB
229
230        // 5. compress each chunk.
231        // Exclude IntDictScheme from the data compressor because DictStrategy (step 3) already
232        // dictionary-encodes columns. Allowing IntDictScheme here would redundantly
233        // dictionary-encode the integer codes produced by that earlier step.
234        let data_compressor: Arc<dyn CompressorPlugin> = match &self.compressor {
235            CompressorConfig::BtrBlocks(builder) => Arc::new(
236                builder
237                    .clone()
238                    .exclude_schemes([IntDictScheme.id()])
239                    .build(),
240            ),
241            CompressorConfig::Opaque(compressor) => Arc::clone(compressor),
242        };
243        let compressing = CompressingStrategy::new(buffered, data_compressor);
244
245        // 4. prior to compression, coalesce up to a minimum size
246        let coalescing = RepartitionStrategy::new(
247            compressing,
248            RepartitionWriterOptions {
249                // Write stream partitions roughly become segments. Because Vortex never reads less
250                // than one segment, the size of segments and, therefore, partitions, must be small
251                // enough to both (1) allow fine-grained random access reads and (2) allow
252                // sufficient read concurrency for the desired throughput. One megabyte is small
253                // enough to achieve this for S3 (Durner et al., "Exploiting Cloud Object Storage for
254                // High-Performance Analytics", VLDB Vol 16, Iss 11).
255                block_size_minimum: ONE_MEG,
256                block_len_multiple: self.row_block_size,
257                block_size_target: Some(ONE_MEG),
258                canonicalize: true,
259            },
260        );
261
262        // 2.1. | 3.1. compress stats tables and dict values.
263        let stats_compressor: Arc<dyn CompressorPlugin> = match self.compressor {
264            CompressorConfig::BtrBlocks(builder) => Arc::new(builder.build()),
265            CompressorConfig::Opaque(compressor) => compressor,
266        };
267        let compress_then_flat = CompressingStrategy::new(flat, stats_compressor);
268
269        // 3. apply dict encoding or fallback
270        let dict = DictStrategy::new(
271            coalescing.clone(),
272            compress_then_flat.clone(),
273            coalescing,
274            Default::default(),
275        );
276
277        // 2. calculate stats for each row group
278        let stats = ZonedStrategy::new(
279            dict,
280            compress_then_flat.clone(),
281            ZonedLayoutOptions {
282                block_size: self.row_block_size,
283                ..Default::default()
284            },
285        );
286
287        // 1. repartition each column to fixed row counts
288        let repartition = RepartitionStrategy::new(
289            stats,
290            RepartitionWriterOptions {
291                // No minimum block size in bytes
292                block_size_minimum: 0,
293                // Always repartition into 8K row blocks
294                block_len_multiple: self.row_block_size,
295                block_size_target: None,
296                canonicalize: false,
297            },
298        );
299
300        // 0. start with splitting columns
301        let validity_strategy = CollectStrategy::new(compress_then_flat);
302
303        // Take any field overrides from the builder and apply them to the final strategy.
304        let table_strategy = TableStrategy::new(Arc::new(validity_strategy), Arc::new(repartition))
305            .with_field_writers(self.field_writers);
306
307        Arc::new(table_strategy)
308    }
309}