tsdb-reader 0.1.0

Zero-copy, read-only parser for Prometheus TSDB blocks: index v1-v3, all chunk encodings, tombstones
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Prometheus TSDB index reader (format v1/v2/v3).
//!
//! Only the symbols and series sections are used: a full export does not need
//! the postings engine, so we deliberately avoid building any label index in
//! memory. Series are visited sequentially in lexicographic label order, which
//! is also the physical order of their chunks in the segment files.

use std::cell::RefCell;
use std::path::Path;
use std::sync::Arc;

use crate::checksum;
use crate::error::{Error, Result};
use crate::storage::{self, Segment};
use crate::varint;

const MAGIC_INDEX: u32 = 0xBAAA_D700;
const HEADER_LEN: usize = 5;
const TOC_LEN: usize = 6 * 8 + 4;
const SERIES_ALIGN: usize = 16;
const SYMBOL_FACTOR: usize = 32;
const SYMBOL_CACHE_BITS: usize = 14;

/// The index table of contents: absolute file offsets of every section.
///
/// All values are byte offsets from the start of the index file. Sections this
/// crate does not parse (`label_indices`, `postings`) are kept so callers can
/// see the layout and compute section boundaries.
#[derive(Debug, Clone, Copy, Default)]
pub struct Toc {
    /// Symbol table offset.
    pub symbols: u64,
    /// Series section offset, 16-byte aligned on v2/v3.
    pub series: u64,
    /// Label index section offset.
    pub label_indices: u64,
    /// Label index table offset.
    pub label_indices_table: u64,
    /// Postings section offset.
    pub postings: u64,
    /// Postings table offset.
    pub postings_table: u64,
}

/// Where one chunk lives and which time range it covers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChunkMeta {
    /// Packed chunk reference: high 32 bits segment index, low 32 bits offset.
    pub reference: u64,
    /// First timestamp in the chunk, in milliseconds since the Unix epoch.
    pub min_time: i64,
    /// Last timestamp in the chunk, in milliseconds since the Unix epoch.
    pub max_time: i64,
}

impl ChunkMeta {
    /// Segment index encoded in [`Self::reference`].
    pub fn segment(&self) -> u32 {
        (self.reference >> 32) as u32
    }

    /// Byte offset of the record inside [`Self::segment`].
    pub fn offset(&self) -> u32 {
        self.reference as u32
    }
}

/// One series: its label set and the chunks that hold its samples.
///
/// Despite the name this is an owned record, not a reference into the file:
/// label strings are resolved through the symbol table once, then shared as
/// `Arc<str>` so a caller can keep them after the iterator moves on.
#[derive(Debug, Clone)]
pub struct SeriesRef {
    /// Reference as stored in the index (v2/v3: byte offset / 16). This is the
    /// same value tombstones use to identify a series.
    pub id: u64,
    /// Byte offset of the series record in the index file.
    pub offset: u64,
    /// Labels in lexicographic order, exactly as stored in the index.
    pub labels: Vec<(Arc<str>, Arc<str>)>,
    /// Chunks in ascending time order.
    pub chunks: Vec<ChunkMeta>,
}

impl SeriesRef {
    /// Looks up a label value by name.
    pub fn label(&self, name: &str) -> Option<&str> {
        self.labels
            .iter()
            .find(|(n, _)| n.as_ref() == name)
            .map(|(_, v)| v.as_ref())
    }
}

/// Series and chunk counts, plus the byte range they were read from.
///
/// [`Self::end_series_offset`] is what a resumed run stores in its checkpoint
/// so it can continue from the same byte.
#[derive(Debug, Clone, Copy, Default)]
pub struct IndexStats {
    /// Number of series records.
    pub series: u64,
    /// Number of chunks referenced by those series.
    pub chunks: u64,
    /// Byte offset where the series section starts.
    pub min_series_offset: u64,
    /// Byte offset just past the last series record that was read.
    pub end_series_offset: u64,
}

/// Direct-mapped cache slot: symbol reference plus its resolved string.
type SymbolCache = Vec<Option<(u32, Arc<str>)>>;

