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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Postings lists and label lookups (index v1, v2 and v3).
//!
//! The index stores, for every `(label name, label value)` pair, a sorted list
//! of series references, plus one extra entry for the empty key that lists
//! every series. Which list a pair owns is recorded in the *postings offset
//! table*:
//!
//! ```text
//! postings table @ toc.postings_table
//!   be32 content_len
//!   content:
//!     be32 entry_count
//!     entry*:  uvarint 2 | uvarint name | uvarint value | uvarint offset
//!   be32 crc32c(content)
//!
//! postings list @ entry.offset
//!   be32 body_len
//!   body:    be32 count | count * be32 series ref
//!   be32 crc32c(body)
//! ```
//!
//! Reading the whole table would cost one allocation per distinct label value,
//! which is exactly the memory the crate promises not to spend. Instead the
//! table is sampled the way Prometheus samples it — entry 0, then every 32nd
//! entry of each label name, plus the last one — and a lookup walks forward
//! from the preceding sample. The sampled table is built on first use and
//! cached behind the same `RefCell` that holds the symbol cache, so `IndexReader`
//! stays `Send` but not `Sync`.

use std::ops::Range;
use std::sync::Arc;

use crate::error::{Error, Result};
use crate::varint;

use super::symbols::SYMBOL_FACTOR;
use super::toc::be32;
use super::IndexReader;

/// One sampled entry: a label value and the table-relative position of its
/// entry, from which a forward scan continues.
#[derive(Debug, Clone)]
struct Sample {
    value: String,
    /// Offset of the entry inside the table content (Prometheus `offsetPos`).
    offset: usize,
}

/// Sampled view of the postings offset table.
#[derive(Debug)]
pub(crate) struct PostingsTable {
    /// Range of the table content (`entry_count` plus entries) in the index.
    content: Range<usize>,
    /// Number of entries declared by the table.
    entries: u32,
    /// Label name to sampled entries, in table order (which is sorted).
    names: Vec<(String, Vec<Sample>)>,
}

