znippy-common 0.12.0

Core logic and data structures for Znippy, a parallel chunked compression system.
Documentation
//! Codec layer: OpenZL compression/decompression.
//! OpenZL is znippy's codec — it wraps zstd+lz4 with improved framing.
//!
//! # The `openzl` feature — this file is the ONE gate
//!
//! The codec is `mopenzl`, OpenZL in safe Rust, whose encoding is byte-identical
//! to Meta's reference library; its zstd stage is `mzstd`, zstd in Rust. No build
//! script and no C compiler. A consumer that wants only the archive format turns
//! the feature off and links no codec at all.
//!
//! Rather than `#[cfg]` the six call sites that touch the codec — `archive.rs`,
//! `views.rs`, `decompress.rs` (×2), `meta_sink_append.rs`, `plugins/wasm_loader.rs`
//! — and fracture the public API into two shapes, the gate lives **here alone**
//! (LAW 5: one writer both paths route through). Every item below keeps its exact
//! signature with the feature off; the bodies return [`NO_CODEC`] instead. So:
//!
//! - the default build links the codec and reads and writes OpenZL frames;
//! - `default-features = false` drops `mopenzl` from the graph outright,
//!   leaving the archive format, the Arrow index, the searchable metadata
//!   sub-index and the plugin trait fully usable;
//! - a caller that *does* reach a compressed blob in such a build gets a named
//!   error, never a wrong answer or a silent empty result.
//!
//! Reading **stored** (uncompressed) entries needs no codec and keeps working
//! either way — that path never enters this module.

use anyhow::{anyhow, Result};

/// The error every entry point in this module returns when the crate was built
/// without the `openzl` feature. Names the feature so the fix is in the message.
#[cfg(not(feature = "openzl"))]
const NO_CODEC: &str = "znippy-common was built without the `openzl` feature, so the OpenZL codec \
     is not linked: compressed blobs cannot be read or written. Stored (uncompressed) \
     entries, the Arrow index and the metadata sub-index are unaffected. Enable the \
     `openzl` feature to link the codec (mopenzl, OpenZL in Rust).";

// ─── Frame format written ───────────────────────────────────────────

/// The OpenZL frame format every archive blob is **written** in. Reading is not
/// limited by it: mopenzl decodes every format from 21 to 27.
///
/// Pinned to 25 on 2026-10-02 so archives stay readable by readers on
/// openzl-sys-rs 0.3.x (OpenZL 0.2.1, max format 25) — the estates, holger and
/// gunnar binaries already deployed. The newest format, mopenzl's default
/// (`FormatVersion::MAX`), is 27, which those readers refuse.
///
/// The flip is two releases, on purpose:
/// 1. this release: every reader understands 27, writers keep producing 25;
/// 2. the next release, once test2 and the gunnar.rs estates run (1): change
///    this one line to 27.
///
/// Raising it before every reader understands 27 makes new archives unreadable
/// to old binaries. `writes_the_pinned_format` checks the value reaches the frame.
pub const OPENZL_WRITE_FORMAT: i32 = 25;

// ─── Compression Context ────────────────────────────────────────────

pub struct CompressCtx {
    #[cfg(feature = "openzl")]
    compressor: mopenzl::Compressor,
}

#[cfg(not(feature = "openzl"))]
impl CompressCtx {
    pub fn new(_compression_level: i32) -> Result<Self> {
        Err(anyhow!(NO_CODEC))
    }

    pub fn compress(&mut self, _input: &[u8]) -> Result<Vec<u8>> {
        Err(anyhow!(NO_CODEC))
    }

    pub fn compress_into(&mut self, _input: &[u8], _out: &mut Vec<u8>) -> Result<usize> {
        Err(anyhow!(NO_CODEC))
    }
}

#[cfg(not(feature = "openzl"))]
pub fn decompress_frame(_compressed: &[u8]) -> Result<Vec<u8>> {
    Err(anyhow!(NO_CODEC))
}

