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
//! End-to-end sample iteration over the vendored block: ordering, range
//! filtering, tombstones and histogram kinds.

use std::collections::HashMap;
use std::path::PathBuf;

use tsdb_reader::sample_iter::{SampleIterOptions, SampleIterator, SampleValue, TimeRange};
use tsdb_reader::{BlockReader, 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()
}

#[derive(serde::Deserialize)]
struct FloatGt {
    t: i64,
}

#[derive(serde::Deserialize)]
struct HistGt {
    t: i64,
}

#[derive(serde::Deserialize)]
struct SeriesGt {
    #[serde(default)]
    floats: Vec<FloatGt>,
    #[serde(default)]
    hists: Vec<HistGt>,
}

#[derive(serde::Deserialize)]
struct BlockGt {
    series: Vec<SeriesGt>,
}

fn ground_truth() -> BlockGt {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/block/ground_truth.json");
    serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}

/// Sums the ground-truth samples that survive the tombstone filter.
fn expected_counts(block: &BlockReader) -> (u64, u64) {
    let gt = ground_truth();
    let mut floats = 0u64;
    let mut hists = 0u64;
    // Ground truth is ordered like the index, so the nth series lines up.
    for (series, gt) in block.series(0).zip(gt.series.iter()) {
        let series = series.unwrap();
        let intervals = block.tombstones().intervals(series.id);
        for f in &gt.floats {
            if !tsdb_reader::tombstones::is_deleted(intervals, f.t) {
                floats += 1;
            }
        }
        for h in &gt.hists {
            if !tsdb_reader::tombstones::is_deleted(intervals, h.t) {
                hists += 1;
            }
        }
    }
    (floats, hists)
}

#[test]
fn iteration_matches_the_ground_truth_with_tombstones_applied() {
    let block = block();
    let (want_floats, want_hists) = expected_counts(&block);

    let mut floats = 0u64;
    let mut hists = 0u64;
    let mut iter = block.samples(TimeRange::all());
    while let Some(sample) = iter.next_sample().unwrap() {
        match sample.value {
            SampleValue::Float(_) => floats += 1,
            SampleValue::IntHistogram(_) | SampleValue::FloatHistogram(_) => hists += 1,
        }
    }
    assert_eq!(floats, want_floats, "float samples after tombstones");
    assert_eq!(hists, want_hists, "histogram samples after tombstones");
    // The fixture has deletions, so filtering must have removed something.
    assert!(
        iter.samples_filtered() > 0,
        "fixture should exercise tombstone filtering"
    );
    assert_eq!(iter.samples_emitted(), floats + hists);
}

#[test]
fn tombstones_can_be_kept_when_asked() {
    let block = block();
    let all = block.meta().stats.num_float_samples + block.meta().stats.num_histogram_samples;

    let mut iter = block.samples_with(SampleIterOptions {
        skip_deleted: false,
        ..SampleIterOptions::default()
    });
    let mut count = 0u64;
    while iter.next_sample().unwrap().is_some() {
        count += 1;
    }
    assert_eq!(count, all, "every stored sample must be exported");
    assert_eq!(iter.samples_filtered(), 0);

    let blocked = block.samples(TimeRange::all());
    let mut iter = blocked;
    let mut kept = 0u64;
    while iter.next_sample().unwrap().is_some() {
        kept += 1;
    }
    assert!(kept < count, "the fixture must have deleted samples");
}

#[test]
fn timestamps_never_go_backwards_within_a_series() {
    let block = block();
    let mut iter = block.samples(TimeRange::all());
    let mut last: HashMap<u64, i64> = HashMap::new();
    let mut samples = 0u64;
    while let Some(sample) = iter.next_sample().unwrap() {
        let id = sample.series.id;
        if let Some(prev) = last.insert(id, sample.timestamp) {
            assert!(
                sample.timestamp >= prev,
                "series {} went back from {prev} to {}",
                sample.series.id,
                sample.timestamp
            );
        }
        samples += 1;
    }
    assert_eq!(samples, iter.samples_emitted());
}

#[test]
fn a_sub_range_selects_exactly_the_samples_inside_it() {
    let block = block();
    // The fixture clusters its samples at the start and end of the block, so
    // the window is taken right after the first timestamp.
    let (start, end) = (1_700_000_000_000i64, 1_700_000_060_000i64);
    let range = TimeRange::new(start, end);

    let mut expected = 0u64;
    let mut iter = block.samples(TimeRange::all());
    while let Some(sample) = iter.next_sample().unwrap() {
        if range.contains(sample.timestamp) {
            expected += 1;
        }
    }

    let mut got = 0u64;
    let mut iter = block.samples(range);
    while let Some(sample) = iter.next_sample().unwrap() {
        assert!(range.contains(sample.timestamp), "{}", sample.timestamp);
        got += 1;
    }
    assert_eq!(got, expected);
    assert!(got > 0, "the range must select something");
    assert!(
        iter.samples_filtered() > 0,
        "the range must exclude the samples outside it"
    );
}