struct Symbols {
    /// Absolute file offset of the first symbol entry.
    base: usize,
    /// Absolute file offset of the end of the symbol section (CRC excluded).
    end: usize,
    count: usize,
    /// Absolute offsets of every 32nd symbol (same scheme as Prometheus).
    offsets: Vec<usize>,
    version: u8,
    cache: RefCell<SymbolCache>,
}

impl Symbols {
    fn empty() -> Self {
        Self {
            base: 0,
            end: 0,
            count: 0,
            offsets: Vec::new(),
            version: 1,
            cache: RefCell::new(vec![None; 1 << SYMBOL_CACHE_BITS]),
        }
    }

    fn new(mmap: &[u8], off: usize, version: u8, verify: bool) -> Result<Self> {
        if off == 0 || off + 8 > mmap.len() {
            return Err(Error::format("invalid symbol table offset"));
        }
        let len = be32(mmap, off)? as usize;
        let count = be32(mmap, off + 4)? as usize;
        let payload_start = off + 4;
        let payload_end = payload_start
            .checked_add(len)
            .ok_or_else(|| Error::format("symbol table length overflow"))?;
        if payload_end + 4 > mmap.len() {
            return Err(Error::format("symbol table exceeds file size"));
        }
        if verify {
            let want = be32(mmap, payload_end)?;
            checksum::verify(
                true,
                want,
                &mmap[payload_start..payload_end],
                "index symbols",
            )?;
        }

        let mut offsets = Vec::with_capacity(1 + count / SYMBOL_FACTOR);
        let mut pos = off + 8; // skip len + count
        let mut seen = 0usize;
        while pos < payload_end {
            if seen % SYMBOL_FACTOR == 0 {
                offsets.push(pos);
            }
            let slen = varint::uvarint(mmap, &mut pos)? as usize;
            pos = pos
                .checked_add(slen)
                .ok_or_else(|| Error::format("symbol length overflow"))?;
            if pos > payload_end {
                return Err(Error::format("symbol exceeds symbol table"));
            }
            seen += 1;
        }
        if seen != count {
            return Err(Error::format(format!(
                "symbol count mismatch: header {count}, scanned {seen}"
            )));
        }

        Ok(Self {
            base: off + 8,
            end: payload_end,
            count,
            offsets,
            version,
            cache: RefCell::new(vec![None; 1 << SYMBOL_CACHE_BITS]),
        })
    }

    #[inline]
    fn lookup(&self, mmap: &[u8], r: u32) -> Result<Arc<str>> {
        let slot = ((r as usize).wrapping_mul(0x9E37_79B1) >> (32 - SYMBOL_CACHE_BITS))
            & ((1 << SYMBOL_CACHE_BITS) - 1);
        if let Some((cached_ref, s)) = &self.cache.borrow()[slot] {
            if *cached_ref == r {
                return Ok(s.clone());
            }
        }

        let mut pos = if self.version == 1 {
            r as usize
        } else {
            let idx = r as usize;
            if idx >= self.count {
                return Err(Error::format(format!(
                    "symbol reference {idx} out of range (count {})",
                    self.count
                )));
            }
            let mut p = *self
                .offsets
                .get(idx / SYMBOL_FACTOR)
                .ok_or_else(|| Error::format("symbol offset group missing"))?;
            for _ in 0..(idx % SYMBOL_FACTOR) {
                let slen = varint::uvarint(mmap, &mut p)? as usize;
                p += slen;
            }
            p
        };

        if pos < self.base || pos >= self.end {
            return Err(Error::format(format!("symbol offset {pos} out of range")));
        }
        let len = varint::uvarint(mmap, &mut pos)? as usize;
        let end = pos
            .checked_add(len)
            .ok_or_else(|| Error::format("symbol length overflow"))?;
        if end > self.end {
            return Err(Error::format("symbol exceeds symbol table"));
        }
        let s: Arc<str> = std::str::from_utf8(&mmap[pos..end])
            .map_err(|e| Error::format(format!("invalid utf-8 symbol: {e}")))?
            .into();
        self.cache.borrow_mut()[slot] = Some((r, s.clone()));
        Ok(s)
    }
}

