Skip to main content

rudb_encoding/
chooser.rs

1//! How the encoder decides which candidate to keep.
2//!
3//! The encoders in [`crate::string`] and [`crate::integer`] are the work. This is the search. They
4//! are separate things and until now they were the same thing, because `encode` both offered every
5//! candidate and encoded every candidate it offered, and there was no way to have one without the
6//! other.
7//!
8//! # Why it is worth separating
9//!
10//! `cargo xtask encode` over a million rows of ClickBench `hits` says where the encoder's seconds
11//! go. String `FRONT` is 32.2 percent of them and is kept once in 142 chunks. String `FSST` is 11.2
12//! percent and is kept twice in 223. Integer `DELTA` is 10.8 percent and is kept never in 607.
13//! String `PLAIN` is 8.7 percent and is kept four times in 223. Those four are 62.9 percent of the
14//! encoder's time and they were kept seven times out of 1,195 offers.
15//!
16//! That is not a bug in any encoder. It is what an exhaustive search costs, and the search is worth
17//! something: the shapes it arrives at are five to one on `hits` and nobody wrote them down in
18//! advance. The question is how much of the search is needed, which is a question about the data
19//! and therefore a question to measure rather than argue about. F2 asks for exactly this, as "the
20//! encoder chooser as a seam, with exhaustive and sampled implementations", with the ablation being
21//! how much size the sampled one gives up.
22//!
23//! # What a chooser sees and what it does not
24//!
25//! A chooser is asked once per chunk per level of the cascade, never once per value. It is handed
26//! the values and the candidates that apply and it returns the ones worth encoding in full. It
27//! cannot invent a candidate that does not apply, so nothing it does can produce a chunk that will
28//! not decode, and the worst a bad chooser can do is pick a bigger encoding than another one would
29//! have. That is the property that makes this safe to swap.
30//!
31//! # Not a `rudb-seam` seam yet, and why
32//!
33//! `SeamId::StorageEncoder` exists and says "how a block of values is encoded on the way to disk",
34//! and this is what belongs behind it. It cannot be registered here: `rudb-seam` is rank 2 and so is
35//! this crate, so the `Strategy` supertrait every seam trait needs is not visible from here. The
36//! registry goes in `rudb-storage` at rank 5, next to the write path, and there is no write path
37//! yet. Until there is, this is a plain trait with two implementations and an ablation, which is
38//! the part that can be measured today.
39
40use crate::{integer, string};
41
42/// Which of the candidates that apply are worth encoding in full.
43///
44/// Crossed once per chunk per level of the cascade. No method here sees a single value on its own,
45/// which is the rule that lets the decision be indirect at all.
46pub trait Chooser: std::fmt::Debug + Sync {
47    /// The name that goes in a report.
48    fn name(&self) -> &'static str;
49
50    /// Which of `offered` to encode in full, for a chunk of strings at `depth`.
51    ///
52    /// `offered` is what applies, in the order the exhaustive chooser would try them. The return
53    /// has to be a subset of it and has to be non empty, because a chunk with no candidate is a
54    /// chunk that cannot be written.
55    fn narrow_strings(
56        &self,
57        values: &[&[u8]],
58        offered: &[string::Kind],
59        depth: u8,
60    ) -> Vec<string::Kind>;
61
62    /// Which of `offered` to encode in full, for a chunk of integers at `depth`.
63    fn narrow_integers(
64        &self,
65        values: &[i64],
66        offered: &[integer::Kind],
67        depth: u8,
68    ) -> Vec<integer::Kind>;
69}
70
71/// Encode every candidate that applies and keep the smallest.
72///
73/// The reference, and what `encode` has always done. It is the thing to beat rather than the thing
74/// to ship: every size this crate has ever reported came out of it, so an alternative's ablation is
75/// against this and a build that wants the old bytes exactly asks for this.
76#[derive(Debug, Clone, Copy, Default)]
77pub struct Exhaustive;
78
79/// The one of these that does not have to be constructed, since it holds nothing.
80pub const EXHAUSTIVE: Exhaustive = Exhaustive;
81
82impl Chooser for Exhaustive {
83    fn name(&self) -> &'static str {
84        "exhaustive"
85    }
86
87    fn narrow_strings(
88        &self,
89        _values: &[&[u8]],
90        offered: &[string::Kind],
91        _depth: u8,
92    ) -> Vec<string::Kind> {
93        offered.to_vec()
94    }
95
96    fn narrow_integers(
97        &self,
98        _values: &[i64],
99        offered: &[integer::Kind],
100        _depth: u8,
101    ) -> Vec<integer::Kind> {
102        offered.to_vec()
103    }
104}
105
106/// Encode every candidate on a sample, then encode only the winner on the whole chunk.
107///
108/// The bet is that a chunk of 122,880 values and a sample of 8,192 drawn from it agree about which
109/// encoding suits them, which is a bet about the data and is what the ablation settles. Where it is
110/// wrong the cost is size and never correctness, because the winner still has to apply to the whole
111/// chunk and is still encoded over all of it.
112///
113/// The sample is windows of consecutive values rather than values picked one at a time, because
114/// three of the candidates are about what a value has in common with the value before it. A sample
115/// of scattered singletons would show `FRONT` and `RLE` nothing to find and would rule them out on
116/// every column, which is the wrong answer arrived at quickly.
117///
118/// There are two guards on whether to sample at all and both of them are there because a measurement
119/// said so. A chunk with fewer values than the sample is not sampled, because encoding every
120/// candidate on something the size of the chunk and then encoding the winner on the chunk is more
121/// work than the exhaustive chooser for the same answer. A chunk holding less than a page of bytes is
122/// not sampled either, because the cost of the search scales with the bytes in the chunk and not
123/// with how many values they are spread over, so on a narrow column there is nothing to save and a
124/// sample that misses the structure gives up real size for it.
125#[derive(Debug, Clone, Copy)]
126pub struct Sampled {
127    window: usize,
128    regions: usize,
129}
130
131/// How many consecutive values one window of the sample holds.
132///
133/// The tile, which is what a bit packing kernel works in and is the smallest run of a column that
134/// has the column's local structure in it rather than one value's worth of accident.
135const WINDOW: usize = 1024;
136
137/// How many windows the sample is drawn from.
138///
139/// Eight windows of a tile each is 8,192 values, a fifteenth of a chunk. Spread across the chunk
140/// rather than taken off the front, because the front of a sorted column is one value repeated and
141/// a chooser that saw only that would pick `CONSTANT` for everything.
142const REGIONS: usize = 8;
143
144/// How few bytes a chunk can hold before sampling it is not worth the risk.
145///
146/// The ablation in #559 found `Params` at a million rows encoding to 21,782 bytes exhaustively and
147/// 128,455 bytes sampled, which is 490 percent for a column that is almost entirely empty strings.
148/// It passed the value count guard because it has a million values, and then the sample missed what
149/// little structure it had. The exhaustive search over a column that small costs almost nothing,
150/// which is the same fact from the other side, so a floor on bytes takes the whole class of column
151/// out of the sampler's hands and gives up nothing to do it.
152///
153/// 256 KiB is one page, which is the smallest unit the format moves. Below that the search is not
154/// where the time is.
155const FLOOR: usize = 256 * 1024;
156
157impl Default for Sampled {
158    fn default() -> Self {
159        Self { window: WINDOW, regions: REGIONS }
160    }
161}
162
163impl Sampled {
164    /// The default sample, which is eight windows of 1,024 values.
165    #[must_use]
166    pub fn new() -> Self {
167        Self::default()
168    }
169
170    /// A sample of a size somebody else picked, which is what the ablation sweeps.
171    #[must_use]
172    pub fn over(window: usize, regions: usize) -> Self {
173        Self { window: window.max(1), regions: regions.max(1) }
174    }
175
176    /// How many values the sample holds, which is one of the two things that decide whether
177    /// sampling is worth doing.
178    #[must_use]
179    pub fn size(self) -> usize {
180        self.window * self.regions
181    }
182
183    /// Whether a chunk of `count` values holding `bytes` bytes is worth sampling.
184    fn worth_it(self, count: usize, bytes: usize) -> bool {
185        count > self.size() && bytes >= FLOOR
186    }
187}
188
189impl Chooser for Sampled {
190    fn name(&self) -> &'static str {
191        "sampled"
192    }
193
194    fn narrow_strings(
195        &self,
196        values: &[&[u8]],
197        offered: &[string::Kind],
198        depth: u8,
199    ) -> Vec<string::Kind> {
200        let bytes = values.iter().map(|value| value.len()).sum();
201        if offered.len() < 2 || !self.worth_it(values.len(), bytes) {
202            return offered.to_vec();
203        }
204        let sample = sample(values, self.window, self.regions);
205        let mut best: Option<(string::Kind, usize)> = None;
206        for &kind in offered {
207            let Ok(Some(size)) = string::size_as(kind, &sample, depth) else {
208                continue;
209            };
210            if best.is_none_or(|(_, smallest)| size < smallest) {
211                best = Some((kind, size));
212            }
213        }
214        // Nothing applied to the sample, which should not happen and is not worth a wrong answer
215        // if it does. Hand back everything and let the exhaustive path sort it out.
216        best.map_or_else(|| offered.to_vec(), |(kind, _)| vec![kind])
217    }
218
219    fn narrow_integers(
220        &self,
221        values: &[i64],
222        offered: &[integer::Kind],
223        depth: u8,
224    ) -> Vec<integer::Kind> {
225        if offered.len() < 2 || !self.worth_it(values.len(), values.len() * 8) {
226            return offered.to_vec();
227        }
228        let sample = sample(values, self.window, self.regions);
229        let mut best: Option<(integer::Kind, usize)> = None;
230        for &kind in offered {
231            let Ok(Some(size)) = integer::size_as(kind, &sample, depth) else {
232                continue;
233            };
234            if best.is_none_or(|(_, smallest)| size < smallest) {
235                best = Some((kind, size));
236            }
237        }
238        best.map_or_else(|| offered.to_vec(), |(kind, _)| vec![kind])
239    }
240}
241
242/// Encode one shape that somebody else settled on, and do not search at all.
243///
244/// [`Sampled`] decides per chunk, which is right when a chunk is big enough to pay for the sample
245/// and when neighbouring chunks are different from each other. Neither holds for a caller that has
246/// thousands of small chunks cut out of one column, because the sample would cost as much as the
247/// encode and because the answer would come out the same thousands of times. Such a caller decides
248/// once, over as much of the column as it likes, and hands the answer here.
249///
250/// A shape is one kind per level of the cascade, which is a simplification of a real one: `FRONT`
251/// produces an integer chunk of prefixes and a string chunk of suffixes at the next level, and both
252/// are narrowed to the same entry. That is enough on real data because the tree is narrow and
253/// because the levels below the second are small. Any level the shape does not reach is searched
254/// exhaustively, which is what makes the shape a hint about the expensive part rather than a
255/// decision about all of it.
256///
257/// An entry that does not apply to a chunk is ignored and the chunk is searched instead. The kinds
258/// that apply are a property of the values, and this is a chooser rather than a way round the
259/// filter, so a shape can never produce something that will not decode.
260#[derive(Debug, Clone)]
261pub struct Settled {
262    strings: Vec<string::Kind>,
263    integers: Vec<integer::Kind>,
264}
265
266impl Settled {
267    /// A shape, outermost level first, for the string levels and the integer levels.
268    #[must_use]
269    pub fn new(strings: Vec<string::Kind>, integers: Vec<integer::Kind>) -> Self {
270        Self { strings, integers }
271    }
272
273    /// The string kinds of the shape, outermost first, which is what a report prints.
274    #[must_use]
275    pub fn strings(&self) -> &[string::Kind] {
276        &self.strings
277    }
278}
279
280impl Chooser for Settled {
281    fn name(&self) -> &'static str {
282        "settled"
283    }
284
285    fn narrow_strings(
286        &self,
287        _values: &[&[u8]],
288        offered: &[string::Kind],
289        depth: u8,
290    ) -> Vec<string::Kind> {
291        match self.strings.get(depth as usize) {
292            Some(kind) if offered.contains(kind) => vec![*kind],
293            _ => offered.to_vec(),
294        }
295    }
296
297    fn narrow_integers(
298        &self,
299        _values: &[i64],
300        offered: &[integer::Kind],
301        depth: u8,
302    ) -> Vec<integer::Kind> {
303        match self.integers.get(depth as usize) {
304            Some(kind) if offered.contains(kind) => vec![*kind],
305            _ => offered.to_vec(),
306        }
307    }
308}
309
310/// `regions` windows of `window` consecutive values each, spread evenly across the input.
311///
312/// The starts are spread over the whole range a window can start at, so the first window begins at
313/// the first value and the last one ends at the last value. A chunk of 122,880 values sampled at
314/// eight windows of 1,024 gives windows starting at 0, 17,408, 34,816 and so on up to 121,856, which
315/// crosses every part of the chunk including both ends of it.
316///
317/// Spreading to the end rather than striding by `len / regions` matters on the columns this is for.
318/// A stride would leave the last stride minus one window of the chunk unsampled, and the tail of a
319/// chunk is exactly where a column that is sorted or clustered stops looking like its front.
320pub(crate) fn sample<T: Copy>(values: &[T], window: usize, regions: usize) -> Vec<T> {
321    let wanted = window * regions;
322    if values.len() <= wanted {
323        return values.to_vec();
324    }
325    let last = values.len() - window;
326    let mut out = Vec::with_capacity(wanted);
327    for region in 0..regions {
328        let from = if regions == 1 { 0 } else { region * last / (regions - 1) };
329        out.extend_from_slice(&values[from..from + window]);
330    }
331    out
332}
333
334#[cfg(test)]
335mod tests {
336    use super::{Chooser, EXHAUSTIVE, Sampled, sample};
337    use crate::{integer, string};
338
339    #[test]
340    fn a_sample_covers_the_whole_input_and_not_one_end_of_it() {
341        let values: Vec<i64> = (0..8000).collect();
342        let taken = sample(&values, 10, 4);
343        assert_eq!(taken.len(), 40);
344        assert_eq!(taken[0], 0);
345        assert_eq!(taken[10], 2663);
346        assert_eq!(taken[20], 5326);
347        assert_eq!(taken[30], 7990);
348        assert_eq!(taken[39], 7999);
349    }
350
351    #[test]
352    fn an_input_no_bigger_than_the_sample_is_the_sample() {
353        let values: Vec<i64> = (0..30).collect();
354        assert_eq!(sample(&values, 10, 4), values);
355    }
356
357    #[test]
358    fn the_last_window_does_not_run_off_the_end() {
359        // Two windows of 40 over 100 values puts the second one at 60, which is the last start that
360        // fits. Windows that overlap because there are more of them than the input has room for is
361        // fine and double counts a few values. Reading past the end is not.
362        let values: Vec<i64> = (0..100).collect();
363        let taken = sample(&values, 40, 2);
364        assert_eq!(taken.len(), 80);
365        assert_eq!(*taken.last().expect("the sample is not empty"), 99);
366    }
367
368    #[test]
369    fn the_exhaustive_chooser_hands_back_exactly_what_it_was_offered() {
370        let offered = [string::Kind::Plain, string::Kind::Fsst, string::Kind::Dict];
371        assert_eq!(EXHAUSTIVE.narrow_strings(&[b"a".as_slice()], &offered, 0), offered);
372        let offered = [integer::Kind::Packed, integer::Kind::Delta];
373        assert_eq!(EXHAUSTIVE.narrow_integers(&[1, 2], &offered, 0), offered);
374    }
375
376    #[test]
377    fn a_chunk_no_bigger_than_the_sample_is_not_narrowed_at_all() {
378        // Sampling a chunk that is smaller than the sample would encode every candidate on
379        // something the size of the chunk and then encode the winner on the chunk, which is more
380        // work than the exhaustive chooser for the same answer.
381        let sampled = Sampled::over(4, 2);
382        let values: Vec<i64> = (0..8).collect();
383        let offered = [integer::Kind::Packed, integer::Kind::Delta];
384        assert_eq!(sampled.narrow_integers(&values, &offered, 0), offered);
385    }
386
387    #[test]
388    fn a_sampled_chooser_returns_one_of_what_it_was_offered() {
389        let sampled = Sampled::over(16, 2);
390        let values: Vec<i64> = (0..40_000).map(|index| index / 200).collect();
391        let offered = [integer::Kind::Packed, integer::Kind::Rle, integer::Kind::Dict];
392        let narrowed = sampled.narrow_integers(&values, &offered, 0);
393        assert_eq!(narrowed.len(), 1);
394        assert!(offered.contains(&narrowed[0]), "{narrowed:?}");
395    }
396
397    #[test]
398    fn a_chunk_with_plenty_of_values_and_hardly_any_bytes_is_not_sampled() {
399        // ClickBench Params at a million rows: a value per row and almost all of them empty. It
400        // passes the value count guard and the exhaustive chooser encodes it in 21,782 bytes while
401        // the sampler took 128,455, so the byte floor is what keeps it out of the sampler's hands.
402        let sampled = Sampled::over(16, 2);
403        let empty = Vec::new();
404        let values: Vec<&[u8]> = vec![empty.as_slice(); 40_000];
405        let offered = [string::Kind::Plain, string::Kind::Fsst, string::Kind::Dict];
406        assert_eq!(sampled.narrow_strings(&values, &offered, 0), offered);
407    }
408}