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: AsDynScheme + 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 serialized IDs this scheme itself may write into its compressed output.
128 ///
129 /// Every declared ID must be permitted for the scheme to be used. Cascaded children are
130 /// compressed by other schemes, which declare their own IDs, so only arrays constructed
131 /// directly by [`compress`](Scheme::compress) belong here. Canonical arrays the scheme
132 /// merely rearranges do not need to be declared.
133 ///
134 /// For most encodings this is the in-memory encoding ID. An encoding with several wire
135 /// formats declares the wire IDs the scheme writes, which may differ from its in-memory ID.
136 fn produced_encodings(&self) -> Vec<ArrayId>;
137
138 /// Returns the variant of this scheme to use given which serialized IDs are `allowed`.
139 ///
140 /// The default returns `self`. A variant must share this scheme's [`SchemeId`]. Every ID the
141 /// variant declares in [`produced_encodings`](Self::produced_encodings) must still be allowed
142 /// for it to be used.
143 fn refine(&self, _allowed: &dyn Fn(&ArrayId) -> bool) -> &dyn Scheme {
144 self.as_dyn()
145 }
146
147 /// Returns the stats generation options this scheme requires. The compressor merges all
148 /// eligible schemes' options before generating stats so that a single stats pass satisfies
149 /// every scheme.
150 fn stats_options(&self) -> GenerateStatsOptions {
151 GenerateStatsOptions::default()
152 }
153
154 /// The number of child arrays this scheme produces when cascading. Returns 0 for leaf
155 /// schemes that produce a final encoded array.
156 fn num_children(&self) -> usize {
157 0
158 }
159
160 /// Schemes to exclude from specific children's subtrees (push direction).
161 ///
162 /// Each rule says: "when I cascade through child Y, do not use scheme X anywhere in that
163 /// subtree." Only meaningful when [`num_children`](Scheme::num_children) > 0.
164 fn descendant_exclusions(&self) -> Vec<DescendantExclusion> {
165 Vec::new()
166 }
167
168 /// Ancestors that make this scheme ineligible (pull direction).
169 ///
170 /// Each rule says: "if ancestor X cascaded through child Y somewhere above me in the chain, do
171 /// not try me."
172 fn ancestor_exclusions(&self) -> Vec<AncestorExclusion> {
173 Vec::new()
174 }
175
176 /// Cheaply estimate the compression ratio for this scheme on the given array.
177 ///
178 /// This method should be fast and infallible. Any expensive or fallible work should be
179 /// deferred to the compressor by returning
180 /// `CompressionEstimate::Deferred(DeferredEstimate::Sample)` or
181 /// `CompressionEstimate::Deferred(DeferredEstimate::Callback(...))`.
182 ///
183 /// The compressor will ask all schemes what their expected compression ratio is given the array
184 /// and statistics. The scheme with the highest estimated ratio will then be applied to the
185 /// entire array.
186 ///
187 /// [`CompressionEstimate::Verdict`] means the scheme already knows the terminal
188 /// [`crate::scheme::EstimateVerdict`]. `CompressionEstimate::Deferred(DeferredEstimate::Sample)`
189 /// asks the compressor to sample. `CompressionEstimate::Deferred(DeferredEstimate::Callback(...))`
190 /// asks the compressor to run custom deferred work. Deferred callbacks must return a
191 /// [`crate::scheme::EstimateVerdict`] directly, never another deferred request.
192 ///
193 /// Note that the compressor will also use this method when compressing samples, so some
194 /// statistics that might hold for the samples may not hold for the entire array (e.g.,
195 /// constancy). Implementations should check `ctx.is_sample` to make sure that they are
196 /// returning the correct information.
197 ///
198 /// The compressor guarantees that empty and all-null arrays are handled before this method is
199 /// called, so implementations may assume the array has at least one valid element. Outside of
200 /// sample compression, the compressor also encodes constant arrays itself before evaluating
201 /// schemes, so implementations only see constant arrays when `ctx.is_sample()` is `true`.
202 fn expected_compression_ratio(
203 &self,
204 _data: &ArrayAndStats,
205 _compress_ctx: CompressorContext,
206 _exec_ctx: &mut ExecutionCtx,
207 ) -> CompressionEstimate;
208
209 /// Compress the array using this scheme.
210 ///
211 /// # Errors
212 ///
213 /// Returns an error if compression fails.
214 fn compress(
215 &self,
216 compressor: &CascadingCompressor,
217 data: &ArrayAndStats,
218 compress_ctx: CompressorContext,
219 exec_ctx: &mut ExecutionCtx,
220 ) -> VortexResult<ArrayRef>;
221}
222
223impl PartialEq for dyn Scheme {
224 fn eq(&self, other: &Self) -> bool {
225 self.id() == other.id()
226 }
227}
228
229impl Eq for dyn Scheme {}
230
231impl Hash for dyn Scheme {
232 fn hash<H: Hasher>(&self, state: &mut H) {
233 self.id().hash(state);
234 }
235}
236
237/// Extension trait providing [`id`](SchemeExt::id) for all [`Scheme`] implementors.
238///
239/// This trait is automatically implemented for every type that implements [`Scheme`]. Because the
240/// blanket implementation covers all types, external crates cannot override `id()`.
241pub trait SchemeExt: Scheme {
242 /// Unique identifier derived from [`scheme_name`](Scheme::scheme_name).
243 fn id(&self) -> SchemeId {
244 SchemeId {
245 name: self.scheme_name(),
246 }
247 }
248}
249
250impl<T: Scheme + ?Sized> SchemeExt for T {}
251
252/// Upcast of a [`Scheme`] implementor to `&dyn Scheme`.
253///
254/// This trait is automatically implemented for every sized type that implements [`Scheme`]. It
255/// lets default methods such as [`refine`](Scheme::refine) return `self` as a trait object.
256pub trait AsDynScheme {
257 /// Returns `self` as a `&dyn Scheme`.
258 fn as_dyn(&self) -> &dyn Scheme;
259}
260
261impl<T: Scheme> AsDynScheme for T {
262 fn as_dyn(&self) -> &dyn Scheme {
263 self
264 }
265}