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_string(buf, &mut p, content_end)?;
117            let value = read_string(buf, &mut p, content_end)?;
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);
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.as_str() > 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    fn read_entry(&self, buf: &[u8], p: &mut usize) -> Result<(String, String, u64)> {
249        if *p >= self.content.end {
250            return Err(Error::format("postings table ended inside an entry"));
251        }
252        let keys = varint::uvarint(buf, p)?;
253        if keys != 2 {
254            return Err(Error::format(format!(
255                "postings table entry has {keys} keys, expected 2"
256            )));
257        }
258        let name = read_string(buf, p, self.content.end)?;
259        let value = read_string(buf, p, self.content.end)?;
260        let offset = varint::uvarint(buf, p)?;
261        Ok((name, value, offset))
262    }
263}
264
265fn read_string(buf: &[u8], p: &mut usize, end: usize) -> Result<String> {
266    let len = varint::uvarint(buf, p)? as usize;
267    let stop = p
268        .checked_add(len)
269        .ok_or_else(|| Error::format("string length overflow in postings table"))?;
270    if stop > end || stop > buf.len() {
271        return Err(Error::format("string exceeds the postings table"));
272    }
273    let s = std::str::from_utf8(&buf[*p..stop])
274        .map_err(|e| Error::format(format!("invalid utf-8 in postings table: {e}")))?
275        .to_string();
276    *p = stop;
277    Ok(s)
278}
279
280/// One postings list, borrowed from the index file.
281#[derive(Debug, Clone)]
282struct List<'a> {
283    refs: &'a [u8],
284    /// Byte offset of the next reference inside `refs`.
285    pos: usize,
286    remaining: u32,
287}
288
289impl<'a> List<'a> {
290    fn next(&mut self) -> Option<u64> {
291        if self.remaining == 0 {
292            return None;
293        }
294        let b = &self.refs[self.pos..self.pos + 4];
295        self.pos += 4;
296        self.remaining -= 1;
297        Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as u64)
298    }
299}
300
301#[derive(Debug, Clone)]
302enum Inner<'a> {
303    Single(List<'a>),
304    /// Union of several lists, kept sorted and deduplicated.
305    Merged {
306        lists: Vec<List<'a>>,
307        heads: Vec<Option<u64>>,
308    },
309}
310
311/// Iterator over a postings list (or the union of several).
312///
313/// Yields series references in ascending order. For index v2/v3 a reference is
314/// `offset / 16` and can be passed to [`crate::IndexReader::series`] only as a
315/// byte offset after multiplying; use [`crate::IndexReader::series_by_ref`] to
316/// resolve one, or pair it with [`SeriesRef::id`](crate::SeriesRef::id) from a
317/// full scan.
318#[derive(Debug, Clone)]
319pub struct Postings<'a> {
320    inner: Inner<'a>,
321    emitted: u64,
322}
323
324impl<'a> Postings<'a> {
325    fn single(list: List<'a>) -> Self {
326        Self {
327            inner: Inner::Single(list),
328            emitted: 0,
329        }
330    }
331
332    fn merged(lists: Vec<List<'a>>) -> Self {
333        let heads = lists.iter().map(|_| None).collect::<Vec<Option<u64>>>();
334        let mut merged = Self {
335            inner: Inner::Merged { lists, heads },
336            emitted: 0,
337        };
338        if let Inner::Merged { lists, heads } = &mut merged.inner {
339            for (i, list) in lists.iter_mut().enumerate() {
340                heads[i] = list.next();
341            }
342        }
343        merged
344    }
345
346    /// Number of references not yet emitted (an upper bound for unions).
347    pub fn len(&self) -> u64 {
348        match &self.inner {
349            Inner::Single(list) => list.remaining as u64,
350            Inner::Merged { lists, .. } => lists.iter().map(|l| l.remaining as u64).sum(),
351        }
352    }
353
354    /// True when no reference is left.
355    pub fn is_empty(&self) -> bool {
356        self.len() == 0
357    }
358
359    /// Empty list.
360    pub fn empty() -> Self {
361        Self::single(List {
362            refs: &[],
363            pos: 0,
364            remaining: 0,
365        })
366    }
367
368    /// Collects the remaining references into a vector.
369    pub fn collect_refs(&mut self) -> Vec<u64> {
370        let mut out = Vec::with_capacity(self.len() as usize);
371        out.extend(self.by_ref());
372        out
373    }
374}
375
376impl Iterator for Postings<'_> {
377    type Item = u64;
378
379    fn next(&mut self) -> Option<u64> {
380        let next = match &mut self.inner {
381            Inner::Single(list) => list.next(),
382            Inner::Merged { lists, heads } => {
383                // Smallest head, then advance every list that holds it so the
384                // union stays deduplicated.
385                let mut best: Option<(usize, u64)> = None;
386                for (i, head) in heads.iter().enumerate() {
387                    if let Some(v) = *head {
388                        if best.map(|(_, bv)| v < bv).unwrap_or(true) {
389                            best = Some((i, v));
390                        }
391                    }
392                }
393                let (idx, value) = best?;
394                heads[idx] = lists[idx].next();
395                for (i, head) in heads.iter_mut().enumerate() {
396                    if *head == Some(value) {
397                        *head = lists[i].next();
398                    }
399                }
400                Some(value)
401            }
402        };
403        if next.is_some() {
404            self.emitted += 1;
405        }
406        next
407    }
408}
409
410/// Statistics from [`IndexReader::validate_postings`].
411#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
412pub struct PostingsStats {
413    /// Entries in the offset table (one per label pair plus the all-series key).
414    pub entries: u32,
415    /// Distinct label names, excluding the all-series key.
416    pub label_names: usize,
417    /// Postings lists that were decoded.
418    pub lists: u64,
419    /// Series references across all lists.
420    pub refs: u64,
421}
422
423impl IndexReader {
424    /// Byte range of the postings section, empty when the block has none.
425    fn postings_range(&self) -> Range<usize> {
426        let toc = self.toc();
427        let start = if toc.postings != 0 {
428            toc.postings
429        } else {
430            toc.label_indices
431        };
432        let table = if toc.postings_table != 0 {
433            toc.postings_table
434        } else {
435            toc.label_indices_table
436        };
437        if start == 0 || table <= start {
438            return 0..0;
439        }
440        start as usize..table as usize
441    }
442
443    /// Builds the sampled offset table, or returns the cached one.
444    fn postings_table(&self) -> Result<Arc<PostingsTable>> {
445        if let Some(table) = self.postings_table.borrow().clone() {
446            return Ok(table);
447        }
448        let toc = self.toc();
449        let table_off = if toc.postings_table != 0 {
450            toc.postings_table
451        } else {
452            toc.label_indices_table
453        };
454        if table_off == 0 {
455            return Err(Error::format("index has no postings offset table"));
456        }
457        let body_end = self.body_end();
458        let table = Arc::new(PostingsTable::parse(
459            &self.mmap,
460            table_off,
461            body_end,
462            self.verify_crc(),
463        )?);
464        *self.postings_table.borrow_mut() = Some(table.clone());
465        Ok(table)
466    }
467
468    /// Label names in the block, sorted, excluding the all-series key.
469    ///
470    /// Costs one pass over the sampled offset table, cached after the first
471    /// call.
472    pub fn label_names(&self) -> Result<Vec<String>> {
473        Ok(self.postings_table()?.label_names())
474    }
475
476    /// Every value of `name`, in the index's (sorted) order.
477    ///
478    /// Returns an empty vector when the label name is absent.
479    pub fn label_values(&self, name: &str) -> Result<Vec<String>> {
480        let table = self.postings_table()?;
481        table.values(&self.mmap, name)
482    }
483
484    /// Postings list for `name=value`, in ascending series-reference order.
485    ///
486    /// An unknown pair yields an empty list, matching Prometheus. The list is
487    /// decoded lazily: only the frame is read up front.
488    pub fn postings(&self, name: &str, value: &str) -> Result<Postings<'_>> {
489        let table = self.postings_table()?;
490        match table.offset_for(&self.mmap, name, value)? {
491            Some(offset) => Ok(Postings::single(self.read_list(offset)?)),
492            None => Ok(Postings::empty()),
493        }
494    }
495
496    /// Union of the postings lists for several values of one label name.
497    ///
498    /// Values do not need to be sorted; duplicates and unknown values are
499    /// ignored. This is the shape a `label=~"a|b"` matcher needs.
500    pub fn postings_multi(&self, name: &str, values: &[&str]) -> Result<Postings<'_>> {
501        if values.is_empty() {
502            return Ok(Postings::empty());
503        }
504        let table = self.postings_table()?;
505        let mut found = Vec::new();
506        for value in values {
507            if let Some(offset) = table.offset_for(&self.mmap, name, value)? {
508                found.push(offset);
509            }
510        }
511        found.sort_unstable();
512        found.dedup();
513        let mut lists = Vec::with_capacity(found.len());
514        for offset in found {
515            lists.push(self.read_list(offset)?);
516        }
517        Ok(Postings::merged(lists))
518    }
519
520    /// Postings list of every series in the block.
521    ///
522    /// This is the empty-key entry, which is also what Prometheus uses for
523    /// "match everything".
524    pub fn all_postings(&self) -> Result<Postings<'_>> {
525        self.postings("", "")
526    }
527
528    /// Resolves a series reference from [`Postings`] into its record.
529    ///
530    /// v2/v3 references are `offset / 16`, so the byte offset has to be
531    /// reconstructed; v1 references are already byte offsets.
532    pub fn series_by_ref(&self, reference: u64) -> Result<super::SeriesRef> {
533        let offset = if self.version() == 1 {
534            reference
535        } else {
536            reference
537                .checked_mul(super::SERIES_ALIGN as u64)
538                .ok_or_else(|| Error::format("series reference overflow"))?
539        };
540        let start = usize::try_from(offset)
541            .map_err(|_| Error::format("series reference does not fit in usize"))?;
542        let (series, _) = self.parse_series(start)?;
543        Ok(series)
544    }
545
546    /// Decodes one postings list, validating its envelope and references.
547    fn read_list(&self, offset: u64) -> Result<List<'_>> {
548        let section = self.postings_range();
549        if section.is_empty() {
550            return Err(Error::format("index has no postings section"));
551        }
552        let start = usize::try_from(offset)
553            .map_err(|_| Error::format("postings offset does not fit in usize"))?;
554        if !section.contains(&start) {
555            return Err(Error::format(format!(
556                "postings list offset {start} outside the postings section {:?}",
557                section
558            )));
559        }
560        let body_len = be32(&self.mmap, start)? as usize;
561        let body_start = start + 4;
562        let body_end = body_start
563            .checked_add(body_len)
564            .ok_or_else(|| Error::format("postings list length overflow"))?;
565        let crc_end = body_end
566            .checked_add(4)
567            .ok_or_else(|| Error::format("postings list length overflow"))?;
568        if crc_end > section.end || crc_end > self.mmap.len() {
569            return Err(Error::format(format!(
570                "postings list at {start} runs past the postings section"
571            )));
572        }
573        if self.verify_crc() {
574            let want = be32(&self.mmap, body_end)?;
575            crate::checksum::verify(
576                true,
577                want,
578                &self.mmap[body_start..body_end],
579                "index postings",
580            )?;
581        }
582        if body_len < 4 {
583            return Err(Error::format("postings list shorter than its count"));
584        }
585        let count = be32(&self.mmap, body_start)?;
586        let expect = 4 + count as usize * 4;
587        if body_len != expect {
588            return Err(Error::format(format!(
589                "postings list at {start} declares {count} references ({expect} bytes) but holds {body_len} bytes"
590            )));
591        }
592        Ok(List {
593            refs: &self.mmap[body_start + 4..body_end],
594            pos: 0,
595            remaining: count,
596        })
597    }
598
599    /// Validates the offset table and every postings list.
600    ///
601    /// Walks all entries (not just the sampled ones), decodes each list once
602    /// and checks that references are strictly increasing and addressable in
603    /// this index version. Cost is proportional to the total number of
604    /// references, so this is the expensive half of block validation.
605    pub fn validate_postings(&self) -> Result<PostingsStats> {
606        let toc = self.toc();
607        if toc.postings_table == 0 && toc.label_indices_table == 0 {
608            // An index without a label space is unusual but not corrupt: the
609            // series section is still readable. Report zero stats so callers
610            // can tell "absent" from "broken".
611            return Ok(PostingsStats::default());
612        }
613        let table = self.postings_table()?;
614        let section = self.postings_range();
615        let mut stats = PostingsStats {
616            entries: table.entries(),
617            label_names: table.label_names().len(),
618            ..Default::default()
619        };
620        if table.entries() == 0 {
621            return Ok(stats);
622        }
623
624        // Walk the table itself to visit every list exactly once.
625        let mut p = table.content.start;
626        let count = be32(&self.mmap, p)?;
627        p += 4;
628        for i in 0..count {
629            let (name, value, offset) = table.read_entry(&self.mmap, &mut p)?;
630            debug_assert!(p <= table.content.end);
631
632            let list = self.read_list(offset).map_err(|e| {
633                Error::format(format!(
634                    "postings list for {name}={value} (offset {offset}, entry {i}): {e}"
635                ))
636            })?;
637            stats.lists += 1;
638            stats.refs += list.remaining as u64;
639
640            let mut prev: Option<u64> = None;
641            let mut list = list;
642            while let Some(reference) = list.next() {
643                if let Some(prev) = prev {
644                    if reference <= prev {
645                        return Err(Error::format(format!(
646                            "postings list for {name}={value} is not sorted: {reference} after {prev}"
647                        )));
648                    }
649                }
650                prev = Some(reference);
651            }
652
653            if let Some(max) = prev {
654                if self.version() != 1 {
655                    let limit = (self.series_end() / super::SERIES_ALIGN as u64) + 1;
656                    if max > limit {
657                        return Err(Error::format(format!(
658                            "postings list for {name}={value} references series {max}, beyond the series section"
659                        )));
660                    }
661                } else if max >= self.series_end() {
662                    return Err(Error::format(format!(
663                        "postings list for {name}={value} references offset {max}, beyond the series section"
664                    )));
665                }
666            }
667
668            // Every entry must point into the postings section.
669            if !section.contains(&(offset as usize)) {
670                return Err(Error::format(format!(
671                    "postings entry for {name}={value} points outside the postings section"
672                )));
673            }
674        }
675        Ok(stats)
676    }
677}
678
679impl IndexReader {
680    /// End of the index body, i.e. where the TOC starts.
681    pub(crate) fn body_end(&self) -> usize {
682        self.mmap.len().saturating_sub(super::toc::TOC_LEN)
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    /// Encodes a postings-list entry: length, body (count + refs), CRC.
691    fn list(refs: &[u32]) -> Vec<u8> {
692        let mut body = Vec::new();
693        body.extend_from_slice(&(refs.len() as u32).to_be_bytes());
694        for r in refs {
695            body.extend_from_slice(&r.to_be_bytes());
696        }
697        let mut out = Vec::new();
698        out.extend_from_slice(&(body.len() as u32).to_be_bytes());
699        out.extend_from_slice(&body);
700        out.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
701        out
702    }
703
704    fn put_uvarint(out: &mut Vec<u8>, mut v: u64) {
705        loop {
706            let mut b = (v & 0x7f) as u8;
707            v >>= 7;
708            if v != 0 {
709                b |= 0x80;
710            }
711            out.push(b);
712            if v == 0 {
713                break;
714            }
715        }
716    }
717
718    fn put_str(out: &mut Vec<u8>, s: &str) {
719        put_uvarint(out, s.len() as u64);
720        out.extend_from_slice(s.as_bytes());
721    }
722
723    /// Builds a table for `(name, value)` -> list offset pairs.
724    fn table(entries: &[(&str, &str, u64)]) -> Vec<u8> {
725        let mut content = Vec::new();
726        content.extend_from_slice(&(entries.len() as u32).to_be_bytes());
727        for (name, value, offset) in entries {
728            put_uvarint(&mut content, 2);
729            put_str(&mut content, name);
730            put_str(&mut content, value);
731            put_uvarint(&mut content, *offset);
732        }
733        let mut out = Vec::new();
734        out.extend_from_slice(&(content.len() as u32).to_be_bytes());
735        let crc = crc32c::crc32c(&content);
736        out.extend_from_slice(&content);
737        out.extend_from_slice(&crc.to_be_bytes());
738        out
739    }
740
741    #[test]
742    fn table_round_trips_and_looks_up_values() {
743        let buf = table(&[
744            ("", "", 0),
745            ("__name__", "a", 8),
746            ("__name__", "b", 20),
747            ("job", "x", 32),
748        ]);
749        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
750        assert_eq!(t.entries(), 4);
751        assert_eq!(
752            t.label_names(),
753            vec!["__name__".to_string(), "job".to_string()]
754        );
755        assert_eq!(t.values(&buf, "__name__").unwrap(), vec!["a", "b"]);
756        assert_eq!(t.values(&buf, "job").unwrap(), vec!["x"]);
757        assert!(t.values(&buf, "absent").unwrap().is_empty());
758        assert_eq!(t.offset_for(&buf, "__name__", "b").unwrap(), Some(20));
759        assert_eq!(t.offset_for(&buf, "__name__", "aa").unwrap(), None);
760        assert_eq!(t.offset_for(&buf, "__name__", "z").unwrap(), None);
761        assert_eq!(t.offset_for(&buf, "", "").unwrap(), Some(0));
762        assert_eq!(t.offset_for(&buf, "absent", "x").unwrap(), None);
763    }
764
765    #[test]
766    fn sampling_keeps_every_32nd_value_and_the_last() {
767        let mut names: Vec<String> = (0..70).map(|i| format!("v{i:03}")).collect();
768        names.push("zzz".to_string());
769        let offsets: Vec<u64> = (0..names.len() as u64).map(|i| i * 10).collect();
770        let mut entries: Vec<(&str, &str, u64)> = vec![("", "", 0)];
771        for (n, o) in names.iter().zip(&offsets) {
772            entries.push(("job", n.as_str(), *o));
773        }
774        let buf = table(&entries);
775        let t = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap();
776        let samples = t.samples("job").unwrap();
777        // 0, 32, 64 sampled by stride, plus the final entry (index 70).
778        let values: Vec<&str> = samples.iter().map(|s| s.value.as_str()).collect();
779        assert_eq!(values, vec!["v000", "v032", "v064", "zzz"]);
780        // Lookups still find values between samples.
781        assert_eq!(t.offset_for(&buf, "job", "v047").unwrap(), Some(470));
782        assert_eq!(t.offset_for(&buf, "job", "v069").unwrap(), Some(690));
783    }
784
785    #[test]
786    fn unsorted_entries_are_rejected() {
787        let buf = table(&[("a", "b", 0), ("a", "a", 0)]);
788        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
789        assert!(err.to_string().contains("not sorted"), "{err}");
790
791        let buf = table(&[("b", "a", 0), ("a", "b", 0)]);
792        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
793        assert!(err.to_string().contains("names are not sorted"), "{err}");
794    }
795
796    #[test]
797    fn a_wrong_key_count_is_rejected() {
798        let mut content = Vec::new();
799        content.extend_from_slice(&1u32.to_be_bytes());
800        put_uvarint(&mut content, 3);
801        put_str(&mut content, "a");
802        put_str(&mut content, "b");
803        put_uvarint(&mut content, 0);
804        let mut buf = Vec::new();
805        buf.extend_from_slice(&(content.len() as u32).to_be_bytes());
806        let crc = crc32c::crc32c(&content);
807        buf.extend_from_slice(&content);
808        buf.extend_from_slice(&crc.to_be_bytes());
809        let err = PostingsTable::parse(&buf, 0, buf.len(), true).unwrap_err();
810        assert!(err.to_string().contains("expected 2"), "{err}");
811    }
812
813    #[test]
814    fn a_truncated_table_is_rejected() {
815        let buf = table(&[("a", "b", 0)]);
816        let err = PostingsTable::parse(&buf, 0, buf.len() - 6, true).unwrap_err();
817        assert!(err.to_string().contains("past the index body"), "{err}");
818    }
819
820    #[test]
821    fn merged_postings_union_is_sorted_and_deduplicated() {
822        // Big-endian references: a = [1, 3, 7], b = [1, 2, 9].
823        let a = List {
824            refs: &[0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 7],
825            pos: 0,
826            remaining: 3,
827        };
828        let b = List {
829            refs: &[0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 9],
830            pos: 0,
831            remaining: 3,
832        };
833        let merged: Vec<u64> = Postings::merged(vec![a, b]).collect();
834        assert_eq!(merged, vec![1, 2, 3, 7, 9]);
835    }
836
837    #[test]
838    fn lists_decode_in_order() {
839        let buf = list(&[5, 6, 9]);
840        let l = List {
841            refs: &buf[8..buf.len() - 4],
842            pos: 0,
843            remaining: 3,
844        };
845        let got: Vec<u64> = Postings::single(l).collect();
846        assert_eq!(got, vec![5, 6, 9]);
847    }
848}