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