impl PostingsTable {
    /// Parses and samples the offset table.
    ///
    /// Validates the length/CRC envelope, the two-key entry shape, entry
    /// ordering (names and values must ascend) and that every string is valid
    /// UTF-8. Any violation means the section is corrupt.
    pub(crate) fn parse(buf: &[u8], table_off: u64, body_end: usize, verify: bool) -> Result<Self> {
        let off = usize::try_from(table_off)
            .map_err(|_| Error::format("postings table offset does not fit in usize"))?;
        if off + 8 > body_end {
            return Err(Error::format(
                "postings table offset outside the index body",
            ));
        }
        let len = be32(buf, off)? as usize;
        let content_start = off + 4;
        let content_end = content_start
            .checked_add(len)
            .ok_or_else(|| Error::format("postings table length overflow"))?;
        let crc_end = content_end
            .checked_add(4)
            .ok_or_else(|| Error::format("postings table length overflow"))?;
        if content_end < content_start + 4 || crc_end > body_end {
            return Err(Error::format(format!(
                "postings table spans {content_start}..{crc_end}, past the index body ({body_end})"
            )));
        }

        if verify {
            let want = be32(buf, content_end)?;
            crate::checksum::verify(
                true,
                want,
                &buf[content_start..content_end],
                "index postings table",
            )?;
        }

        let mut p = content_start;
        let entries = be32(buf, p)?;
        p += 4;
        let mut names: Vec<(String, Vec<Sample>)> = Vec::new();
        // Sampling state for the name currently being scanned.
        let mut pending_last: Option<Sample> = None;
        let mut name_entries: usize = 0;
        let mut last_name: Option<String> = None;
        let mut last_value: Option<String> = None;

        for i in 0..entries {
            let entry_pos = p;
            let key_count = varint::uvarint(buf, &mut p)?;
            if key_count != 2 {
                return Err(Error::format(format!(
                    "postings table entry {i} has {key_count} keys, expected 2"
                )));
            }
            let name = read_string(buf, &mut p, content_end)?;
            let value = read_string(buf, &mut p, content_end)?;
            let _list_offset = varint::uvarint(buf, &mut p)?;

            // The table is sorted; a violation means the section is unusable
            // for lookups rather than merely unusual.
            match (&last_name, &last_value) {
                (Some(prev_name), Some(prev_value)) if *prev_name == name => {
                    if value <= *prev_value {
                        return Err(Error::format(format!(
                            "postings table entries for {name:?} are not sorted: {value:?} after {prev_value:?}"
                        )));
                    }
                }
                (Some(prev_name), _) if name < *prev_name => {
                    return Err(Error::format(format!(
                        "postings table names are not sorted: {name:?} after {prev_name:?}"
                    )));
                }
                _ => {}
            }

            if names.last().map(|(n, _)| n.as_str()) == Some(name.as_str()) {
                name_entries += 1;
                let samples = &mut names.last_mut().expect("checked above").1;
                if name_entries % SYMBOL_FACTOR == 0 {
                    samples.push(Sample {
                        value: value.clone(),
                        offset: entry_pos - content_start,
                    });
                }
            } else {
                // A new label name starts: keep the previous name's last entry,
                // which is always sampled.
                if let (Some(last), Some((_, samples))) = (pending_last.take(), names.last_mut()) {
                    if samples.last().map(|s| s.offset) != Some(last.offset) {
                        samples.push(last);
                    }
                }
                name_entries = 0;
                names.push((name.clone(), Vec::new()));
                names.last_mut().expect("just pushed").1.push(Sample {
                    value: value.clone(),
                    offset: entry_pos - content_start,
                });
            }

            pending_last = Some(Sample {
                value: value.clone(),
                offset: entry_pos - content_start,
            });
            last_name = Some(name);
            last_value = Some(value);
        }

        if let (Some(last), Some((_, samples))) = (pending_last.take(), names.last_mut()) {
            if samples.last().map(|s| s.offset) != Some(last.offset) {
                samples.push(last);
            }
        }

        Ok(Self {
            content: content_start..content_end,
            entries,
            names,
        })
    }

    /// Number of entries in the table.
    pub(crate) fn entries(&self) -> u32 {
        self.entries
    }

    /// Label names in table (sorted) order, excluding the all-series key.
    pub(crate) fn label_names(&self) -> Vec<String> {
        self.names
            .iter()
            .filter(|(name, _)| !name.is_empty())
            .map(|(name, _)| name.clone())
            .collect()
    }

    /// Sampled entries for one label name.
    fn samples(&self, name: &str) -> Option<&[Sample]> {
        self.names
            .binary_search_by(|(n, _)| n.as_str().cmp(name))
            .ok()
            .map(|i| self.names[i].1.as_slice())
    }

    /// Every value of `name`, in table order.
    fn values(&self, buf: &[u8], name: &str) -> Result<Vec<String>> {
        let Some(samples) = self.samples(name) else {
            return Ok(Vec::new());
        };
        let mut out = Vec::new();
        let mut p = self.content.start + samples[0].offset;
        while p < self.content.end {
            let (entry_name, value, _) = self.read_entry(buf, &mut p)?;
            if entry_name != name {
                break;
            }
            out.push(value);
        }
        Ok(out)
    }

    /// Table-relative offset of the list holding `name=value`.
    fn offset_for(&self, buf: &[u8], name: &str, value: &str) -> Result<Option<u64>> {
        let Some(samples) = self.samples(name) else {
            return Ok(None);
        };
        // Last sample whose value is <= the target; the list may be a few
        // entries further along the table.
        let idx = samples.partition_point(|s| s.value.as_str() <= value);
        let Some(start) = idx.checked_sub(1) else {
            return Ok(None);
        };
        let mut p = self.content.start + samples[start].offset;
        while p < self.content.end {
            let (entry_name, entry_value, offset) = self.read_entry(buf, &mut p)?;
            if entry_name != name || entry_value.as_str() > value {
                return Ok(None);
            }
            if entry_value == value {
                return Ok(Some(offset));
            }
        }
        Ok(None)
    }

