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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
//! Prometheus TSDB index reader (format v1/v2/v3).
//!
//! Two access patterns share this reader. A sequential export walks the series
//! section in lexicographic label order, which is also the physical order of
//! their chunks in the segment files; [`IndexReader::series`] does that without
//! touching any label index. A lookup-driven consumer asks for one label pair
//! instead; [`IndexReader::postings`] serves that from a sampled view of the
//! postings offset table, so no full label index is ever held in memory.
//!
//! Module layout:
//!
//! | Module | Responsibility |
//! |--------|----------------|
//! | `toc` | table of contents: section offsets, bounds and ordering |
//! | `symbols` | symbol table (v1 inline refs, v2/v3 offset groups) |
//! | `series` | series records, chunk metadata, sequential iterator |
//! | `postings` | postings lists, label names/values, sorted unions |
//! | `validation` | section boundary and layout checks |

pub mod postings;
mod series;
mod symbols;
mod toc;

pub mod validation;

pub use postings::{Postings, PostingsStats};
pub use series::{ChunkMeta, IndexStats, SeriesIter, SeriesRef};
pub(crate) use symbols::Symbols;
pub use toc::Toc;

use std::path::Path;

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

use toc::{be32, TOC_LEN};

const MAGIC_INDEX: u32 = 0xBAAA_D700;
const HEADER_LEN: usize = 5;
/// Series records are padded to 16 bytes so a 32-bit reference can address them.
pub(crate) const SERIES_ALIGN: usize = 16;

