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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Differential test against a block written by Prometheus itself.
//!
//! `tests/data/diff` holds a block produced by `fixtures/gen` through
//! Prometheus' `BlockWriter` (so index, chunk segment, tombstones and
//! meta.json all come from the reference implementation) plus
//! `reference.json`: every series, sample and deletion interval read back
//! through Prometheus' index/chunk/tombstone readers.
//!
//! Everything below therefore compares our reader against Go, not against a
//! hand-written expectation.

use std::collections::HashMap;
use std::path::PathBuf;

use tsdb_reader::chunkenc::{
    self, CounterResetHint, FloatHistogramSample, IntHistogramSample, SampleSink, Span,
};
use tsdb_reader::{BlockReader, Postings, ReaderOptions, SampleValue, TimeRange};

#[derive(serde::Deserialize, Debug)]
struct RefIndex {
    names: Vec<String>,
    values: std::collections::HashMap<String, Vec<String>>,
    postings: Vec<RefPostings>,
    all_postings: Vec<u64>,
}

#[derive(serde::Deserialize, Debug)]
struct RefPostings {
    name: String,
    value: String,
    refs: Vec<u64>,
}

#[derive(serde::Deserialize, Debug)]
struct RefBlock {
    ulid: String,
    min_time: i64,
    max_time: i64,
    num_series: u64,
    num_chunks: u64,
    num_float_samples: u64,
    num_histogram_samples: u64,
    series: Vec<RefSeries>,
    index: RefIndex,
}

#[derive(serde::Deserialize, Debug)]
struct RefSeries {
    key: String,
    labels: Vec<(String, String)>,
    series_id: u64,
    floats: Vec<RefFloat>,
    int_hists: Vec<IntSampleRef>,
    float_hists: Vec<FloatSampleRef>,
    tombstones: Vec<(i64, i64)>,
}

#[derive(serde::Deserialize, Debug)]
struct RefFloat {
    t: i64,
    bits: u64,
}

#[derive(serde::Deserialize, Debug, Clone)]
struct SpanRef {
    offset: i32,
    length: u32,
}

#[derive(serde::Deserialize, Debug)]
struct IntSampleRef {
    t: i64,
    count: u64,
    zero_count: u64,
    sum_bits: u64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<SpanRef>,
    neg_spans: Vec<SpanRef>,
    pos_deltas: Vec<i64>,
    neg_deltas: Vec<i64>,
    pos_counts: Vec<i64>,
    neg_counts: Vec<i64>,
    chunk_reset_hint: u8,
    counter_reset_hint: u8,
}

#[derive(serde::Deserialize, Debug)]
struct FloatSampleRef {
    t: i64,
    count: f64,
    zero_count: f64,
    sum_bits: u64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<SpanRef>,
    neg_spans: Vec<SpanRef>,
    pos_buckets: Vec<f64>,
    neg_buckets: Vec<f64>,
    chunk_reset_hint: u8,
    counter_reset_hint: u8,
}

fn diff_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/data/diff")
}

fn reference() -> RefBlock {
    let path = diff_dir().join("reference.json");
    let raw = std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("{}: {e}; run fixtures/gen", path.display()));
    serde_json::from_str(&raw).expect("reference.json parses")
}

fn block(refb: &RefBlock) -> BlockReader {
    BlockReader::open(&diff_dir().join(&refb.ulid), ReaderOptions::default()).unwrap()
}

fn canonical(labels: &[(std::sync::Arc<str>, std::sync::Arc<str>)]) -> String {
    let mut s = String::new();
    for (n, v) in labels {
        s.push_str(n);
        s.push('\0');
        s.push_str(v);
        s.push('\0');
    }
    s
}

fn spans(v: &[SpanRef]) -> Vec<Span> {
    v.iter()
        .map(|s| Span {
            offset: s.offset,
            length: s.length,
        })
        .collect()
}

fn hint(v: u8) -> CounterResetHint {
    match v {
        1 => CounterResetHint::CounterReset,
        2 => CounterResetHint::NotCounterReset,
        3 => CounterResetHint::GaugeType,
        _ => CounterResetHint::Unknown,
    }
}

#[derive(Default)]
struct Collector {
    floats: Vec<(i64, u64)>,
    ints: Vec<OwnedInt>,
    floats_hist: Vec<OwnedFloat>,
    kinds: Vec<&'static str>,
}

