Skip to main content

tsdb_reader/index/
mod.rs

1//! Prometheus TSDB index reader (format v1/v2/v3).
2//!
3//! Two access patterns share this reader. A sequential export walks the series
4//! section in lexicographic label order, which is also the physical order of
5//! their chunks in the segment files; [`IndexReader::series`] does that without
6//! touching any label index. A lookup-driven consumer asks for one label pair
7//! instead; [`IndexReader::postings`] serves that from a sampled view of the
8//! postings offset table, so no full label index is ever held in memory.
9//!
10//! Module layout:
11//!
12//! | Module | Responsibility |
13//! |--------|----------------|
14//! | `toc` | table of contents: section offsets, bounds and ordering |
15//! | `symbols` | symbol table (v1 inline refs, v2/v3 offset groups) |
16//! | `series` | series records, chunk metadata, sequential iterator |
17//! | `postings` | postings lists, label names/values, sorted unions |
18//! | `postings_ops` | intersection, union and difference over postings |
19//! | `label_index` | the [`LabelIndexReader`] trait over the label space |
20//! | `matcher` | label matchers and the postings plan they compile to |
21//! | `validation` | section boundary and layout checks |
22
23pub mod label_index;
24pub mod matcher;
25pub mod postings;
26pub mod postings_ops;
27mod series;
28mod symbols;
29mod toc;
30
31pub mod validation;
32
33pub use label_index::LabelIndexReader;
34pub use matcher::{LabelMatcher, MatchType};
35pub use postings::{MergedPostings, Postings, PostingsList, PostingsStats, VecPostings};
36pub use postings_ops::{
37    difference, intersect, intersect_all, union_all, BoxPostings, Difference, Intersection, Union,
38};
39pub use series::{ChunkMeta, IndexStats, SeriesIter, SeriesRef};
40pub(crate) use symbols::Symbols;
41pub use toc::Toc;
42
43use std::path::Path;
44
45use crate::error::{Error, Result};
46use crate::storage::{self, Segment};
47use crate::varint;
48
49use toc::{be32, TOC_LEN};
50
51const MAGIC_INDEX: u32 = 0xBAAA_D700;
52const HEADER_LEN: usize = 5;
53/// Series records are padded to 16 bytes so a 32-bit reference can address them.
54pub(crate) const SERIES_ALIGN: usize = 16;
55
56/// Reader for the index of one block.
57///
58/// The symbol table and the series section are parsed eagerly; the postings
59/// offset table is parsed on first lookup and kept in its sampled form. No full
60/// label index is ever built.
61///
62/// `IndexReader` is `Send + Sync`. Mutable state lives elsewhere: each
63/// [`SeriesIter`] owns its symbol cache and cursor, and the postings table is
64/// initialised once through a `OnceLock`. Several threads can therefore query
65/// the same reader concurrently, each with its own iterators.
66pub struct IndexReader {
67    pub(crate) mmap: Segment,
68    pub(crate) version: u8,
69    toc: Toc,
70    pub(crate) symbols: Symbols,
71    /// End of the series section: the first byte that is not a series record.
72    pub(crate) series_end: usize,
73    verify_crc: bool,
74    /// Sampled postings offset table, built on first use.
75    ///
76    /// A `OnceLock` (not a `RefCell`) keeps `IndexReader` `Sync`: two threads
77    /// may race to build the table, and whichever wins is used by both.
78    pub(super) postings_table: std::sync::OnceLock<std::sync::Arc<postings::PostingsTable>>,
79}
80
81impl std::fmt::Debug for IndexReader {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.debug_struct("IndexReader")
84            .field("version", &self.version)
85            .field("toc", &self.toc)
86            .field("series_end", &self.series_end)
87            .finish()
88    }
89}
90
91impl IndexReader {
92    /// Opens and validates an `index` file.
93    pub fn open(path: &Path, verify_crc: bool) -> Result<Self> {
94        Self::from_segment(storage::open(path)?, verify_crc)
95    }
96
97    /// Wraps an already-mapped index file.
98    #[cfg(feature = "mmap")]
99    pub fn from_mmap(mmap: memmap2::Mmap, verify_crc: bool) -> Result<Self> {
100        Self::from_segment(storage::mapped(mmap), verify_crc)
101    }
102
103    /// Wraps an index file that is already in memory.
104    ///
105    /// Useful when the bytes come from an object store, a network stream or a
106    /// test fixture instead of the local filesystem.
107    pub fn from_bytes(bytes: Vec<u8>, verify_crc: bool) -> Result<Self> {
108        Self::from_segment(storage::owned(bytes), verify_crc)
109    }
110
111    fn from_segment(mmap: Segment, verify_crc: bool) -> Result<Self> {
112        let len = mmap.len();
113        if len < HEADER_LEN + TOC_LEN {
114            return Err(Error::format("index file too small"));
115        }
116        let magic = be32(&mmap, 0)?;
117        if magic != MAGIC_INDEX {
118            return Err(Error::format(format!("invalid index magic 0x{magic:08x}")));
119        }
120        let version = mmap[4];
121        if !(1..=3).contains(&version) {
122            return Err(Error::Unsupported(format!(
123                "index format version {version}"
124            )));
125        }
126
127        let toc = Toc::read(&mmap, verify_crc)?;
128        let series_start = toc.series as usize;
129        if toc.series != 0 && (series_start >= len || series_start < HEADER_LEN) {
130            return Err(Error::format("series section offset out of range"));
131        }
132
133        // The series section ends where the next section starts. `label_indices`
134        // is the canonical boundary for v2/v3; fall back defensively if a writer
135        // left it unset.
136        let mut series_end = len - TOC_LEN;
137        for cand in [toc.label_indices, toc.postings, toc.postings_table] {
138            let c = cand as usize;
139            if cand != 0 && c > series_start && c <= len - TOC_LEN {
140                series_end = series_end.min(c);
141            }
142        }
143        if toc.series == 0 || series_start >= series_end {
144            series_end = series_start;
145        }
146
147        let symbols = if toc.symbols == 0 || toc.symbols as usize >= len {
148            Symbols::empty()
149        } else {
150            Symbols::new(&mmap, toc.symbols as usize, version, verify_crc)?
151        };
152
153        Ok(Self {
154            mmap,
155            version,
156            toc,
157            symbols,
158            series_end,
159            verify_crc,
160            postings_table: std::sync::OnceLock::new(),
161        })
162    }
163
164    /// Index format version (1, 2 or 3).
165    pub fn version(&self) -> u8 {
166        self.version
167    }
168
169    /// Raw table of contents of the file.
170    pub fn toc(&self) -> Toc {
171        self.toc
172    }
173
174    /// Byte offset where the series section starts, after alignment.
175    pub fn series_start(&self) -> u64 {
176        align_up(self.toc.series as usize, self.align()) as u64
177    }
178
179    /// Byte offset where the series section ends.
180    pub fn series_end(&self) -> u64 {
181        self.series_end as u64
182    }
183
184    /// The whole index file as bytes.
185    pub fn bytes(&self) -> &[u8] {
186        &self.mmap
187    }
188
189    /// Number of symbols declared by the symbol table.
190    pub fn symbol_count(&self) -> usize {
191        self.symbols.count()
192    }
193
194    /// True when series records carry a CRC that is being verified.
195    pub fn verify_crc(&self) -> bool {
196        self.verify_crc
197    }
198
199    #[inline]
200    pub(crate) fn align(&self) -> usize {
201        if self.version == 1 {
202            1
203        } else {
204            SERIES_ALIGN
205        }
206    }
207
208    /// Iterates series beginning at the given byte offset (0 means "from the
209    /// start of the series section").
210    pub fn series(&self, start_offset: u64) -> SeriesIter<'_> {
211        let start = if start_offset == 0 {
212            self.series_start() as usize
213        } else {
214            start_offset as usize
215        };
216        SeriesIter {
217            index: self,
218            pos: start,
219            done: false,
220            cache: symbols::SymbolCache::new(),
221        }
222    }
223
224    /// Scans the series section without resolving symbols, collecting exact
225    /// series and chunk counts.
226    ///
227    /// Use this when `meta.json` carries no stats. It walks every record but
228    /// never touches the symbol table, so it stays cheap on wide label sets.
229    /// Records are still bounds-checked: a corrupt section is reported instead
230    /// of being counted.
231    pub fn scan_stats(&self) -> Result<IndexStats> {
232        let mut pos = self.series_start() as usize;
233        let mut stats = IndexStats {
234            min_series_offset: pos as u64,
235            end_series_offset: pos as u64,
236            ..Default::default()
237        };
238        let mut scratch = Vec::new();
239        while pos < self.series_end {
240            if self.mmap.get(pos).copied().unwrap_or(0) == 0 {
241                break;
242            }
243            let head = self.series_bounds(pos)?;
244            let mut p = head.payload_start;
245            let labels = varint::uvarint(&self.mmap, &mut p)?;
246            self.skip_labels(labels, &mut p, &head)?;
247            scratch.clear();
248            stats.chunks += self.read_chunk_metas(&mut p, &head, &mut scratch)?;
249            if p > head.payload_end {
250                return Err(Error::format(format!("series at {pos}: payload truncated")));
251            }
252            stats.series += 1;
253            stats.end_series_offset = head.next as u64;
254            pos = head.next;
255        }
256        Ok(stats)
257    }
258
259    /// Validates the record framing at `pos` and returns its payload bounds.
260    ///
261    /// Enforces everything that makes a record addressable and safe to parse:
262    /// the offset lies inside the series section, is aligned like the writer
263    /// requires, and the declared payload plus CRC fits before the next section.
264    fn series_bounds(&self, pos: usize) -> Result<SeriesHead> {
265        let start = pos;
266        if start < self.series_start() as usize || start >= self.series_end {
267            return Err(Error::format(format!(
268                "series offset {start} outside the series section"
269            )));
270        }
271        if self.align() > 1 && start % SERIES_ALIGN != 0 {
272            return Err(Error::format(format!(
273                "series offset {start} is not {SERIES_ALIGN}-byte aligned"
274            )));
275        }
276        let (payload_len, payload_start) = varint::peek_uvarint(&self.mmap, start)?;
277        let payload_len = usize::try_from(payload_len)
278            .map_err(|_| Error::format("series length does not fit in usize"))?;
279        let payload_end = payload_start
280            .checked_add(payload_len)
281            .ok_or_else(|| Error::format("series length overflow"))?;
282        // payload + 4-byte CRC must stay inside the series section, not merely
283        // inside the file: otherwise a bad length silently reads symbols or
284        // postings as series data.
285        let crc_end = payload_end
286            .checked_add(4)
287            .ok_or_else(|| Error::format("series length overflow"))?;
288        if crc_end > self.series_end {
289            return Err(Error::format(format!(
290                "series at {start}: payload ends at {crc_end}, past the series section ({})",
291                self.series_end
292            )));
293        }
294        let next = align_up(crc_end, self.align());
295        if next <= start {
296            return Err(Error::format("series parser made no progress"));
297        }
298        Ok(SeriesHead {
299            start,
300            payload_start,
301            payload_end,
302            next,
303        })
304    }
305
306    /// Skips `num_labels` symbol-reference pairs, checking they fit the payload.
307    fn skip_labels(&self, num_labels: u64, p: &mut usize, head: &SeriesHead) -> Result<()> {
308        // Every label pair takes at least two bytes, so this bounds the loop by
309        // the payload size instead of trusting an arbitrary count.
310        let room = head.payload_end.saturating_sub(*p) as u64;
311        if num_labels.saturating_mul(2) > room {
312            return Err(Error::format(format!(
313                "series at {}: {num_labels} labels do not fit in {room} bytes",
314                head.start
315            )));
316        }
317        for _ in 0..num_labels {
318            varint::uvarint(&self.mmap, p)?;
319            varint::uvarint(&self.mmap, p)?;
320        }
321        Ok(())
322    }
323
324    /// Reads the chunk metadata of one series record.
325    ///
326    /// Validates the writer's invariants as it goes: chunk count fits the
327    /// payload, `max_time >= min_time`, chunk time ranges strictly increase,
328    /// and references are non-decreasing. Violations mean the record is
329    /// corrupt, so they are reported instead of being handed to a caller.
330    fn read_chunk_metas(
331        &self,
332        p: &mut usize,
333        head: &SeriesHead,
334        out: &mut Vec<ChunkMeta>,
335    ) -> Result<u64> {
336        let num_chunks = varint::uvarint(&self.mmap, p)?;
337        if num_chunks == 0 {
338            return Ok(0);
339        }
340        // The smallest possible chunk triple is three one-byte varints.
341        let room = head.payload_end.saturating_sub(*p) as u64;
342        if num_chunks.saturating_mul(3) > room {
343            return Err(Error::format(format!(
344                "series at {}: {num_chunks} chunks do not fit in {room} bytes",
345                head.start
346            )));
347        }
348
349        let mint = varint::varint(&self.mmap, p)?;
350        let maxt = mint
351            .checked_add(varint::uvarint(&self.mmap, p)? as i64)
352            .ok_or_else(|| Error::format("chunk maxt overflow"))?;
353        if maxt < mint {
354            return Err(Error::format(format!(
355                "series at {}: chunk max time {maxt} before min time {mint}",
356                head.start
357            )));
358        }
359        let reference = varint::uvarint(&self.mmap, p)?;
360        out.push(ChunkMeta {
361            reference,
362            min_time: mint,
363            max_time: maxt,
364        });
365
366        let mut prev_maxt = maxt;
367        let mut prev_ref = reference;
368        for _ in 1..num_chunks {
369            let mint = prev_maxt
370                .checked_add(varint::uvarint(&self.mmap, p)? as i64)
371                .ok_or_else(|| Error::format("chunk mint overflow"))?;
372            let maxt = mint
373                .checked_add(varint::uvarint(&self.mmap, p)? as i64)
374                .ok_or_else(|| Error::format("chunk maxt overflow"))?;
375            let delta = varint::varint(&self.mmap, p)?;
376            let reference = (prev_ref as i64)
377                .checked_add(delta)
378                .ok_or_else(|| Error::format("chunk ref overflow"))?
379                as u64;
380            if mint <= prev_maxt {
381                return Err(Error::format(format!(
382                    "series at {}: chunk starts at {mint}, previous chunk ends at {prev_maxt}",
383                    head.start
384                )));
385            }
386            if maxt < mint {
387                return Err(Error::format(format!(
388                    "series at {}: chunk max time {maxt} before min time {mint}",
389                    head.start
390                )));
391            }
392            if reference < prev_ref {
393                return Err(Error::format(format!(
394                    "series at {}: chunk reference {reference} precedes {prev_ref}",
395                    head.start
396                )));
397            }
398            prev_maxt = maxt;
399            prev_ref = reference;
400            out.push(ChunkMeta {
401                reference,
402                min_time: mint,
403                max_time: maxt,
404            });
405        }
406        Ok(num_chunks)
407    }
408
409    /// Parses one series record at `pos`, returning it and the next offset.
410    pub(crate) fn parse_series(
411        &self,
412        pos: usize,
413        cache: &mut symbols::SymbolCache,
414    ) -> Result<(SeriesRef, usize)> {
415        let head = self.series_bounds(pos)?;
416        if self.verify_crc {
417            let want = be32(&self.mmap, head.payload_end)?;
418            crate::checksum::verify(
419                true,
420                want,
421                &self.mmap[head.payload_start..head.payload_end],
422                "index series",
423            )?;
424        }
425
426        let mut p = head.payload_start;
427        let num_labels = varint::uvarint(&self.mmap, &mut p)?;
428        let mut labels = Vec::with_capacity(num_labels.min(64) as usize);
429        let room = head.payload_end.saturating_sub(p) as u64;
430        if num_labels.saturating_mul(2) > room {
431            return Err(Error::format(format!(
432                "series at {}: {num_labels} labels do not fit in {room} bytes",
433                head.start
434            )));
435        }
436        for _ in 0..num_labels {
437            let name = varint::uvarint32(&self.mmap, &mut p)?;
438            let value = varint::uvarint32(&self.mmap, &mut p)?;
439            labels.push((
440                self.symbols.lookup(&self.mmap, name, cache)?,
441                self.symbols.lookup(&self.mmap, value, cache)?,
442            ));
443        }
444
445        let mut chunks = Vec::new();
446        self.read_chunk_metas(&mut p, &head, &mut chunks)?;
447        if p > head.payload_end {
448            return Err(Error::format(format!(
449                "series at {}: payload truncated",
450                head.start
451            )));
452        }
453
454        let id = if self.version == 1 {
455            head.start as u64
456        } else {
457            (head.start / SERIES_ALIGN) as u64
458        };
459        Ok((
460            SeriesRef {
461                id,
462                offset: head.start as u64,
463                labels,
464                chunks,
465            },
466            head.next,
467        ))
468    }
469}
470
471/// Framing of one series record: where its payload lives and what follows it.
472struct SeriesHead {
473    /// Byte offset of the record (also the base of the series reference).
474    start: usize,
475    /// First byte of the payload (labels + chunks).
476    payload_start: usize,
477    /// First byte after the payload (the CRC starts here).
478    payload_end: usize,
479    /// Byte offset of the next record.
480    next: usize,
481}
482
483#[inline]
484pub(crate) fn align_up(v: usize, align: usize) -> usize {
485    if align <= 1 {
486        v
487    } else {
488        (v + align - 1) & !(align - 1)
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    /// Encodes an unsigned LEB128 varint, the way Prometheus writes lengths
497    /// and references.
498    fn put_uvarint(out: &mut Vec<u8>, mut v: u64) {
499        loop {
500            let mut b = (v & 0x7f) as u8;
501            v >>= 7;
502            if v != 0 {
503                b |= 0x80;
504            }
505            out.push(b);
506            if v == 0 {
507                break;
508            }
509        }
510    }
511
512    /// Encodes a zig-zag signed varint, used for timestamps and ref deltas.
513    fn put_varint(out: &mut Vec<u8>, v: i64) {
514        put_uvarint(out, ((v << 1) ^ (v >> 63)) as u64);
515    }
516
517    /// Builds a series payload: labels as (name,value) symbol refs plus chunks.
518    fn payload(labels: &[(u32, u32)], chunks: &[(i64, i64, u64)]) -> Vec<u8> {
519        let mut out = Vec::new();
520        put_uvarint(&mut out, labels.len() as u64);
521        for (n, v) in labels {
522            put_uvarint(&mut out, *n as u64);
523            put_uvarint(&mut out, *v as u64);
524        }
525        put_uvarint(&mut out, chunks.len() as u64);
526        if let Some(((mint, maxt, reference), rest)) = chunks.split_first() {
527            put_varint(&mut out, *mint);
528            put_uvarint(&mut out, (maxt - mint) as u64);
529            put_uvarint(&mut out, *reference);
530            let mut prev_maxt = *maxt;
531            let mut prev_ref = *reference as i64;
532            for (mint, maxt, reference) in rest {
533                put_uvarint(&mut out, (mint - prev_maxt) as u64);
534                put_uvarint(&mut out, (maxt - mint) as u64);
535                put_varint(&mut out, *reference as i64 - prev_ref);
536                prev_maxt = *maxt;
537                prev_ref = *reference as i64;
538            }
539        }
540        out
541    }
542
543    /// Assembles a minimal but valid v2 index around the given payloads.
544    fn build_index(payloads: &[Vec<u8>]) -> Vec<u8> {
545        build_index_version(2, payloads)
546    }
547
548    /// Assembles a minimal index of the requested version.
549    ///
550    /// Layout: header, symbol table ("a", "b"), series section (16-byte aligned
551    /// on v2/v3, byte packed on v1), then the TOC. `label_indices` marks the end
552    /// of the series section so the boundary checks have something exact to
553    /// compare against.
554    fn build_index_version(version: u8, payloads: &[Vec<u8>]) -> Vec<u8> {
555        let align = if version == 1 { 1 } else { SERIES_ALIGN };
556        let mut out = Vec::new();
557        out.extend_from_slice(&0xBAAA_D700u32.to_be_bytes());
558        out.push(version);
559
560        let symbols_off = out.len();
561        let mut sym = Vec::new();
562        for name in ["a", "b"] {
563            sym.push(name.len() as u8);
564            sym.extend_from_slice(name.as_bytes());
565        }
566        out.extend_from_slice(&((sym.len() + 4) as u32).to_be_bytes());
567        out.extend_from_slice(&2u32.to_be_bytes());
568        out.extend_from_slice(&sym);
569        let sym_crc = crc32c::crc32c(&out[symbols_off + 4..]);
570        out.extend_from_slice(&sym_crc.to_be_bytes());
571
572        while out.len() % align != 0 {
573            out.push(0);
574        }
575        let series_off = out.len();
576        for body in payloads {
577            let mut len = Vec::new();
578            put_uvarint(&mut len, body.len() as u64);
579            out.extend_from_slice(&len);
580            out.extend_from_slice(body);
581            let crc = crc32c::crc32c(body);
582            out.extend_from_slice(&crc.to_be_bytes());
583            while out.len() % align != 0 {
584                out.push(0);
585            }
586        }
587        let end_series = out.len();
588
589        let mut toc = Vec::new();
590        toc.extend_from_slice(&(symbols_off as u64).to_be_bytes());
591        toc.extend_from_slice(&(series_off as u64).to_be_bytes());
592        toc.extend_from_slice(&(end_series as u64).to_be_bytes());
593        toc.extend_from_slice(&0u64.to_be_bytes());
594        toc.extend_from_slice(&0u64.to_be_bytes());
595        toc.extend_from_slice(&0u64.to_be_bytes());
596        let toc_crc = crc32c::crc32c(&toc);
597        out.extend_from_slice(&toc);
598        out.extend_from_slice(&toc_crc.to_be_bytes());
599        out
600    }
601
602    fn reader(payloads: &[Vec<u8>]) -> IndexReader {
603        IndexReader::from_bytes(build_index(payloads), true).unwrap()
604    }
605
606    fn one_series(chunks: &[(i64, i64, u64)]) -> IndexReader {
607        reader(&[payload(&[(0, 1)], chunks)])
608    }
609
610    #[test]
611    fn alignment() {
612        assert_eq!(align_up(0, 16), 0);
613        assert_eq!(align_up(1, 16), 16);
614        assert_eq!(align_up(16, 16), 16);
615        assert_eq!(align_up(17, 16), 32);
616        assert_eq!(align_up(17, 1), 17);
617    }
618
619    #[test]
620    fn series_id_uses_offset_div_16() {
621        assert_eq!((160usize / SERIES_ALIGN) as u64, 10);
622    }
623
624    #[test]
625    fn be_helpers_reject_short_buffers() {
626        assert!(be32(&[0, 0], 0).is_err());
627        assert!(toc::be64(&[0, 0, 0, 0], 0).is_err());
628    }
629
630    #[test]
631    fn parses_a_well_formed_record() {
632        let idx = one_series(&[(100, 200, 8), (300, 400, 60)]);
633        let series: Vec<_> = idx.series(0).collect::<Result<Vec<_>>>().unwrap();
634        assert_eq!(series.len(), 1);
635        assert_eq!(series[0].labels.len(), 1);
636        assert_eq!(&*series[0].labels[0].0, "a");
637        assert_eq!(&*series[0].labels[0].1, "b");
638        assert_eq!(series[0].chunks.len(), 2);
639        assert_eq!(series[0].chunks[0].min_time, 100);
640        assert_eq!(series[0].chunks[1].max_time, 400);
641        assert_eq!(series[0].chunks[1].reference, 60);
642        assert_eq!(series[0].id, series[0].offset / SERIES_ALIGN as u64);
643        // The offsets reported are the same ones a resumed run would use.
644        assert_eq!(idx.series(0).position(), idx.series_start());
645        assert_eq!(idx.scan_stats().unwrap().series, 1);
646        assert_eq!(idx.scan_stats().unwrap().chunks, 2);
647    }
648
649    #[test]
650    fn unaligned_resume_offsets_are_rejected() {
651        let idx = one_series(&[(100, 200, 8)]);
652        let error = idx
653            .series(idx.series_start() + 1)
654            .next()
655            .unwrap()
656            .unwrap_err();
657        assert!(error.to_string().contains("aligned"), "{error}");
658    }
659
660    #[test]
661    fn offsets_outside_the_section_are_rejected() {
662        let idx = one_series(&[(100, 200, 8)]);
663        let past = idx.series_end() + SERIES_ALIGN as u64;
664        assert!(
665            idx.series(past).next().is_none(),
666            "past the end yields nothing"
667        );
668        let before = idx.series_start() - SERIES_ALIGN as u64;
669        let error = idx.series(before).next().unwrap().unwrap_err();
670        assert!(error.to_string().contains("outside"), "{error}");
671    }
672
673    #[test]
674    fn payload_length_past_the_section_is_rejected() {
675        let mut bytes = build_index(&[payload(&[(0, 1)], &[(100, 200, 8)])]);
676        // Find the series section and inflate the first length varint.
677        let idx = IndexReader::from_bytes(bytes.clone(), false).unwrap();
678        let start = idx.series_start() as usize;
679        bytes[start] = 0xff;
680        bytes[start + 1] = 0x7f;
681        let idx = IndexReader::from_bytes(bytes, false).unwrap();
682        let error = idx.series(0).next().unwrap().unwrap_err();
683        assert!(
684            error.to_string().contains("past the series section"),
685            "{error}"
686        );
687        // The fast path must agree instead of counting a bogus record.
688        assert!(idx.scan_stats().is_err());
689    }
690
691    #[test]
692    fn label_count_beyond_the_payload_is_rejected() {
693        let mut body = Vec::new();
694        put_uvarint(&mut body, 1_000_000); // absurd label count
695        let idx = reader(&[body]);
696        let error = idx.series(0).next().unwrap().unwrap_err();
697        assert!(error.to_string().contains("labels do not fit"), "{error}");
698    }
699
700    #[test]
701    fn chunk_count_beyond_the_payload_is_rejected() {
702        let mut body = Vec::new();
703        put_uvarint(&mut body, 0); // no labels
704        put_uvarint(&mut body, 100_000); // absurd chunk count
705        let idx = reader(&[body]);
706        let error = idx.series(0).next().unwrap().unwrap_err();
707        assert!(error.to_string().contains("chunks do not fit"), "{error}");
708    }
709
710    #[test]
711    fn chunk_max_time_before_min_time_is_rejected() {
712        // `maxt - mint` is read as an unsigned delta, so a value above i64::MAX
713        // turns negative and would move maxt before mint.
714        let mut body = Vec::new();
715        put_uvarint(&mut body, 0); // no labels
716        put_uvarint(&mut body, 1); // one chunk
717        put_varint(&mut body, 100);
718        put_uvarint(&mut body, u64::MAX); // (i64) -1
719        put_uvarint(&mut body, 8);
720        let idx = reader(&[body]);
721        let error = idx.series(0).next().unwrap().unwrap_err();
722        assert!(error.to_string().contains("before min time"), "{error}");
723    }
724
725    #[test]
726    fn non_increasing_chunk_times_are_rejected() {
727        let idx = one_series(&[(100, 200, 8), (200, 300, 60)]);
728        let error = idx.series(0).next().unwrap().unwrap_err();
729        assert!(error.to_string().contains("previous chunk ends"), "{error}");
730    }
731
732    #[test]
733    fn decreasing_chunk_references_are_rejected() {
734        let idx = one_series(&[(100, 200, 60), (300, 400, 8)]);
735        let error = idx.series(0).next().unwrap().unwrap_err();
736        assert!(error.to_string().contains("precedes"), "{error}");
737    }
738
739    #[test]
740    fn v1_indexes_are_byte_packed_and_reference_offsets() {
741        // v1 symbol references are byte offsets of the symbol entries, not
742        // indexes: the table starts at 5, so its payload (and the first symbol)
743        // is at 13 and the second follows the 1-byte length prefix of "a".
744        let idx = IndexReader::from_bytes(
745            build_index_version(
746                1,
747                &[
748                    payload(&[(13, 15)], &[(100, 200, 8)]),
749                    payload(&[(13, 15), (15, 13)], &[(300, 400, 60)]),
750                ],
751            ),
752            true,
753        )
754        .unwrap();
755        assert_eq!(idx.version(), 1);
756        idx.validate_layout().expect("v1 layout");
757
758        let series: Vec<_> = idx.series(0).collect::<Result<Vec<_>>>().unwrap();
759        assert_eq!(series.len(), 2);
760        // v1 references are byte offsets, not offset/16.
761        assert_eq!(series[0].id, series[0].offset);
762        assert_eq!(series[1].id, series[1].offset);
763        assert_ne!(series[0].offset % SERIES_ALIGN as u64, 0);
764
765        // A reference from a postings list resolves the same way.
766        let resolved = idx.series_by_ref(series[1].offset).unwrap();
767        assert_eq!(resolved.labels.len(), 2);
768        assert_eq!(resolved.chunks[0].reference, 60);
769        // v2-style padded references must not resolve to a v1 record.
770        assert!(idx
771            .series_by_ref(series[1].offset * SERIES_ALIGN as u64)
772            .is_err());
773
774        assert_eq!(idx.scan_stats().unwrap().series, 2);
775        assert_eq!(idx.validate_postings().unwrap(), PostingsStats::default());
776    }
777
778    #[test]
779    fn an_index_without_a_label_space_is_not_corrupt() {
780        // The synthetic builder writes no postings sections at all.
781        let idx = one_series(&[(100, 200, 8)]);
782        let stats = idx.validate_postings().unwrap();
783        assert_eq!(stats, PostingsStats::default());
784        // Lookups are unavailable rather than silently empty.
785        assert!(idx.label_names().is_err());
786        assert!(idx.postings("a", "b").is_err());
787        // The series section is still readable.
788        assert_eq!(idx.series(0).count(), 1);
789    }
790
791    #[test]
792    fn scan_stats_matches_the_iterator() {
793        let idx = reader(&[
794            payload(&[(0, 1)], &[(100, 200, 8), (300, 400, 60)]),
795            payload(&[(0, 1), (1, 0)], &[(500, 600, 120)]),
796        ]);
797        let stats = idx.scan_stats().unwrap();
798        let mut series = 0;
799        let mut chunks = 0;
800        for s in idx.series(0) {
801            let s = s.unwrap();
802            series += 1;
803            chunks += s.chunks.len();
804        }
805        assert_eq!(stats.series, series);
806        assert_eq!(stats.chunks, chunks as u64);
807        assert!(stats.end_series_offset > stats.min_series_offset);
808    }
809}