Skip to main content

Crate tsdb_reader

Crate tsdb_reader 

Source
Expand description

§tsdb-reader

A read-only, zero-copy, memory-efficient Prometheus TSDB block reader written in Rust.

The crate reads persisted blocks and nothing else: it does not write, does not run queries, and does not depend on a query engine or a storage engine. That makes it usable as the bottom layer of a migration tool, an exporter to Parquet/DuckDB, a PromQL series source, or any other consumer that needs the bytes Prometheus wrote.

§Goals

  1. Correctness — every format detail of a Prometheus block is preserved: index v1/v2/v3, all chunk encodings, integer and float histograms with exact counts, tombstone intervals, stale markers.
  2. Efficiency — mmap-backed reads, lazy iteration and bounded memory: a block larger than RAM streams at a constant footprint.
  3. Reusability — no DuckDB, Arrow or PromQL in here. Downstream crates can depend on this one without inheriting anything.

§Install

[dependencies]
tsdb-reader = "0.3"

§What it supports

AreaCoverage
Index formatv1, v2, v3 (Prometheus 2.x–3.x)
Chunk encodingsXOR, XOR2, histogram, float histogram, and their ST variants
Histogramsinteger histograms with exact u64/i64 counts, float histograms, custom buckets, counter-reset hints, stale markers
Label lookupslabel names/values, postings lists, sorted unions, the all-series key
Matchers=, !=, =~, !~ with Prometheus’ anchoring, dotall and missing-label semantics
Set operationspostings intersection, union and difference, lazy and seek-aware
Tombstonesv1, closed intervals, merged on load, applied by the sample iterator
ValidationTOC/section bounds, series framing invariants, segment numbering, metadata cross-checks
LayoutPrometheus data directory or a single block directory

§What it does not support

  • chunks_head/ and the WAL — only persisted blocks.
  • A query engine: matchers compile to postings plans, but there is no PromQL parser, no expression evaluation and no offset handling — that belongs to a query layer. Sequential export does not need any of it either: series are visited in lexicographic label order without touching the label index.
  • Multi-block access: one reader is one immutable block. Selecting blocks, merging equal label sets across blocks and resolving overlapping ranges is a higher layer (tsdb-blockset in the design), deliberately not in this crate.
  • Writing blocks.
  • no_std or wasm32-unknown-unknown: the crate maps files with memmap2 and relies on std::fs.

§Module layout

ModuleResponsibilityNot responsible for
metameta.json parsing and block discoveryquery execution
indexTOC, symbols, series records, exact countschunk decoding
index::postings / postings_ops / matcherpostings lists, set operations, matcher plansPromQL
chunkssegment files, record framing, CRC32Csample decoding
chunks::rangechunk selection by time rangesample filtering
chunkencXOR/XOR2/histogram decoders, decode limitsblock deletion semantics
tombstonesdeletion intervals and lookupssample iteration
blockwiring index + chunks + tombstones togetherPromQL
sample_itercross-chunk iteration, range and tombstone filteringDuckDB writes
time_rangehalf-open ranges shared by the index and chunk layersPromQL windows
validationcross-file consistency checkspayload decoding
storagemmap / owned-buffer abstractionbusiness logic

§Two API levels

Low level — walk series, fetch a chunk, decode it into your own sink. Use this when you want to batch a whole chunk, or to reorder work across threads.

use std::path::Path;
use tsdb_reader::chunkenc::{
    self, FloatHistogramSample, IntHistogramSample, SampleSink,
};
use tsdb_reader::{BlockReader, ReaderOptions};

#[derive(Default)]
struct PrintSink;
impl SampleSink for PrintSink {
    fn push_float(&mut self, ts: i64, value: f64) {
        println!("{ts} {value}");
    }
    fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
        println!("{} histogram count={}", h.ts, h.count);
    }
    fn push_float_histogram(&mut self, _h: &FloatHistogramSample<'_>) {}
}

let block = BlockReader::open(
    Path::new("/data/01ARZ3NDEKTSV4RRFFQ69G5FAV"),
    ReaderOptions::default(),
)?;
let mut sink = PrintSink;

for series in block.series(0) {
    let series = series?;
    for chunk in &series.chunks {
        let slice = block.chunk(chunk)?;
        chunkenc::decode(slice.encoding, slice.data, &mut sink)?;
    }
}

High level — SampleIterator does the traversal for you: series in index order, chunks in time order, tombstones applied, one chunk in memory at a time.

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

let block = BlockReader::open(
    "/data/01ARZ3NDEKTSV4RRFFQ69G5FAV".as_ref(),
    ReaderOptions::default(),
)?;

