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
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
//! 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_str(buf, &mut p, content_end)?.to_string();
            let value = read_str(buf, &mut p, content_end)?.to_string();
            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.to_string());
        }
        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 > value {
                return Ok(None);
            }
            if entry_value == value {
                return Ok(Some(offset));
            }
        }
        Ok(None)
    }

    /// Reads one table entry, advancing `p` past it.
    ///
    /// Borrows from `buf` so a full-table scan allocates nothing per entry.
    fn read_entry<'b>(&self, buf: &'b [u8], p: &mut usize) -> Result<(&'b str, &'b str, 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_str(buf, p, self.content.end)?;
        let value = read_str(buf, p, self.content.end)?;
        let offset = varint::uvarint(buf, p)?;
        Ok((name, value, offset))
    }
}

fn read_str<'b>(buf: &'b [u8], p: &mut usize, end: usize) -> Result<&'b str> {
    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}")))?;
    *p = stop;
    Ok(s)
}

/// A sorted, lazily decoded sequence of series references.
///
/// Implementations never materialise the whole list, so a label pair with
/// millions of series costs one 4-byte read per step. References are yielded in
/// ascending order; `seek` skips forward in logarithmic time where the concrete
/// type can binary search.
///
/// The trait is object safe: `Box<dyn Postings>` is the currency of
/// [`crate::index::postings_ops`], which is how matcher plans are combined.
pub trait Postings {
    /// Returns the next reference, or `None` at the end.
    fn next(&mut self) -> Result<Option<u64>>;

    /// Advances to the first reference `>= target` and returns it.
    ///
    /// Every reference smaller than `target` is consumed. Returns `None` when
    /// the list is exhausted.
    fn seek(&mut self, target: u64) -> Result<Option<u64>>;

    /// Drains the remaining references into a vector.
    ///
    /// Only for callers that genuinely need the whole set (small lists, tests,
    /// checkpoints); it allocates proportional to the list length.
    fn collect_refs(&mut self) -> Result<Vec<u64>>
    where
        Self: Sized,
    {
        let mut out = Vec::new();
        while let Some(reference) = self.next()? {
            out.push(reference);
        }
        Ok(out)
    }
}

/// A boxed source behaves like the source it wraps, so plans can be nested:
/// `Box<dyn Postings>` is itself a `Postings`.
impl Postings for Box<dyn Postings + '_> {
    fn next(&mut self) -> Result<Option<u64>> {
        (**self).next()
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        (**self).seek(target)
    }
}

/// Cursor over 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 List<'_> {
    /// Reference at index `i` of the *remaining* window.
    fn at(&self, i: usize) -> u64 {
        let b = &self.refs[self.pos + i * 4..self.pos + i * 4 + 4];
        u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as u64
    }

    fn next_value(&mut self) -> Option<u64> {
        if self.remaining == 0 {
            return None;
        }
        let v = self.at(0);
        self.pos += 4;
        self.remaining -= 1;
        Some(v)
    }

    /// Binary search over the remaining window; the writer stores references
    /// ascending, and `validate_postings` enforces it.
    fn seek_value(&mut self, target: u64) -> Option<u64> {
        let mut lo = 0usize;
        let mut hi = self.remaining as usize;
        while lo < hi {
            let mid = lo + (hi - lo) / 2;
            if self.at(mid) < target {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        self.pos += lo * 4;
        self.remaining -= lo as u32;
        self.next_value()
    }

    fn len(&self) -> u64 {
        self.remaining as u64
    }
}

/// A single postings list.
#[derive(Debug, Clone)]
pub struct PostingsList<'a> {
    list: List<'a>,
}

impl<'a> PostingsList<'a> {
    fn new(list: List<'a>) -> Self {
        Self { list }
    }

    /// A list with no references.
    pub fn empty() -> Self {
        Self {
            list: List {
                refs: &[],
                pos: 0,
                remaining: 0,
            },
        }
    }

    /// Number of references left, exactly.
    pub fn len(&self) -> u64 {
        self.list.len()
    }

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

impl Postings for PostingsList<'_> {
    fn next(&mut self) -> Result<Option<u64>> {
        Ok(self.list.next_value())
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        Ok(self.list.seek_value(target))
    }
}

/// The union of several postings lists, sorted and deduplicated.
#[derive(Debug, Clone)]
pub struct MergedPostings<'a> {
    lists: Vec<List<'a>>,
    heads: Vec<Option<u64>>,
}

impl<'a> MergedPostings<'a> {
    fn new(lists: Vec<List<'a>>) -> Self {
        let heads = lists.iter().map(|_| None).collect::<Vec<Option<u64>>>();
        let mut merged = Self { lists, heads };
        merged.prime();
        merged
    }