    /// Reads one table entry, advancing `p` past it.
    fn read_entry(&self, buf: &[u8], p: &mut usize) -> Result<(String, String, u64)> {
        if *p >= self.content.end {
            return Err(Error::format("postings table ended inside an entry"));
        }
        let keys = varint::uvarint(buf, p)?;
        if keys != 2 {
            return Err(Error::format(format!(
                "postings table entry has {keys} keys, expected 2"
            )));
        }
        let name = read_string(buf, p, self.content.end)?;
        let value = read_string(buf, p, self.content.end)?;
        let offset = varint::uvarint(buf, p)?;
        Ok((name, value, offset))
    }
}

fn read_string(buf: &[u8], p: &mut usize, end: usize) -> Result<String> {
    let len = varint::uvarint(buf, p)? as usize;
    let stop = p
        .checked_add(len)
        .ok_or_else(|| Error::format("string length overflow in postings table"))?;
    if stop > end || stop > buf.len() {
        return Err(Error::format("string exceeds the postings table"));
    }
    let s = std::str::from_utf8(&buf[*p..stop])
        .map_err(|e| Error::format(format!("invalid utf-8 in postings table: {e}")))?
        .to_string();
    *p = stop;
    Ok(s)
}

/// One postings list, borrowed from the index file.
#[derive(Debug, Clone)]
struct List<'a> {
    refs: &'a [u8],
    /// Byte offset of the next reference inside `refs`.
    pos: usize,
    remaining: u32,
}

impl<'a> List<'a> {
    fn next(&mut self) -> Option<u64> {
        if self.remaining == 0 {
            return None;
        }
        let b = &self.refs[self.pos..self.pos + 4];
        self.pos += 4;
        self.remaining -= 1;
        Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as u64)
    }
}

#[derive(Debug, Clone)]
enum Inner<'a> {
    Single(List<'a>),
    /// Union of several lists, kept sorted and deduplicated.
    Merged {
        lists: Vec<List<'a>>,
        heads: Vec<Option<u64>>,
    },
}

/// Iterator over a postings list (or the union of several).
///
/// Yields series references in ascending order. For index v2/v3 a reference is
/// `offset / 16` and can be passed to [`crate::IndexReader::series`] only as a
/// byte offset after multiplying; use [`crate::IndexReader::series_by_ref`] to
/// resolve one, or pair it with [`SeriesRef::id`](crate::SeriesRef::id) from a
/// full scan.
#[derive(Debug, Clone)]
pub struct Postings<'a> {
    inner: Inner<'a>,
    emitted: u64,
}

impl<'a> Postings<'a> {
    fn single(list: List<'a>) -> Self {
        Self {
            inner: Inner::Single(list),
            emitted: 0,
        }
    }

    fn merged(lists: Vec<List<'a>>) -> Self {
        let heads = lists.iter().map(|_| None).collect::<Vec<Option<u64>>>();
        let mut merged = Self {
            inner: Inner::Merged { lists, heads },
            emitted: 0,
        };
        if let Inner::Merged { lists, heads } = &mut merged.inner {
            for (i, list) in lists.iter_mut().enumerate() {
                heads[i] = list.next();
            }
        }
        merged
    }

    /// Number of references not yet emitted (an upper bound for unions).
    pub fn len(&self) -> u64 {
        match &self.inner {
            Inner::Single(list) => list.remaining as u64,
            Inner::Merged { lists, .. } => lists.iter().map(|l| l.remaining as u64).sum(),
        }
    }

    /// True when no reference is left.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Empty list.
    pub fn empty() -> Self {
        Self::single(List {
            refs: &[],
            pos: 0,
            remaining: 0,
        })
    }