let mut iter = block.samples(TimeRange::new(1_700_000_000_000, 1_700_003_600_000));
while let Some(sample) = iter.next_sample()? {
    match sample.value {
        SampleValue::Float(v) => {
            println!("{} {} {}", sample.timestamp, sample.series.metric_name().unwrap_or(""), v)
        }
        SampleValue::IntHistogram(h) => {
            println!("{} histogram count={}", sample.timestamp, h.count)
        }
        SampleValue::FloatHistogram(h) => {
            println!("{} float histogram count={}", sample.timestamp, h.count)
        }
    }
}

A complete, working POC implementation can be found at https://github.com/zhuyanxi/migrate-tsdb.

§Label lookups

Postings are served from a sampled view of the offset table: the table is parsed on first use, keeping entry 0 and every 32nd entry of each label name plus the last one, and a lookup walks forward from the preceding sample. That keeps memory proportional to distinct_values / 32 instead of one string per label value, while lookups stay a short scan.

use tsdb_reader::{BlockReader, Postings, ReaderOptions};

let block = BlockReader::open(
    "/data/01ARZ3NDEKTSV4RRFFQ69G5FAV".as_ref(),
    ReaderOptions::default(),
)?;
let index = block.index();

for name in index.label_names()? {
    let values = index.label_values(&name)?;
    println!("{name}: {} values", values.len());
}

// One label pair: ascending series references.
let mut postings = index.postings("job", "api")?;
while let Some(reference) = postings.next()? {
    let series = index.series_by_ref(reference)?;
    println!("{reference}: {}", series.metric_name().unwrap_or(""));
}

// Union, as a `label=~"a|b"` matcher would build it; sorted and deduplicated.
let mut union = index.postings_multi("job", &["api", "worker"])?;
let count = union.collect_refs()?.len();

// Every series in the block (the empty key).
let all = index.all_postings()?.collect_refs()?.len();

IndexReader::validate_postings walks the table and every list, checking framing, CRCs and strictly increasing references; BlockReader::validate runs it as part of its report.

§Query building blocks

A query layer compiles its matchers into a LabelMatcher list, gets one lazy postings source, and iterates the selected series — no intermediate set is materialised:

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

let block = BlockReader::open(
    "/data/01ARZ3NDEKTSV4RRFFQ69G5FAV".as_ref(),
    ReaderOptions::default(),
)?;

// {job="api", instance=~"host-0[0-2]", shard!="canary"}
let matchers = [
    LabelMatcher::equal("job", "api"),
    LabelMatcher::regex("instance", "host-0[0-2]"),
    LabelMatcher::not_equal("shard", "canary"),
];

let mut postings = block.index().postings_for_matchers(&matchers)?;
while let Some(reference) = postings.next()? {
    let series = block.index().series_by_ref(reference)?;
    // Only the chunks that can hold samples for this window are decoded.
    let mut iter = block.samples(TimeRange::new(1_700_000_000_000, 1_700_003_600_000));
    let _ = (&series, &mut iter);
}

Details that are easy to get wrong, and are covered by the differential tests: =~/!~ are fully anchored with the dotall flag (Prometheus’ ^(?s:expr)$), and a missing label is the empty string, so {foo=""} selects series without foo. SeriesRef::chunks_in_range narrows a series to the chunks overlapping a window; per-sample filtering still happens in SampleIterator.

The regex engine lives behind the regex feature. Without it the equality matchers keep working and =~/!~ report Error::Unsupported.

§Bounded decoding

Every count a chunk declares (samples, spans, buckets, custom bounds) comes from the file, so chunkenc::DecodeLimits caps all of them before anything is allocated. Defaults accept anything Prometheus writes; use chunkenc::decode_with_limits to tighten them for untrusted input or widen them for unusual blocks, and DecodeLimits::UNLIMITED only for data you already trust.

§Validating a block

Opening a block validates each file on its own. BlockReader::validate cross-checks them and returns a report with warning/error findings:

use tsdb_reader::{BlockReader, Postings, ReaderOptions};

let block = BlockReader::open(
    "/data/01ARZ3NDEKTSV4RRFFQ69G5FAV".as_ref(),
    ReaderOptions::default(),
)?;
let report = block.validate()?;
for finding in &report.findings {
    eprintln!("{finding:?}");
}
report.into_result()?; // fail on any finding, warnings included

It checks TOC section bounds and ordering, the series framing invariants (alignment, payload bounds, monotonic chunk times and references), the postings table and every postings list, segment numbering and record tiling, meta.json stats against an index scan, every chunk reference against its segment, and tombstone references/intervals.

Note that meta.json’s version is the meta format version (Prometheus always writes 1); the index format version lives in the index header and is exposed as IndexReader::version.

§Cargo features

All four are enabled by default. default-features = false leaves only serde and thiserror, which the type definitions need.

FeatureDefaultPulls inTurn it off to
mmaponmemmap2drop the memory-mapping dependency and read segments into owned buffers
crconcrc32cskip checksum verification entirely and drop the CRC dependency
metaonserde_jsondrop JSON parsing and supply BlockMeta from your own store
regexonregexdrop the regex engine; =~/!~ then report Error::Unsupported