#[cfg(not(feature = "openzl"))]
pub fn decompress_into(_compressed: &[u8], _out: &mut Vec<u8>) -> Result<usize> {
    Err(anyhow!(NO_CODEC))
}

#[cfg(not(feature = "openzl"))]
pub fn decompress_into_budgeted(
    _compressed: &[u8],
    _out: &mut Vec<u8>,
    _max: usize,
) -> Result<usize> {
    Err(anyhow!(NO_CODEC))
}

#[cfg(not(feature = "openzl"))]
pub fn decompress_into_max(_compressed: &[u8], _out: &mut Vec<u8>, _max: usize) -> Result<usize> {
    Err(anyhow!(NO_CODEC))
}

#[cfg(feature = "openzl")]
impl CompressCtx {
    pub fn new(compression_level: i32) -> Result<Self> {
        use mopenzl::{Compressor, EncoderConfig, FormatVersion, Level};
        let level = Level::try_from(compression_level)
            .map_err(|e| anyhow!("OpenZL level {compression_level}: {e}"))?;
        // NOT the newest format (mopenzl's default, 27): readers on openzl-sys-rs
        // 0.3.x cannot decode it. See OPENZL_WRITE_FORMAT.
        let format = u32::try_from(OPENZL_WRITE_FORMAT)
            .ok()
            .and_then(|v| FormatVersion::try_from(v).ok())
            .ok_or_else(|| {
                anyhow!("OpenZL format {OPENZL_WRITE_FORMAT} is not one mopenzl writes")
            })?;
        let config = EncoderConfig::default()
            .with_level(level)
            .with_format_version(format);
        let compressor = Compressor::new(config).map_err(|e| anyhow!("OpenZL compressor: {e}"))?;
        Ok(Self { compressor })
    }

    pub fn compress(&mut self, input: &[u8]) -> Result<Vec<u8>> {
        self.compressor
            .compress(input)
            .map_err(|e| anyhow!("OpenZL compress: {e}"))
    }

