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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Large-scale read benchmark: end-to-end throughput and peak RSS.
//!
//! A plain binary (`harness = false`), so it needs no bench-only dependency and
//! runs on stable:
//!
//! ```text
//! cargo bench --bench rss -- --series 50000
//! cargo bench --bench rss -- --series 50000 --json
//! ```
//!
//! Blocks are synthesised from the chunk payloads Prometheus wrote into
//! `tests/data/chunks.json`: one XOR2 float chunk and one integer histogram
//! chunk are copied into a new segment and referenced by many series. That
//! keeps the generator dependency-free while still decoding real payloads, and
//! it scales the series (and therefore sample) count without inflating the
//! chunk files.
//!
//! Reported metrics:
//!
//! - wall time and samples/s for a full [`BlockReader::samples`] pass,
//! - decoded samples/s per kind,
//! - peak RSS before/after, read from `/proc/self/status` (Linux) or `ps`
//!   (macOS). Mapped pages are counted once touched, so this is the resident
//!   cost a migration actually pays.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Instant;

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

/// Series records are padded to this boundary; postings reference `offset / 16`.
const SERIES_ALIGN: usize = 16;

#[derive(serde::Deserialize)]
struct ChunkFixture {
    name: String,
    encoding: String,
    bytes_hex: String,
    #[serde(default)]
    floats: Vec<SampleGt>,
    #[serde(default)]
    hists: Vec<SampleGt>,
}

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

struct Payload {
    encoding: u8,
    body: Vec<u8>,
    samples: u64,
    min_time: i64,
    max_time: i64,
}

fn main() {
    let cfg = Config::from_args();
    if cfg.help {
        println!("{}", Config::usage());
        return;
    }

    let float = payload("XOR2").expect("XOR2 fixture");
    let hist = payload("histogram").expect("histogram fixture");

    let dir = std::env::temp_dir().join(format!("tsdb-reader-bench-{}", std::process::id()));
    let build = Instant::now();
    for i in 0..cfg.blocks {
        write_block(&dir, i, &cfg, &float, &hist).expect("write block");
    }
    let build_secs = build.elapsed().as_secs_f64();

    let rss_before = peak_rss_kb();

    let start = Instant::now();
    let mut samples = 0u64;
    let mut floats = 0u64;
    let mut histograms = 0u64;
    let mut series_seen = 0u64;
    let mut chunk_mib = 0.0f64;
    let mut findings = 0usize;
    let mut postings_entries = 0u32;
    for i in 0..cfg.blocks {
        let block = BlockReader::open(&dir.join(format!("block-{i:03}")), ReaderOptions::default())
            .expect("open block");
        series_seen += block.scan_stats().expect("scan stats").series;
        chunk_mib += block.chunk_bytes() as f64 / (1024.0 * 1024.0);
        if cfg.validate {
            // Smoke check: a block we just wrote must validate with no findings.
            let report = block.validate().expect("validate block");
            findings += report.findings.len();
            for finding in &report.findings {
                eprintln!("  block {i}: {finding:?}");
            }
            if let Some(stats) = report.postings {
                postings_entries += stats.entries;
            }
        }
        let mut iter = block.samples(TimeRange::all());
        while let Some(sample) = iter.next_sample().expect("read sample") {
            samples += 1;
            match sample.value {
                SampleValue::Float(_) => floats += 1,
                SampleValue::IntHistogram(_) | SampleValue::FloatHistogram(_) => histograms += 1,
            }
        }
    }
    let secs = start.elapsed().as_secs_f64();
    let rss_after = peak_rss_kb();

    if cfg.json {
        println!(
            "{{\"blocks\":{},\"series\":{},\"samples\":{},\"floats\":{},\"histograms\":{},\
             \"seconds\":{secs:.3},\"samples_per_second\":{:.0},\"chunk_mib\":{chunk_mib:.2},\
             \"peak_rss_kb_before\":{rss_before},\"peak_rss_kb_after\":{rss_after},\
             \"rss_delta_kb\":{},\"validate_findings\":{findings},\
             \"postings_entries\":{postings_entries},\"build_seconds\":{build_secs:.3}}}",
            cfg.blocks,
            series_seen,
            samples,
            floats,
            histograms,
            samples as f64 / secs,
            rss_after.saturating_sub(rss_before),
        );
    } else {
        println!("blocks           {}", cfg.blocks);
        println!("series           {series_seen}");
        println!("samples          {samples} ({floats} float, {histograms} histogram)");
        println!("elapsed          {secs:.2}s");
        println!("throughput       {:.0} samples/s", samples as f64 / secs);
        println!("chunk payload    {chunk_mib:.2} MiB");
        if cfg.validate {
            println!("validation       {findings} finding(s), {postings_entries} postings entries");
        }
        println!("peak RSS before  {rss_before} KiB");
        println!("peak RSS after   {rss_after} KiB");
        println!(
            "peak RSS delta   {} KiB",
            rss_after.saturating_sub(rss_before)
        );
        println!("(block build took {build_secs:.2}s)");
        println!(
            "per-series cost  {:.1} KiB RSS",
            (rss_after.saturating_sub(rss_before)) as f64 / series_seen.max(1) as f64
        );
    }

    if cfg.keep {
        println!("kept {}", dir.display());
    } else {
        let _ = std::fs::remove_dir_all(&dir);
    }
}