The features are independent: any combination compiles and is tested in CI.

What changes without them:

  • mmap off — IndexReader::open and ChunkReader::open read files into memory instead of mapping them. IndexReader::from_bytes and ChunkReader::from_segments accept buffers either way, so object-store and in-memory pipelines are unaffected. IndexReader::from_mmap only exists with the feature on.
  • crc off — ReaderOptions::verify_crc and the verify_crc arguments become no-ops; Error::Checksum is never produced. Corrupt data then surfaces as a parse error, or not at all.
  • meta off — read_meta, discover_blocks and BlockReader::open are not compiled. Use BlockReader::open_with_meta(path, meta, opts) or BlockReader::open_info(info, opts) instead.
  • regex off — the regex crate is not linked. LabelMatcher::matches and postings_for_matchers return Error::Unsupported for =~/!~; equality matchers are unaffected.

§Discover and open

use std::path::Path;
use tsdb_reader::{BlockReader, ReaderOptions, discover_blocks};

let blocks = discover_blocks(Path::new("/var/lib/prometheus/data"))?;

for info in &blocks {
    let block = BlockReader::open(&info.path, ReaderOptions::default())?;
    println!(
        "{}: {} series, {} chunks, {}..{}",
        block.block_id(),
        block.meta().stats.num_series,
        block.meta().stats.num_chunks,
        block.meta().min_time,
        block.meta().max_time,
    );
}

§Threading model

BlockReader (and IndexReader, ChunkReader, Tombstones) are Send + Sync: one reader can be shared by many query threads. All mutable state belongs to the iterators — each SeriesIter owns its cursor and its own symbol cache, and each SampleIterator owns its decode buffer — so iterators are Send and can migrate between threads but are not shared.

The only shared lazily-initialised state is the sampled postings offset table, which is built once through a OnceLock and read-only afterwards. Symbol lookups therefore never touch a lock: an iterator’s cache is private to it.

§Verification

  • tests/data holds golden fixtures generated by the upstream Prometheus implementation (fixtures/gen): a block, one chunk fixture per encoding, and a second block written through Prometheus’ chunk/index/tombstone writers with a full reference dump.
  • tests/differential.rs compares labels, series references, every sample (bit-exact for floats, exact u64/i64 for integer histograms) and every tombstone interval against that dump.
  • tests/robustness.rs truncates and bit-flips every fixture and requires an error instead of a panic; fuzz/ has cargo-fuzz targets for the same paths.
  • benches/rss.rs reports throughput and peak RSS for a full read pass.
cargo test
cargo bench --bench rss -- --series 50000 --json

§License

MIT — see the LICENSE file.

The chunk decoders in src/chunkenc/ are a Rust port of Prometheus’ TSDB encoders and stay under the Apache License 2.0 (see LICENSE-APACHE and NOTICE for the exact file list and attribution).

Re-exports§

pub use block::BlockReader;
pub use block::ReaderOptions;
pub use chunkenc::CounterResetHint;
pub use chunkenc::FloatHistogramSample;
pub use chunkenc::HistogramKind;
pub use chunkenc::IntHistogramSample;
pub use chunkenc::SampleSink;
pub use chunkenc::Span;
pub use chunks::ChunkReader;
pub use chunks::ChunkSlice;
pub use error::Error;
pub use error::Result;
pub use index::BoxPostings;
pub use index::ChunkMeta;
pub use index::Difference;
pub use index::IndexReader;
pub use index::IndexStats;
pub use index::Intersection;
pub use index::LabelIndexReader;
pub use index::LabelMatcher;
pub use index::MatchType;
pub use index::MergedPostings;
pub use index::Postings;
pub use index::PostingsList;
pub use index::PostingsStats;
pub use index::SeriesIter;
pub use index::SeriesRef;
pub use index::Union;
pub use index::VecPostings;
pub use meta::discover_blocks;
pub use meta::BlockInfo;
pub use meta::BlockMeta;
pub use meta::BlockStats;
pub use sample_iter::Sample;
pub use sample_iter::SampleIterOptions;
pub use sample_iter::SampleIterator;
pub use sample_iter::SampleValue;
pub use time_range::TimeRange;
pub use tombstones::Tombstones;
pub use validation::Finding;
pub use validation::Severity;
pub use validation::ValidationReport;

Modules§

block
A single TSDB block: index + chunk segments + tombstones.
chunkenc
Chunk encoding dispatch and shared sample types.
chunks
Chunk segment access.
error
Error type shared by every parser in the crate.
index
Prometheus TSDB index reader (format v1/v2/v3).
meta
Block discovery and meta.json parsing.
sample_iter
Lazy, tombstone-aware sample iteration across series and chunks.
time_range
Half-open time ranges.
tombstones
Tombstones reader.
validation
Block-level consistency checks.
varint
Go-compatible varint decoding (binary.PutUvarint / PutVarint).