Skip to main content

tsdb_reader/index/
validation.rs

1//! Structural validation of the index TOC and section boundaries.
2//!
3//! The reader is already defensive while parsing, but a corrupt TOC can make
4//! the sections overlap in ways that only show up much later (a series record
5//! decoded from inside the symbol table, for example). These checks run once,
6//! before any record is touched, so callers can reject a block cheaply.
7
8use crate::error::{Error, Result};
9
10use super::{IndexReader, SERIES_ALIGN};
11
12/// Result of the layout check.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct IndexLayout {
15    /// Byte offset where the series section starts.
16    pub series_start: u64,
17    /// Byte offset where the series section ends.
18    pub series_end: u64,
19    /// Index format version read from the header.
20    pub version: u8,
21}
22
23impl IndexReader {
24    /// Checks TOC ordering, section bounds and series alignment.
25    ///
26    /// This is a pure metadata check: no series record is parsed and the symbol
27    /// table is not walked again, so it is safe to call on every open.
28    pub fn validate_layout(&self) -> Result<IndexLayout> {
29        let len = self.mmap.len();
30        let toc_end = len
31            .checked_sub(super::toc::TOC_LEN)
32            .ok_or_else(|| Error::format("index file too small"))?;
33
34        // Sections live in the file body, before the TOC trailer. A section
35        // may start exactly at the TOC when it is empty (a v1 index can leave
36        // `label_indices` unused this way); a table needs at least an empty
37        // content plus its CRC.
38        for (name, off) in self.toc.offsets() {
39            if off == 0 {
40                continue;
41            }
42            let is_table = name.ends_with("_table");
43            let limit = if is_table {
44                toc_end.saturating_sub(8)
45            } else {
46                toc_end
47            };
48            if off as usize > limit {
49                return Err(Error::format(format!(
50                    "index {name} section offset {off} overlaps the TOC"
51                )));
52            }
53        }
54
55        if self.toc.symbols == 0 {
56            return Err(Error::format("index has no symbol table"));
57        }
58
59        // v2 writes `label_indices`/`postings` at the same offset (and the same
60        // for their tables), so only the relations below are invariant.
61        let series = self.toc.series;
62        if series != 0 && series < self.toc.symbols {
63            return Err(Error::format(format!(
64                "index series section at {series} precedes the symbol table at {}",
65                self.toc.symbols
66            )));
67        }
68        for (name, off) in [
69            ("label_indices", self.toc.label_indices),
70            ("postings", self.toc.postings),
71        ] {
72            if off != 0 && off < series {
73                return Err(Error::format(format!(
74                    "index {name} section at {off} precedes the series section at {series}"
75                )));
76            }
77        }
78        for (name, section, table) in [
79            (
80                "label_indices",
81                self.toc.label_indices,
82                self.toc.label_indices_table,
83            ),
84            ("postings", self.toc.postings, self.toc.postings_table),
85        ] {
86            if table != 0 && table < section {
87                return Err(Error::format(format!(
88                    "index {name} table at {table} precedes its section at {section}"
89                )));
90            }
91        }
92
93        let series_start = self.series_start() as usize;
94        if series_start > toc_end || self.series_end > toc_end {
95            return Err(Error::format("series section exceeds the index body"));
96        }
97        if self.series_end < series_start {
98            return Err(Error::format("series section ends before it starts"));
99        }
100
101        // v2/v3 series references are `offset / 16`, so misaligned records are
102        // unaddressable by tombstones and postings.
103        if self.version != 1 && series_start % SERIES_ALIGN != 0 {
104            return Err(Error::format(format!(
105                "series section starts at unaligned offset {series_start}"
106            )));
107        }
108
109        Ok(IndexLayout {
110            series_start: series_start as u64,
111            series_end: self.series_end as u64,
112            version: self.version,
113        })
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use std::path::PathBuf;
121
122    fn fixture() -> IndexReader {
123        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
124            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R/index");
125        IndexReader::open(&path, true).unwrap()
126    }
127
128    #[test]
129    fn fixture_layout_is_valid() {
130        let layout = fixture().validate_layout().unwrap();
131        assert_eq!(layout.version, 2);
132        assert!(layout.series_end > layout.series_start);
133        assert_eq!(layout.series_start % SERIES_ALIGN as u64, 0);
134    }
135
136    #[test]
137    fn a_corrupt_toc_is_rejected() {
138        let good = fixture();
139        let mut bytes = good.bytes().to_vec();
140        // Put the label index before the series section, which the reader
141        // tolerates but a structural check must not.
142        let toc_off = bytes.len() - super::super::toc::TOC_LEN;
143        let bad = 100u64;
144        bytes[toc_off + 16..toc_off + 24].copy_from_slice(&bad.to_be_bytes());
145        let reader = IndexReader::from_bytes(bytes, false).unwrap();
146        let error = reader.validate_layout().unwrap_err();
147        assert!(
148            error.to_string().contains("precedes the series"),
149            "unexpected error: {error}"
150        );
151    }
152}