    /// Collects the remaining references into a vector.
    pub fn collect_refs(&mut self) -> Vec<u64> {
        let mut out = Vec::with_capacity(self.len() as usize);
        out.extend(self.by_ref());
        out
    }
}

impl Iterator for Postings<'_> {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        let next = match &mut self.inner {
            Inner::Single(list) => list.next(),
            Inner::Merged { lists, heads } => {
                // Smallest head, then advance every list that holds it so the
                // union stays deduplicated.
                let mut best: Option<(usize, u64)> = None;
                for (i, head) in heads.iter().enumerate() {
                    if let Some(v) = *head {
                        if best.map(|(_, bv)| v < bv).unwrap_or(true) {
                            best = Some((i, v));
                        }
                    }
                }
                let (idx, value) = best?;
                heads[idx] = lists[idx].next();
                for (i, head) in heads.iter_mut().enumerate() {
                    if *head == Some(value) {
                        *head = lists[i].next();
                    }
                }
                Some(value)
            }
        };
        if next.is_some() {
            self.emitted += 1;
        }
        next
    }
}

/// Statistics from [`IndexReader::validate_postings`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PostingsStats {
    /// Entries in the offset table (one per label pair plus the all-series key).
    pub entries: u32,
    /// Distinct label names, excluding the all-series key.
    pub label_names: usize,
    /// Postings lists that were decoded.
    pub lists: u64,
    /// Series references across all lists.
    pub refs: u64,
}

impl IndexReader {
    /// Byte range of the postings section, empty when the block has none.
    fn postings_range(&self) -> Range<usize> {
        let toc = self.toc();
        let start = if toc.postings != 0 {
            toc.postings
        } else {
            toc.label_indices
        };
        let table = if toc.postings_table != 0 {
            toc.postings_table
        } else {
            toc.label_indices_table
        };
        if start == 0 || table <= start {
            return 0..0;
        }
        start as usize..table as usize
    }

    /// Builds the sampled offset table, or returns the cached one.
    fn postings_table(&self) -> Result<Arc<PostingsTable>> {
        if let Some(table) = self.postings_table.borrow().clone() {
            return Ok(table);
        }
        let toc = self.toc();
        let table_off = if toc.postings_table != 0 {
            toc.postings_table
        } else {
            toc.label_indices_table
        };
        if table_off == 0 {
            return Err(Error::format("index has no postings offset table"));
        }
        let body_end = self.body_end();
        let table = Arc::new(PostingsTable::parse(
            &self.mmap,
            table_off,
            body_end,
            self.verify_crc(),
        )?);
        *self.postings_table.borrow_mut() = Some(table.clone());
        Ok(table)
    }

    /// Label names in the block, sorted, excluding the all-series key.
    ///
    /// Costs one pass over the sampled offset table, cached after the first
    /// call.
    pub fn label_names(&self) -> Result<Vec<String>> {
        Ok(self.postings_table()?.label_names())
    }

    /// Every value of `name`, in the index's (sorted) order.
    ///
    /// Returns an empty vector when the label name is absent.
    pub fn label_values(&self, name: &str) -> Result<Vec<String>> {
        let table = self.postings_table()?;
        table.values(&self.mmap, name)
    }

