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
//! Block-level validation: metadata vs index, chunk references, tombstones.
//!
//! These tests work on copies of the vendored Prometheus block so they can
//! corrupt one thing at a time without touching the fixture other tests use.

use std::path::{Path, PathBuf};

use tsdb_reader::chunks::validation::SegmentReport;
use tsdb_reader::{BlockReader, Error, ReaderOptions};

const ULID: &str = "01M70C8VV61N5H5VWXB17HQQ1R";

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

/// Copies the block into a fresh temporary directory.
fn copy_block(tag: &str) -> PathBuf {
    let src = fixture_dir().join(ULID);
    let dst = std::env::temp_dir().join(format!(
        "tsdb-reader-block-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(dst.join("chunks")).unwrap();
    std::fs::copy(src.join("index"), dst.join("index")).unwrap();
    std::fs::copy(src.join("meta.json"), dst.join("meta.json")).unwrap();
    std::fs::copy(src.join("tombstones"), dst.join("tombstones")).unwrap();
    std::fs::copy(src.join("chunks/000001"), dst.join("chunks/000001")).unwrap();
    dst
}

fn open(dir: &Path) -> BlockReader {
    BlockReader::open(dir, ReaderOptions::default()).unwrap()
}

fn rewrite_meta(dir: &Path, edit: impl FnOnce(&mut serde_json::Value)) {
    let path = dir.join("meta.json");
    let raw = std::fs::read_to_string(&path).unwrap();
    let mut value: serde_json::Value = serde_json::from_str(&raw).unwrap();
    edit(&mut value);
    std::fs::write(&path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
}

#[test]
fn the_vendored_block_validates_cleanly() {
    let block = BlockReader::open(&fixture_dir().join(ULID), ReaderOptions::default()).unwrap();
    let report = block.validate().unwrap();

    assert!(report.is_ok(), "unexpected findings: {:?}", report.findings);
    assert_eq!(report.error_count(), 0);
    assert_eq!(report.index_version, 2);
    assert_eq!(report.meta_version, 1);
    assert_eq!(report.series, 42);
    assert_eq!(report.chunks, 100);
    assert_eq!(report.segments.segments, 1);
    assert_eq!(report.segments.records, 100);
    let postings = report.postings.expect("the block has a postings section");
    assert_eq!(postings.label_names, 4);
    assert_eq!(postings.entries, 54);
    // A clean block must also pass the strict interpretation.
    report.into_result().unwrap();
}

#[test]
fn meta_stats_that_disagree_with_the_index_are_errors() {
    let dir = copy_block("stats");
    rewrite_meta(&dir, |v| v["stats"]["numSeries"] = 41.into());
    let report = open(&dir).validate().unwrap();

    assert!(!report.is_ok());
    let messages: Vec<&str> = report.findings.iter().map(|f| f.message.as_str()).collect();
    assert!(
        messages
            .iter()
            .any(|m| m.contains("reports 41 series, index has 42")),
        "{messages:?}"
    );
    // into_result turns the finding into a single corruption error.
    match report.into_result() {
        Err(Error::Corrupt(msg)) => assert!(msg.contains("block 01M70C8VV"), "{msg}"),
        other => panic!("expected a corruption error, got {other:?}"),
    }
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn an_unexpected_meta_version_is_only_a_warning() {
    let dir = copy_block("metaversion");
    rewrite_meta(&dir, |v| v["version"] = 7.into());
    let report = open(&dir).validate().unwrap();

    assert!(report.is_ok(), "a meta version must not reject the block");
    assert_eq!(report.warning_count(), 1);
    // The warning explains the meta/index distinction, which is the field
    // most likely to be misread.
    let message = &report.findings[0].message;
    assert!(message.contains("meta format version"), "{message}");
    // Strict mode still refuses it.
    assert!(report.into_result().is_err());
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn chunk_references_that_do_not_resolve_are_errors() {
    let dir = copy_block("badref");
    // Leave only the segment header: every reference now points past the end.
    let segment = dir.join("chunks/000001");
    let head = std::fs::read(&segment).unwrap();
    std::fs::write(&segment, &head[..8]).unwrap();

    let report = open(&dir).validate().unwrap();
    assert!(!report.is_ok());
    let joined = format!("{:?}", report.findings);
    assert!(
        joined.contains("chunk references do not resolve"),
        "{joined}"
    );
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_narrowed_segment_file_is_reported_by_the_walk() {
    let dir = copy_block("narrow");
    let segment = dir.join("chunks/000001");
    let mut bytes = std::fs::read(&segment).unwrap();
    bytes.truncate(bytes.len() - 4);
    std::fs::write(&segment, &bytes).unwrap();

    let block = open(&dir);
    // The record walk notices the last record no longer fits.
    let error = block
        .chunk_reader()
        .validate_segments()
        .expect_err("a truncated segment must not validate");
    assert!(error.is_corruption(), "{error}");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn tombstones_outside_the_block_range_are_warnings() {
    let dir = copy_block("tombrange");
    // A valid tombstone file for series 0 covering a range before the block.
    let mut body = Vec::new();
    body.extend_from_slice(&0x0130_BA30u32.to_be_bytes());
    body.push(1);
    body.push(0); // ref 0
    body.push(0x02); // mint 1 (zig-zag)
    body.push(0x04); // maxt 2
    let crc = crc32c::crc32c(&body[5..]);
    body.extend_from_slice(&crc.to_be_bytes());
    std::fs::write(dir.join("tombstones"), &body).unwrap();

    let report = open(&dir).validate().unwrap();
    assert!(report.is_ok(), "warnings must not fail validation");
    let joined = format!("{:?}", report.findings);
    assert!(joined.contains("outside the block range"), "{joined}");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_tombstone_interval_with_inverted_bounds_is_an_error() {
    let dir = copy_block("tombbad");
    let mut body = Vec::new();
    body.extend_from_slice(&0x0130_BA30u32.to_be_bytes());
    body.push(1);
    body.push(0); // ref 0
    body.push(0x08); // mint 4
    body.push(0x02); // maxt 1
    let crc = crc32c::crc32c(&body[5..]);
    body.extend_from_slice(&crc.to_be_bytes());
    std::fs::write(dir.join("tombstones"), &body).unwrap();

    let report = open(&dir).validate().unwrap();
    assert!(!report.is_ok());
    let joined = format!("{:?}", report.findings);
    assert!(joined.contains("maxTime before minTime"), "{joined}");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_corrupt_postings_table_is_reported() {
    let dir = copy_block("postings");
    // The table starts at toc.postings_table; flip a byte inside its content so
    // the stored CRC no longer matches.
    let path = dir.join("index");
    let mut bytes = std::fs::read(&path).unwrap();
    let toc_start = bytes.len() - 52;
    let table_off =
        u64::from_be_bytes(bytes[toc_start + 40..toc_start + 48].try_into().unwrap()) as usize;
    bytes[table_off + 16] ^= 0x40;
    std::fs::write(&path, &bytes).unwrap();

    let block = open(&dir);
    let report = block.validate().unwrap();
    assert!(!report.is_ok(), "a broken label space must not validate");
    let joined = format!("{:?}", report.findings);
    assert!(joined.contains("postings"), "{joined}");
    assert!(report.postings.is_none());

    // Lookups fail too, instead of returning silently wrong lists.
    assert!(block.index().label_names().is_err());
    assert!(block.index().postings("job", "fixture").is_err());
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn a_block_without_a_label_space_only_warns() {
    let dir = copy_block("nolabels");
    // Zero the postings/label-index fields of the TOC and refresh its CRC: the
    // series section stays valid, the label space is simply absent.
    let path = dir.join("index");
    let mut bytes = std::fs::read(&path).unwrap();
    let toc_off = bytes.len() - 52;
    for field in [16usize, 24, 32, 40] {
        bytes[toc_off + field..toc_off + field + 8].copy_from_slice(&0u64.to_be_bytes());
    }
    let crc = crc32c::crc32c(&bytes[toc_off..toc_off + 48]);
    bytes[toc_off + 48..toc_off + 52].copy_from_slice(&crc.to_be_bytes());
    std::fs::write(&path, &bytes).unwrap();

    let block = open(&dir);
    let report = block.validate().unwrap();
    assert!(report.is_ok(), "an absent label space is not corruption");
    assert!(report.postings.is_none());
    let joined = format!("{:?}", report.findings);
    assert!(joined.contains("no postings offset table"), "{joined}");
    assert_eq!(report.series, 42, "the series section must stay readable");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn segment_report_defaults_are_empty() {
    let report = SegmentReport::default();
    assert_eq!(report.segments, 0);
    assert_eq!(report.records, 0);
    assert_eq!(report.bytes, 0);
}