/// Sequential reader for the index of one block.
///
/// Only the symbol table and the series section are parsed: a full export does
/// not need postings, so no label index is built in memory. `IndexReader` is
/// `Send` but not `Sync` because the symbol cache is a `RefCell`; see the crate
/// level threading notes.
pub struct IndexReader {
    mmap: Segment,
    version: u8,
    toc: Toc,
    symbols: Symbols,
    series_end: usize,
    verify_crc: bool,
}

impl std::fmt::Debug for IndexReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IndexReader")
            .field("version", &self.version)
            .field("toc", &self.toc)
            .field("series_end", &self.series_end)
            .finish()
    }
}

impl IndexReader {
    /// Opens and validates an `index` file.
    pub fn open(path: &Path, verify_crc: bool) -> Result<Self> {
        Self::from_segment(storage::open(path)?, verify_crc)
    }

    /// Wraps an already-mapped index file.
    #[cfg(feature = "mmap")]
    pub fn from_mmap(mmap: memmap2::Mmap, verify_crc: bool) -> Result<Self> {
        Self::from_segment(storage::mapped(mmap), verify_crc)
    }

    /// Wraps an index file that is already in memory.
    ///
    /// Useful when the bytes come from an object store, a network stream or a
    /// test fixture instead of the local filesystem.
    pub fn from_bytes(bytes: Vec<u8>, verify_crc: bool) -> Result<Self> {
        Self::from_segment(storage::owned(bytes), verify_crc)
    }

    fn from_segment(mmap: Segment, verify_crc: bool) -> Result<Self> {
        let len = mmap.len();
        if len < HEADER_LEN + TOC_LEN {
            return Err(Error::format("index file too small"));
        }
        let magic = be32(&mmap, 0)?;
        if magic != MAGIC_INDEX {
            return Err(Error::format(format!("invalid index magic 0x{magic:08x}")));
        }
        let version = mmap[4];
        if !(1..=3).contains(&version) {
            return Err(Error::Unsupported(format!(
                "index format version {version}"
            )));
        }

        let toc_off = len - TOC_LEN;
        let want = be32(&mmap, toc_off + 48)?;
        if verify_crc {
            checksum::verify(true, want, &mmap[toc_off..toc_off + 48], "index toc")?;
        }
        let toc = Toc {
            symbols: be64(&mmap, toc_off)?,
            series: be64(&mmap, toc_off + 8)?,
            label_indices: be64(&mmap, toc_off + 16)?,
            label_indices_table: be64(&mmap, toc_off + 24)?,
            postings: be64(&mmap, toc_off + 32)?,
            postings_table: be64(&mmap, toc_off + 40)?,
        };
        let series_start = toc.series as usize;
        if toc.series != 0 && (series_start >= len || series_start < HEADER_LEN) {
            return Err(Error::format("series section offset out of range"));
        }

        // The series section ends where the next section starts. `label_indices`
        // is the canonical boundary for v2/v3; fall back defensively if a writer
        // left it unset.
        let mut series_end = len - TOC_LEN;
        for cand in [toc.label_indices, toc.postings, toc.postings_table] {
            let c = cand as usize;
            if cand != 0 && c > series_start && c <= len - TOC_LEN {
                series_end = series_end.min(c);
            }
        }
        if toc.series == 0 || series_start >= series_end {
            series_end = series_start;
        }

        let symbols = if toc.symbols == 0 || toc.symbols as usize >= len {
            Symbols::empty()
        } else {
            Symbols::new(&mmap, toc.symbols as usize, version, verify_crc)?
        };

        Ok(Self {
            mmap,
            version,
            toc,
            symbols,
            series_end,
            verify_crc,
        })
    }

    /// Index format version (1, 2 or 3).
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Raw table of contents of the file.
    pub fn toc(&self) -> Toc {
        self.toc
    }

    /// Byte offset where the series section starts, after alignment.
    pub fn series_start(&self) -> u64 {
        align_up(self.toc.series as usize, self.align()) as u64
    }

