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
//! Set operations over the vendored block, checked against brute force.
//!
//! The oracle is the series section itself: for any pair of label matchers the
//! expected answer is "the ids of the series whose labels satisfy both". That
//! keeps the test independent of the postings encoding.

use std::collections::BTreeSet;
use std::path::PathBuf;

use tsdb_reader::index::postings_ops::{difference, intersect, intersect_all, union_all};
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()
}

struct Series {
    id: u64,
    labels: Vec<(String, String)>,
}

fn all_series(block: &BlockReader) -> Vec<Series> {
    block
        .series(0)
        .map(|s| {
            let s = s.unwrap();
            Series {
                id: s.id,
                labels: s
                    .labels
                    .iter()
                    .map(|(n, v)| (n.to_string(), v.to_string()))
                    .collect(),
            }
        })
        .collect()
}

fn has(series: &Series, name: &str, value: &str) -> bool {
    series.labels.iter().any(|(n, v)| n == name && v == value)
}

/// Every (name, value) pair in the block, sorted for determinism.
fn pairs(series: &[Series]) -> Vec<(String, String)> {
    let mut out: BTreeSet<(String, String)> = BTreeSet::new();
    for s in series {
        for (n, v) in &s.labels {
            out.insert((n.clone(), v.clone()));
        }
    }
    out.into_iter().collect()
}

fn drain(mut p: impl Postings) -> Vec<u64> {
    p.collect_refs().unwrap()
}

#[test]
fn intersections_match_the_series_that_carry_both_pairs() {
    let block = block();
    let series = all_series(&block);
    let pairs = pairs(&series);

    for (i, left) in pairs.iter().enumerate() {
        for right in pairs.iter().skip(i) {
            let mut got = drain(intersect(
                Box::new(block.index().postings(&left.0, &left.1).unwrap()),
                Box::new(block.index().postings(&right.0, &right.1).unwrap()),
            ));
            got.sort_unstable();

            let mut want: Vec<u64> = series
                .iter()
                .filter(|s| has(s, &left.0, &left.1) && has(s, &right.0, &right.1))
                .map(|s| s.id)
                .collect();
            want.sort_unstable();

            assert_eq!(got, want, "{}={} ∩ {}={}", left.0, left.1, right.0, right.1);
        }
    }
}

#[test]
fn differences_match_the_series_without_the_pair() {
    let block = block();
    let series = all_series(&block);
    let all: Vec<u64> = series.iter().map(|s| s.id).collect();

    for (name, value) in pairs(&series) {
        let got = drain(difference(
            Box::new(block.index().all_postings().unwrap()),
            Box::new(block.index().postings(&name, &value).unwrap()),
        ));
        let want: Vec<u64> = series
            .iter()
            .filter(|s| !has(s, &name, &value))
            .map(|s| s.id)
            .collect();
        assert_eq!(got, want, "all \\ {name}={value}");

        // Subtracting a list from itself yields nothing.
        let empty = drain(difference(
            Box::new(block.index().postings(&name, &value).unwrap()),
            Box::new(block.index().postings(&name, &value).unwrap()),
        ));
        assert!(empty.is_empty(), "{name}={value} \\ itself");
    }
    assert_eq!(
        drain(difference(
            Box::new(block.index().all_postings().unwrap()),
            Box::new(block.index().all_postings().unwrap())
        ))
        .len(),
        0
    );
    assert_eq!(all.len(), series.len());
}

#[test]
fn unions_cover_every_value_of_a_label() {
    let block = block();
    let series = all_series(&block);
    let values = block.index().label_values("instance").unwrap();
    assert!(values.len() > 1, "fixture needs several instances");

    let parts = values
        .iter()
        .map(|v| Box::new(block.index().postings("instance", v).unwrap()) as Box<dyn Postings + '_>)
        .collect::<Vec<_>>();
    let got = drain(union_all(parts));

    let mut want: Vec<u64> = series
        .iter()
        .filter(|s| s.labels.iter().any(|(n, _)| n == "instance"))
        .map(|s| s.id)
        .collect();
    want.sort_unstable();
    assert_eq!(got, want);
}

#[test]
fn intersections_of_several_label_pairs_compose() {
    let block = block();
    let series = all_series(&block);
    let parts = vec![
        Box::new(block.index().postings("job", "fixture").unwrap()) as Box<dyn Postings + '_>,
        Box::new(block.index().postings("instance", "host-00").unwrap()),
        Box::new(block.index().postings("shard", "0").unwrap()),
    ];
    let got = drain(intersect_all(parts));

    let mut want: Vec<u64> = series
        .iter()
        .filter(|s| {
            has(s, "job", "fixture") && has(s, "instance", "host-00") && has(s, "shard", "0")
        })
        .map(|s| s.id)
        .collect();
    want.sort_unstable();
    assert_eq!(got, want);
    assert!(!want.is_empty(), "fixture must contain this combination");
}

#[test]
fn seek_walks_the_same_references_as_next() {
    let block = block();
    let all = drain(block.index().all_postings().unwrap());
    assert!(all.len() > 10);

    // Repeated seek must reproduce the filtered sequence exactly.
    let targets: Vec<u64> = (0..all.len() as u64 * 3).step_by(7).collect();
    let mut walked = Vec::new();
    let mut p = block.index().all_postings().unwrap();
    for target in &targets {
        match p.seek(*target).unwrap() {
            Some(v) => {
                assert!(v >= *target);
                walked.push(v);
            }
            None => break,
        }
    }
    // Oracle: skip to the first reference >= each target, then consume it.
    let mut expected = Vec::new();
    let mut idx = 0usize;
    for target in targets {
        while idx < all.len() && all[idx] < target {
            idx += 1;
        }
        if idx == all.len() {
            break;
        }
        expected.push(all[idx]);
        idx += 1;
    }
    assert_eq!(walked, expected);
}

#[test]
fn seek_on_an_intersection_lands_on_a_common_reference() {
    let block = block();
    let series = all_series(&block);
    let left = block
        .index()
        .postings("__name__", "fixture_metric_00")
        .unwrap();
    let right = block.index().postings("job", "fixture").unwrap();
    let mut plan = intersect(Box::new(left), Box::new(right));
    let mut got = Vec::new();
    while let Some(v) = plan.seek(got.last().map(|v| v + 1).unwrap_or(0)).unwrap() {
        assert!(has(
            series.iter().find(|s| s.id == v).unwrap(),
            "__name__",
            "fixture_metric_00"
        ));
        got.push(v);
    }
    let want: Vec<u64> = series
        .iter()
        .filter(|s| has(s, "__name__", "fixture_metric_00") && has(s, "job", "fixture"))
        .map(|s| s.id)
        .collect();
    assert_eq!(got, want);
}