tsdb-reader 0.2.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings lookups, tombstones
Documentation

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.2"

What it supports

Area Coverage
Index format v1, v2, v3 (Prometheus 2.x–3.x)
Chunk encodings XOR, XOR2, histogram, float histogram, and their ST variants
Histograms integer histograms with exact u64/i64 counts, float histograms, custom buckets, counter-reset hints, stale markers
Label lookups label names/values, postings lists, sorted unions, the all-series key
Tombstones v1, closed intervals, merged on load, applied by the sample iterator
Validation TOC/section bounds, series framing invariants, segment numbering, metadata cross-checks
Layout Prometheus data directory or a single block directory

What it does not support

  • chunks_head/ and the WAL — only persisted blocks.
  • A matcher/query engine: label lookups and postings lists are provided, but you combine them yourself (intersections, regexes and offset are caller code). Sequential export does not need them either — series are visited in lexicographic label order without touching the label index.
  • Writing blocks.
  • no_std or wasm32-unknown-unknown: the crate maps files with memmap2 and relies on std::fs.

Module layout

Module Responsibility Not responsible for
meta meta.json parsing and block discovery query execution
index TOC, symbols, series records, postings and label lookups, exact counts chunk decoding
chunks segment files, record framing, CRC32C sample decoding
chunkenc XOR/XOR2/histogram decoders, decode limits block deletion semantics
tombstones deletion intervals and lookups sample iteration
block wiring index + chunks + tombstones together PromQL
sample_iter cross-chunk iteration, range and tombstone filtering DuckDB writes
validation cross-file consistency checks payload decoding
storage mmap / owned-buffer abstraction business 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.

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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)?;
    }
}
# }
# Ok(())
# }

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.

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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)
        }
    }
}
# }
# Ok(())
# }

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.

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
use tsdb_reader::{BlockReader, 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.by_ref().count();

// Every series in the block (the empty key).
let all = index.all_postings()?.count();
# let _ = (count, all);
# }
# Ok(())
# }

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.

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:

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
use tsdb_reader::{BlockReader, 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
# }
# Ok(())
# }

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 three are enabled by default. default-features = false leaves only serde and thiserror, which the type definitions need.

Feature Default Pulls in Turn it off to
mmap on memmap2 drop the memory-mapping dependency and read segments into owned buffers
crc on crc32c skip checksum verification entirely and drop the CRC dependency
meta on serde_json drop JSON parsing and supply BlockMeta from your own store

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.

Discover and open

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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,
    );
}
# }
# Ok(())
# }

Threading model

ChunkReader is Send + Sync: chunk segments can be decoded from several threads at once (BlockReader::chunk_reader() or into_parts()). IndexReader and therefore BlockReader are Send but not Sync — the symbol cache is a RefCell, so index traversal must stay on one thread. A worker that needs its own iterator gets one from into_parts() and SampleIterator::new.

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).