    /// Byte offset where the series section ends.
    pub fn series_end(&self) -> u64 {
        self.series_end as u64
    }

    /// The whole index file as bytes.
    pub fn bytes(&self) -> &[u8] {
        &self.mmap
    }

    #[inline]
    fn align(&self) -> usize {
        if self.version == 1 {
            1
        } else {
            SERIES_ALIGN
        }
    }

    /// Iterates series beginning at the given byte offset (0 means "from the
    /// start of the series section").
    pub fn series(&self, start_offset: u64) -> SeriesIter<'_> {
        let start = if start_offset == 0 {
            self.series_start() as usize
        } else {
            start_offset as usize
        };
        SeriesIter {
            index: self,
            pos: start,
            done: false,
        }
    }

    /// Scans the series section without resolving symbols, collecting exact
    /// series and chunk counts.
    ///
    /// Use this when `meta.json` carries no stats. It walks every record but
    /// never touches the symbol table, so it stays cheap on wide label sets.
    pub fn scan_stats(&self) -> Result<IndexStats> {
        let mut pos = self.series_start() as usize;
        let mut stats = IndexStats {
            min_series_offset: pos as u64,
            end_series_offset: pos as u64,
            ..Default::default()
        };
        while pos < self.series_end {
            if self.mmap.get(pos).copied().unwrap_or(0) == 0 {
                break;
            }
            let start = pos;
            let (payload_len, mut p) = varint::peek_uvarint(&self.mmap, pos)?;
            let payload_end = p
                .checked_add(payload_len as usize)
                .ok_or_else(|| Error::format("series length overflow"))?;
            if payload_end + 4 > self.series_end {
                return Err(Error::format("series record exceeds series section"));
            }
            let labels = varint::uvarint(&self.mmap, &mut p)?;
            for _ in 0..labels {
                varint::uvarint(&self.mmap, &mut p)?;
                varint::uvarint(&self.mmap, &mut p)?;
            }
            let chunks = varint::uvarint(&self.mmap, &mut p)?;
            if chunks > 0 {
                varint::varint(&self.mmap, &mut p)?; // mint
                varint::uvarint(&self.mmap, &mut p)?; // maxt - mint
                varint::uvarint(&self.mmap, &mut p)?; // ref
                for _ in 1..chunks {
                    varint::uvarint(&self.mmap, &mut p)?;
                    varint::uvarint(&self.mmap, &mut p)?;
                    varint::varint(&self.mmap, &mut p)?;
                }
            }
            if p > payload_end {
                return Err(Error::format("series payload truncated"));
            }
            stats.series += 1;
            stats.chunks += chunks;

            let next = align_up(payload_end + 4, self.align());
            pos = next;
            stats.end_series_offset = next as u64;
            if next <= start {
                return Err(Error::format("series parser made no progress"));
            }
        }
        Ok(stats)
    }

    fn parse_series(&self, pos: usize) -> Result<(SeriesRef, usize)> {
        let start = pos;
        let (payload_len, payload_start) = varint::peek_uvarint(&self.mmap, start)?;
        let payload_len = payload_len as usize;
        let payload_end = payload_start
            .checked_add(payload_len)
            .ok_or_else(|| Error::format("series length overflow"))?;
        if payload_end + 4 > self.mmap.len() {
            return Err(Error::format("series record exceeds index file"));
        }
        if self.verify_crc {
            let want = be32(&self.mmap, payload_end)?;
            checksum::verify(
                true,
                want,
                &self.mmap[payload_start..payload_end],
                "index series",
            )?;
        }

        let mut p = payload_start;
        let num_labels = varint::uvarint(&self.mmap, &mut p)?;
        let mut labels = Vec::with_capacity(num_labels.min(64) as usize);
        for _ in 0..num_labels {
            let name = varint::uvarint32(&self.mmap, &mut p)?;
            let value = varint::uvarint32(&self.mmap, &mut p)?;
            labels.push((
                self.symbols.lookup(&self.mmap, name)?,
                self.symbols.lookup(&self.mmap, value)?,
            ));
        }

        let num_chunks = varint::uvarint(&self.mmap, &mut p)?;
        let mut chunks = Vec::with_capacity(num_chunks.min(1024) as usize);
        if num_chunks > 0 {
            let mint = varint::varint(&self.mmap, &mut p)?;
            let maxt = mint
                .checked_add(varint::uvarint(&self.mmap, &mut p)? as i64)
                .ok_or_else(|| Error::format("chunk maxt overflow"))?;
            let reference = varint::uvarint(&self.mmap, &mut p)?;
            let mut prev_maxt = maxt;
            let mut prev_ref = reference as i64;
            chunks.push(ChunkMeta {
                reference,
                min_time: mint,
                max_time: maxt,
            });
            for _ in 1..num_chunks {
                let mint = prev_maxt
                    .checked_add(varint::uvarint(&self.mmap, &mut p)? as i64)
                    .ok_or_else(|| Error::format("chunk mint overflow"))?;
                let maxt = mint
                    .checked_add(varint::uvarint(&self.mmap, &mut p)? as i64)
                    .ok_or_else(|| Error::format("chunk maxt overflow"))?;
                let delta = varint::varint(&self.mmap, &mut p)?;
                let reference = prev_ref
                    .checked_add(delta)
                    .ok_or_else(|| Error::format("chunk ref overflow"))?
                    as u64;
                prev_maxt = maxt;
                prev_ref = reference as i64;
                chunks.push(ChunkMeta {
                    reference,
                    min_time: mint,
                    max_time: maxt,
                });
            }
        }
        if p > payload_end {
            return Err(Error::format("series payload truncated"));
        }

        let next = align_up(payload_end + 4, self.align());
        let id = if self.version == 1 {
            start as u64
        } else {
            (start / SERIES_ALIGN) as u64
        };
        Ok((
            SeriesRef {
                id,
                offset: start as u64,
                labels,
                chunks,
            },
            next,
        ))
    }
}

