tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Deterministic robustness tests: mutate real block bytes and require that
//! every parser reports an error instead of panicking, hanging or allocating
//! wildly.
//!
//! This is the part of fuzzing that runs in `cargo test` (the `fuzz/` crate
//! needs nightly and libFuzzer). The mutation strategy is deliberately simple
//! and reproducible: truncation at every length, single-bit flips at a stride,
//! and byte overwrites with 0x00/0xFF.

use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::PathBuf;

use tsdb_reader::chunkenc::{self, FloatHistogramSample, IntHistogramSample, SampleSink};
use tsdb_reader::{IndexReader, Postings, Tombstones};

/// Offset of the record after the one at `offset`, from the segment bytes.
fn next_record(segment: &[u8], offset: usize) -> Option<usize> {
    let mut p = offset;
    let mut shift = 0u32;
    let mut len = 0usize;
    loop {
        let b = *segment.get(p)?;
        p += 1;
        len |= ((b & 0x7f) as usize).checked_shl(shift)?;
        if b & 0x80 == 0 {
            break;
        }
        shift += 7;
        if shift > 28 {
            return None;
        }
    }
    // length + encoding byte + body + CRC
    p.checked_add(1)?.checked_add(len)?.checked_add(4)
}

struct NullSink;
impl SampleSink for NullSink {
    fn push_float(&mut self, _ts: i64, _value: f64) {}
    fn push_int_histogram(&mut self, _h: &IntHistogramSample<'_>) {}
    fn push_float_histogram(&mut self, _h: &FloatHistogramSample<'_>) {}
}

fn block_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R")
}

/// Runs `f` for one mutation, turning a panic into a test failure that names
/// the mutation.
fn guarded<F: FnOnce()>(what: String, f: F) {
    let result = catch_unwind(AssertUnwindSafe(f));
    assert!(result.is_ok(), "panic while handling mutation: {what}");
}

/// Every truncation length must yield an error, never a panic.
fn check_truncations(name: &str, bytes: &[u8], mut run: impl FnMut(&[u8])) {
    for len in 0..bytes.len() {
        let prefix = &bytes[..len];
        guarded(format!("{name} truncated to {len}"), || run(prefix));
    }
}

/// Single-bit flips at a stride, plus byte overwrites.
fn check_corruptions(name: &str, bytes: &[u8], mut run: impl FnMut(&[u8])) {
    let stride = (bytes.len() / 512).max(1);
    for offset in (0..bytes.len()).step_by(stride) {
        for bit in [0u8, 3, 7] {
            let mut copy = bytes.to_vec();
            copy[offset] ^= 1 << bit;
            guarded(format!("{name} bit {bit} at {offset}"), || run(&copy));
        }
        for value in [0x00u8, 0xff] {
            let mut copy = bytes.to_vec();
            copy[offset] = value;
            guarded(format!("{name} byte {offset} = {value:#04x}"), || {
                run(&copy)
            });
        }
    }
}

#[test]
fn index_parser_survives_mutations() {
    let bytes = std::fs::read(block_dir().join("index")).unwrap();
    let run = |data: &[u8]| {
        if let Ok(index) = IndexReader::from_bytes(data.to_vec(), true) {
            let _ = index.validate_layout();
            let _ = index.scan_stats();
            for series in index.series(0).take(4) {
                if series.is_err() {
                    break;
                }
            }
            // The label space must be equally panic-free: every lookup returns
            // either a result or an error, never a panic.
            let _ = index.validate_postings();
            if let Ok(names) = index.label_names() {
                for name in names.iter().take(2) {
                    if let Ok(values) = index.label_values(name) {
                        for value in values.iter().take(3) {
                            if let Ok(mut p) = index.postings(name, value) {
                                for _ in 0..8 {
                                    if !matches!(p.next(), Ok(Some(_))) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if let Ok(mut all) = index.all_postings() {
                for _ in 0..8 {
                    if !matches!(all.next(), Ok(Some(_))) {
                        break;
                    }
                }
            }
        }
    };
    check_truncations("index", &bytes, run);
    check_corruptions("index", &bytes, run);
}

#[test]
fn tombstones_parser_survives_mutations() {
    let bytes = std::fs::read(block_dir().join("tombstones")).unwrap();
    let dir = std::env::temp_dir().join(format!(
        "tsdb-reader-robust-tomb-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("tombstones");

    let run = |data: &[u8]| {
        std::fs::write(&path, data).unwrap();
        if let Ok(t) = Tombstones::open(&dir, true) {
            for (reference, intervals) in t.iter_raw() {
                let _ = t.is_deleted(*reference, 0);
                let _ = t.is_deleted_range(*reference, i64::MIN, i64::MAX);
                for (mint, maxt) in intervals {
                    let _ = t.is_deleted_range(*reference, *mint + 1, *maxt - 1);
                }
            }
        }
    };
    check_truncations("tombstones", &bytes, run);
    check_corruptions("tombstones", &bytes, run);
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn chunk_decoder_survives_mutations() {
    let dir = block_dir().join("chunks");
    let segment = std::fs::read(dir.join("000001")).unwrap();
    let reader = tsdb_reader::ChunkReader::open(&dir, true, false).unwrap();

    // Walk the real records, then mutate each payload's bytes and decode.
    let mut offset = 8usize;
    let mut checked = 0;
    while offset + 5 <= segment.len() {
        let reference = offset as u64;
        let Ok(slice) = reader.chunk(reference) else {
            break;
        };
        let (encoding, body) = (slice.encoding, slice.data.to_vec());
        checked += 1;

        check_truncations("chunk", &body, |data| {
            let _ = chunkenc::decode(encoding, data, &mut NullSink);
        });
        let stride = (body.len() / 64).max(1);
        for pos in (0..body.len()).step_by(stride) {
            let mut copy = body.clone();
            copy[pos] ^= 0x01;
            guarded(format!("chunk byte {pos}"), || {
                let _ = chunkenc::decode(encoding, &copy, &mut NullSink);
            });
        }
        // Continue with the next record.
        offset = next_record(&segment, offset).expect("a valid record has a successor");
        if checked > 8 {
            break;
        }
    }
    assert!(checked > 0, "the fixture must contain chunk records");
}

#[test]
fn a_flipped_length_field_never_reads_out_of_bounds() {
    let dir = block_dir().join("chunks");
    let mut segment = std::fs::read(dir.join("000001")).unwrap();
    let tmp = std::env::temp_dir().join(format!(
        "tsdb-reader-robust-chunk-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&tmp).unwrap();

    // The length varint of the first record starts at offset 8. Try every
    // single-byte value: the reader must either reject the record or read a
    // shorter body, never run past the segment.
    for value in 0..=255u8 {
        segment[8] = value;
        std::fs::write(tmp.join("000001"), &segment).unwrap();
        guarded(format!("length byte {value}"), || {
            if let Ok(reader) = tsdb_reader::ChunkReader::open(&tmp, false, false) {
                if let Ok(slice) = reader.chunk(8) {
                    assert!(slice.data.len() <= reader.bytes() as usize);
                }
            }
        });
    }
    std::fs::remove_dir_all(&tmp).unwrap();
}