Skip to main content

vortex_compressor/compressor/
cascade.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Core cascading compression flow.
5
6use vortex_array::ArrayRef;
7use vortex_array::Canonical;
8use vortex_array::CanonicalValidity;
9use vortex_array::ExecutionCtx;
10use vortex_array::IntoArray;
11use vortex_array::arrays::Constant;
12use vortex_array::arrays::ConstantArray;
13use vortex_array::arrays::ExtensionArray;
14use vortex_array::arrays::FixedSizeListArray;
15use vortex_array::arrays::Masked;
16use vortex_array::arrays::StructArray;
17use vortex_array::arrays::UnionArray;
18use vortex_array::arrays::Variant;
19use vortex_array::arrays::VariantArray;
20use vortex_array::arrays::extension::ExtensionArrayExt;
21use vortex_array::arrays::fixed_size_list::FixedSizeListArrayExt;
22use vortex_array::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
23use vortex_array::arrays::listview::ListViewArraySlotsExt;
24use vortex_array::arrays::listview::list_from_list_view;
25use vortex_array::arrays::masked::MaskedArraySlotsExt;
26use vortex_array::arrays::struct_::StructArrayExt;
27use vortex_array::arrays::union::UnionArrayExt;
28use vortex_array::arrays::union::UnionArraySlotsExt;
29use vortex_array::arrays::variant::VariantArraySlotsExt;
30use vortex_array::scalar::Scalar;
31use vortex_error::VortexResult;
32
33use super::CascadingCompressor;
34use super::constant;
35use crate::scheme::CompressorContext;
36use crate::scheme::Scheme;
37use crate::scheme::SchemeExt;
38use crate::scheme::SchemeId;
39use crate::stats::ArrayAndStats;
40use crate::stats::GenerateStatsOptions;
41use crate::trace;
42
43impl CascadingCompressor {
44    /// Compresses an array using cascading adaptive compression.
45    ///
46    /// First canonicalizes and compacts the array, then applies optimal compression schemes.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error if canonicalization or compression fails.
51    pub fn compress(
52        &self,
53        array: &ArrayRef,
54        exec_ctx: &mut ExecutionCtx,
55    ) -> VortexResult<ArrayRef> {
56        let before_nbytes = array.nbytes();
57        let span = trace::compress_span(array.len(), array.dtype(), before_nbytes);
58        let _enter = span.enter();
59
60        let canonical = array.clone().execute::<CanonicalValidity>(exec_ctx)?.0;
61        let compact = canonical.compact(exec_ctx)?;
62        let compressed = self.compress_canonical(compact, CompressorContext::new(), exec_ctx)?;
63
64        trace::record_compress_outcome(&span, before_nbytes, compressed.nbytes());
65
66        Ok(compressed)
67    }
68
69    /// Compresses a child array produced by a cascading scheme.
70    ///
71    /// If the cascade budget is exhausted, the canonical array is returned as-is. Otherwise, the
72    /// child context is created by descending and recording the parent scheme + child index, and
73    /// compression proceeds normally.
74    ///
75    /// # Errors
76    ///
77    /// Returns an error if compression fails.
78    pub fn compress_child(
79        &self,
80        child: &ArrayRef,
81        parent_ctx: &CompressorContext,
82        parent_id: SchemeId,
83        child_index: usize,
84        exec_ctx: &mut ExecutionCtx,
85    ) -> VortexResult<ArrayRef> {
86        if parent_ctx.finished_cascading() {
87            trace::cascade_exhausted(parent_id, child_index);
88            return Ok(child.clone());
89        }
90
91        let canonical = child.clone().execute::<CanonicalValidity>(exec_ctx)?.0;
92        let compact = canonical.compact(exec_ctx)?;
93
94        let child_ctx = parent_ctx
95            .clone()
96            .descend_with_scheme(parent_id, child_index);
97        self.compress_canonical(compact, child_ctx, exec_ctx)
98    }
99
100    /// Compresses a canonical array by dispatching to type-specific logic.
101    ///
102    /// # Errors
103    ///
104    /// Returns an error if compression of any sub-array fails.
105    pub(super) fn compress_canonical(
106        &self,
107        array: Canonical,
108        compress_ctx: CompressorContext,
109        exec_ctx: &mut ExecutionCtx,
110    ) -> VortexResult<ArrayRef> {
111        match array {
112            Canonical::Null(null_array) => Ok(null_array.into_array()),
113            Canonical::Bool(bool_array) => {
114                self.choose_and_compress(Canonical::Bool(bool_array), compress_ctx, exec_ctx)
115            }
116            Canonical::Primitive(primitive) => {
117                self.choose_and_compress(Canonical::Primitive(primitive), compress_ctx, exec_ctx)
118            }
119            Canonical::Decimal(decimal) => {
120                self.choose_and_compress(Canonical::Decimal(decimal), compress_ctx, exec_ctx)
121            }
122            Canonical::Struct(struct_array) => {
123                let fields = struct_array
124                    .iter_unmasked_fields()
125                    .map(|field| self.compress(field, exec_ctx))
126                    .collect::<Result<Vec<_>, _>>()?;
127
128                Ok(StructArray::try_new(
129                    struct_array.names().clone(),
130                    fields,
131                    struct_array.len(),
132                    struct_array.validity()?,
133                )?
134                .into_array())
135            }
136            Canonical::Union(union_array) => {
137                let type_ids = self.compress(union_array.type_ids(), exec_ctx)?;
138                let children = union_array
139                    .iter_children()
140                    .map(|child| self.compress(child, exec_ctx))
141                    .collect::<Result<Vec<_>, _>>()?;
142
143                Ok(
144                    UnionArray::try_new(type_ids, union_array.variants().clone(), children)?
145                        .into_array(),
146                )
147            }
148            Canonical::List(list_view_array) => {
149                if list_view_array.is_zero_copy_to_list() || list_view_array.elements().is_empty() {
150                    let list_array = list_from_list_view(list_view_array, exec_ctx)?;
151                    self.compress_list_array(list_array, compress_ctx, exec_ctx)
152                } else {
153                    self.compress_list_view_array(list_view_array, compress_ctx, exec_ctx)
154                }
155            }
156            Canonical::Map(map_array) => self.compress_map_array(map_array, compress_ctx, exec_ctx),
157            Canonical::FixedSizeList(fsl_array) => {
158                let compressed_elems = self.compress(fsl_array.elements(), exec_ctx)?;
159
160                Ok(FixedSizeListArray::try_new(
161                    compressed_elems,
162                    fsl_array.list_size(),
163                    fsl_array.validity()?,
164                    fsl_array.len(),
165                )?
166                .into_array())
167            }
168            Canonical::VarBinView(varbinview) => {
169                self.choose_and_compress(Canonical::VarBinView(varbinview), compress_ctx, exec_ctx)
170            }
171            Canonical::Extension(ext_array) => {
172                // Try scheme-based compression first.
173                let scheme_compressed = self.choose_and_compress(
174                    Canonical::Extension(ext_array.clone()),
175                    compress_ctx,
176                    exec_ctx,
177                )?;
178
179                // A constant extension array (that might be masked) is already in its terminal
180                // representation, and compressing the storage separately cannot do better.
181                if scheme_compressed.is::<Constant>() {
182                    return Ok(scheme_compressed);
183                }
184                if let Some(masked) = scheme_compressed.as_opt::<Masked>()
185                    && masked.child().is::<Constant>()
186                {
187                    return Ok(scheme_compressed);
188                }
189
190                // Also compress the underlying storage array. Some extension schemes can beat the
191                // extension storage but still lose to ordinary storage compression.
192                let compressed_storage = self.compress(ext_array.storage_array(), exec_ctx)?;
193                let storage_compressed =
194                    ExtensionArray::new(ext_array.ext_dtype().clone(), compressed_storage)
195                        .into_array();
196
197                if scheme_compressed.nbytes() < storage_compressed.nbytes() {
198                    Ok(scheme_compressed)
199                } else {
200                    Ok(storage_compressed)
201                }
202            }
203            Canonical::Variant(variant_array) => {
204                let core_storage =
205                    self.compress_physical_slots(variant_array.core_storage(), exec_ctx)?;
206                let shredded = variant_array
207                    .shredded()
208                    .map(|arr| {
209                        // Avoid stack-overflow for variant shredded values
210                        if arr.is::<Variant>() {
211                            self.compress_physical_slots(arr, exec_ctx)
212                        } else {
213                            self.compress(arr, exec_ctx)
214                        }
215                    })
216                    .transpose()?;
217
218                Ok(VariantArray::try_new(core_storage, shredded)?.into_array())
219            }
220        }
221    }
222
223    /// The main scheme-selection entry point for a single leaf array.
224    ///
225    /// Filters allowed schemes by [`matches`] and exclusion rules, merges their [`stats_options`]
226    /// into a single [`GenerateStatsOptions`], and picks the winner by estimated compression
227    /// ratio.
228    ///
229    /// If a winner is found and its compressed output is actually smaller, that output is
230    /// returned. Otherwise, the original array is returned unchanged.
231    ///
232    /// Empty, all-null, and constant arrays are handled by the compressor itself before any
233    /// scheme evaluation (constant detection is skipped while compressing samples).
234    ///
235    /// [`matches`]: Scheme::matches
236    /// [`stats_options`]: Scheme::stats_options
237    fn choose_and_compress(
238        &self,
239        canonical: Canonical,
240        compress_ctx: CompressorContext,
241        exec_ctx: &mut ExecutionCtx,
242    ) -> VortexResult<ArrayRef> {
243        let eligible_schemes: Vec<&'static dyn Scheme> = self
244            .schemes
245            .iter()
246            .copied()
247            .filter(|s| s.matches(&canonical) && !self.is_excluded(*s, &compress_ctx))
248            .collect();
249
250        let array: ArrayRef = canonical.into();
251
252        if array.is_empty() {
253            return Ok(array);
254        }
255
256        if array.all_invalid(exec_ctx)? {
257            return Ok(
258                ConstantArray::new(Scalar::null(array.dtype().clone()), array.len()).into_array(),
259            );
260        }
261
262        let before_nbytes = array.nbytes();
263
264        let merged_opts = eligible_schemes
265            .iter()
266            .fold(GenerateStatsOptions::default(), |acc, s| {
267                acc.merge(s.stats_options())
268            });
269        let compress_ctx = compress_ctx.with_merged_stats_options(merged_opts);
270
271        let data = ArrayAndStats::new(array, merged_opts);
272
273        // Constant detection is built into the compressor: a constant leaf always short-circuits
274        // scheme selection. Samples are exempt because a constant sample does not imply that the
275        // full array is constant.
276        if !compress_ctx.is_sample() && constant::is_constant_for_compression(&data, exec_ctx)? {
277            let _winner_span =
278                trace::winner_compress_span(constant::CONSTANT_SCHEME_ID, before_nbytes).entered();
279            let compressed = constant::compress_constant(data.array(), exec_ctx)?;
280
281            let after_nbytes = compressed.nbytes();
282            let actual_ratio =
283                (after_nbytes != 0).then(|| before_nbytes as f64 / after_nbytes as f64);
284            let accepted = after_nbytes < before_nbytes;
285            trace::record_winner_compress_result(after_nbytes, None, actual_ratio, accepted);
286
287            return if accepted {
288                Ok(compressed)
289            } else {
290                Ok(data.into_array())
291            };
292        }
293
294        if eligible_schemes.is_empty() {
295            return Ok(data.into_array());
296        }
297
298        let Some((winner, winner_estimate)) =
299            self.choose_best_scheme(&eligible_schemes, &data, compress_ctx.clone(), exec_ctx)?
300        else {
301            return Ok(data.into_array());
302        };
303
304        // Run the winning scheme's `compress`. On failure, emit an ERROR event carrying the
305        // scheme name and cascade history before propagating.
306        let error_ctx = trace::enabled_error_context(&compress_ctx);
307        let _winner_span = trace::winner_compress_span(winner.id(), before_nbytes).entered();
308        let compressed = winner
309            .compress(self, &data, compress_ctx, exec_ctx)
310            .inspect_err(|err| {
311                // NB: this is the only way we can tell which scheme panicked / bailed on their
312                // data, especially for third-party schemes where the error site may not carry any
313                // compressor context.
314                trace::scheme_compress_failed(winner.id(), before_nbytes, error_ctx.as_ref(), err);
315            })?;
316
317        let after_nbytes = compressed.nbytes();
318        let actual_ratio = (after_nbytes != 0).then(|| before_nbytes as f64 / after_nbytes as f64);
319
320        let accepted = after_nbytes < before_nbytes;
321
322        trace::record_winner_compress_result(
323            after_nbytes,
324            winner_estimate.trace_ratio(),
325            actual_ratio,
326            accepted,
327        );
328
329        if accepted {
330            Ok(compressed)
331        } else {
332            Ok(data.into_array())
333        }
334    }
335}