/// Loads one chunk payload (body only, encoding stripped) from the fixtures.
fn payload(want: &str) -> Option<Payload> {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/chunks.json");
    let raw = std::fs::read_to_string(path).ok()?;
    let fixtures: Vec<ChunkFixture> = serde_json::from_str(&raw).ok()?;
    let fx = fixtures
        .into_iter()
        .find(|f| f.name.contains(want) || f.encoding == want)?;
    let body: Vec<u8> = (0..fx.bytes_hex.len() / 2)
        .map(|i| u8::from_str_radix(&fx.bytes_hex[i * 2..i * 2 + 2], 16).unwrap())
        .collect();
    let mut times: Vec<i64> = fx
        .floats
        .iter()
        .chain(fx.hists.iter())
        .map(|s| s.t)
        .collect();
    times.sort_unstable();
    Some(Payload {
        encoding: match fx.encoding.as_str() {
            "XOR" => 1,
            "histogram" => 2,
            "floathistogram" => 3,
            "XOR2" => 4,
            "histogramST" => 5,
            "floathistogramST" => 6,
            other => panic!("unknown fixture encoding {other}"),
        },
        samples: times.len() as u64,
        min_time: *times.first()?,
        max_time: *times.last()?,
        body,
    })
}

struct Config {
    blocks: usize,
    series: usize,
    /// Target size of distinct chunk payloads per block, in MiB.
    chunk_mib: usize,
    /// Run `BlockReader::validate` on every block (on by default).
    validate: bool,
    json: bool,
    keep: bool,
    help: bool,
}

impl Config {
    fn from_args() -> Self {
        let mut cfg = Self {
            blocks: 1,
            series: 20_000,
            chunk_mib: 16,
            validate: true,
            json: false,
            keep: false,
            help: false,
        };
        let mut args = std::env::args().skip(1);
        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--blocks" => cfg.blocks = parse(&mut args, "--blocks"),
                "--series" => cfg.series = parse(&mut args, "--series"),
                "--chunk-mib" => cfg.chunk_mib = parse(&mut args, "--chunk-mib"),
                "--no-validate" => cfg.validate = false,
                "--json" => cfg.json = true,
                "--keep" => cfg.keep = true,
                "--help" | "-h" => cfg.help = true,
                // Cargo passes its own flags through to harness=false benches.
                "--bench" => {}
                other => {
                    eprintln!("unknown argument {other}");
                    cfg.help = true;
                }
            }
        }
        cfg
    }

    fn usage() -> String {
        [
            "tsdb-reader read benchmark",
            "",
            "  --blocks N       blocks to generate (default 1)",
            "  --series N       series per block (default 20000)",
            "  --chunk-mib N    distinct chunk payload per block, MiB (default 16)",
            "  --no-validate    skip BlockReader::validate on each block",
            "  --json           emit one machine-readable line",
            "  --keep           keep the generated blocks",
            "",
            "Every tenth series carries the integer histogram chunk, the rest the",
            "XOR2 float chunk. Throughput is measured over a full SampleIterator",
            "pass with tombstone filtering and default decode limits.",
        ]
        .join("\n")
    }
}

fn parse(args: &mut impl Iterator<Item = String>, flag: &str) -> usize {
    args.next()
        .and_then(|v| v.parse().ok())
        .unwrap_or_else(|| panic!("{flag} expects a number"))
}

