Skip to main content

vortex_compressor/scheme/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Everything a scheme author implements or receives: the [`Scheme`] trait, exclusion rules,
5//! compression estimates, and the compression context.
6
7mod ctx;
8pub use ctx::CompressorContext;
9pub use ctx::MAX_CASCADE;
10
11pub(crate) mod estimate;
12mod exclusion;
13use std::fmt;
14use std::fmt::Debug;
15use std::hash::Hash;
16use std::hash::Hasher;
17
18pub use estimate::CompressionEstimate;
19pub use estimate::DeferredEstimate;
20pub use estimate::EstimateFn;
21pub use estimate::EstimateScore;
22pub use estimate::EstimateVerdict;
23pub use exclusion::AncestorExclusion;
24pub use exclusion::ChildSelection;
25pub use exclusion::DescendantExclusion;
26use vortex_array::ArrayId;
27use vortex_array::ArrayRef;
28use vortex_array::Canonical;
29use vortex_array::ExecutionCtx;
30use vortex_error::VortexResult;
31
32use crate::CascadingCompressor;
33use crate::stats::ArrayAndStats;
34use crate::stats::GenerateStatsOptions;
35
36/// Unique identifier for a compression scheme.
37///
38/// The only way to obtain a [`SchemeId`] is through [`SchemeExt::id()`], which is auto-implemented
39/// for all [`Scheme`] types. There is no public constructor.
40///
41/// The only exception to this is for the compressor's synthetic `ROOT_SCHEME_ID`.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43pub struct SchemeId {
44    /// Only constructable within `vortex-compressor`.
45    ///
46    /// The only public way to obtain a [`SchemeId`] is through [`SchemeExt::id()`].
47    pub(super) name: &'static str,
48}
49
50impl fmt::Display for SchemeId {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_str(self.name)
53    }
54}
55
56// TODO(connor): Remove all default implemented methods.
57/// A single compression encoding that the [`CascadingCompressor`] can select from.
58///
59/// The compressor evaluates every registered scheme whose [`matches`] returns `true` for a given
60/// array, picks the one with the highest [`expected_compression_ratio`], and calls [`compress`] on
61/// the winner.
62///
63/// One of the key features of the compressor in this crate is that schemes may "cascade". A
64/// scheme's [`compress`] can call back into the compressor via
65/// [`CascadingCompressor::compress_child`] to compress child or transformed arrays, building up
66/// multiple encoding layers (e.g. frame-of-reference and then bit-packing).
67///
68/// # Scheme IDs
69///
70/// Every scheme has a globally unique name returned by [`scheme_name`]. The [`SchemeExt::id`]
71/// method (auto-implemented, cannot be overridden) wraps that name in an opaque [`SchemeId`] used
72/// for equality, hashing, and exclusion rules (see below).
73///
74/// # Cascading and children
75///
76/// Schemes that produce child arrays for further compression must declare [`num_children`] > 0.
77/// Each child should be identified by a stable index. Cascading schemes should use
78/// [`CascadingCompressor::compress_child`] to compress each child array, which handles cascade
79/// level / budget tracking and context management automatically.
80///
81/// No scheme may appear twice in a cascade (descendant) chain (enforced by the compressor). This
82/// keeps the search space a tree.
83///
84/// # Exclusion rules
85///
86/// Schemes declare exclusion rules to prevent incompatible scheme combinations in the cascade
87/// chain:
88///
89/// - [`descendant_exclusions`] (push): "exclude scheme X from my child Y's subtree." Used when the
90///   declaring scheme knows about the excluded scheme.
91/// - [`ancestor_exclusions`] (pull): "exclude me if ancestor X's child Y is above me." Used when
92///   the declaring scheme knows about the ancestor.
93///
94/// We do this because different schemes will live in different crates, and we cannot know the
95/// dependency direction ahead of time.
96///
97/// # Implementing a scheme
98///
99/// [`expected_compression_ratio`] should return
100/// `CompressionEstimate::Deferred(DeferredEstimate::Sample)` when a cheap heuristic is not
101/// available, asking the compressor to estimate via sampling. Implementors should return an
102/// immediate [`CompressionEstimate::Verdict`] when possible.
103///
104/// Schemes that need statistics that may be expensive to compute should override [`stats_options`]
105/// to declare what they require. The compressor merges all eligible schemes' options before
106/// generating stats, so each stat is always computed at most once for a given array.
107///
108/// A scheme implementation should be deterministic for a fixed input array and context. The
109/// compressor uses scheme order for deterministic tie-breaking, so non-deterministic estimates make
110/// compressed output harder to reproduce and compare.
111///
112/// [`scheme_name`]: Scheme::scheme_name
113/// [`matches`]: Scheme::matches
114/// [`compress`]: Scheme::compress
115/// [`expected_compression_ratio`]: Scheme::expected_compression_ratio
116/// [`stats_options`]: Scheme::stats_options
117/// [`num_children`]: Scheme::num_children
118/// [`descendant_exclusions`]: Scheme::descendant_exclusions
119/// [`ancestor_exclusions`]: Scheme::ancestor_exclusions
120pub trait Scheme: Debug + Send + Sync {
121    /// The globally unique name for this scheme (e.g. `"vortex.int.bitpacking"`).
122    fn scheme_name(&self) -> &'static str;
123
124    /// Whether this scheme can compress the given canonical array.
125    fn matches(&self, canonical: &Canonical) -> bool;
126
127    /// The array encodings this scheme itself may introduce into its compressed output.
128    ///
129    /// Cascaded children are compressed by other schemes, which declare their own encodings,
130    /// so only encodings constructed directly by [`compress`](Scheme::compress) belong here.
131    /// Canonical arrays the scheme merely rearranges do not need to be declared.
132    fn produced_encodings(&self) -> Vec<ArrayId>;
133
134    /// Returns the stats generation options this scheme requires. The compressor merges all
135    /// eligible schemes' options before generating stats so that a single stats pass satisfies
136    /// every scheme.
137    fn stats_options(&self) -> GenerateStatsOptions {
138        GenerateStatsOptions::default()
139    }
140
141    /// The number of child arrays this scheme produces when cascading. Returns 0 for leaf
142    /// schemes that produce a final encoded array.
143    fn num_children(&self) -> usize {
144        0
145    }
146
147    /// Schemes to exclude from specific children's subtrees (push direction).
148    ///
149    /// Each rule says: "when I cascade through child Y, do not use scheme X anywhere in that
150    /// subtree." Only meaningful when [`num_children`](Scheme::num_children) > 0.
151    fn descendant_exclusions(&self) -> Vec<DescendantExclusion> {
152        Vec::new()
153    }
154
155    /// Ancestors that make this scheme ineligible (pull direction).
156    ///
157    /// Each rule says: "if ancestor X cascaded through child Y somewhere above me in the chain, do
158    /// not try me."
159    fn ancestor_exclusions(&self) -> Vec<AncestorExclusion> {
160        Vec::new()
161    }
162
163    /// Cheaply estimate the compression ratio for this scheme on the given array.
164    ///
165    /// This method should be fast and infallible. Any expensive or fallible work should be
166    /// deferred to the compressor by returning
167    /// `CompressionEstimate::Deferred(DeferredEstimate::Sample)` or
168    /// `CompressionEstimate::Deferred(DeferredEstimate::Callback(...))`.
169    ///
170    /// The compressor will ask all schemes what their expected compression ratio is given the array
171    /// and statistics. The scheme with the highest estimated ratio will then be applied to the
172    /// entire array.
173    ///
174    /// [`CompressionEstimate::Verdict`] means the scheme already knows the terminal
175    /// [`crate::scheme::EstimateVerdict`]. `CompressionEstimate::Deferred(DeferredEstimate::Sample)`
176    /// asks the compressor to sample. `CompressionEstimate::Deferred(DeferredEstimate::Callback(...))`
177    /// asks the compressor to run custom deferred work. Deferred callbacks must return a
178    /// [`crate::scheme::EstimateVerdict`] directly, never another deferred request.
179    ///
180    /// Note that the compressor will also use this method when compressing samples, so some
181    /// statistics that might hold for the samples may not hold for the entire array (e.g.,
182    /// constancy). Implementations should check `ctx.is_sample` to make sure that they are
183    /// returning the correct information.
184    ///
185    /// The compressor guarantees that empty and all-null arrays are handled before this method is
186    /// called, so implementations may assume the array has at least one valid element. Outside of
187    /// sample compression, the compressor also encodes constant arrays itself before evaluating
188    /// schemes, so implementations only see constant arrays when `ctx.is_sample()` is `true`.
189    fn expected_compression_ratio(
190        &self,
191        _data: &ArrayAndStats,
192        _compress_ctx: CompressorContext,
193        _exec_ctx: &mut ExecutionCtx,
194    ) -> CompressionEstimate;
195
196    /// Compress the array using this scheme.
197    ///
198    /// # Errors
199    ///
200    /// Returns an error if compression fails.
201    fn compress(
202        &self,
203        compressor: &CascadingCompressor,
204        data: &ArrayAndStats,
205        compress_ctx: CompressorContext,
206        exec_ctx: &mut ExecutionCtx,
207    ) -> VortexResult<ArrayRef>;
208}
209
210impl PartialEq for dyn Scheme {
211    fn eq(&self, other: &Self) -> bool {
212        self.id() == other.id()
213    }
214}
215
216impl Eq for dyn Scheme {}
217
218impl Hash for dyn Scheme {
219    fn hash<H: Hasher>(&self, state: &mut H) {
220        self.id().hash(state);
221    }
222}
223
224/// Extension trait providing [`id`](SchemeExt::id) for all [`Scheme`] implementors.
225///
226/// This trait is automatically implemented for every type that implements [`Scheme`]. Because the
227/// blanket implementation covers all types, external crates cannot override `id()`.
228pub trait SchemeExt: Scheme {
229    /// Unique identifier derived from [`scheme_name`](Scheme::scheme_name).
230    fn id(&self) -> SchemeId {
231        SchemeId {
232            name: self.scheme_name(),
233        }
234    }
235}
236
237impl<T: Scheme + ?Sized> SchemeExt for T {}