struct OwnedInt {
    ts: i64,
    count: u64,
    zero_count: u64,
    sum: f64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<Span>,
    neg_spans: Vec<Span>,
    pos_deltas: Vec<i64>,
    neg_deltas: Vec<i64>,
    pos_counts: Vec<i64>,
    neg_counts: Vec<i64>,
    chunk_reset_hint: CounterResetHint,
    counter_reset_hint: CounterResetHint,
}

struct OwnedFloat {
    ts: i64,
    count: f64,
    zero_count: f64,
    sum: f64,
    schema: i32,
    zero_threshold: f64,
    pos_spans: Vec<Span>,
    neg_spans: Vec<Span>,
    pos_buckets: Vec<f64>,
    neg_buckets: Vec<f64>,
    chunk_reset_hint: CounterResetHint,
    counter_reset_hint: CounterResetHint,
}

impl SampleSink for Collector {
    fn push_float(&mut self, ts: i64, value: f64) {
        self.kinds.push("float");
        self.floats.push((ts, value.to_bits()));
    }

    fn push_int_histogram(&mut self, h: &IntHistogramSample<'_>) {
        self.kinds.push("int_histogram");
        self.ints.push(OwnedInt {
            ts: h.ts,
            count: h.count,
            zero_count: h.zero_count,
            sum: h.sum,
            schema: h.schema,
            zero_threshold: h.zero_threshold,
            pos_spans: h.pos_spans.to_vec(),
            neg_spans: h.neg_spans.to_vec(),
            pos_deltas: h.pos_deltas.to_vec(),
            neg_deltas: h.neg_deltas.to_vec(),
            pos_counts: h.pos_counts.to_vec(),
            neg_counts: h.neg_counts.to_vec(),
            chunk_reset_hint: h.chunk_reset_hint,
            counter_reset_hint: h.counter_reset_hint,
        });
    }

    fn push_float_histogram(&mut self, h: &FloatHistogramSample<'_>) {
        self.kinds.push("float_histogram");
        self.floats_hist.push(OwnedFloat {
            ts: h.ts,
            count: h.count,
            zero_count: h.zero_count,
            sum: h.sum,
            schema: h.schema,
            zero_threshold: h.zero_threshold,
            pos_spans: h.pos_spans.to_vec(),
            neg_spans: h.neg_spans.to_vec(),
            pos_buckets: h.pos_buckets.to_vec(),
            neg_buckets: h.neg_buckets.to_vec(),
            chunk_reset_hint: h.chunk_reset_hint,
            counter_reset_hint: h.counter_reset_hint,
        });
    }
}

#[test]
fn metadata_matches_the_reference_block() {
    let refb = reference();
    let block = block(&refb);

    assert_eq!(block.block_id(), refb.ulid);
    assert_eq!(block.meta().min_time, refb.min_time);
    assert_eq!(block.meta().max_time, refb.max_time);
    assert_eq!(block.meta().stats.num_series, refb.num_series);
    assert_eq!(block.meta().stats.num_chunks, refb.num_chunks);
    assert_eq!(block.meta().stats.num_float_samples, refb.num_float_samples);
    assert_eq!(
        block.meta().stats.num_histogram_samples,
        refb.num_histogram_samples
    );

    let stats = block.scan_stats().unwrap();
    assert_eq!(stats.series, refb.num_series);
    assert_eq!(stats.chunks, refb.num_chunks);
}

#[test]
fn every_series_matches_labels_id_and_tombstones() {
    let refb = reference();
    let block = block(&refb);
    let by_key: HashMap<&str, &RefSeries> =
        refb.series.iter().map(|s| (s.key.as_str(), s)).collect();

    let mut seen = 0;
    for series in block.series(0) {
        let series = series.unwrap();
        let key = canonical(&series.labels);
        let want = by_key
            .get(key.as_str())
            .unwrap_or_else(|| panic!("series {key:?} missing from the reference"));
        seen += 1;

        assert_eq!(series.id, want.series_id, "series reference for {key:?}");
        assert_eq!(
            series.labels.len(),
            want.labels.len(),
            "label count {key:?}"
        );
        for (n, v) in &series.labels {
            let expected = want
                .labels
                .iter()
                .find(|(name, _)| name.as_str() == n.as_ref())
                .map(|(_, value)| value.as_str());
            assert_eq!(expected, Some(v.as_ref()), "label {n} of {key:?}");
        }

        let deleted = block.tombstones().intervals(series.id);
        assert_eq!(
            deleted,
            want.tombstones.as_slice(),
            "tombstone intervals for {key:?}"
        );
    }
    assert_eq!(seen, refb.series.len());
}