    /// Compress into a reusable buffer; returns the number of bytes written
    /// (`out` holds exactly the frame). Reuse the same `out` across slices to
    /// keep the compress path allocation-free (the no-hot-path-alloc rule).
    pub fn compress_into(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<usize> {
        out.clear();
        self.compressor
            .compress_into(input, out)
            .map_err(|e| anyhow!("OpenZL compress: {e}"))?;
        Ok(out.len())
    }
}

#[cfg(feature = "openzl")]
pub fn decompress_frame(compressed: &[u8]) -> Result<Vec<u8>> {
    let mut out = Vec::new();
    decompress_into(compressed, &mut out)?;
    Ok(out)
}

/// Decompress into a reusable buffer; returns bytes written (`out` holds exactly
/// them). Reuse the same `out` across chunks to keep the decompress path
/// allocation-free (the no-hot-path-alloc rule).
#[cfg(feature = "openzl")]
pub fn decompress_into(compressed: &[u8], out: &mut Vec<u8>) -> Result<usize> {
    decode(mopenzl::Decompressor::default(), compressed, out)
}

/// One frame into `out`, which ends up holding exactly the decoded bytes.
#[cfg(feature = "openzl")]
fn decode(
    mut decoder: mopenzl::Decompressor,
    compressed: &[u8],
    out: &mut Vec<u8>,
) -> Result<usize> {
    out.clear();
    decoder
        .decompress_into(compressed, out)
        .map_err(|e| anyhow!("OpenZL decompress: {e}"))?;
    Ok(out.len())
}

/// The decompressed size a frame's header declares.
#[cfg(feature = "openzl")]
fn declared_size(compressed: &[u8]) -> Result<u64> {
    let info = mopenzl::Decompressor::default()
        .frame_info(compressed)
        .map_err(|e| anyhow!("OpenZL frame header: {e}"))?;
    Ok(info.decompressed_size())
}

// ─── Untrusted frames ───────────────────────────────────────────────

/// [`decompress_into_max`] for an UNTRUSTED frame: the decoder itself also
/// refuses a frame that would regenerate more than `max` bytes or read more
/// than the frame's own bytes (mopenzl `DecodeLimits`).
///
/// OpenZL sizes its internal streams from the frame's graph, not from the
/// header, so a 36-byte frame could make the C library allocate and fill a
/// gigabyte before it failed (the heimdall fuzz find). mopenzl bounds every
/// stream it regenerates to 16 bytes per output byte still to come, plus 1 MiB,
/// and refuses a frame that asks for more; the header's size is held to `max`
/// before that, so the bound follows the chunk's declared size.
///
/// The output buffer itself is Rust's and bounded by `max` before it grows.
#[cfg(feature = "openzl")]
pub fn decompress_into_budgeted(compressed: &[u8], out: &mut Vec<u8>, max: usize) -> Result<usize> {
    use mopenzl::{DecodeLimits, DecoderConfig, Decompressor};
    check_declared(compressed, max)?;
    let limits = DecodeLimits::default()
        .with_max_input_bytes(Some(compressed.len() as u64))
        .with_max_output_bytes(Some(max as u64));
    decode(
        Decompressor::new(DecoderConfig::default().with_limits(limits)),
        compressed,
        out,
    )
}

/// [`decompress_into`] for a frame the caller has a size for: a frame whose
/// header declares more than `max` bytes is refused BEFORE `out` is grown, so
/// the header alone can never size an allocation. The reader passes the index
/// row's `uncompressed_size` (see `archive::frame_limit`).
#[cfg(feature = "openzl")]
pub fn decompress_into_max(compressed: &[u8], out: &mut Vec<u8>, max: usize) -> Result<usize> {
    check_declared(compressed, max)?;
    decompress_into(compressed, out)
}

/// Refuses a frame whose header declares more than `max` decompressed bytes.
#[cfg(feature = "openzl")]
fn check_declared(compressed: &[u8], max: usize) -> Result<()> {
    let declared = declared_size(compressed)?;
    if declared > max as u64 {
        return Err(anyhow!(
            "OpenZL frame declares {declared} decompressed bytes, more than the {max} its chunk allows"
        ));
    }
    Ok(())
}

/// With the `openzl` feature OFF the codec is not linked. Prove that every entry
/// point says so **out loud** — an `Err` naming the feature — instead of the two
/// failure modes that would actually hurt: a silent `Ok` with empty/garbage bytes,
/// or a panic. LAW 2: this is the red the default build can never show, so it is
/// asserted from the build that can.
#[cfg(all(test, not(feature = "openzl")))]
mod no_codec_tests {
    use super::*;

    fn assert_names_the_feature(err: anyhow::Error) {
        let msg = err.to_string();
        assert!(
            msg.contains("`openzl` feature"),
            "error must name the feature that is missing, got: {msg}"
        );
    }

    #[test]
    fn compress_ctx_refuses_to_exist() {
        assert_names_the_feature(
            CompressCtx::new(3)
                .err()
                .expect("CompressCtx::new must fail with no codec linked"),
        );
    }

    #[test]
    fn decompress_refuses_and_does_not_touch_the_buffer() {
        // A real OpenZL frame header; without the codec it must not be decoded,
        // and `out` must be left exactly as the caller handed it over.
        let frame = [0x5Bu8, 0x2A, 0x4D, 0x18, 0x00, 0x00, 0x00, 0x00];
        let mut out = vec![0xAAu8; 4];
        assert_names_the_feature(
            decompress_into(&frame, &mut out)
                .err()
                .expect("decompress_into must fail"),
        );
        assert_eq!(out, vec![0xAAu8; 4], "buffer must be untouched on refusal");
        assert_names_the_feature(
            decompress_frame(&frame)
                .err()
                .expect("decompress_frame must fail"),
        );
    }
}

#[cfg(all(test, feature = "openzl"))]
mod tests {
    use super::*;