/// Iterator over the series section, in on-disk (label-sorted) order.
///
/// Yields `Result<SeriesRef>`: a malformed record stops the iteration after
/// reporting the error, so callers can checkpoint at the last good offset.
pub struct SeriesIter<'a> {
    index: &'a IndexReader,
    pos: usize,
    done: bool,
}

impl SeriesIter<'_> {
    /// Current byte offset in the index; the start of the next series.
    pub fn position(&self) -> u64 {
        self.pos as u64
    }

    /// True once the iterator has passed the end of the section.
    pub fn is_done(&self) -> bool {
        self.done || self.pos >= self.index.series_end
    }
}

impl Iterator for SeriesIter<'_> {
    type Item = Result<SeriesRef>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        if self.pos >= self.index.series_end {
            self.done = true;
            return None;
        }
        // Series sections are zero padded before the next section starts.
        if self.index.mmap.get(self.pos).copied().unwrap_or(0) == 0 {
            self.done = true;
            return None;
        }
        match self.index.parse_series(self.pos) {
            Ok((series, next)) => {
                self.pos = next;
                Some(Ok(series))
            }
            Err(e) => {
                self.done = true;
                Some(Err(e))
            }
        }
    }
}

#[inline]
fn align_up(v: usize, align: usize) -> usize {
    if align <= 1 {
        v
    } else {
        (v + align - 1) & !(align - 1)
    }
}

#[inline]
fn be32(buf: &[u8], off: usize) -> Result<u32> {
    let b = buf.get(off..off + 4).ok_or(Error::Eof(off))?;
    Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}

#[inline]
fn be64(buf: &[u8], off: usize) -> Result<u64> {
    let b = buf.get(off..off + 8).ok_or(Error::Eof(off))?;
    Ok(u64::from_be_bytes([
        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
    ]))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn alignment() {
        assert_eq!(align_up(0, 16), 0);
        assert_eq!(align_up(1, 16), 16);
        assert_eq!(align_up(16, 16), 16);
        assert_eq!(align_up(17, 16), 32);
        assert_eq!(align_up(17, 1), 17);
    }

    #[test]
    fn series_id_uses_offset_div_16() {
        assert_eq!((160usize / SERIES_ALIGN) as u64, 10);
    }
}