/// Writes one block: a segment holding the two payloads, then an index with
/// `series` records pointing at them.
fn write_block(
    root: &Path,
    index: usize,
    cfg: &Config,
    float: &Payload,
    hist: &Payload,
) -> std::io::Result<()> {
    let dir = root.join(format!("block-{index:03}"));
    std::fs::create_dir_all(dir.join("chunks"))?;

    // Segment: header, then `copies` records of each payload. Distinct copies
    // give the read pass distinct pages to fault in, so RSS and throughput are
    // not measured against a single cache-hot record.
    let target = cfg.chunk_mib * 1024 * 1024;
    let copies = (target / (float.body.len() + hist.body.len()).max(1)).max(1);
    let mut segment = Vec::new();
    segment.extend_from_slice(&0x85BD_40DDu32.to_be_bytes());
    segment.push(1);
    segment.extend_from_slice(&[0, 0, 0]);
    let mut float_offsets = Vec::with_capacity(copies);
    let mut hist_offsets = Vec::with_capacity(copies);
    for _ in 0..copies {
        float_offsets.push(segment.len() as u64);
        push_record(&mut segment, float);
        hist_offsets.push(segment.len() as u64);
        push_record(&mut segment, hist);
    }
    std::fs::write(dir.join("chunks/000001"), &segment)?;

    // Symbols.
    let mut symbols: Vec<String> = Vec::new();
    for s in 0..cfg.series {
        symbols.push("__name__".to_string());
        symbols.push(format!("bench_metric_{:04}", s % 50));
        symbols.push("job".to_string());
        symbols.push(format!("job-{}", s / 50));
        symbols.push("instance".to_string());
        symbols.push(format!("instance-{s:06}"));
    }
    symbols.sort();
    symbols.dedup();

    let mut file = Vec::new();
    file.extend_from_slice(&0xBAAA_D700u32.to_be_bytes());
    file.push(2);
    let symbols_off = file.len();
    let mut sym = Vec::new();
    for name in &symbols {
        put_uvarint(&mut sym, name.len() as u64);
        sym.extend_from_slice(name.as_bytes());
    }
    file.extend_from_slice(&((sym.len() + 4) as u32).to_be_bytes());
    file.extend_from_slice(&(symbols.len() as u32).to_be_bytes());
    file.extend_from_slice(&sym);
    let sym_crc = crc32c::crc32c(&file[symbols_off + 4..]);
    file.extend_from_slice(&sym_crc.to_be_bytes());
    while file.len() % 16 != 0 {
        file.push(0);
    }

    let series_off = file.len();
    let mut series_bytes = 0usize;
    // Label space: collect the series ids carrying each label pair, plus the
    // all-series key, so the block is structurally complete and validate() can
    // be exercised.
    let mut postings: BTreeMap<(String, String), Vec<u32>> = BTreeMap::new();
    for s in 0..cfg.series {
        let metric = format!("bench_metric_{:04}", s % 50);
        let job = format!("job-{}", s / 50);
        let instance = format!("instance-{s:06}");
        let labels = [
            ("__name__", metric.as_str()),
            ("job", job.as_str()),
            ("instance", instance.as_str()),
        ];
        let (payload, offset) = if s % 10 == 0 {
            (hist, hist_offsets[(s / 10) % copies])
        } else {
            (float, float_offsets[s % copies])
        };

        let mut body = Vec::new();
        put_uvarint(&mut body, labels.len() as u64);
        for (name, value) in labels {
            put_uvarint(
                &mut body,
                symbols.binary_search(&name.to_string()).unwrap() as u64,
            );
            put_uvarint(
                &mut body,
                symbols.binary_search(&value.to_string()).unwrap() as u64,
            );
        }
        put_uvarint(&mut body, 1); // one chunk
        put_varint(&mut body, payload.min_time);
        put_uvarint(&mut body, (payload.max_time - payload.min_time) as u64);
        put_uvarint(&mut body, offset);

        let record_off = file.len();
        let reference = (record_off / SERIES_ALIGN) as u32;
        put_uvarint(&mut file, body.len() as u64);
        file.extend_from_slice(&body);
        file.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
        while file.len() % 16 != 0 {
            file.push(0);
        }
        series_bytes += body.len();

        for (name, value) in labels {
            postings
                .entry((name.to_string(), value.to_string()))
                .or_default()
                .push(reference);
        }
        postings
            .entry((String::new(), String::new()))
            .or_default()
            .push(reference);
    }
    // Series section ends where the postings section starts, so the reader can
    // derive the boundary from the TOC alone.
    // Postings section: aligned lists, then the offset table.
    let postings_off = file.len();
    let mut table: Vec<(String, String, u64)> = Vec::with_capacity(postings.len());
    for ((name, value), refs) in &postings {
        while file.len() % 4 != 0 {
            file.push(0);
        }
        let list_off = file.len() as u64;
        let mut body = Vec::with_capacity(4 + refs.len() * 4);
        body.extend_from_slice(&(refs.len() as u32).to_be_bytes());
        for r in refs {
            body.extend_from_slice(&r.to_be_bytes());
        }
        file.extend_from_slice(&(body.len() as u32).to_be_bytes());
        file.extend_from_slice(&body);
        file.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
        table.push((name.clone(), value.clone(), list_off));
    }
    let table_off = file.len();
    let mut content = Vec::new();
    content.extend_from_slice(&(table.len() as u32).to_be_bytes());
    for (name, value, list_off) in &table {
        put_uvarint(&mut content, 2);
        put_uvarint(&mut content, name.len() as u64);
        content.extend_from_slice(name.as_bytes());
        put_uvarint(&mut content, value.len() as u64);
        content.extend_from_slice(value.as_bytes());
        put_uvarint(&mut content, *list_off);
    }
    let table_crc = crc32c::crc32c(&content);
    file.extend_from_slice(&(content.len() as u32).to_be_bytes());
    file.extend_from_slice(&content);
    file.extend_from_slice(&table_crc.to_be_bytes());

    let mut toc = Vec::new();
    toc.extend_from_slice(&(symbols_off as u64).to_be_bytes());
    toc.extend_from_slice(&(series_off as u64).to_be_bytes());
    // v2 stores label_indices and postings at the same offsets.
    toc.extend_from_slice(&(postings_off as u64).to_be_bytes());
    toc.extend_from_slice(&(table_off as u64).to_be_bytes());
    toc.extend_from_slice(&(postings_off as u64).to_be_bytes());
    toc.extend_from_slice(&(table_off as u64).to_be_bytes());
    let toc_crc = crc32c::crc32c(&toc);
    file.extend_from_slice(&toc);
    file.extend_from_slice(&toc_crc.to_be_bytes());
    std::fs::write(dir.join("index"), &file)?;

    let hist_series = cfg.series.div_ceil(10);
    let float_series = cfg.series - hist_series;
    let min_time = float.min_time.min(hist.min_time);
    let max_time = float.max_time.max(hist.max_time) + 1;
    let meta = format!(
        "{{\n\t\"ulid\": \"bench-{index:03}\",\n\t\"minTime\": {min_time},\n\t\"maxTime\": {max_time},\n\
         \t\"stats\": {{\"numSamples\": {}, \"numFloatSamples\": {}, \"numHistogramSamples\": {},\
         \"numSeries\": {}, \"numChunks\": {}}},\n\t\"compaction\": {{\"level\": 1}},\n\t\"version\": 1\n}}\n",
        float_series as u64 * float.samples + hist_series as u64 * hist.samples,
        float_series as u64 * float.samples,
        hist_series as u64 * hist.samples,
        cfg.series,
        cfg.series,
    );
    std::fs::write(dir.join("meta.json"), meta)?;

    let _ = series_bytes;
    Ok(())
}