    fn prime(&mut self) {
        for (i, list) in self.lists.iter_mut().enumerate() {
            if self.heads[i].is_none() {
                self.heads[i] = list.next_value();
            }
        }
    }

    /// Upper bound on the references left; duplicates across lists are merged
    /// away, so the real count can be smaller.
    pub fn len(&self) -> u64 {
        self.lists.iter().map(|l| l.len()).sum()
    }

    /// True when no list has anything left.
    pub fn is_empty(&self) -> bool {
        self.heads.iter().all(|h| h.is_none())
    }

    fn advance(&mut self) -> Option<u64> {
        let mut best: Option<(usize, u64)> = None;
        for (i, head) in self.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?;
        self.heads[idx] = self.lists[idx].next_value();
        // Advance every other list that held the same reference so the union
        // stays deduplicated.
        for (i, head) in self.heads.iter_mut().enumerate() {
            if *head == Some(value) {
                *head = self.lists[i].next_value();
            }
        }
        Some(value)
    }
}

impl Postings for MergedPostings<'_> {
    fn next(&mut self) -> Result<Option<u64>> {
        Ok(self.advance())
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        for (i, list) in self.lists.iter_mut().enumerate() {
            if self.heads[i].is_some_and(|head| head < target) {
                self.heads[i] = list.seek_value(target);
            }
        }
        Ok(self.advance())
    }
}

/// An in-memory postings list: sorted references held in a `Vec`.
///
/// Useful to combine literal sets with index-backed lists (tests, cached
/// results, a plan that starts from a known set) without going through the
/// postings section.
#[derive(Debug, Clone, Default)]
pub struct VecPostings {
    refs: Vec<u64>,
    pos: usize,
}

impl VecPostings {
    /// Wraps a vector of references.
    ///
    /// The references are sorted and deduplicated so the `Postings` contract
    /// (ascending, no duplicates) holds for any input.
    pub fn new(mut refs: Vec<u64>) -> Self {
        refs.sort_unstable();
        refs.dedup();
        Self { refs, pos: 0 }
    }

    /// References left to yield.
    pub fn len(&self) -> u64 {
        (self.refs.len() - self.pos) as u64
    }

    /// True when nothing is left.
    pub fn is_empty(&self) -> bool {
        self.pos >= self.refs.len()
    }

    fn seek_index(&mut self, target: u64) -> Option<u64> {
        let window = &self.refs[self.pos..];
        let skip = window.partition_point(|r| *r < target);
        self.pos += skip;
        let v = self.refs.get(self.pos).copied();
        if v.is_some() {
            self.pos += 1;
        }
        v
    }
}

impl Postings for VecPostings {
    fn next(&mut self) -> Result<Option<u64>> {
        if self.pos >= self.refs.len() {
            return Ok(None);
        }
        let v = self.refs[self.pos];
        self.pos += 1;
        Ok(Some(v))
    }

    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
        Ok(self.seek_index(target))
    }
}