#[test]
fn decoded_chunks_match_the_reference_samples() {
    let refb = reference();
    let block = block(&refb);
    let by_key: HashMap<&str, &RefSeries> =
        refb.series.iter().map(|s| (s.key.as_str(), s)).collect();

    for series in block.series(0) {
        let series = series.unwrap();
        let key = canonical(&series.labels);
        let want = by_key.get(key.as_str()).unwrap();

        let mut sink = Collector::default();
        for chunk in &series.chunks {
            let slice = block.chunk(chunk).unwrap();
            chunkenc::decode(slice.encoding, slice.data, &mut sink)
                .unwrap_or_else(|e| panic!("decode {key:?}: {e}"));
        }

        // Floats: bit-exact, including stale markers.
        let want_floats: Vec<(i64, u64)> = want.floats.iter().map(|f| (f.t, f.bits)).collect();
        assert_eq!(sink.floats, want_floats, "float samples of {key:?}");

        // Integer histograms: exact counts, deltas and reset hints.
        assert_eq!(
            sink.ints.len(),
            want.int_hists.len(),
            "integer histogram count of {key:?}"
        );
        for (got, want) in sink.ints.iter().zip(&want.int_hists) {
            assert_eq!(got.ts, want.t, "ts of {key:?}");
            assert_eq!(got.count, want.count, "exact count of {key:?}");
            assert_eq!(got.zero_count, want.zero_count, "zero count of {key:?}");
            assert_eq!(got.sum.to_bits(), want.sum_bits, "sum of {key:?}");
            assert_eq!(got.schema, want.schema, "schema of {key:?}");
            assert_eq!(
                got.zero_threshold.to_bits(),
                want.zero_threshold.to_bits(),
                "zero threshold of {key:?}"
            );
            assert_eq!(got.pos_spans, spans(&want.pos_spans), "pos spans {key:?}");
            assert_eq!(got.neg_spans, spans(&want.neg_spans), "neg spans {key:?}");
            assert_eq!(got.pos_deltas, want.pos_deltas, "pos deltas {key:?}");
            assert_eq!(got.neg_deltas, want.neg_deltas, "neg deltas {key:?}");
            assert_eq!(got.pos_counts, want.pos_counts, "pos counts {key:?}");
            assert_eq!(got.neg_counts, want.neg_counts, "neg counts {key:?}");
            assert_eq!(
                got.chunk_reset_hint,
                hint(want.chunk_reset_hint),
                "chunk reset hint {key:?}"
            );
            assert_eq!(
                got.counter_reset_hint,
                hint(want.counter_reset_hint),
                "counter reset hint {key:?}"
            );
        }

        // Float histograms.
        assert_eq!(
            sink.floats_hist.len(),
            want.float_hists.len(),
            "float histogram count of {key:?}"
        );
        for (got, want) in sink.floats_hist.iter().zip(&want.float_hists) {
            assert_eq!(got.ts, want.t, "float hist ts of {key:?}");
            assert_eq!(got.count, want.count, "float hist count of {key:?}");
            assert_eq!(
                got.zero_count, want.zero_count,
                "float hist zero of {key:?}"
            );
            assert_eq!(got.sum.to_bits(), want.sum_bits, "float hist sum {key:?}");
            assert_eq!(got.schema, want.schema, "float hist schema {key:?}");
            assert_eq!(
                got.zero_threshold.to_bits(),
                want.zero_threshold.to_bits(),
                "float hist zero threshold of {key:?}"
            );
            assert_eq!(
                got.pos_spans,
                spans(&want.pos_spans),
                "float hist pos spans of {key:?}"
            );
            assert_eq!(
                got.neg_spans,
                spans(&want.neg_spans),
                "float hist neg spans of {key:?}"
            );
            assert_eq!(
                got.pos_buckets, want.pos_buckets,
                "float hist buckets of {key:?}"
            );
            assert_eq!(
                got.neg_buckets, want.neg_buckets,
                "float hist neg buckets of {key:?}"
            );
            assert_eq!(
                got.chunk_reset_hint,
                hint(want.chunk_reset_hint),
                "float hist chunk reset header of {key:?}"
            );
            assert_eq!(
                got.counter_reset_hint,
                hint(want.counter_reset_hint),
                "float hist reset hint {key:?}"
            );
        }
    }
}

