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
//! Postings and label lookups against the vendored Prometheus block.
//!
//! The expectations are derived from `ground_truth.json` (which was produced by
//! the reference implementation) rather than hand-written: for every label pair
//! the expected postings are the sorted series ids of the series that carry it.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use tsdb_reader::chunkenc::{self, FloatHistogramSample, IntHistogramSample, SampleSink};
use tsdb_reader::{BlockReader, Postings, ReaderOptions};

const ULID: &str = "01M70C8VV61N5H5VWXB17HQQ1R";

fn block() -> BlockReader {
    let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/data/block")
        .join(ULID);
    BlockReader::open(&dir, ReaderOptions::default()).unwrap()
}

/// (series id, labels) in index order.
fn series_with_ids(block: &BlockReader) -> Vec<(u64, Vec<(String, String)>)> {
    let mut out = Vec::new();
    for series in block.series(0) {
        let series = series.unwrap();
        out.push((
            series.id,
            series
                .labels
                .iter()
                .map(|(n, v)| (n.to_string(), v.to_string()))
                .collect(),
        ));
    }
    out
}

#[test]
fn label_names_and_values_match_the_series_section() {
    let block = block();
    let series = series_with_ids(&block);

    let mut names: BTreeSet<String> = BTreeSet::new();
    let mut values: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for (_, labels) in &series {
        for (name, value) in labels {
            names.insert(name.clone());
            values
                .entry(name.clone())
                .or_default()
                .insert(value.clone());
        }
    }

    let got_names = block.index().label_names().unwrap();
    assert_eq!(got_names, names.iter().cloned().collect::<Vec<_>>());
    for name in &got_names {
        let got = block.index().label_values(name).unwrap();
        let want: Vec<String> = values[name].iter().cloned().collect();
        assert_eq!(got, want, "values of {name}");
    }
    assert!(block.index().label_values("absent").unwrap().is_empty());
}

#[test]
fn every_postings_list_matches_the_series_that_carry_the_pair() {
    let block = block();
    let series = series_with_ids(&block);

    let mut expected: BTreeMap<(String, String), Vec<u64>> = BTreeMap::new();
    for (id, labels) in &series {
        for (name, value) in labels {
            expected
                .entry((name.clone(), value.clone()))
                .or_default()
                .push(*id);
        }
    }

    for ((name, value), want) in &expected {
        let got = block.index().postings(name, value).unwrap();
        assert_eq!(
            got.len(),
            want.len() as u64,
            "postings length for {name}={value}"
        );
        let refs = block
            .index()
            .postings(name, value)
            .unwrap()
            .collect_refs()
            .unwrap();
        assert_eq!(&refs, want, "postings for {name}={value}");
        assert!(
            refs.windows(2).all(|w| w[0] < w[1]),
            "postings for {name}={value} must be strictly increasing"
        );
    }

    // Unknown pairs are empty rather than an error.
    assert!(block
        .index()
        .postings("__name__", "nope")
        .unwrap()
        .is_empty());
    assert!(block.index().postings("nope", "nope").unwrap().is_empty());
}

#[test]
fn all_postings_covers_every_series() {
    let block = block();
    let mut all: Vec<u64> = block
        .index()
        .all_postings()
        .unwrap()
        .collect_refs()
        .unwrap();
    let mut expected: Vec<u64> = series_with_ids(&block).iter().map(|(id, _)| *id).collect();
    assert_eq!(all.len(), expected.len());
    all.sort_unstable();
    expected.sort_unstable();
    assert_eq!(all, expected);
}

#[test]
fn unions_are_sorted_and_deduplicated() {
    let block = block();
    let mut got = block
        .index()
        .postings_multi("instance", &["host-00", "host-00", "host-01", "missing"])
        .unwrap()
        .collect_refs()
        .unwrap();
    let mut want = block
        .index()
        .postings("instance", "host-00")
        .unwrap()
        .collect_refs()
        .unwrap();
    want.extend(
        block
            .index()
            .postings("instance", "host-01")
            .unwrap()
            .collect_refs()
            .unwrap(),
    );
    want.sort_unstable();
    want.dedup();
    assert!(!want.is_empty());
    assert!(got.windows(2).all(|w| w[0] < w[1]));
    got.sort_unstable();
    assert_eq!(got, want);
    assert!(block
        .index()
        .postings_multi("instance", &[])
        .unwrap()
        .is_empty());
}

#[test]
fn a_reference_resolves_to_the_same_series() {
    let block = block();
    for (id, labels) in series_with_ids(&block) {
        let series = block.index().series_by_ref(id).unwrap();
        assert_eq!(series.id, id);
        let got: Vec<(String, String)> = series
            .labels
            .iter()
            .map(|(n, v)| (n.to_string(), v.to_string()))
            .collect();
        assert_eq!(got, labels);
    }
}

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<'_>) {}
}

#[test]
fn postings_can_drive_a_chunk_read() {
    // The lookup path must lead to the same samples as a full scan of the one
    // series it resolves.
    let block = block();
    let name = "__name__";
    let value = "fixture_metric_00";
    let mut refs = block.index().postings(name, value).unwrap();
    let id = refs.next().unwrap().expect("the fixture has this series");
    assert!(refs.next().unwrap().is_none(), "one series per metric name");

    let via_postings = block.index().series_by_ref(id).unwrap();
    let via_scan = block
        .series(0)
        .map(Result::unwrap)
        .find(|s| s.id == id)
        .expect("series is present");
    assert_eq!(via_postings.labels, via_scan.labels);

    let mut samples = 0u64;
    for chunk in &via_postings.chunks {
        let slice = block.chunk(chunk).unwrap();
        let mut sink = NullSink;
        let outcome = chunkenc::decode(slice.encoding, slice.data, &mut sink).unwrap();
        samples += outcome.samples();
    }
    assert!(samples > 0, "the resolved series must have samples");
}

#[test]
fn validation_reports_postings_statistics() {
    let block = block();
    let stats = block.index().validate_postings().unwrap();
    assert_eq!(stats.label_names, 4);
    assert_eq!(stats.entries as u64, stats.lists);
    // One all-series entry plus one per distinct pair.
    assert_eq!(stats.entries, 54);
    assert_eq!(stats.refs, 206);
}