Skip to main content

tsdb_reader/index/
postings.rs

1//! Postings lists and label lookups (index v1, v2 and v3).
2//!
3//! The index stores, for every `(label name, label value)` pair, a sorted list
4//! of series references, plus one extra entry for the empty key that lists
5//! every series. Which list a pair owns is recorded in the *postings offset
6//! table*:
7//!
8//! ```text
9//! postings table @ toc.postings_table
10//!   be32 content_len
11//!   content:
12//!     be32 entry_count
13//!     entry*:  uvarint 2 | uvarint name | uvarint value | uvarint offset
14//!   be32 crc32c(content)
15//!
16//! postings list @ entry.offset
17//!   be32 body_len
18//!   body:    be32 count | count * be32 series ref
19//!   be32 crc32c(body)
20//! ```
21//!
22//! Reading the whole table would cost one allocation per distinct label value,
23//! which is exactly the memory the crate promises not to spend. Instead the
24//! table is sampled the way Prometheus samples it — entry 0, then every 32nd
25//! entry of each label name, plus the last one — and a lookup walks forward
26//! from the preceding sample. The sampled table is built on first use and
27//! cached behind the same `RefCell` that holds the symbol cache, so `IndexReader`
28//! stays `Send` but not `Sync`.
29
30use std::ops::Range;
31use std::sync::Arc;
32
33use crate::error::{Error, Result};
34use crate::varint;
35
36use super::symbols::SYMBOL_FACTOR;
37use super::toc::be32;
38use super::IndexReader;
39
40/// One sampled entry: a label value and the table-relative position of its
41/// entry, from which a forward scan continues.
42#[derive(Debug, Clone)]
43struct Sample {
44    value: String,
45    /// Offset of the entry inside the table content (Prometheus `offsetPos`).
46    offset: usize,
47}
48
49/// Sampled view of the postings offset table.
50#[derive(Debug)]
51pub(crate) struct PostingsTable {
52    /// Range of the table content (`entry_count` plus entries) in the index.
53    content: Range<usize>,
54    /// Number of entries declared by the table.
55    entries: u32,
56    /// Label name to sampled entries, in table order (which is sorted).
57    names: Vec<(String, Vec<Sample>)>,
58}
59
60impl PostingsTable {
61    /// Parses and samples the offset table.
62    ///
63    /// Validates the length/CRC envelope, the two-key entry shape, entry
64    /// ordering (names and values must ascend) and that every string is valid
65    /// UTF-8. Any violation means the section is corrupt.
66    pub(crate) fn parse(buf: &[u8], table_off: u64, body_end: usize, verify: bool) -> Result<Self> {
67        let off = usize::try_from(table_off)
68            .map_err(|_| Error::format("postings table offset does not fit in usize"))?;
69        if off + 8 > body_end {
70            return Err(Error::format(
71                "postings table offset outside the index body",
72            ));
73        }
74        let len = be32(buf, off)? as usize;
75        let content_start = off + 4;
76        let content_end = content_start
77            .checked_add(len)
78            .ok_or_else(|| Error::format("postings table length overflow"))?;
79        let crc_end = content_end
80            .checked_add(4)
81            .ok_or_else(|| Error::format("postings table length overflow"))?;
82        if content_end < content_start + 4 || crc_end > body_end {
83            return Err(Error::format(format!(
84                "postings table spans {content_start}..{crc_end}, past the index body ({body_end})"
85            )));
86        }
87
88        if verify {
89            let want = be32(buf, content_end)?;
90            crate::checksum::verify(
91                true,
92                want,
93                &buf[content_start..content_end],
94                "index postings table",
95            )?;
96        }
97
98        let mut p = content_start;
99        let entries = be32(buf, p)?;
100        p += 4;
101        let mut names: Vec<(String, Vec<Sample>)> = Vec::new();
102        // Sampling state for the name currently being scanned.
103        let mut pending_last: Option<Sample> = None;
104        let mut name_entries: usize = 0;
105        let mut last_name: Option<String> = None;
106        let mut last_value: Option<String> = None;
107
108        for i in 0..entries {
109            let entry_pos = p;
110            let key_count = varint::uvarint(buf, &mut p)?;
111            if key_count != 2 {
112                return Err(Error::format(format!(
113                    "postings table entry {i} has {key_count} keys, expected 2"
114                )));
115            }
116            let name = read_str(buf, &mut p, content_end)?.to_string();
117            let value = read_str(buf, &mut p, content_end)?.to_string();
118            let _list_offset = varint::uvarint(buf, &mut p)?;
119
120            // The table is sorted; a violation means the section is unusable
121            // for lookups rather than merely unusual.
122            match (&last_name, &last_value) {
123                (Some(prev_name), Some(prev_value)) if *prev_name == name => {
124                    if value <= *prev_value {
125                        return Err(Error::format(format!(
126                            "postings table entries for {name:?} are not sorted: {value:?} after {prev_value:?}"
127                        )));
128                    }
129                }
130                (Some(prev_name), _) if name < *prev_name => {
131                    return Err(Error::format(format!(
132                        "postings table names are not sorted: {name:?} after {prev_name:?}"
133                    )));
134                }
135                _ => {}
136            }
137
138            if names.last().map(|(n, _)| n.as_str()) == Some(name.as_str()) {
139                name_entries += 1;
140                let samples = &mut names.last_mut().expect("checked above").1;
141                if name_entries % SYMBOL_FACTOR == 0 {
142                    samples.push(Sample {
143                        value: value.clone(),
144                        offset: entry_pos - content_start,
145                    });
146                }
147            } else {
148                // A new label name starts: keep the previous name's last entry,
149                // which is always sampled.
150                if let (Some(last), Some((_, samples))) = (pending_last.take(), names.last_mut()) {
151                    if samples.last().map(|s| s.offset) != Some(last.offset) {
152                        samples.push(last);
153                    }
154                }
155                name_entries = 0;
156                names.push((name.clone(), Vec::new()));
157                names.last_mut().expect("just pushed").1.push(Sample {
158                    value: value.clone(),
159                    offset: entry_pos - content_start,
160                });
161            }
162
163            pending_last = Some(Sample {
164                value: value.clone(),
165                offset: entry_pos - content_start,
166            });
167            last_name = Some(name);
168            last_value = Some(value);
169        }
170
171        if let (Some(last), Some((_, samples))) = (pending_last.take(), names.last_mut()) {
172            if samples.last().map(|s| s.offset) != Some(last.offset) {
173                samples.push(last);
174            }
175        }
176
177        Ok(Self {
178            content: content_start..content_end,
179            entries,
180            names,
181        })
182    }
183
184    /// Number of entries in the table.
185    pub(crate) fn entries(&self) -> u32 {
186        self.entries
187    }
188
189    /// Label names in table (sorted) order, excluding the all-series key.
190    pub(crate) fn label_names(&self) -> Vec<String> {
191        self.names
192            .iter()
193            .filter(|(name, _)| !name.is_empty())
194            .map(|(name, _)| name.clone())
195            .collect()
196    }
197
198    /// Sampled entries for one label name.
199    fn samples(&self, name: &str) -> Option<&[Sample]> {
200        self.names
201            .binary_search_by(|(n, _)| n.as_str().cmp(name))
202            .ok()
203            .map(|i| self.names[i].1.as_slice())
204    }
205
206    /// Every value of `name`, in table order.
207    fn values(&self, buf: &[u8], name: &str) -> Result<Vec<String>> {
208        let Some(samples) = self.samples(name) else {
209            return Ok(Vec::new());
210        };
211        let mut out = Vec::new();
212        let mut p = self.content.start + samples[0].offset;
213        while p < self.content.end {
214            let (entry_name, value, _) = self.read_entry(buf, &mut p)?;
215            if entry_name != name {
216                break;
217            }
218            out.push(value.to_string());
219        }
220        Ok(out)
221    }
222
223    /// Table-relative offset of the list holding `name=value`.
224    fn offset_for(&self, buf: &[u8], name: &str, value: &str) -> Result<Option<u64>> {
225        let Some(samples) = self.samples(name) else {
226            return Ok(None);
227        };
228        // Last sample whose value is <= the target; the list may be a few
229        // entries further along the table.
230        let idx = samples.partition_point(|s| s.value.as_str() <= value);
231        let Some(start) = idx.checked_sub(1) else {
232            return Ok(None);
233        };
234        let mut p = self.content.start + samples[start].offset;
235        while p < self.content.end {
236            let (entry_name, entry_value, offset) = self.read_entry(buf, &mut p)?;
237            if entry_name != name || entry_value > value {
238                return Ok(None);
239            }
240            if entry_value == value {
241                return Ok(Some(offset));
242            }
243        }
244        Ok(None)
245    }
246
247    /// Reads one table entry, advancing `p` past it.
248    ///
249    /// Borrows from `buf` so a full-table scan allocates nothing per entry.
250    fn read_entry<'b>(&self, buf: &'b [u8], p: &mut usize) -> Result<(&'b str, &'b str, u64)> {
251        if *p >= self.content.end {
252            return Err(Error::format("postings table ended inside an entry"));
253        }
254        let keys = varint::uvarint(buf, p)?;
255        if keys != 2 {
256            return Err(Error::format(format!(
257                "postings table entry has {keys} keys, expected 2"
258            )));
259        }
260        let name = read_str(buf, p, self.content.end)?;
261        let value = read_str(buf, p, self.content.end)?;
262        let offset = varint::uvarint(buf, p)?;
263        Ok((name, value, offset))
264    }
265}
266
267fn read_str<'b>(buf: &'b [u8], p: &mut usize, end: usize) -> Result<&'b str> {
268    let len = varint::uvarint(buf, p)? as usize;
269    let stop = p
270        .checked_add(len)
271        .ok_or_else(|| Error::format("string length overflow in postings table"))?;
272    if stop > end || stop > buf.len() {
273        return Err(Error::format("string exceeds the postings table"));
274    }
275    let s = std::str::from_utf8(&buf[*p..stop])
276        .map_err(|e| Error::format(format!("invalid utf-8 in postings table: {e}")))?;
277    *p = stop;
278    Ok(s)
279}
280
281/// A sorted, lazily decoded sequence of series references.
282///
283/// Implementations never materialise the whole list, so a label pair with
284/// millions of series costs one 4-byte read per step. References are yielded in
285/// ascending order; `seek` skips forward in logarithmic time where the concrete
286/// type can binary search.
287///
288/// The trait is object safe: `Box<dyn Postings>` is the currency of
289/// [`crate::index::postings_ops`], which is how matcher plans are combined.
290pub trait Postings {
291    /// Returns the next reference, or `None` at the end.
292    fn next(&mut self) -> Result<Option<u64>>;
293
294    /// Advances to the first reference `>= target` and returns it.
295    ///
296    /// Every reference smaller than `target` is consumed. Returns `None` when
297    /// the list is exhausted.
298    fn seek(&mut self, target: u64) -> Result<Option<u64>>;
299
300    /// Drains the remaining references into a vector.
301    ///
302    /// Only for callers that genuinely need the whole set (small lists, tests,
303    /// checkpoints); it allocates proportional to the list length.
304    fn collect_refs(&mut self) -> Result<Vec<u64>>
305    where
306        Self: Sized,
307    {
308        let mut out = Vec::new();
309        while let Some(reference) = self.next()? {
310            out.push(reference);
311        }
312        Ok(out)
313    }
314}
315
316/// A boxed source behaves like the source it wraps, so plans can be nested:
317/// `Box<dyn Postings>` is itself a `Postings`.
318impl Postings for Box<dyn Postings + '_> {
319    fn next(&mut self) -> Result<Option<u64>> {
320        (**self).next()
321    }
322
323    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
324        (**self).seek(target)
325    }
326}
327
328/// Cursor over one postings list, borrowed from the index file.
329#[derive(Debug, Clone)]
330struct List<'a> {
331    refs: &'a [u8],
332    /// Byte offset of the next reference inside `refs`.
333    pos: usize,
334    remaining: u32,
335}
336
337impl List<'_> {
338    /// Reference at index `i` of the *remaining* window.
339    fn at(&self, i: usize) -> u64 {
340        let b = &self.refs[self.pos + i * 4..self.pos + i * 4 + 4];
341        u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as u64
342    }
343
344    fn next_value(&mut self) -> Option<u64> {
345        if self.remaining == 0 {
346            return None;
347        }
348        let v = self.at(0);
349        self.pos += 4;
350        self.remaining -= 1;
351        Some(v)
352    }
353
354    /// Binary search over the remaining window; the writer stores references
355    /// ascending, and `validate_postings` enforces it.
356    fn seek_value(&mut self, target: u64) -> Option<u64> {
357        let mut lo = 0usize;
358        let mut hi = self.remaining as usize;
359        while lo < hi {
360            let mid = lo + (hi - lo) / 2;
361            if self.at(mid) < target {
362                lo = mid + 1;
363            } else {
364                hi = mid;
365            }
366        }
367        self.pos += lo * 4;
368        self.remaining -= lo as u32;
369        self.next_value()
370    }
371
372    fn len(&self) -> u64 {
373        self.remaining as u64
374    }
375}
376
377/// A single postings list.
378#[derive(Debug, Clone)]
379pub struct PostingsList<'a> {
380    list: List<'a>,
381}
382
383impl<'a> PostingsList<'a> {
384    fn new(list: List<'a>) -> Self {
385        Self { list }
386    }
387
388    /// A list with no references.
389    pub fn empty() -> Self {
390        Self {
391            list: List {
392                refs: &[],
393                pos: 0,
394                remaining: 0,
395            },
396        }
397    }
398
399    /// Number of references left, exactly.
400    pub fn len(&self) -> u64 {
401        self.list.len()
402    }
403
404    /// True when no reference is left.
405    pub fn is_empty(&self) -> bool {
406        self.list.len() == 0
407    }
408}
409
410impl Postings for PostingsList<'_> {
411    fn next(&mut self) -> Result<Option<u64>> {
412        Ok(self.list.next_value())
413    }
414
415    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
416        Ok(self.list.seek_value(target))
417    }
418}
419
420/// The union of several postings lists, sorted and deduplicated.
421#[derive(Debug, Clone)]
422pub struct MergedPostings<'a> {
423    lists: Vec<List<'a>>,
424    heads: Vec<Option<u64>>,
425}
426
427impl<'a> MergedPostings<'a> {
428    fn new(lists: Vec<List<'a>>) -> Self {
429        let heads = lists.iter().map(|_| None).collect::<Vec<Option<u64>>>();
430        let mut merged = Self { lists, heads };
431        merged.prime();
432        merged
433    }
434
435    fn prime(&mut self) {
436        for (i, list) in self.lists.iter_mut().enumerate() {
437            if self.heads[i].is_none() {
438                self.heads[i] = list.next_value();
439            }
440        }
441    }
442
443    /// Upper bound on the references left; duplicates across lists are merged
444    /// away, so the real count can be smaller.
445    pub fn len(&self) -> u64 {
446        self.lists.iter().map(|l| l.len()).sum()
447    }
448
449    /// True when no list has anything left.
450    pub fn is_empty(&self) -> bool {
451        self.heads.iter().all(|h| h.is_none())
452    }
453
454    fn advance(&mut self) -> Option<u64> {
455        let mut best: Option<(usize, u64)> = None;
456        for (i, head) in self.heads.iter().enumerate() {
457            if let Some(v) = *head {
458                if best.map(|(_, bv)| v < bv).unwrap_or(true) {
459                    best = Some((i, v));
460                }
461            }
462        }
463        let (idx, value) = best?;
464        self.heads[idx] = self.lists[idx].next_value();
465        // Advance every other list that held the same reference so the union
466        // stays deduplicated.
467        for (i, head) in self.heads.iter_mut().enumerate() {
468            if *head == Some(value) {
469                *head = self.lists[i].next_value();
470            }
471        }
472        Some(value)
473    }
474}
475
476impl Postings for MergedPostings<'_> {
477    fn next(&mut self) -> Result<Option<u64>> {
478        Ok(self.advance())
479    }
480
481    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
482        for (i, list) in self.lists.iter_mut().enumerate() {
483            if self.heads[i].is_some_and(|head| head < target) {
484                self.heads[i] = list.seek_value(target);
485            }
486        }
487        Ok(self.advance())
488    }
489}
490
491/// An in-memory postings list: sorted references held in a `Vec`.
492///
493/// Useful to combine literal sets with index-backed lists (tests, cached
494/// results, a plan that starts from a known set) without going through the
495/// postings section.
496#[derive(Debug, Clone, Default)]
497pub struct VecPostings {
498    refs: Vec<u64>,
499    pos: usize,
500}
501
502impl VecPostings {
503    /// Wraps a vector of references.
504    ///
505    /// The references are sorted and deduplicated so the `Postings` contract
506    /// (ascending, no duplicates) holds for any input.
507    pub fn new(mut refs: Vec<u64>) -> Self {
508        refs.sort_unstable();
509        refs.dedup();
510        Self { refs, pos: 0 }
511    }
512
513    /// References left to yield.
514    pub fn len(&self) -> u64 {
515        (self.refs.len() - self.pos) as u64
516    }
517
518    /// True when nothing is left.
519    pub fn is_empty(&self) -> bool {
520        self.pos >= self.refs.len()
521    }
522
523    fn seek_index(&mut self, target: u64) -> Option<u64> {
524        let window = &self.refs[self.pos..];
525        let skip = window.partition_point(|r| *r < target);
526        self.pos += skip;
527        let v = self.refs.get(self.pos).copied();
528        if v.is_some() {
529            self.pos += 1;
530        }
531        v
532    }
533}
534
535impl Postings for VecPostings {
536    fn next(&mut self) -> Result<Option<u64>> {
537        if self.pos >= self.refs.len() {
538            return Ok(None);
539        }
540        let v = self.refs[self.pos];
541        self.pos += 1;
542        Ok(Some(v))
543    }
544
545    fn seek(&mut self, target: u64) -> Result<Option<u64>> {
546        Ok(self.seek_index(target))
547    }
548}
549
550/// Statistics from [`IndexReader::validate_postings`].
551#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
552pub struct PostingsStats {
553    /// Entries in the offset table (one per label pair plus the all-series key).
554    pub entries: u32,
555    /// Distinct label names, excluding the all-series key.
556    pub label_names: usize,
557    /// Postings lists that were decoded.
558    pub lists: u64,
559    /// Series references across all lists.
560    pub refs: u64,
561}
562
563impl IndexReader {
564    /// Byte range of the postings section, empty when the block has none.
565    fn postings_range(&self) -> Range<usize> {
566        let toc = self.toc();
567        let start = if toc.postings != 0 {
568            toc.postings
569        } else {
570            toc.label_indices
571        };
572        let table = if toc.postings_table != 0 {
573            toc.postings_table
574        } else {
575            toc.label_indices_table
576        };
577        if start == 0 || table <= start {
578            return 0..0;
579        }
580        start as usize..table as usize
581    }
582
583    /// Builds the sampled offset table, or returns the cached one.
584    fn postings_table(&self) -> Result<Arc<PostingsTable>> {
585        if let Some(table) = self.postings_table.get() {
586            return Ok(table.clone());
587        }
588        let toc = self.toc();
589        let table_off = if toc.postings_table != 0 {
590            toc.postings_table
591        } else {
592            toc.label_indices_table
593        };
594        if table_off == 0 {
595            return Err(Error::format("index has no postings offset table"));
596        }
597        let body_end = self.body_end();
598        let table = Arc::new(PostingsTable::parse(
599            &self.mmap,
600            table_off,
601            body_end,
602            self.verify_crc(),
603        )?);
604        // Another thread may have won the race; both tables describe the same
605        // bytes, so use whichever landed in the cell.
606        Ok(self.postings_table.get_or_init(|| table).clone())
607    }
608
609    /// Label names in the block, sorted, excluding the all-series key.
610    ///
611    /// Costs one pass over the sampled offset table, cached after the first
612    /// call.
613    pub fn label_names(&self) -> Result<Vec<String>> {
614        Ok(self.postings_table()?.label_names())
615    }
616
617    /// Every value of `name`, in the index's (sorted) order.
618    ///
619    /// Returns an empty vector when the label name is absent.
620    pub fn label_values(&self, name: &str) -> Result<Vec<String>> {
621        let table = self.postings_table()?;
622        table.values(&self.mmap, name)
623    }
624
625    /// Postings list for `name=value`, in ascending series-reference order.
626    ///
627    /// An unknown pair yields an empty list, matching Prometheus. The list is
628    /// decoded lazily: only the frame is read up front.
629    pub fn postings(&self, name: &str, value: &str) -> Result<PostingsList<'_>> {
630        let table = self.postings_table()?;
631        match table.offset_for(&self.mmap, name, value)? {
632            Some(offset) => Ok(PostingsList::new(self.read_list(offset)?)),
633            None => Ok(PostingsList::empty()),
634        }
635    }
636
637    /// Union of the postings lists for several values of one label name.
638    ///
639    /// Values do not need to be sorted; duplicates and unknown values are
640    /// ignored. This is the shape a `label=~"a|b"` matcher needs.
641    pub fn postings_multi(&self, name: &str, values: &[&str]) -> Result<MergedPostings<'_>> {
642        if values.is_empty() {
643            return Ok(MergedPostings::new(Vec::new()));
644        }
645        let table = self.postings_table()?;
646        let mut found = Vec::new();
647        for value in values {
648            if let Some(offset) = table.offset_for(&self.mmap, name, value)? {
649                found.push(offset);
650            }
651        }
652        found.sort_unstable();
653        found.dedup();
654        let mut lists = Vec::with_capacity(found.len());
655        for offset in found {
656            lists.push(self.read_list(offset)?);
657        }
658        Ok(MergedPostings::new(lists))
659    }
660
661    /// Postings list of every series in the block.
662    ///
663    /// This is the empty-key entry, which is also what Prometheus uses for
664    /// "match everything".
665    pub fn all_postings(&self) -> Result<PostingsList<'_>> {
666        self.postings("", "")
667    }
668
669    /// Resolves a series reference from [`Postings`] into its record.
670    ///
671    /// v2/v3 references are `offset / 16`, so the byte offset has to be
672    /// reconstructed; v1 references are already byte offsets.
673    pub fn series_by_ref(&self, reference: u64) -> Result<super::SeriesRef> {
674        let offset = if self.version() == 1 {
675            reference
676        } else {
677            reference
678                .checked_mul(super::SERIES_ALIGN as u64)
679                .ok_or_else(|| Error::format("series reference overflow"))?
680        };
681        let start = usize::try_from(offset)
682            .map_err(|_| Error::format("series reference does not fit in usize"))?;
683        let mut cache = super::symbols::SymbolCache::small();
684        let (series, _) = self.parse_series(start, &mut cache)?;
685        Ok(series)
686    }
687
688    /// Decodes one postings list, validating its envelope and references.
689    fn read_list(&self, offset: u64) -> Result<List<'_>> {
690        let section = self.postings_range();
691        if section.is_empty() {
692            return Err(Error::format("index has no postings section"));
693        }
694        let start = usize::try_from(offset)
695            .map_err(|_| Error::format("postings offset does not fit in usize"))?;
696        if !section.contains(&start) {
697            return Err(Error::format(format!(
698                "postings list offset {start} outside the postings section {:?}",
699                section
700            )));
701        }
702        let body_len = be32(&self.mmap, start)? as usize;
703        let body_start = start + 4;
704        let body_end = body_start
705            .checked_add(body_len)
706            .ok_or_else(|| Error::format("postings list length overflow"))?;
707        let crc_end = body_end
708            .checked_add(4)
709            .ok_or_else(|| Error::format("postings list length overflow"))?;
710        if crc_end > section.end || crc_end > self.mmap.len() {
711            return Err(Error::format(format!(
712                "postings list at {start} runs past the postings section"
713            )));
714        }
715        if self.verify_crc() {
716            let want = be32(&self.mmap, body_end)?;
717            crate::checksum::verify(
718                true,
719                want,
720                &self.mmap[body_start..body_end],
721                "index postings",
722            )?;
723        }
724        if body_len < 4 {
725            return Err(Error::format("postings list shorter than its count"));
726        }
727        let count = be32(&self.mmap, body_start)?;
728        let expect = 4 + count as usize * 4;
729        if body_len != expect {
730            return Err(Error::format(format!(
731                "postings list at {start} declares {count} references ({expect} bytes) but holds {body_len} bytes"
732            )));
733        }
734        Ok(List {
735            refs: &self.mmap[body_start + 4..body_end],
736            pos: 0,
737            remaining: count,
738        })
739    }
740
741    /// Union of the postings of every value of `name` accepted by `predicate`.
742    ///
743    /// The label values are streamed from the offset table (borrowed, no
744    /// per-value allocation); only the offsets of the selected lists are kept.
745    /// This is the primitive a regex matcher needs, since it has to inspect
746    /// every value of one label.
747    pub fn postings_for_values<'a>(
748        &'a self,
749        name: &str,
750        predicate: impl Fn(&str) -> bool,
751    ) -> Result<super::postings_ops::BoxPostings<'a>> {
752        let table = self.postings_table()?;
753        let Some(samples) = table.samples(name) else {
754            return Ok(Box::new(PostingsList::empty()));
755        };
756        let mut lists = Vec::new();
757        let mut p = table.content.start + samples[0].offset;
758        let buf = &*self.mmap;
759        while p < table.content.end {
760            let (entry_name, value, offset) = table.read_entry(buf, &mut p)?;
761            if entry_name != name {
762                break;
763            }
764            if predicate(value) {
765                lists.push(self.read_list(offset)?);
766            }
767        }
768        if lists.is_empty() {
769            return Ok(Box::new(PostingsList::empty()));
770        }
771        Ok(Box::new(MergedPostings::new(lists)))
772    }
773
774    /// Calls `f` for every value of `name`, in index order, without collecting
775    /// them.
776    ///
777    /// Returns the number of values visited. Useful for a query layer that wants
778    /// to inspect a label's cardinality without allocating the value strings.
779    pub fn for_each_label_value(&self, name: &str, mut f: impl FnMut(&str)) -> Result<usize> {
780        let table = self.postings_table()?;
781        let Some(samples) = table.samples(name) else {
782            return Ok(0);
783        };
784        let mut seen = 0usize;
785        let mut p = table.content.start + samples[0].offset;
786        let buf = &*self.mmap;
787        while p < table.content.end {
788            let (entry_name, value, _) = table.read_entry(buf, &mut p)?;
789            if entry_name != name {
790                break;
791            }
792            f(value);
793            seen += 1;
794        }
795        Ok(seen)
796    }
797
798    /// Validates the offset table and every postings list.
799    ///
800    /// Walks all entries (not just the sampled ones), decodes each list once
801    /// and checks that references are strictly increasing and addressable in
802    /// this index version. Cost is proportional to the total number of
803    /// references, so this is the expensive half of block validation.
804    pub fn validate_postings(&self) -> Result<PostingsStats> {
805        let toc = self.toc();
806        if toc.postings_table == 0 && toc.label_indices_table == 0 {
807            // An index without a label space is unusual but not corrupt: the
808            // series section is still readable. Report zero stats so callers
809            // can tell "absent" from "broken".
810            return Ok(PostingsStats::default());
811        }
812        let table = self.postings_table()?;
813        let section = self.postings_range();
814        let mut stats = PostingsStats {
815            entries: table.entries(),
816            label_names: table.label_names().len(),
817            ..Default::default()
818        };
819        if table.entries() == 0 {
820            return Ok(stats);
821        }
822
823        // Walk the table itself to visit every list exactly once.
824        let mut p = table.content.start;
825        let count = be32(&self.mmap, p)?;
826        p += 4;
827        for i in 0..count {
828            let (name, value, offset) = table.read_entry(&self.mmap, &mut p)?;
829            debug_assert!(p <= table.content.end);
830
831            let list = self.read_list(offset).map_err(|e| {
832                Error::format(format!(
833                    "postings list for {name}={value} (offset {offset}, entry {i}): {e}"
834                ))
835            })?;
836            stats.lists += 1;
837            stats.refs += list.remaining as u64;
838
839            let mut prev: Option<u64> = None;
840            let mut list = list;
841            while let Some(reference) = list.next_value() {
842                if let Some(prev) = prev {
843                    if reference <= prev {
844                        return Err(Error::format(format!(
845                            "postings list for {name}={value} is not sorted: {reference} after {prev}"
846                        )));
847                    }
848                }
849                prev = Some(reference);
850            }
851
852            if let Some(max) = prev {
853                if self.version() != 1 {
854                    let limit = (self.series_end() / super::SERIES_ALIGN as u64) + 1;
855                    if max > limit {
856                        return Err(Error::format(format!(
857                            "postings list for {name}={value} references series {max}, beyond the series section"
858                        )));
859                    }
860                } else if max >= self.series_end() {
861                    return Err(Error::format(format!(
862                        "postings list for {name}={value} references offset {max}, beyond the series section"
863                    )));
864                }
865            }
866
867            // Every entry must point into the postings section.
868            if !section.contains(&(offset as usize)) {
869                return Err(Error::format(format!(
870                    "postings entry for {name}={value} points outside the postings section"
871                )));
872            }
873        }
874        Ok(stats)
875    }
876}
877
878impl IndexReader {
879    /// End of the index body, i.e. where the TOC starts.
880    pub(crate) fn body_end(&self) -> usize {
881        self.mmap.len().saturating_sub(super::toc::TOC_LEN)
882    }
883}
884
885#[cfg(test)]
886mod tests {
887    use super::*;
888
889    /// Encodes a postings-list entry: length, body (count + refs), CRC.
890    fn list(refs: &[u32]) -> Vec<u8> {
891        let mut body = Vec::new();
892        body.extend_from_slice(&(refs.len() as u32).to_be_bytes());
893        for r in refs {
894            body.extend_from_slice(&r.to_be_bytes());
895        }
896        let mut out = Vec::new();
897        out.extend_from_slice(&(body.len() as u32).to_be_bytes());
898        out.extend_from_slice(&body);
899        out.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
900        out
901    }
902
903    fn put_uvarint(out: &mut Vec<u8>, mut v: u64) {
904        loop {
905            let mut b = (v & 0x7f) as u8;
906            v >>= 7;
907            if v != 0 {
908                b |= 0x80;
909            }
910            out.push(b);
911            if v == 0 {
912                break;
913            }
914        }
915    }
916
917    fn put_str(out: &mut Vec<u8>, s: &str) {
918        put_uvarint(out, s.len() as u64);
919        out.extend_from_slice(s.as_bytes());
920    }
921
922    /// Builds a table for `(name, value)` -> list offset pairs.
923    fn table(entries: &[(&str, &str, u64)]) -> Vec<u8> {
924        let mut content = Vec::new();
925        content.extend_from_slice(&(entries.len() as u32).to_be_bytes());
926        for (name, value, offset) in entries {
927            put_uvarint(&mut content, 2);
928            put_str(&mut content, name);
929            put_str(&mut content, value);
930            put_uvarint(&mut content, *offset);
931        }
932        let mut out = Vec::new();
933        out.extend_from_slice(&(content.len() as u32).to_be_bytes());
934        let crc = crc32c::crc32c(&content);
935        out.extend_from_slice(&content);
936        out.extend_from_slice(&crc.to_be_bytes());
937        out
938    }
939
940    #[test]
941    fn table_round_trips_and_looks_up_values() {
942        let buf = table(&[
943            ("", "", 0),
944            ("__name__", "a", 8),
945            ("__name__", "b", 20),
946            ("job", "x", 32),
947        ]);
948        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
949        assert_eq!(t.entries(), 4);
950        assert_eq!(
951            t.label_names(),
952            vec!["__name__".to_string(), "job".to_string()]
953        );
954        assert_eq!(t.values(&buf, "__name__").unwrap(), vec!["a", "b"]);
955        assert_eq!(t.values(&buf, "job").unwrap(), vec!["x"]);
956        assert!(t.values(&buf, "absent").unwrap().is_empty());
957        assert_eq!(t.offset_for(&buf, "__name__", "b").unwrap(), Some(20));
958        assert_eq!(t.offset_for(&buf, "__name__", "aa").unwrap(), None);
959        assert_eq!(t.offset_for(&buf, "__name__", "z").unwrap(), None);
960        assert_eq!(t.offset_for(&buf, "", "").unwrap(), Some(0));
961        assert_eq!(t.offset_for(&buf, "absent", "x").unwrap(), None);
962    }
963
964    #[test]
965    fn sampling_keeps_every_32nd_value_and_the_last() {
966        let mut names: Vec<String> = (0..70).map(|i| format!("v{i:03}")).collect();
967        names.push("zzz".to_string());
968        let offsets: Vec<u64> = (0..names.len() as u64).map(|i| i * 10).collect();
969        let mut entries: Vec<(&str, &str, u64)> = vec![("", "", 0)];
970        for (n, o) in names.iter().zip(&offsets) {
971            entries.push(("job", n.as_str(), *o));
972        }
973        let buf = table(&entries);
974        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
975        let samples = t.samples("job").unwrap();
976        // 0, 32, 64 sampled by stride, plus the final entry (index 70).
977        let values: Vec<&str> = samples.iter().map(|s| s.value.as_str()).collect();
978        assert_eq!(values, vec!["v000", "v032", "v064", "zzz"]);
979        // Lookups still find values between samples.
980        assert_eq!(t.offset_for(&buf, "job", "v047").unwrap(), Some(470));
981        assert_eq!(t.offset_for(&buf, "job", "v069").unwrap(), Some(690));
982    }
983
984    #[test]
985    fn unsorted_entries_are_rejected() {
986        let buf = table(&[("a", "b", 0), ("a", "a", 0)]);
987        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
988        assert!(err.to_string().contains("not sorted"), "{err}");
989
990        let buf = table(&[("b", "a", 0), ("a", "b", 0)]);
991        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
992        assert!(err.to_string().contains("names are not sorted"), "{err}");
993    }
994
995    #[test]
996    fn a_wrong_key_count_is_rejected() {
997        let mut content = Vec::new();
998        content.extend_from_slice(&1u32.to_be_bytes());
999        put_uvarint(&mut content, 3);
1000        put_str(&mut content, "a");
1001        put_str(&mut content, "b");
1002        put_uvarint(&mut content, 0);
1003        let mut buf = Vec::new();
1004        buf.extend_from_slice(&(content.len() as u32).to_be_bytes());
1005        let crc = crc32c::crc32c(&content);
1006        buf.extend_from_slice(&content);
1007        buf.extend_from_slice(&crc.to_be_bytes());
1008        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
1009        assert!(err.to_string().contains("expected 2"), "{err}");
1010    }
1011
1012    #[test]
1013    fn a_truncated_table_is_rejected() {
1014        let buf = table(&[("a", "b", 0)]);
1015        let err = PostingsTable::parse(&buf, 0, buf.len() - 6, true).unwrap_err();
1016        assert!(err.to_string().contains("past the index body"), "{err}");
1017    }
1018
1019    #[test]
1020    fn merged_postings_union_is_sorted_and_deduplicated() {
1021        // Big-endian references: a = [1, 3, 7], b = [1, 2, 9].
1022        let a = List {
1023            refs: &[0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 7],
1024            pos: 0,
1025            remaining: 3,
1026        };
1027        let b = List {
1028            refs: &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 9],
1029            pos: 0,
1030            remaining: 3,
1031        };
1032        let merged = MergedPostings::new(vec![a, b]).collect_refs().unwrap();
1033        assert_eq!(merged, vec![1, 2, 3, 7, 9]);
1034    }
1035
1036    /// Builds a `PostingsList` over big-endian references.
1037    fn list_of(refs: &[u32]) -> PostingsList<'static> {
1038        let leaked: &'static [u8] = Box::leak(
1039            refs.iter()
1040                .flat_map(|r| r.to_be_bytes())
1041                .collect::<Vec<u8>>()
1042                .into_boxed_slice(),
1043        );
1044        PostingsList::new(List {
1045            refs: leaked,
1046            pos: 0,
1047            remaining: refs.len() as u32,
1048        })
1049    }
1050
1051    #[test]
1052    fn seek_lands_on_the_first_reference_at_or_after_the_target() {
1053        // Each case starts from a fresh list: a hit consumes the reference.
1054        let mut exact = list_of(&[5, 9, 17, 40]);
1055        assert_eq!(exact.seek(9).unwrap(), Some(9));
1056
1057        let mut between = list_of(&[5, 9, 17, 40]);
1058        assert_eq!(between.seek(10).unwrap(), Some(17));
1059
1060        let mut before = list_of(&[5, 9, 17, 40]);
1061        assert_eq!(before.seek(0).unwrap(), Some(5));
1062
1063        let mut past = list_of(&[5, 9, 17, 40]);
1064        assert_eq!(past.seek(41).unwrap(), None);
1065        assert_eq!(past.next().unwrap(), None);
1066        assert_eq!(past.seek(1).unwrap(), None);
1067    }
1068
1069    #[test]
1070    fn seek_only_moves_forward() {
1071        let mut p = list_of(&[5, 9, 17, 40]);
1072        assert_eq!(p.next().unwrap(), Some(5));
1073        // Seeking backwards returns the current position's next value, never a
1074        // previously consumed one.
1075        assert_eq!(p.seek(1).unwrap(), Some(9));
1076        assert_eq!(p.len(), 2);
1077    }
1078
1079    #[test]
1080    fn empty_lists_yield_nothing() {
1081        let mut p = PostingsList::empty();
1082        assert!(p.is_empty());
1083        assert_eq!(p.next().unwrap(), None);
1084        assert_eq!(p.seek(3).unwrap(), None);
1085        assert_eq!(p.collect_refs().unwrap(), Vec::<u64>::new());
1086    }
1087
1088    #[test]
1089    fn merged_seek_advances_every_list() {
1090        // a = [2, 10], b = [4, 10, 20]
1091        let a = List {
1092            refs: &[0, 0, 0, 2, 0, 0, 0, 10],
1093            pos: 0,
1094            remaining: 2,
1095        };
1096        let b = List {
1097            refs: &[0, 0, 0, 4, 0, 0, 0, 10, 0, 0, 0, 20],
1098            pos: 0,
1099            remaining: 3,
1100        };
1101        let mut merged = MergedPostings::new(vec![a, b]);
1102        assert_eq!(merged.seek(5).unwrap(), Some(10));
1103        // The duplicate 10 from both lists must be emitted once.
1104        assert_eq!(merged.next().unwrap(), Some(20));
1105        assert_eq!(merged.next().unwrap(), None);
1106    }
1107
1108    #[test]
1109    fn merged_empty_union_is_empty() {
1110        let mut merged = MergedPostings::new(Vec::new());
1111        assert!(merged.is_empty());
1112        assert_eq!(merged.next().unwrap(), None);
1113        assert_eq!(merged.seek(7).unwrap(), None);
1114    }
1115
1116    #[test]
1117    fn lists_decode_in_order() {
1118        let buf = list(&[5, 6, 9]);
1119        let l = List {
1120            refs: &buf[8..buf.len() - 4],
1121            pos: 0,
1122            remaining: 3,
1123        };
1124        let got = PostingsList::new(l).collect_refs().unwrap();
1125        assert_eq!(got, vec![5, 6, 9]);
1126    }
1127}