#[test]
fn sample_iterator_matches_the_reference_with_tombstones_applied() {
    let refb = reference();
    let block = block(&refb);

    // Build the expected stream: reference samples in series order, minus the
    // ones inside a reference tombstone interval.
    let mut want: Vec<(u64, i64, &'static str)> = Vec::new();
    for series in &refb.series {
        let id = series.series_id;
        let deleted = |t: i64| {
            series
                .tombstones
                .iter()
                .any(|(mint, maxt)| t >= *mint && t <= *maxt)
        };
        for f in &series.floats {
            if !deleted(f.t) {
                want.push((id, f.t, "float"));
            }
        }
        for h in &series.int_hists {
            if !deleted(h.t) {
                want.push((id, h.t, "int_histogram"));
            }
        }
        for h in &series.float_hists {
            if !deleted(h.t) {
                want.push((id, h.t, "float_histogram"));
            }
        }
    }

    let mut got = Vec::new();
    let mut iter = block.samples(TimeRange::all());
    while let Some(sample) = iter.next_sample().unwrap() {
        let kind = match sample.value {
            SampleValue::Float(_) => "float",
            SampleValue::IntHistogram(_) => "int_histogram",
            SampleValue::FloatHistogram(_) => "float_histogram",
        };
        got.push((sample.series.id, sample.timestamp, kind));
    }

    assert_eq!(got.len(), want.len(), "sample count");
    for (i, (g, w)) in got.iter().zip(&want).enumerate() {
        assert_eq!(g, w, "sample {i}");
    }
    // The fixture must actually contain deletions and both histogram kinds.
    assert!(iter.samples_filtered() > 0, "fixture must delete samples");
    assert!(want.iter().any(|(_, _, k)| *k == "int_histogram"));
    assert!(want.iter().any(|(_, _, k)| *k == "float_histogram"));
}

#[test]
fn deleted_samples_are_exactly_the_tombstoned_ones() {
    let refb = reference();
    let block = block(&refb);

    let mut all = 0u64;
    let mut iter = block.samples_with(tsdb_reader::SampleIterOptions {
        skip_deleted: false,
        ..Default::default()
    });
    while iter.next_sample().unwrap().is_some() {
        all += 1;
    }
    let total = refb
        .series
        .iter()
        .map(|s| s.floats.len() + s.int_hists.len() + s.float_hists.len())
        .sum::<usize>() as u64;
    assert_eq!(all, total, "every reference sample must be exported");

    let mut kept = 0u64;
    let mut iter = block.samples(TimeRange::all());
    while iter.next_sample().unwrap().is_some() {
        kept += 1;
    }
    let tombstoned = refb
        .series
        .iter()
        .map(|s| {
            let deleted = |t: i64| {
                s.tombstones
                    .iter()
                    .any(|(mint, maxt)| t >= *mint && t <= *maxt)
            };
            s.floats.iter().filter(|f| deleted(f.t)).count()
                + s.int_hists.iter().filter(|h| deleted(h.t)).count()
                + s.float_hists.iter().filter(|h| deleted(h.t)).count()
        })
        .sum::<usize>() as u64;
    assert!(tombstoned > 0, "fixture must have deleted samples");
    assert_eq!(kept, all - tombstoned);
}

#[test]
fn label_lookups_match_the_reference_postings() {
    let refb = reference();
    let block = block(&refb);
    let index = block.index();

    assert_eq!(index.label_names().unwrap(), refb.index.names);
    for (name, want) in &refb.index.values {
        assert_eq!(&index.label_values(name).unwrap(), want, "values of {name}");
    }

    for entry in &refb.index.postings {
        let refs = index
            .postings(&entry.name, &entry.value)
            .unwrap()
            .collect_refs()
            .unwrap();
        assert_eq!(
            refs, entry.refs,
            "postings for {}={}",
            entry.name, entry.value
        );
        assert!(
            refs.windows(2).all(|w| w[0] < w[1]),
            "postings for {}={} must be strictly increasing",
            entry.name,
            entry.value
        );
    }

    let mut all = index.all_postings().unwrap().collect_refs().unwrap();
    let mut want = refb.index.all_postings.clone();
    assert_eq!(all.len(), want.len(), "all-postings length");
    all.sort_unstable();
    want.sort_unstable();
    assert_eq!(all, want);

    // Every reference the label space hands out must resolve to the series the
    // reference dump lists under the same id.
    for entry in &refb.index.postings {
        let mut p = index.postings(&entry.name, &entry.value).unwrap();
        while let Some(reference) = p.next().unwrap() {
            let series = index.series_by_ref(reference).unwrap();
            assert_eq!(
                series.label(&entry.name).map(|v| v.to_string()),
                Some(entry.value.clone()),
                "series {reference} must carry {}={}",
                entry.name,
                entry.value
            );
        }
    }
}