    /// Postings list for `name=value`, in ascending series-reference order.
    ///
    /// An unknown pair yields an empty list, matching Prometheus. The list is
    /// decoded lazily: only the frame is read up front.
    pub fn postings(&self, name: &str, value: &str) -> Result<Postings<'_>> {
        let table = self.postings_table()?;
        match table.offset_for(&self.mmap, name, value)? {
            Some(offset) => Ok(Postings::single(self.read_list(offset)?)),
            None => Ok(Postings::empty()),
        }
    }

    /// Union of the postings lists for several values of one label name.
    ///
    /// Values do not need to be sorted; duplicates and unknown values are
    /// ignored. This is the shape a `label=~"a|b"` matcher needs.
    pub fn postings_multi(&self, name: &str, values: &[&str]) -> Result<Postings<'_>> {
        if values.is_empty() {
            return Ok(Postings::empty());
        }
        let table = self.postings_table()?;
        let mut found = Vec::new();
        for value in values {
            if let Some(offset) = table.offset_for(&self.mmap, name, value)? {
                found.push(offset);
            }
        }
        found.sort_unstable();
        found.dedup();
        let mut lists = Vec::with_capacity(found.len());
        for offset in found {
            lists.push(self.read_list(offset)?);
        }
        Ok(Postings::merged(lists))
    }

    /// Postings list of every series in the block.
    ///
    /// This is the empty-key entry, which is also what Prometheus uses for
    /// "match everything".
    pub fn all_postings(&self) -> Result<Postings<'_>> {
        self.postings("", "")
    }

    /// Resolves a series reference from [`Postings`] into its record.
    ///
    /// v2/v3 references are `offset / 16`, so the byte offset has to be
    /// reconstructed; v1 references are already byte offsets.
    pub fn series_by_ref(&self, reference: u64) -> Result<super::SeriesRef> {
        let offset = if self.version() == 1 {
            reference
        } else {
            reference
                .checked_mul(super::SERIES_ALIGN as u64)
                .ok_or_else(|| Error::format("series reference overflow"))?
        };
        let start = usize::try_from(offset)
            .map_err(|_| Error::format("series reference does not fit in usize"))?;
        let (series, _) = self.parse_series(start)?;
        Ok(series)
    }

    /// Decodes one postings list, validating its envelope and references.
    fn read_list(&self, offset: u64) -> Result<List<'_>> {
        let section = self.postings_range();
        if section.is_empty() {
            return Err(Error::format("index has no postings section"));
        }
        let start = usize::try_from(offset)
            .map_err(|_| Error::format("postings offset does not fit in usize"))?;
        if !section.contains(&start) {
            return Err(Error::format(format!(
                "postings list offset {start} outside the postings section {:?}",
                section
            )));
        }
        let body_len = be32(&self.mmap, start)? as usize;
        let body_start = start + 4;
        let body_end = body_start
            .checked_add(body_len)
            .ok_or_else(|| Error::format("postings list length overflow"))?;
        let crc_end = body_end
            .checked_add(4)
            .ok_or_else(|| Error::format("postings list length overflow"))?;
        if crc_end > section.end || crc_end > self.mmap.len() {
            return Err(Error::format(format!(
                "postings list at {start} runs past the postings section"
            )));
        }
        if self.verify_crc() {
            let want = be32(&self.mmap, body_end)?;
            crate::checksum::verify(
                true,
                want,
                &self.mmap[body_start..body_end],
                "index postings",
            )?;
        }
        if body_len < 4 {
            return Err(Error::format("postings list shorter than its count"));
        }
        let count = be32(&self.mmap, body_start)?;
        let expect = 4 + count as usize * 4;
        if body_len != expect {
            return Err(Error::format(format!(
                "postings list at {start} declares {count} references ({expect} bytes) but holds {body_len} bytes"
            )));
        }
        Ok(List {
            refs: &self.mmap[body_start + 4..body_end],
            pos: 0,
            remaining: count,
        })
    }

    /// Validates the offset table and every postings list.
    ///
    /// Walks all entries (not just the sampled ones), decodes each list once
    /// and checks that references are strictly increasing and addressable in
    /// this index version. Cost is proportional to the total number of
    /// references, so this is the expensive half of block validation.
    pub fn validate_postings(&self) -> Result<PostingsStats> {
        let toc = self.toc();
        if toc.postings_table == 0 && toc.label_indices_table == 0 {
            // An index without a label space is unusual but not corrupt: the
            // series section is still readable. Report zero stats so callers
            // can tell "absent" from "broken".
            return Ok(PostingsStats::default());
        }
        let table = self.postings_table()?;
        let section = self.postings_range();
        let mut stats = PostingsStats {
            entries: table.entries(),
            label_names: table.label_names().len(),
            ..Default::default()
        };
        if table.entries() == 0 {
            return Ok(stats);
        }

        // Walk the table itself to visit every list exactly once.
        let mut p = table.content.start;
        let count = be32(&self.mmap, p)?;
        p += 4;
        for i in 0..count {
            let (name, value, offset) = table.read_entry(&self.mmap, &mut p)?;
            debug_assert!(p <= table.content.end);

            let list = self.read_list(offset).map_err(|e| {
                Error::format(format!(
                    "postings list for {name}={value} (offset {offset}, entry {i}): {e}"
                ))
            })?;
            stats.lists += 1;
            stats.refs += list.remaining as u64;

            let mut prev: Option<u64> = None;
            let mut list = list;
            while let Some(reference) = list.next() {
                if let Some(prev) = prev {
                    if reference <= prev {
                        return Err(Error::format(format!(
                            "postings list for {name}={value} is not sorted: {reference} after {prev}"
                        )));
                    }
                }
                prev = Some(reference);
            }

            if let Some(max) = prev {
                if self.version() != 1 {
                    let limit = (self.series_end() / super::SERIES_ALIGN as u64) + 1;
                    if max > limit {
                        return Err(Error::format(format!(
                            "postings list for {name}={value} references series {max}, beyond the series section"
                        )));
                    }
                } else if max >= self.series_end() {
                    return Err(Error::format(format!(
                        "postings list for {name}={value} references offset {max}, beyond the series section"
                    )));
                }
            }

            // Every entry must point into the postings section.
            if !section.contains(&(offset as usize)) {
                return Err(Error::format(format!(
                    "postings entry for {name}={value} points outside the postings section"
                )));
            }
        }
        Ok(stats)
    }
}