    #[test]
    fn test_roundtrip() {
        let mut ctx = CompressCtx::new(3).unwrap();
        let input = b"Hello world! This is a test of compression roundtrip. Repeated data helps compression. Repeated data helps compression. Repeated data helps compression.";
        let compressed = ctx.compress(input).unwrap();
        println!("Compressed {} -> {} bytes", input.len(), compressed.len());
        let decompressed = decompress_frame(&compressed).unwrap();
        assert_eq!(&decompressed[..], &input[..]);
    }

    #[test]
    fn test_multi_compress_same_ctx() {
        let mut ctx = CompressCtx::new(3).unwrap();
        for i in 0..10 {
            let input: Vec<u8> = (0..4096).map(|x| ((x + i) % 251) as u8).collect();
            let compressed = ctx.compress(&input).unwrap();
            let decompressed = decompress_frame(&compressed).unwrap();
            assert_eq!(decompressed, input, "Failed at iteration {}", i);
        }
        println!("10 sequential compress calls OK");
    }

    #[test]
    fn test_parallel_contexts() {
        let handles: Vec<_> = (0..8)
            .map(|t| {
                std::thread::spawn(move || {
                    let mut ctx = CompressCtx::new(3).unwrap();
                    for i in 0..5 {
                        let input: Vec<u8> =
                            (0..8192).map(|x| ((x + i + t * 100) % 251) as u8).collect();
                        let compressed = ctx.compress(&input).unwrap();
                        let decompressed = decompress_frame(&compressed).unwrap();
                        assert_eq!(decompressed, input);
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        println!("8 parallel contexts x 5 calls each OK");
    }

    /// The frame format a blob was written in, read from the frame header.
    fn frame_format(frame: &[u8]) -> u32 {
        let info = mopenzl::Decompressor::default()
            .frame_info(frame)
            .expect("a readable OpenZL frame");
        u32::from(info.version())
    }

    fn sample() -> Vec<u8> {
        (0..65_536u32)
            .map(|x| ((x * 7 + x / 13) % 251) as u8)
            .collect()
    }

    /// Writes stay on the pinned format even though the codec's own default is
    /// newer — the guarantee old readers depend on.
    #[test]
    fn writes_the_pinned_format() {
        let default = u32::from(mopenzl::FormatVersion::default());
        assert!(
            default >= OPENZL_WRITE_FORMAT as u32,
            "the codec defaults to {default}, older than the pinned write format"
        );
        let frame = CompressCtx::new(3).unwrap().compress(&sample()).unwrap();
        assert_eq!(frame_format(&frame), OPENZL_WRITE_FORMAT as u32);
        assert_eq!(decompress_frame(&frame).unwrap(), sample());
    }

    /// The reader decodes the newest format the codec writes (27), which is
    /// what writers will switch to in the release after the pin.
    #[test]
    fn reads_the_latest_format() {
        use mopenzl::{Compressor, EncoderConfig, FormatVersion, Level};
        let latest = FormatVersion::MAX;
        let config = EncoderConfig::default()
            .with_level(Level::try_from(3).unwrap())
            .with_format_version(latest);
        let input = sample();
        let frame = Compressor::new(config).unwrap().compress(&input).unwrap();
        assert_eq!(frame_format(&frame), u32::from(latest));
        assert_eq!(decompress_frame(&frame).unwrap(), input);
    }

    /// A frame written by the OLD wrapper (openzl-sys-rs 0.3.1 = OpenZL 0.2.1,
    /// format 25) — every archive on disk today — still decodes. The fixture and
    /// its plaintext were produced by openzl-sys-rs 0.3.1 from crates.io; see
    /// tests/fixtures/openzl/README.md.
    #[test]
    fn reads_frames_from_wrapper_0_3_1() {
        let frame = include_bytes!("../tests/fixtures/openzl/wrapper-0.3.1-format25.zl");
        let plain = include_bytes!("../tests/fixtures/openzl/plain.bin");
        assert_eq!(frame_format(frame), 25);
        assert_eq!(decompress_frame(frame).unwrap(), &plain[..]);
    }
}