Skip to main content

zu_encoding/
segment.rs

1//! Segment-level encoding selection, the BtrBlocks-style cascade.
2//!
3//! `encode_auto` reads the chunk once, prices every legal candidate off
4//! what that pass found, encodes with the winner, and falls back to
5//! Plain if the winner loses to Plain on the full input. The payload is
6//! prefixed with one stable `EncodingId` byte, so `decode_any` needs no
7//! side channel.
8//!
9//! Pricing is arithmetic rather than a trial encode, and that is the
10//! whole of what makes a write cheap. Sizing seven candidates by
11//! encoding each of them costs seven encodes of every chunk a column
12//! rewrite touches, and a fold is column rewrites: profiling a stream of
13//! single row writes put two thirds of the engine's processor time
14//! inside the encoders, nearly all of it in candidates that lost. The
15//! containers are simple enough to price exactly instead. Frame of
16//! reference is a minimum and a width per 1024 values, the patched
17//! container prices its own width off a histogram this pass already
18//! builds, and the rest are a count of runs, a count of distinct values
19//! and the count of the value that dominates. Only the winner is
20//! encoded, and the Plain guard below catches an estimate that was
21//! wrong about the shape rather than about the arithmetic.
22
23use zu_common::{Result, ZuError};
24
25use crate::bitpack::{CHUNK, packed_bytes};
26use crate::counts;
27use crate::delta::zigzag;
28use crate::{
29    EncodingId, bits_needed, bool_bitpack, delta, delta_patch, dict, for_bitpack, frequency, rle,
30};
31
32/// Encodes `values` with the estimated-best encoding, returning the id used.
33pub fn encode_auto(values: &[u64], out: &mut Vec<u8>) -> EncodingId {
34    let id = choose(values);
35    let start = out.len();
36    out.push(id as u8);
37    encode_with(id, values, out);
38    // The sample can mislead; never ship a segment larger than Plain.
39    if out.len() - start > 9 + values.len() * 8 {
40        out.truncate(start);
41        out.push(EncodingId::Plain as u8);
42        encode_with(EncodingId::Plain, values, out);
43        return EncodingId::Plain;
44    }
45    id
46}
47
48/// Decodes a segment produced by `encode_auto`, appending at most
49/// `max_values` values to `out`. Every encoding here amplifies, that
50/// is the point of compression, so decoded counts are claims until the
51/// caller vouches for them: a container claiming more than the ceiling
52/// is rejected before anything is allocated for it. Callers always
53/// know the bound, the row count their segment meta or chunk index
54/// promised.
55pub fn decode_any(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
56    let corrupt = |detail: &str| ZuError::Corrupt {
57        what: "segment",
58        detail: detail.to_string(),
59    };
60    let (&id, payload) = bytes.split_first().ok_or_else(|| corrupt("empty"))?;
61    match EncodingId::try_from(id)? {
62        EncodingId::Plain => decode_plain(payload, max_values, out),
63        EncodingId::Constant => decode_constant(payload, max_values, out),
64        EncodingId::Rle => rle::decode(payload, max_values, out),
65        EncodingId::Dict => dict::decode(payload, max_values, out),
66        EncodingId::ForBitPack => for_bitpack::decode(payload, max_values, out),
67        EncodingId::DeltaBitPack => delta::decode(payload, max_values, out),
68        EncodingId::DeltaPatch => delta_patch::decode(payload, max_values, out),
69        EncodingId::BoolBitpack => bool_bitpack::decode(payload, max_values, out),
70        EncodingId::Frequency => frequency::decode(payload, max_values, out),
71        other => Err(ZuError::Unsupported {
72            what: "segment encoding",
73            id: other as u8 as u32,
74        }),
75    }
76}
77
78fn encode_with(id: EncodingId, values: &[u64], out: &mut Vec<u8>) {
79    match id {
80        EncodingId::Plain => encode_plain(values, out),
81        EncodingId::Constant => encode_constant(values, out),
82        EncodingId::Rle => {
83            rle::encode(values, out);
84        }
85        EncodingId::Dict => {
86            dict::encode(values, out);
87        }
88        EncodingId::ForBitPack => {
89            for_bitpack::encode(values, out);
90        }
91        EncodingId::DeltaBitPack => {
92            delta::encode(values, out);
93        }
94        EncodingId::DeltaPatch => {
95            delta_patch::encode(values, out);
96        }
97        EncodingId::BoolBitpack => {
98            bool_bitpack::encode(values, out);
99        }
100        EncodingId::Frequency => {
101            frequency::encode(values, out);
102        }
103        _ => unreachable!("choose never returns other ids"),
104    }
105}
106
107fn choose(values: &[u64]) -> EncodingId {
108    if values.is_empty() {
109        return EncodingId::Plain;
110    }
111    let shape = Shape::read(values);
112    if shape.constant {
113        return EncodingId::Constant;
114    }
115    // Candidate order breaks ties toward the shallower cascade.
116    // BoolBitpack is legal only when the whole input is binary, and Dict
117    // only under the format cap on distinct values, both of which this
118    // pass answers for every value rather than for a sample of them.
119    let mut best = EncodingId::Plain;
120    let mut best_size = 4 + values.len() * 8;
121    let candidates = [
122        EncodingId::BoolBitpack,
123        EncodingId::ForBitPack,
124        EncodingId::DeltaBitPack,
125        EncodingId::DeltaPatch,
126        EncodingId::Rle,
127        EncodingId::Dict,
128        EncodingId::Frequency,
129    ];
130    for id in candidates {
131        let Some(size) = shape.price(id) else {
132            continue;
133        };
134        if size < best_size {
135            best = id;
136            best_size = size;
137        }
138    }
139    best
140}
141
142/// What one pass over a chunk says, which is enough to price every
143/// candidate the cascade offers.
144///
145/// The three container sizes are exact: frame of reference stores a
146/// minimum and a width per 1024 values, and the patched container picks
147/// its width off the same width histogram its encoder builds, by the
148/// same suffix walk. The rest are priced off counts, and the only
149/// looseness is the width the exception streams pack at, which is taken
150/// as the chunk's own width rather than the exceptions' own. That
151/// overprices Frequency slightly and never underprices it.
152struct Shape {
153    len: usize,
154    min: u64,
155    max: u64,
156    /// Every value the same, which Constant says in twelve bytes.
157    constant: bool,
158    /// Every value 0 or 1, which is what makes BoolBitpack legal.
159    binary: bool,
160    /// The frame of reference container over the values themselves.
161    for_bytes: usize,
162    /// The same container over the zigzag deltas, which is DeltaBitPack
163    /// below its eight byte base.
164    delta_bytes: usize,
165    /// The patched container over those deltas, which is DeltaPatch
166    /// below the same base.
167    patch_bytes: usize,
168    runs: usize,
169    run_len_min: u64,
170    run_len_max: u64,
171    /// Distinct values, or None past the Dict cap, which is what says
172    /// Dict is not legal here.
173    distinct: Option<usize>,
174    /// How often the most common value appears, which is everything
175    /// Frequency is not an exception of.
176    top_count: usize,
177}
178
179impl Shape {
180    fn read(values: &[u64]) -> Shape {
181        let mut shape = Shape {
182            len: values.len(),
183            min: u64::MAX,
184            max: 0,
185            constant: true,
186            binary: true,
187            for_bytes: 4,
188            delta_bytes: 4,
189            patch_bytes: 4,
190            runs: 0,
191            run_len_min: u64::MAX,
192            run_len_max: 0,
193            distinct: None,
194            top_count: 0,
195        };
196        let first = values[0];
197        // The delta encoders seed the running previous from the first
198        // value, so the first delta is zero and no chunk pays for the
199        // magnitude the column starts at.
200        let mut prev = first;
201        let mut run = 0u64;
202        for block in values.chunks(CHUNK) {
203            let (mut bmin, mut bmax) = (u64::MAX, 0u64);
204            let (mut dmin, mut dmax) = (u64::MAX, 0u64);
205            let mut hist = [0usize; 65];
206            let mut wide = 0u32;
207            for &v in block {
208                bmin = bmin.min(v);
209                bmax = bmax.max(v);
210                shape.constant &= v == first;
211                shape.binary &= v <= 1;
212                let zz = zigzag(v.wrapping_sub(prev) as i64);
213                dmin = dmin.min(zz);
214                dmax = dmax.max(zz);
215                let width = bits_needed(zz);
216                hist[width as usize] += 1;
217                wide = wide.max(width);
218                if v == prev && run > 0 {
219                    run += 1;
220                } else {
221                    shape.close_run(run);
222                    run = 1;
223                }
224                prev = v;
225            }
226            shape.min = shape.min.min(bmin);
227            shape.max = shape.max.max(bmax);
228            shape.for_bytes += 9 + packed_bytes(bits_needed(bmax - bmin), block.len());
229            shape.delta_bytes += 9 + packed_bytes(bits_needed(dmax - dmin), block.len());
230            shape.patch_bytes += 2 + patch_body(&hist, wide, block.len());
231        }
232        shape.close_run(run);
233        // Dict cannot hold more than the format cap, and past it the
234        // count of distinct values buys nothing else, so the table stops
235        // there rather than growing with the column.
236        let counts = counts::count(values, dict::MAX_ENTRIES);
237        shape.distinct = counts.distinct;
238        shape.top_count = counts.top_count;
239        shape
240    }
241
242    fn close_run(&mut self, len: u64) {
243        if len > 0 {
244            self.runs += 1;
245            self.run_len_min = self.run_len_min.min(len);
246            self.run_len_max = self.run_len_max.max(len);
247        }
248    }
249
250    /// What `id` would cost on this chunk, or None when the format does
251    /// not allow it here.
252    fn price(&self, id: EncodingId) -> Option<usize> {
253        let spread = self.max - self.min;
254        match id {
255            EncodingId::BoolBitpack => self.binary.then(|| 4 + self.len.div_ceil(8)),
256            EncodingId::ForBitPack => Some(self.for_bytes),
257            EncodingId::DeltaBitPack => Some(8 + self.delta_bytes),
258            EncodingId::DeltaPatch => Some(8 + self.patch_bytes),
259            EncodingId::Rle => Some(
260                8 + for_bytes(self.runs, bits_needed(spread))
261                    + for_bytes(self.runs, bits_needed(self.run_len_max - self.run_len_min)),
262            ),
263            EncodingId::Dict => self.distinct.map(|d| {
264                4 + for_bytes(d, bits_needed(spread))
265                    + for_bytes(self.len, bits_needed(d.saturating_sub(1) as u64))
266            }),
267            EncodingId::Frequency => {
268                let exceptions = self.len - self.top_count;
269                Some(
270                    16 + for_bytes(exceptions, bits_needed(self.len as u64))
271                        + for_bytes(exceptions, bits_needed(spread)),
272                )
273            }
274            _ => None,
275        }
276    }
277}
278
279/// What a frame of reference container costs: its count, then a minimum
280/// and a width per 1024 values, then the packed body.
281fn for_bytes(count: usize, width: u32) -> usize {
282    4 + count.div_ceil(CHUNK) * 9 + packed_bytes(width, count)
283}
284
285/// What the patched container's body costs for one chunk, by the walk
286/// its encoder runs: every width from the widest down, paying the
287/// packed body, the presence bitmap and the exceptions above it.
288fn patch_body(hist: &[usize; 65], wide: u32, take: usize) -> usize {
289    let mut best = packed_bytes(wide, take) + packed_bytes(1, take);
290    let mut exceptions = 0usize;
291    for width in (0..wide).rev() {
292        exceptions += hist[width as usize + 1];
293        let cost =
294            packed_bytes(width, take) + packed_bytes(1, take) + packed_bytes(wide, exceptions);
295        best = best.min(cost);
296    }
297    best
298}
299
300fn encode_plain(values: &[u64], out: &mut Vec<u8>) {
301    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
302    for v in values {
303        out.extend_from_slice(&v.to_le_bytes());
304    }
305}
306
307fn decode_plain(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
308    let corrupt = |detail: &str| ZuError::Corrupt {
309        what: "plain",
310        detail: detail.to_string(),
311    };
312    let count = u32::from_le_bytes(
313        bytes
314            .get(..4)
315            .ok_or_else(|| corrupt("truncated count"))?
316            .try_into()
317            .unwrap(),
318    ) as usize;
319    if count > max_values {
320        return Err(corrupt("count above the caller ceiling"));
321    }
322    let body = bytes
323        .get(4..4 + count * 8)
324        .ok_or_else(|| corrupt("truncated body"))?;
325    out.reserve(count);
326    out.extend(
327        body.as_chunks::<8>()
328            .0
329            .iter()
330            .map(|c| u64::from_le_bytes(*c)),
331    );
332    Ok(())
333}
334
335fn encode_constant(values: &[u64], out: &mut Vec<u8>) {
336    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
337    out.extend_from_slice(&values[0].to_le_bytes());
338}
339
340fn decode_constant(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
341    let corrupt = |detail: &str| ZuError::Corrupt {
342        what: "constant",
343        detail: detail.to_string(),
344    };
345    let body = bytes.get(..12).ok_or_else(|| corrupt("truncated"))?;
346    let count = u32::from_le_bytes(body[..4].try_into().unwrap()) as usize;
347    // Twelve bytes claim any count at all; this wall is the whole
348    // defense, and the first thing the fuzzer found without it.
349    if count > max_values {
350        return Err(corrupt("count above the caller ceiling"));
351    }
352    let value = u64::from_le_bytes(body[4..12].try_into().unwrap());
353    out.extend(std::iter::repeat_n(value, count));
354    Ok(())
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    fn roundtrip(values: &[u64]) -> EncodingId {
362        let mut buf = Vec::new();
363        let id = encode_auto(values, &mut buf);
364        let mut out = Vec::new();
365        decode_any(&buf, values.len(), &mut out).unwrap();
366        assert_eq!(values, out.as_slice());
367        id
368    }
369
370    #[test]
371    fn picks_constant() {
372        assert_eq!(roundtrip(&vec![9u64; 5000]), EncodingId::Constant);
373    }
374
375    #[test]
376    fn picks_delta_for_sorted() {
377        let values: Vec<u64> = (0..10_000u64).map(|i| 1_000_000 + i * 3).collect();
378        assert_eq!(roundtrip(&values), EncodingId::DeltaBitPack);
379    }
380
381    #[test]
382    fn picks_delta_patch_for_adjacency() {
383        // Concatenated sorted neighbor lists: tight in-list gaps with a
384        // wide restart and hub jump per list. The wide deltas inside any
385        // 128-value sample run are real outliers, so the patched delta
386        // must win over plain delta's max-width chunks.
387        let mut rng = 0x2545F4914F6CDD1Du64;
388        let mut values = Vec::new();
389        for list in 0..2_000u64 {
390            let anchor = (list.wrapping_mul(0x9E3779B97F4A7C15) % 4_000_000).max(1);
391            values.push(anchor % 1000);
392            let mut v = anchor;
393            for _ in 0..13 {
394                rng ^= rng << 13;
395                rng ^= rng >> 7;
396                rng ^= rng << 17;
397                v += 1 + rng % 30;
398                values.push(v);
399            }
400        }
401        assert_eq!(roundtrip(&values), EncodingId::DeltaPatch);
402    }
403
404    #[test]
405    fn picks_for_on_small_range_noise() {
406        let mut rng = 0xABCDEFu64;
407        let values: Vec<u64> = (0..10_000)
408            .map(|_| {
409                rng ^= rng << 13;
410                rng ^= rng >> 7;
411                rng ^= rng << 17;
412                5_000_000 + rng % 1000
413            })
414            .collect();
415        assert_eq!(roundtrip(&values), EncodingId::ForBitPack);
416    }
417
418    #[test]
419    fn picks_rle_for_runs() {
420        let mut values = Vec::new();
421        for run in 0..40u64 {
422            values.extend(std::iter::repeat_n(run * 1_000_000_007, 500));
423        }
424        assert_eq!(roundtrip(&values), EncodingId::Rle);
425    }
426
427    #[test]
428    fn picks_dict_for_scattered_low_cardinality() {
429        let pool: Vec<u64> = (0..16u64)
430            .map(|i| i.wrapping_mul(0x9E3779B97F4A7C15))
431            .collect();
432        let values: Vec<u64> = (0..10_000).map(|i| pool[(i * 7) % pool.len()]).collect();
433        assert_eq!(roundtrip(&values), EncodingId::Dict);
434    }
435
436    #[test]
437    fn picks_bool_for_binary() {
438        // Mixed 0/1 noise: Constant does not apply, and BoolBitpack must
439        // beat width-1 FOR on the tie because it sits first in line.
440        let values: Vec<u64> = (0..10_000u64).map(|i| (i * i / 7) & 1).collect();
441        assert_eq!(roundtrip(&values), EncodingId::BoolBitpack);
442    }
443
444    #[test]
445    fn bool_never_picked_when_a_single_value_is_wider() {
446        // Binary everywhere except one value the sample misses: the
447        // legality check scans the whole input, so BoolBitpack must not
448        // be offered at all.
449        let mut values: Vec<u64> = (0..10_000u64).map(|i| i & 1).collect();
450        values[9_999] = 2;
451        let id = roundtrip(&values);
452        assert_ne!(id, EncodingId::BoolBitpack);
453    }
454
455    #[test]
456    fn dict_never_offered_past_the_distinct_cap() {
457        // Sixteen scattered wide values inside any sample window, but a
458        // fresh sixteen every 64 rows: the sample prices Dict as a clear
459        // winner while the full input holds ten thousand distinct
460        // values, past the format cap. The legality gate has to keep
461        // Dict out, or the encoder would ship a dictionary no reader
462        // accepts.
463        let values: Vec<u64> = (0..40_000usize)
464            .map(|i| {
465                let pool = (i / 64 * 16 + (i * 7) % 16) as u64;
466                pool.wrapping_mul(0x9E37_79B9_7F4A_7C15)
467            })
468            .collect();
469        let mut buf = Vec::new();
470        let id = encode_auto(&values, &mut buf);
471        assert_ne!(id, EncodingId::Dict);
472        let mut out = Vec::new();
473        decode_any(&buf, values.len(), &mut out).unwrap();
474        assert_eq!(values, out);
475    }
476
477    #[test]
478    fn picks_frequency_for_dominant_scattered() {
479        // 90% one value, 10% wide random exceptions: runs are too short
480        // for RLE, exception cardinality too high for Dict, values too
481        // wide for FOR, and the exceptions are cheap as patches.
482        let mut rng = 0x9E3779B97F4A7C15u64;
483        let values: Vec<u64> = (0..10_000)
484            .map(|i| {
485                rng ^= rng << 13;
486                rng ^= rng >> 7;
487                rng ^= rng << 17;
488                if i % 10 == 3 { rng } else { 777 }
489            })
490            .collect();
491        assert_eq!(roundtrip(&values), EncodingId::Frequency);
492    }
493
494    #[test]
495    fn random_wide_data_stays_decodable() {
496        let mut rng = 0x123456789u64;
497        let values: Vec<u64> = (0..5000)
498            .map(|_| {
499                rng ^= rng << 13;
500                rng ^= rng >> 7;
501                rng ^= rng << 17;
502                rng
503            })
504            .collect();
505        roundtrip(&values);
506    }
507
508    #[test]
509    fn empty_input() {
510        assert_eq!(roundtrip(&[]), EncodingId::Plain);
511    }
512
513    #[test]
514    fn unknown_id_rejected() {
515        let mut out = Vec::new();
516        assert!(decode_any(&[200, 0, 0], 16, &mut out).is_err());
517        assert!(decode_any(&[], 16, &mut out).is_err());
518        // FSST is a known id without a shipped decoder yet; it must error
519        // by name, not panic.
520        assert!(decode_any(&[8, 1, 2], 16, &mut out).is_err());
521    }
522
523    #[test]
524    fn fuzzer_found_constant_flood_rejected() {
525        // The exact payload libFuzzer produced in 21 execs against the
526        // unguarded decoder: Constant claiming 0xFFF607D0 values, which
527        // was a 34 GB allocation from a 14 byte input. The ceiling turns
528        // it into a Corrupt error.
529        let bytes = [1, 208, 7, 246, 255, 88, 42, 0, 0, 0, 0, 16, 0, 0];
530        let mut out = Vec::new();
531        assert!(decode_any(&bytes, 2048, &mut out).is_err());
532        assert!(out.is_empty());
533    }
534}