/// 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.get() {
            return Ok(table.clone());
        }
        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(),
        )?);
        // Another thread may have won the race; both tables describe the same
        // bytes, so use whichever landed in the cell.
        Ok(self.postings_table.get_or_init(|| table).clone())
    }

    /// 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<PostingsList<'_>> {
        let table = self.postings_table()?;
        match table.offset_for(&self.mmap, name, value)? {
            Some(offset) => Ok(PostingsList::new(self.read_list(offset)?)),
            None => Ok(PostingsList::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<MergedPostings<'_>> {
        if values.is_empty() {
            return Ok(MergedPostings::new(Vec::new()));
        }
        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(MergedPostings::new(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<PostingsList<'_>> {
        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 mut cache = super::symbols::SymbolCache::small();
        let (series, _) = self.parse_series(start, &mut cache)?;
        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,
        })
    }

    /// Union of the postings of every value of `name` accepted by `predicate`.
    ///
    /// The label values are streamed from the offset table (borrowed, no
    /// per-value allocation); only the offsets of the selected lists are kept.
    /// This is the primitive a regex matcher needs, since it has to inspect
    /// every value of one label.
    pub fn postings_for_values<'a>(
        &'a self,
        name: &str,
        predicate: impl Fn(&str) -> bool,
    ) -> Result<super::postings_ops::BoxPostings<'a>> {
        let table = self.postings_table()?;
        let Some(samples) = table.samples(name) else {
            return Ok(Box::new(PostingsList::empty()));
        };
        let mut lists = Vec::new();
        let mut p = table.content.start + samples[0].offset;
        let buf = &*self.mmap;
        while p < table.content.end {
            let (entry_name, value, offset) = table.read_entry(buf, &mut p)?;
            if entry_name != name {
                break;
            }
            if predicate(value) {
                lists.push(self.read_list(offset)?);
            }
        }
        if lists.is_empty() {
            return Ok(Box::new(PostingsList::empty()));
        }
        Ok(Box::new(MergedPostings::new(lists)))
    }

    /// Calls `f` for every value of `name`, in index order, without collecting
    /// them.
    ///
    /// Returns the number of values visited. Useful for a query layer that wants
    /// to inspect a label's cardinality without allocating the value strings.
    pub fn for_each_label_value(&self, name: &str, mut f: impl FnMut(&str)) -> Result<usize> {
        let table = self.postings_table()?;
        let Some(samples) = table.samples(name) else {
            return Ok(0);
        };
        let mut seen = 0usize;
        let mut p = table.content.start + samples[0].offset;
        let buf = &*self.mmap;
        while p < table.content.end {
            let (entry_name, value, _) = table.read_entry(buf, &mut p)?;
            if entry_name != name {
                break;
            }
            f(value);
            seen += 1;
        }
        Ok(seen)
    }

    /// 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_value() {
                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 = MergedPostings::new(vec![a, b]).collect_refs().unwrap();
        assert_eq!(merged, vec![1, 2, 3, 7, 9]);
    }

    /// Builds a `PostingsList` over big-endian references.
    fn list_of(refs: &[u32]) -> PostingsList<'static> {
        let leaked: &'static [u8] = Box::leak(
            refs.iter()
                .flat_map(|r| r.to_be_bytes())
                .collect::<Vec<u8>>()
                .into_boxed_slice(),
        );
        PostingsList::new(List {
            refs: leaked,
            pos: 0,
            remaining: refs.len() as u32,
        })
    }

    #[test]
    fn seek_lands_on_the_first_reference_at_or_after_the_target() {
        // Each case starts from a fresh list: a hit consumes the reference.
        let mut exact = list_of(&[5, 9, 17, 40]);
        assert_eq!(exact.seek(9).unwrap(), Some(9));

        let mut between = list_of(&[5, 9, 17, 40]);
        assert_eq!(between.seek(10).unwrap(), Some(17));

        let mut before = list_of(&[5, 9, 17, 40]);
        assert_eq!(before.seek(0).unwrap(), Some(5));

        let mut past = list_of(&[5, 9, 17, 40]);
        assert_eq!(past.seek(41).unwrap(), None);
        assert_eq!(past.next().unwrap(), None);
        assert_eq!(past.seek(1).unwrap(), None);
    }

    #[test]
    fn seek_only_moves_forward() {
        let mut p = list_of(&[5, 9, 17, 40]);
        assert_eq!(p.next().unwrap(), Some(5));
        // Seeking backwards returns the current position's next value, never a
        // previously consumed one.
        assert_eq!(p.seek(1).unwrap(), Some(9));
        assert_eq!(p.len(), 2);
    }

    #[test]
    fn empty_lists_yield_nothing() {
        let mut p = PostingsList::empty();
        assert!(p.is_empty());
        assert_eq!(p.next().unwrap(), None);
        assert_eq!(p.seek(3).unwrap(), None);
        assert_eq!(p.collect_refs().unwrap(), Vec::<u64>::new());
    }

    #[test]
    fn merged_seek_advances_every_list() {
        // a = [2, 10], b = [4, 10, 20]
        let a = List {
            refs: &[0, 0, 0, 2, 0, 0, 0, 10],
            pos: 0,
            remaining: 2,
        };
        let b = List {
            refs: &[0, 0, 0, 4, 0, 0, 0, 10, 0, 0, 0, 20],
            pos: 0,
            remaining: 3,
        };
        let mut merged = MergedPostings::new(vec![a, b]);
        assert_eq!(merged.seek(5).unwrap(), Some(10));
        // The duplicate 10 from both lists must be emitted once.
        assert_eq!(merged.next().unwrap(), Some(20));
        assert_eq!(merged.next().unwrap(), None);
    }

    #[test]
    fn merged_empty_union_is_empty() {
        let mut merged = MergedPostings::new(Vec::new());
        assert!(merged.is_empty());
        assert_eq!(merged.next().unwrap(), None);
        assert_eq!(merged.seek(7).unwrap(), None);
    }

    #[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 = PostingsList::new(l).collect_refs().unwrap();
        assert_eq!(got, vec![5, 6, 9]);
    }
}