/// Appends `len || encoding || body || crc` for one payload.
fn push_record(segment: &mut Vec<u8>, payload: &Payload) {
    put_uvarint(segment, payload.body.len() as u64);
    let start = segment.len();
    segment.push(payload.encoding);
    segment.extend_from_slice(&payload.body);
    let crc = crc32c::crc32c(&segment[start..]);
    segment.extend_from_slice(&crc.to_be_bytes());
}

fn put_uvarint(out: &mut Vec<u8>, mut v: u64) {
    loop {
        let mut b = (v & 0x7f) as u8;
        v >>= 7;
        if v != 0 {
            b |= 0x80;
        }
        out.push(b);
        if v == 0 {
            break;
        }
    }
}

fn put_varint(out: &mut Vec<u8>, v: i64) {
    put_uvarint(out, ((v << 1) ^ (v >> 63)) as u64);
}

/// Peak resident set size in KiB.
///
/// `getrusage(RUSAGE_SELF)` reports the high-water mark since process start,
/// which is what a migration job is usually budgeted against. Linux returns
/// KiB, macOS bytes; both are normalised to KiB here. Returns 0 when the
/// platform has no `getrusage`.
fn peak_rss_kb() -> u64 {
    #[cfg(unix)]
    {
        // SAFETY: `getrusage` only writes into the struct we hand it, and
        // `ru_maxrss` is a plain integer field.
        let mut usage: libc::rusage = unsafe { std::mem::zeroed() };
        if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut usage) } != 0 {
            return 0;
        }
        let max = usage.ru_maxrss as u64;
        if cfg!(target_os = "macos") {
            max / 1024
        } else {
            max
        }
    }
    #[cfg(not(unix))]
    {
        0
    }
}