#[test]
fn a_range_only_decodes_the_chunks_it_touches() {
    let block = block();
    // The fixture clusters its samples at the start and end of the block, so a
    // window right after the first timestamp sees only the first chunks.
    let range = TimeRange::new(1_700_000_000_000, 1_700_000_020_000);

    // Expected: number of chunks of every series that overlap the range.
    let expected: u64 = block
        .series(0)
        .map(|s| {
            let s = s.unwrap();
            s.chunks_in_range(range).count() as u64
        })
        .sum();

    let mut iter = block.samples(range);
    let mut seen = 0u64;
    while iter.next_sample().unwrap().is_some() {
        seen += 1;
    }
    assert!(seen > 0);
    assert_eq!(
        iter.chunks_decoded(),
        expected,
        "only chunks overlapping the range may be decoded"
    );
    let total: usize = block.series(0).map(|s| s.unwrap().chunks.len()).sum();
    assert!(
        expected < total as u64,
        "the range must narrow the chunk set"
    );
}

#[test]
fn an_empty_range_decodes_nothing() {
    let block = block();
    let mut iter = block.samples(TimeRange::new(5, 5));
    assert!(iter.next_sample().unwrap().is_none());
    assert_eq!(iter.chunks_decoded(), 0);
    assert_eq!(iter.samples_emitted(), 0);
}

#[test]
fn histogram_samples_keep_exact_integer_counts() {
    let block = block();
    let mut iter = block.samples(TimeRange::all());
    let mut seen = 0;
    while let Some(sample) = iter.next_sample().unwrap() {
        if let SampleValue::IntHistogram(h) = sample.value {
            seen += 1;
            // Fixture counts are small, but the type must be exact: a u64
            // survives a round trip while the f64 view would too only because
            // the values are tiny.
            assert_eq!(h.count as f64 as u64, h.count);
            assert_eq!(h.pos_counts.len(), h.pos_deltas.len());
            let mut acc = 0i64;
            for d in h.pos_deltas {
                acc += *d;
            }
            if let Some(last) = h.pos_counts.last() {
                assert_eq!(acc, *last);
            }
        }
    }
    assert!(seen > 0, "fixture contains integer histograms");
}

#[test]
fn parts_can_be_used_to_build_independent_iterators() {
    let block = block();
    let (index, chunks, tombstones, _info) = block.into_parts();
    let opts = SampleIterOptions::default();
    let mut a = SampleIterator::new(&index, &chunks, &tombstones, opts.clone());
    let mut b = SampleIterator::new(&index, &chunks, &tombstones, opts);

    let mut count = 0u64;
    while let Some(sample) = a.next_sample().unwrap() {
        assert!(!sample.series.labels.is_empty());
        count += 1;
    }
    assert!(count > 0);
    assert_eq!(a.index().version(), 2);
    // A second iterator over the same parts sees the same stream.
    let mut other = 0u64;
    while b.next_sample().unwrap().is_some() {
        other += 1;
    }
    assert_eq!(count, other);
}

#[test]
fn decode_errors_carry_the_series_and_chunk() {
    // A chunk that declares 65535 samples but holds none: swap the segment for
    // one record so iteration surfaces a contextual decode error.
    let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/data/block")
        .join(ULID);
    let tmp = std::env::temp_dir().join(format!(
        "tsdb-reader-iter-ctx-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(tmp.join("chunks")).unwrap();
    std::fs::copy(dir.join("index"), tmp.join("index")).unwrap();
    std::fs::copy(dir.join("meta.json"), tmp.join("meta.json")).unwrap();
    let mut segment = vec![0x85, 0xBD, 0x40, 0xDD, 1, 0, 0, 0];
    // One XOR record: len=2, encoding=1, header claims 65535 samples.
    segment.extend_from_slice(&[2, 1, 0xff, 0xff]);
    segment.extend_from_slice(&crc32c::crc32c(&[1, 0xff, 0xff]).to_be_bytes());
    std::fs::write(tmp.join("chunks/000001"), segment).unwrap();

    let block = BlockReader::open(&tmp, ReaderOptions::default()).unwrap();
    let mut iter = block.samples(TimeRange::all());
    let error = iter.next_sample().expect_err("decode must fail");
    let message = error.to_string();
    assert!(message.contains("series "), "{message}");
    assert!(message.contains("chunk 0"), "{message}");
    assert!(error.is_corruption(), "{message}");
    std::fs::remove_dir_all(&tmp).unwrap();
}