# 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
```toml
[dependencies]
tsdb-reader = "0.3"
```
## What it supports
| 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 |
| Matchers | `=`, `!=`, `=~`, `!~` with Prometheus' anchoring, dotall and missing-label semantics |
| Set operations | postings intersection, union and difference, lazy and seek-aware |
| 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 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
| `meta` | `meta.json` parsing and block discovery | query execution |
| `index` | TOC, symbols, series records, exact counts | chunk decoding |
| `index::postings` / `postings_ops` / `matcher` | postings lists, set operations, matcher plans | PromQL |
| `chunks` | segment files, record framing, CRC32C | sample decoding |
| `chunks::range` | chunk selection by time range | sample filtering |
| `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 |
| `time_range` | half-open ranges shared by the index and chunk layers | PromQL windows |
| `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.
```rust,no_run
# 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.
```rust,no_run
# 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.
```rust,no_run
# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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();
# 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.
## 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:
```rust,no_run
# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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);
}
# }
# Ok(())
# }
```
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:
```rust,no_run
# fn main() -> Result<(), Box<dyn std::error::Error>> {
# #[cfg(feature = "meta")]
# {
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
# }
# 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 four are enabled by default. `default-features = false` leaves only `serde`
and `thiserror`, which the type definitions need.
| `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 |
| `regex` | on | `regex` | drop 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
```rust,no_run
# 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
`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.
```sh
cargo test
cargo bench --bench rss -- --series 50000 --json
```
## License
MIT — see the [LICENSE file](https://github.com/zhuyanxi/tsdb-reader/blob/main/LICENSE).
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).