zudb-encoding 0.0.2

Lightweight columnar encodings for zu (FastLanes, ALP, FSST, cascades)
Documentation
//! Frequency encoding (encoding id 10), the BtrBlocks shape for columns
//! where one value dominates but the rest are wide and scattered, so
//! neither RLE (short runs) nor Dict (high exception cardinality) wins.
//!
//! The dominant value is stored once; everything else becomes an
//! exception patched back in by position. Both exception streams ride
//! the frame-of-reference container.
//! Layout: `count: u32 LE`, `top: u64 LE`, `positions_len: u32 LE`,
//! positions container, values container.

use zu_common::{Result, ZuError};

use crate::bitpack::CHUNK;
use crate::for_bitpack;

/// Encodes `values` into `out`, returning the encoded byte length.
pub fn encode(values: &[u64], out: &mut Vec<u8>) -> usize {
    let start = out.len();
    // The dominant value, off the shared counting table rather than a
    // hash map: the map hashed every value of every chunk with SipHash,
    // and this encoder is on the write path of every fold.
    let top = match values.is_empty() {
        true => 0,
        false => crate::counts::count(values, values.len()).top,
    };
    let mut positions = Vec::new();
    let mut exceptions = Vec::new();
    for (i, &v) in values.iter().enumerate() {
        if v != top {
            positions.push(i as u64);
            exceptions.push(v);
        }
    }
    out.extend_from_slice(&(values.len() as u32).to_le_bytes());
    out.extend_from_slice(&top.to_le_bytes());
    let mut positions_buf = Vec::new();
    for_bitpack::encode(&positions, &mut positions_buf);
    out.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
    out.extend_from_slice(&positions_buf);
    for_bitpack::encode(&exceptions, out);
    out.len() - start
}

/// Decodes an encoded buffer, appending at most `max_values` values to
/// `out`. The count and both exception streams are claims until checked:
/// the count against the caller ceiling, the streams against each other,
/// and every position against the materialized range. The exception
/// streams patch chunk by chunk in lockstep, so scratch stays two
/// MiniBlock chunks however many exceptions the segment holds.
pub fn decode(bytes: &[u8], max_values: usize, out: &mut Vec<u64>) -> Result<()> {
    let corrupt = |detail: &str| ZuError::Corrupt {
        what: "frequency",
        detail: detail.to_string(),
    };
    let header = bytes.get(..16).ok_or_else(|| corrupt("truncated header"))?;
    let count = u32::from_le_bytes(header[..4].try_into().unwrap()) as usize;
    let top = u64::from_le_bytes(header[4..12].try_into().unwrap());
    let positions_len = u32::from_le_bytes(header[12..16].try_into().unwrap()) as usize;
    if count > max_values {
        return Err(corrupt("count above the caller ceiling"));
    }
    let positions_bytes = bytes
        .get(16..16 + positions_len)
        .ok_or_else(|| corrupt("truncated positions"))?;
    let values_bytes = bytes
        .get(16 + positions_len..)
        .ok_or_else(|| corrupt("truncated exception values"))?;
    let mut positions_cur = for_bitpack::ChunkCursor::new(positions_bytes, count)?;
    let mut values_cur = for_bitpack::ChunkCursor::new(values_bytes, count)?;
    if positions_cur.count() != values_cur.count() {
        return Err(corrupt("stream length mismatch"));
    }
    let base = out.len();
    out.extend(std::iter::repeat_n(top, count));
    let mut sp = [0u64; CHUNK];
    let mut sv = [0u64; CHUNK];
    let bad = 'chunks: loop {
        let (pmin, tp) = match positions_cur.next(&mut sp) {
            Ok(Some(chunk)) => chunk,
            Ok(None) => break None,
            Err(e) => break Some(e),
        };
        let (vmin, tv) = match values_cur.next(&mut sv) {
            Ok(Some(chunk)) => chunk,
            Ok(None) => break Some(corrupt("value stream ended early")),
            Err(e) => break Some(e),
        };
        for (&p, &v) in sp[..tp.min(tv)].iter().zip(&sv) {
            let pos = pmin.wrapping_add(p);
            if pos >= count as u64 {
                break 'chunks Some(corrupt("position past the value count"));
            }
            out[base + pos as usize] = vmin.wrapping_add(v);
        }
    };
    if let Some(e) = bad {
        out.truncate(base);
        return Err(e);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrip_dominant_scattered() {
        let mut rng = 0x9E3779B97F4A7C15u64;
        let values: Vec<u64> = (0..10_000)
            .map(|i| {
                rng ^= rng << 13;
                rng ^= rng >> 7;
                rng ^= rng << 17;
                if i % 10 == 3 { rng } else { 777 }
            })
            .collect();
        let mut buf = Vec::new();
        let len = encode(&values, &mut buf);
        assert!(
            len < values.len() * 2,
            "10% exceptions should encode near a tenth of raw, got {len}"
        );
        let mut out = Vec::new();
        decode(&buf, values.len(), &mut out).unwrap();
        assert_eq!(values, out);
    }

    #[test]
    fn roundtrip_edges() {
        for values in [vec![], vec![5u64], vec![1, 2, 3, 4], vec![0; 100]] {
            let mut buf = Vec::new();
            encode(&values, &mut buf);
            let mut out = Vec::new();
            decode(&buf, values.len(), &mut out).unwrap();
            assert_eq!(values, out);
        }
    }

    #[test]
    fn corrupt_and_hostile() {
        let mut out = Vec::new();
        assert!(decode(&[1, 2, 3], 16, &mut out).is_err());
        // A flood claim dies on the ceiling before anything materializes.
        let mut buf = u32::MAX.to_le_bytes().to_vec();
        buf.extend_from_slice(&[0; 12]);
        assert!(decode(&buf, 1 << 20, &mut out).is_err());
        assert!(out.is_empty());
    }

    #[test]
    fn hostile_position_past_count_rejected() {
        // A valid-looking payload whose exception position lands outside
        // the materialized range must be a Corrupt error, not a write
        // into whatever the caller already had in `out`.
        let mut buf = 4u32.to_le_bytes().to_vec();
        buf.extend_from_slice(&7u64.to_le_bytes());
        let mut positions_buf = Vec::new();
        for_bitpack::encode(&[3], &mut positions_buf);
        buf.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
        buf.extend_from_slice(&positions_buf);
        for_bitpack::encode(&[99], &mut buf);
        let mut out = Vec::new();
        decode(&buf, 16, &mut out).unwrap();
        assert_eq!(out, [7, 7, 7, 99]);
        // Same payload, position 4 in a count of 4.
        let mut buf = 4u32.to_le_bytes().to_vec();
        buf.extend_from_slice(&7u64.to_le_bytes());
        let mut positions_buf = Vec::new();
        for_bitpack::encode(&[4], &mut positions_buf);
        buf.extend_from_slice(&(positions_buf.len() as u32).to_le_bytes());
        buf.extend_from_slice(&positions_buf);
        for_bitpack::encode(&[99], &mut buf);
        let mut out = vec![1, 2, 3];
        assert!(decode(&buf, 16, &mut out).is_err());
        assert_eq!(out, [1, 2, 3], "a rejected payload must not touch out");
    }
}