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