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
//! Concurrent reads: the reader is shared, every cursor is private.
//!
//! `BlockReader` must be `Send + Sync` so a query layer can hand one reader to
//! several worker threads. Each thread builds its own iterators; the only
//! shared mutable state is the lazily built postings table, which is
//! initialised once and then read-only.

use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::thread;

use tsdb_reader::{BlockReader, LabelMatcher, Postings, ReaderOptions, SampleValue, TimeRange};

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()
}

/// Compile-time proof that the reader can be shared.
fn assert_send_sync<T: Send + Sync>() {}

#[test]
fn the_reader_is_send_and_sync() {
    assert_send_sync::<BlockReader>();
    assert_send_sync::<tsdb_reader::IndexReader>();
    assert_send_sync::<tsdb_reader::ChunkReader>();
    assert_send_sync::<tsdb_reader::Tombstones>();
    // An iterator is movable across threads (each thread owns one).
    fn assert_send<T: Send>() {}
    assert_send::<tsdb_reader::SeriesIter<'static>>();
    assert_send::<tsdb_reader::SampleIterator<'static>>();
}

#[test]
fn many_threads_share_one_reader() {
    let block = Arc::new(block());
    let total_samples = AtomicU64::new(0);
    let total_series = AtomicU64::new(0);

    // Each thread performs the full mix: sequential scan, label lookup, sample
    // iteration. All of them share the same reader.
    thread::scope(|scope| {
        for worker in 0..8 {
            let block = Arc::clone(&block);
            let total_samples = &total_samples;
            let total_series = &total_series;
            scope.spawn(move || {
                let mut series = 0u64;
                for s in block.series(0) {
                    let s = s.unwrap();
                    // Resolving labels goes through the per-iterator cache.
                    assert!(!s.labels.is_empty());
                    series += 1;
                }

                // Lookups build (or reuse) the shared postings table.
                let mut postings = block
                    .index()
                    .postings_for_matchers(&[LabelMatcher::equal("job", "fixture")])
                    .unwrap();
                let mut refs = 0u64;
                while postings.next().unwrap().is_some() {
                    refs += 1;
                }
                assert_eq!(refs, 42, "worker {worker}");

                // A private sample iterator per thread.
                let mut samples = 0u64;
                let mut histograms = 0u64;
                let mut iter = block.samples(TimeRange::all());
                while let Some(sample) = iter.next_sample().unwrap() {
                    match sample.value {
                        SampleValue::Float(_) => {}
                        SampleValue::IntHistogram(_) | SampleValue::FloatHistogram(_) => {
                            histograms += 1
                        }
                    }
                    samples += 1;
                }
                assert!(histograms <= samples);

                total_series.fetch_add(series, Ordering::Relaxed);
                total_samples.fetch_add(samples, Ordering::Relaxed);
            });
        }
    });

    let series = total_series.load(Ordering::Relaxed);
    let samples = total_samples.load(Ordering::Relaxed);
    assert_eq!(series, 42 * 8, "every worker must see every series");
    assert!(samples > 0);
    // Identical work per worker: the total must be a clean multiple.
    assert_eq!(samples % 8, 0, "workers disagree about the sample stream");
}

#[test]
fn iterators_created_on_one_thread_can_move_to_another() {
    let block = block();
    let mut series = block.series(0);
    let first = series.next().unwrap().unwrap();

    thread::scope(|scope| {
        // The iterator (and its symbol cache) moves into the worker.
        let handle = scope.spawn(move || {
            let mut count = 1u64;
            while series.next().transpose().unwrap().is_some() {
                count += 1;
            }
            count
        });
        assert_eq!(handle.join().unwrap(), 42);
    });

    assert_eq!(first.labels.len(), 2);
    // The reader is still usable afterwards.
    assert_eq!(block.scan_stats().unwrap().series, 42);
}

#[test]
fn concurrent_lookups_agree() {
    let block = Arc::new(block());
    let names = block.index().label_names().unwrap();
    assert!(!names.is_empty());

    let results: Vec<Vec<u64>> = thread::scope(|scope| {
        let handles: Vec<_> = (0..6)
            .map(|_| {
                let block = Arc::clone(&block);
                let names = names.clone();
                scope.spawn(move || {
                    let mut out = Vec::new();
                    for name in &names {
                        for value in block.index().label_values(name).unwrap() {
                            let mut p = block.index().postings(name, &value).unwrap();
                            while let Some(v) = p.next().unwrap() {
                                out.push(v);
                            }
                        }
                    }
                    out
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });

    for window in results.windows(2) {
        assert_eq!(window[0], window[1], "lookups must be deterministic");
    }
}