impl IndexReader {
    /// End of the index body, i.e. where the TOC starts.
    pub(crate) fn body_end(&self) -> usize {
        self.mmap.len().saturating_sub(super::toc::TOC_LEN)
    }
}

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

    /// Encodes a postings-list entry: length, body (count + refs), CRC.
    fn list(refs: &[u32]) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(&(refs.len() as u32).to_be_bytes());
        for r in refs {
            body.extend_from_slice(&r.to_be_bytes());
        }
        let mut out = Vec::new();
        out.extend_from_slice(&(body.len() as u32).to_be_bytes());
        out.extend_from_slice(&body);
        out.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
        out
    }

    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_str(out: &mut Vec<u8>, s: &str) {
        put_uvarint(out, s.len() as u64);
        out.extend_from_slice(s.as_bytes());
    }

    /// Builds a table for `(name, value)` -> list offset pairs.
    fn table(entries: &[(&str, &str, u64)]) -> Vec<u8> {
        let mut content = Vec::new();
        content.extend_from_slice(&(entries.len() as u32).to_be_bytes());
        for (name, value, offset) in entries {
            put_uvarint(&mut content, 2);
            put_str(&mut content, name);
            put_str(&mut content, value);
            put_uvarint(&mut content, *offset);
        }
        let mut out = Vec::new();
        out.extend_from_slice(&(content.len() as u32).to_be_bytes());
        let crc = crc32c::crc32c(&content);
        out.extend_from_slice(&content);
        out.extend_from_slice(&crc.to_be_bytes());
        out
    }

    #[test]
    fn table_round_trips_and_looks_up_values() {
        let buf = table(&[
            ("", "", 0),
            ("__name__", "a", 8),
            ("__name__", "b", 20),
            ("job", "x", 32),
        ]);
        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
        assert_eq!(t.entries(), 4);
        assert_eq!(
            t.label_names(),
            vec!["__name__".to_string(), "job".to_string()]
        );
        assert_eq!(t.values(&buf, "__name__").unwrap(), vec!["a", "b"]);
        assert_eq!(t.values(&buf, "job").unwrap(), vec!["x"]);
        assert!(t.values(&buf, "absent").unwrap().is_empty());
        assert_eq!(t.offset_for(&buf, "__name__", "b").unwrap(), Some(20));
        assert_eq!(t.offset_for(&buf, "__name__", "aa").unwrap(), None);
        assert_eq!(t.offset_for(&buf, "__name__", "z").unwrap(), None);
        assert_eq!(t.offset_for(&buf, "", "").unwrap(), Some(0));
        assert_eq!(t.offset_for(&buf, "absent", "x").unwrap(), None);
    }

    #[test]
    fn sampling_keeps_every_32nd_value_and_the_last() {
        let mut names: Vec<String> = (0..70).map(|i| format!("v{i:03}")).collect();
        names.push("zzz".to_string());
        let offsets: Vec<u64> = (0..names.len() as u64).map(|i| i * 10).collect();
        let mut entries: Vec<(&str, &str, u64)> = vec![("", "", 0)];
        for (n, o) in names.iter().zip(&offsets) {
            entries.push(("job", n.as_str(), *o));
        }
        let buf = table(&entries);
        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
        let samples = t.samples("job").unwrap();
        // 0, 32, 64 sampled by stride, plus the final entry (index 70).
        let values: Vec<&str> = samples.iter().map(|s| s.value.as_str()).collect();
        assert_eq!(values, vec!["v000", "v032", "v064", "zzz"]);
        // Lookups still find values between samples.
        assert_eq!(t.offset_for(&buf, "job", "v047").unwrap(), Some(470));
        assert_eq!(t.offset_for(&buf, "job", "v069").unwrap(), Some(690));
    }

    #[test]
    fn unsorted_entries_are_rejected() {
        let buf = table(&[("a", "b", 0), ("a", "a", 0)]);
        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
        assert!(err.to_string().contains("not sorted"), "{err}");

        let buf = table(&[("b", "a", 0), ("a", "b", 0)]);
        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
        assert!(err.to_string().contains("names are not sorted"), "{err}");
    }

    #[test]
    fn a_wrong_key_count_is_rejected() {
        let mut content = Vec::new();
        content.extend_from_slice(&1u32.to_be_bytes());
        put_uvarint(&mut content, 3);
        put_str(&mut content, "a");
        put_str(&mut content, "b");
        put_uvarint(&mut content, 0);
        let mut buf = Vec::new();
        buf.extend_from_slice(&(content.len() as u32).to_be_bytes());
        let crc = crc32c::crc32c(&content);
        buf.extend_from_slice(&content);
        buf.extend_from_slice(&crc.to_be_bytes());
        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
        assert!(err.to_string().contains("expected 2"), "{err}");
    }

    #[test]
    fn a_truncated_table_is_rejected() {
        let buf = table(&[("a", "b", 0)]);
        let err = PostingsTable::parse(&buf, 0, buf.len() - 6, true).unwrap_err();
        assert!(err.to_string().contains("past the index body"), "{err}");
    }

    #[test]
    fn merged_postings_union_is_sorted_and_deduplicated() {
        // Big-endian references: a = [1, 3, 7], b = [1, 2, 9].
        let a = List {
            refs: &[0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 7],
            pos: 0,
            remaining: 3,
        };
        let b = List {
            refs: &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 9],
            pos: 0,
            remaining: 3,
        };
        let merged: Vec<u64> = Postings::merged(vec![a, b]).collect();
        assert_eq!(merged, vec![1, 2, 3, 7, 9]);
    }

    #[test]
    fn lists_decode_in_order() {
        let buf = list(&[5, 6, 9]);
        let l = List {
            refs: &buf[8..buf.len() - 4],
            pos: 0,
            remaining: 3,
        };
        let got: Vec<u64> = Postings::single(l).collect();
        assert_eq!(got, vec![5, 6, 9]);
    }
}