/// Reader for the index of one block.
///
/// The symbol table and the series section are parsed eagerly; the postings
/// offset table is parsed on first lookup and kept in its sampled form. No full
/// label index is ever built. `IndexReader` is `Send` but not `Sync` because
/// both caches are `RefCell`s; see the crate level threading notes.
pub struct IndexReader {
    pub(crate) mmap: Segment,
    pub(crate) version: u8,
    toc: Toc,
    pub(crate) symbols: Symbols,
    /// End of the series section: the first byte that is not a series record.
    pub(crate) series_end: usize,
    verify_crc: bool,
    /// Sampled postings offset table, built on first use.
    pub(super) postings_table: std::cell::RefCell<Option<std::sync::Arc<postings::PostingsTable>>>,
}

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 = Toc::read(&mmap, verify_crc)?;
        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,
            postings_table: std::cell::RefCell::new(None),
        })
    }

    /// 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
    }

    /// Number of symbols declared by the symbol table.
    pub fn symbol_count(&self) -> usize {
        self.symbols.count()
    }

    /// True when series records carry a CRC that is being verified.
    pub fn verify_crc(&self) -> bool {
        self.verify_crc
    }

    #[inline]
    pub(crate) 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.
    /// Records are still bounds-checked: a corrupt section is reported instead
    /// of being counted.
    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()
        };
        let mut scratch = Vec::new();
        while pos < self.series_end {
            if self.mmap.get(pos).copied().unwrap_or(0) == 0 {
                break;
            }
            let head = self.series_bounds(pos)?;
            let mut p = head.payload_start;
            let labels = varint::uvarint(&self.mmap, &mut p)?;
            self.skip_labels(labels, &mut p, &head)?;
            scratch.clear();
            stats.chunks += self.read_chunk_metas(&mut p, &head, &mut scratch)?;
            if p > head.payload_end {
                return Err(Error::format(format!("series at {pos}: payload truncated")));
            }
            stats.series += 1;
            stats.end_series_offset = head.next as u64;
            pos = head.next;
        }
        Ok(stats)
    }

    /// Validates the record framing at `pos` and returns its payload bounds.
    ///
    /// Enforces everything that makes a record addressable and safe to parse:
    /// the offset lies inside the series section, is aligned like the writer
    /// requires, and the declared payload plus CRC fits before the next section.
    fn series_bounds(&self, pos: usize) -> Result<SeriesHead> {
        let start = pos;
        if start < self.series_start() as usize || start >= self.series_end {
            return Err(Error::format(format!(
                "series offset {start} outside the series section"
            )));
        }
        if self.align() > 1 && start % SERIES_ALIGN != 0 {
            return Err(Error::format(format!(
                "series offset {start} is not {SERIES_ALIGN}-byte aligned"
            )));
        }
        let (payload_len, payload_start) = varint::peek_uvarint(&self.mmap, start)?;
        let payload_len = usize::try_from(payload_len)
            .map_err(|_| Error::format("series length does not fit in usize"))?;
        let payload_end = payload_start
            .checked_add(payload_len)
            .ok_or_else(|| Error::format("series length overflow"))?;
        // payload + 4-byte CRC must stay inside the series section, not merely
        // inside the file: otherwise a bad length silently reads symbols or
        // postings as series data.
        let crc_end = payload_end
            .checked_add(4)
            .ok_or_else(|| Error::format("series length overflow"))?;
        if crc_end > self.series_end {
            return Err(Error::format(format!(
                "series at {start}: payload ends at {crc_end}, past the series section ({})",
                self.series_end
            )));
        }
        let next = align_up(crc_end, self.align());
        if next <= start {
            return Err(Error::format("series parser made no progress"));
        }
        Ok(SeriesHead {
            start,
            payload_start,
            payload_end,
            next,
        })
    }

    /// Skips `num_labels` symbol-reference pairs, checking they fit the payload.
    fn skip_labels(&self, num_labels: u64, p: &mut usize, head: &SeriesHead) -> Result<()> {
        // Every label pair takes at least two bytes, so this bounds the loop by
        // the payload size instead of trusting an arbitrary count.
        let room = head.payload_end.saturating_sub(*p) as u64;
        if num_labels.saturating_mul(2) > room {
            return Err(Error::format(format!(
                "series at {}: {num_labels} labels do not fit in {room} bytes",
                head.start
            )));
        }
        for _ in 0..num_labels {
            varint::uvarint(&self.mmap, p)?;
            varint::uvarint(&self.mmap, p)?;
        }
        Ok(())
    }

    /// Reads the chunk metadata of one series record.
    ///
    /// Validates the writer's invariants as it goes: chunk count fits the
    /// payload, `max_time >= min_time`, chunk time ranges strictly increase,
    /// and references are non-decreasing. Violations mean the record is
    /// corrupt, so they are reported instead of being handed to a caller.
    fn read_chunk_metas(
        &self,
        p: &mut usize,
        head: &SeriesHead,
        out: &mut Vec<ChunkMeta>,
    ) -> Result<u64> {
        let num_chunks = varint::uvarint(&self.mmap, p)?;
        if num_chunks == 0 {
            return Ok(0);
        }
        // The smallest possible chunk triple is three one-byte varints.
        let room = head.payload_end.saturating_sub(*p) as u64;
        if num_chunks.saturating_mul(3) > room {
            return Err(Error::format(format!(
                "series at {}: {num_chunks} chunks do not fit in {room} bytes",
                head.start
            )));
        }

        let mint = varint::varint(&self.mmap, p)?;
        let maxt = mint
            .checked_add(varint::uvarint(&self.mmap, p)? as i64)
            .ok_or_else(|| Error::format("chunk maxt overflow"))?;
        if maxt < mint {
            return Err(Error::format(format!(
                "series at {}: chunk max time {maxt} before min time {mint}",
                head.start
            )));
        }
        let reference = varint::uvarint(&self.mmap, p)?;
        out.push(ChunkMeta {
            reference,
            min_time: mint,
            max_time: maxt,
        });

        let mut prev_maxt = maxt;
        let mut prev_ref = reference;
        for _ in 1..num_chunks {
            let mint = prev_maxt
                .checked_add(varint::uvarint(&self.mmap, p)? as i64)
                .ok_or_else(|| Error::format("chunk mint overflow"))?;
            let maxt = mint
                .checked_add(varint::uvarint(&self.mmap, p)? as i64)
                .ok_or_else(|| Error::format("chunk maxt overflow"))?;
            let delta = varint::varint(&self.mmap, p)?;
            let reference = (prev_ref as i64)
                .checked_add(delta)
                .ok_or_else(|| Error::format("chunk ref overflow"))?
                as u64;
            if mint <= prev_maxt {
                return Err(Error::format(format!(
                    "series at {}: chunk starts at {mint}, previous chunk ends at {prev_maxt}",
                    head.start
                )));
            }
            if maxt < mint {
                return Err(Error::format(format!(
                    "series at {}: chunk max time {maxt} before min time {mint}",
                    head.start
                )));
            }
            if reference < prev_ref {
                return Err(Error::format(format!(
                    "series at {}: chunk reference {reference} precedes {prev_ref}",
                    head.start
                )));
            }
            prev_maxt = maxt;
            prev_ref = reference;
            out.push(ChunkMeta {
                reference,
                min_time: mint,
                max_time: maxt,
            });
        }
        Ok(num_chunks)
    }

    /// Parses one series record at `pos`, returning it and the next offset.
    pub(crate) fn parse_series(&self, pos: usize) -> Result<(SeriesRef, usize)> {
        let head = self.series_bounds(pos)?;
        if self.verify_crc {
            let want = be32(&self.mmap, head.payload_end)?;
            crate::checksum::verify(
                true,
                want,
                &self.mmap[head.payload_start..head.payload_end],
                "index series",
            )?;
        }

        let mut p = head.payload_start;
        let num_labels = varint::uvarint(&self.mmap, &mut p)?;
        let mut labels = Vec::with_capacity(num_labels.min(64) as usize);
        let room = head.payload_end.saturating_sub(p) as u64;
        if num_labels.saturating_mul(2) > room {
            return Err(Error::format(format!(
                "series at {}: {num_labels} labels do not fit in {room} bytes",
                head.start
            )));
        }
        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 mut chunks = Vec::new();
        self.read_chunk_metas(&mut p, &head, &mut chunks)?;
        if p > head.payload_end {
            return Err(Error::format(format!(
                "series at {}: payload truncated",
                head.start
            )));
        }

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

/// Framing of one series record: where its payload lives and what follows it.
struct SeriesHead {
    /// Byte offset of the record (also the base of the series reference).
    start: usize,
    /// First byte of the payload (labels + chunks).
    payload_start: usize,
    /// First byte after the payload (the CRC starts here).
    payload_end: usize,
    /// Byte offset of the next record.
    next: usize,
}

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

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

    /// Encodes an unsigned LEB128 varint, the way Prometheus writes lengths
    /// and references.
    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;
            }
        }
    }

    /// Encodes a zig-zag signed varint, used for timestamps and ref deltas.
    fn put_varint(out: &mut Vec<u8>, v: i64) {
        put_uvarint(out, ((v << 1) ^ (v >> 63)) as u64);
    }

    /// Builds a series payload: labels as (name,value) symbol refs plus chunks.
    fn payload(labels: &[(u32, u32)], chunks: &[(i64, i64, u64)]) -> Vec<u8> {
        let mut out = Vec::new();
        put_uvarint(&mut out, labels.len() as u64);
        for (n, v) in labels {
            put_uvarint(&mut out, *n as u64);
            put_uvarint(&mut out, *v as u64);
        }
        put_uvarint(&mut out, chunks.len() as u64);
        if let Some(((mint, maxt, reference), rest)) = chunks.split_first() {
            put_varint(&mut out, *mint);
            put_uvarint(&mut out, (maxt - mint) as u64);
            put_uvarint(&mut out, *reference);
            let mut prev_maxt = *maxt;
            let mut prev_ref = *reference as i64;
            for (mint, maxt, reference) in rest {
                put_uvarint(&mut out, (mint - prev_maxt) as u64);
                put_uvarint(&mut out, (maxt - mint) as u64);
                put_varint(&mut out, *reference as i64 - prev_ref);
                prev_maxt = *maxt;
                prev_ref = *reference as i64;
            }
        }
        out
    }

    /// Assembles a minimal but valid v2 index around the given payloads.
    fn build_index(payloads: &[Vec<u8>]) -> Vec<u8> {
        build_index_version(2, payloads)
    }

    /// Assembles a minimal index of the requested version.
    ///
    /// Layout: header, symbol table ("a", "b"), series section (16-byte aligned
    /// on v2/v3, byte packed on v1), then the TOC. `label_indices` marks the end
    /// of the series section so the boundary checks have something exact to
    /// compare against.
    fn build_index_version(version: u8, payloads: &[Vec<u8>]) -> Vec<u8> {
        let align = if version == 1 { 1 } else { SERIES_ALIGN };
        let mut out = Vec::new();
        out.extend_from_slice(&0xBAAA_D700u32.to_be_bytes());
        out.push(version);

        let symbols_off = out.len();
        let mut sym = Vec::new();
        for name in ["a", "b"] {
            sym.push(name.len() as u8);
            sym.extend_from_slice(name.as_bytes());
        }
        out.extend_from_slice(&((sym.len() + 4) as u32).to_be_bytes());
        out.extend_from_slice(&2u32.to_be_bytes());
        out.extend_from_slice(&sym);
        let sym_crc = crc32c::crc32c(&out[symbols_off + 4..]);
        out.extend_from_slice(&sym_crc.to_be_bytes());

        while out.len() % align != 0 {
            out.push(0);
        }
        let series_off = out.len();
        for body in payloads {
            let mut len = Vec::new();
            put_uvarint(&mut len, body.len() as u64);
            out.extend_from_slice(&len);
            out.extend_from_slice(body);
            let crc = crc32c::crc32c(body);
            out.extend_from_slice(&crc.to_be_bytes());
            while out.len() % align != 0 {
                out.push(0);
            }
        }
        let end_series = out.len();

        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());
        toc.extend_from_slice(&(end_series as u64).to_be_bytes());
        toc.extend_from_slice(&0u64.to_be_bytes());
        toc.extend_from_slice(&0u64.to_be_bytes());
        toc.extend_from_slice(&0u64.to_be_bytes());
        let toc_crc = crc32c::crc32c(&toc);
        out.extend_from_slice(&toc);
        out.extend_from_slice(&toc_crc.to_be_bytes());
        out
    }

    fn reader(payloads: &[Vec<u8>]) -> IndexReader {
        IndexReader::from_bytes(build_index(payloads), true).unwrap()
    }

    fn one_series(chunks: &[(i64, i64, u64)]) -> IndexReader {
        reader(&[payload(&[(0, 1)], chunks)])
    }

    #[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);
    }

    #[test]
    fn be_helpers_reject_short_buffers() {
        assert!(be32(&[0, 0], 0).is_err());
        assert!(toc::be64(&[0, 0, 0, 0], 0).is_err());
    }

    #[test]
    fn parses_a_well_formed_record() {
        let idx = one_series(&[(100, 200, 8), (300, 400, 60)]);
        let series: Vec<_> = idx.series(0).collect::<Result<Vec<_>>>().unwrap();
        assert_eq!(series.len(), 1);
        assert_eq!(series[0].labels.len(), 1);
        assert_eq!(&*series[0].labels[0].0, "a");
        assert_eq!(&*series[0].labels[0].1, "b");
        assert_eq!(series[0].chunks.len(), 2);
        assert_eq!(series[0].chunks[0].min_time, 100);
        assert_eq!(series[0].chunks[1].max_time, 400);
        assert_eq!(series[0].chunks[1].reference, 60);
        assert_eq!(series[0].id, series[0].offset / SERIES_ALIGN as u64);
        // The offsets reported are the same ones a resumed run would use.
        assert_eq!(idx.series(0).position(), idx.series_start());
        assert_eq!(idx.scan_stats().unwrap().series, 1);
        assert_eq!(idx.scan_stats().unwrap().chunks, 2);
    }

    #[test]
    fn unaligned_resume_offsets_are_rejected() {
        let idx = one_series(&[(100, 200, 8)]);
        let error = idx
            .series(idx.series_start() + 1)
            .next()
            .unwrap()
            .unwrap_err();
        assert!(error.to_string().contains("aligned"), "{error}");
    }

    #[test]
    fn offsets_outside_the_section_are_rejected() {
        let idx = one_series(&[(100, 200, 8)]);
        let past = idx.series_end() + SERIES_ALIGN as u64;
        assert!(
            idx.series(past).next().is_none(),
            "past the end yields nothing"
        );
        let before = idx.series_start() - SERIES_ALIGN as u64;
        let error = idx.series(before).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("outside"), "{error}");
    }

    #[test]
    fn payload_length_past_the_section_is_rejected() {
        let mut bytes = build_index(&[payload(&[(0, 1)], &[(100, 200, 8)])]);
        // Find the series section and inflate the first length varint.
        let idx = IndexReader::from_bytes(bytes.clone(), false).unwrap();
        let start = idx.series_start() as usize;
        bytes[start] = 0xff;
        bytes[start + 1] = 0x7f;
        let idx = IndexReader::from_bytes(bytes, false).unwrap();
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(
            error.to_string().contains("past the series section"),
            "{error}"
        );
        // The fast path must agree instead of counting a bogus record.
        assert!(idx.scan_stats().is_err());
    }

    #[test]
    fn label_count_beyond_the_payload_is_rejected() {
        let mut body = Vec::new();
        put_uvarint(&mut body, 1_000_000); // absurd label count
        let idx = reader(&[body]);
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("labels do not fit"), "{error}");
    }

    #[test]
    fn chunk_count_beyond_the_payload_is_rejected() {
        let mut body = Vec::new();
        put_uvarint(&mut body, 0); // no labels
        put_uvarint(&mut body, 100_000); // absurd chunk count
        let idx = reader(&[body]);
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("chunks do not fit"), "{error}");
    }

    #[test]
    fn chunk_max_time_before_min_time_is_rejected() {
        // `maxt - mint` is read as an unsigned delta, so a value above i64::MAX
        // turns negative and would move maxt before mint.
        let mut body = Vec::new();
        put_uvarint(&mut body, 0); // no labels
        put_uvarint(&mut body, 1); // one chunk
        put_varint(&mut body, 100);
        put_uvarint(&mut body, u64::MAX); // (i64) -1
        put_uvarint(&mut body, 8);
        let idx = reader(&[body]);
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("before min time"), "{error}");
    }

    #[test]
    fn non_increasing_chunk_times_are_rejected() {
        let idx = one_series(&[(100, 200, 8), (200, 300, 60)]);
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("previous chunk ends"), "{error}");
    }

    #[test]
    fn decreasing_chunk_references_are_rejected() {
        let idx = one_series(&[(100, 200, 60), (300, 400, 8)]);
        let error = idx.series(0).next().unwrap().unwrap_err();
        assert!(error.to_string().contains("precedes"), "{error}");
    }

    #[test]
    fn v1_indexes_are_byte_packed_and_reference_offsets() {
        // v1 symbol references are byte offsets of the symbol entries, not
        // indexes: the table starts at 5, so its payload (and the first symbol)
        // is at 13 and the second follows the 1-byte length prefix of "a".
        let idx = IndexReader::from_bytes(
            build_index_version(
                1,
                &[
                    payload(&[(13, 15)], &[(100, 200, 8)]),
                    payload(&[(13, 15), (15, 13)], &[(300, 400, 60)]),
                ],
            ),
            true,
        )
        .unwrap();
        assert_eq!(idx.version(), 1);
        idx.validate_layout().expect("v1 layout");

        let series: Vec<_> = idx.series(0).collect::<Result<Vec<_>>>().unwrap();
        assert_eq!(series.len(), 2);
        // v1 references are byte offsets, not offset/16.
        assert_eq!(series[0].id, series[0].offset);
        assert_eq!(series[1].id, series[1].offset);
        assert_ne!(series[0].offset % SERIES_ALIGN as u64, 0);

        // A reference from a postings list resolves the same way.
        let resolved = idx.series_by_ref(series[1].offset).unwrap();
        assert_eq!(resolved.labels.len(), 2);
        assert_eq!(resolved.chunks[0].reference, 60);
        // v2-style padded references must not resolve to a v1 record.
        assert!(idx
            .series_by_ref(series[1].offset * SERIES_ALIGN as u64)
            .is_err());

        assert_eq!(idx.scan_stats().unwrap().series, 2);
        assert_eq!(idx.validate_postings().unwrap(), PostingsStats::default());
    }

    #[test]
    fn an_index_without_a_label_space_is_not_corrupt() {
        // The synthetic builder writes no postings sections at all.
        let idx = one_series(&[(100, 200, 8)]);
        let stats = idx.validate_postings().unwrap();
        assert_eq!(stats, PostingsStats::default());
        // Lookups are unavailable rather than silently empty.
        assert!(idx.label_names().is_err());
        assert!(idx.postings("a", "b").is_err());
        // The series section is still readable.
        assert_eq!(idx.series(0).count(), 1);
    }

    #[test]
    fn scan_stats_matches_the_iterator() {
        let idx = reader(&[
            payload(&[(0, 1)], &[(100, 200, 8), (300, 400, 60)]),
            payload(&[(0, 1), (1, 0)], &[(500, 600, 120)]),
        ]);
        let stats = idx.scan_stats().unwrap();
        let mut series = 0;
        let mut chunks = 0;
        for s in idx.series(0) {
            let s = s.unwrap();
            series += 1;
            chunks += s.chunks.len();
        }
        assert_eq!(stats.series, series);
        assert_eq!(stats.chunks, chunks as u64);
        assert!(stats.end_series_offset > stats.min_series_offset);
    }
}