tsdb-reader 0.3.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings and label matchers, tombstones
Documentation
//! Structural validation of the index TOC and section boundaries.
//!
//! The reader is already defensive while parsing, but a corrupt TOC can make
//! the sections overlap in ways that only show up much later (a series record
//! decoded from inside the symbol table, for example). These checks run once,
//! before any record is touched, so callers can reject a block cheaply.

use crate::error::{Error, Result};

use super::{IndexReader, SERIES_ALIGN};

/// Result of the layout check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexLayout {
    /// Byte offset where the series section starts.
    pub series_start: u64,
    /// Byte offset where the series section ends.
    pub series_end: u64,
    /// Index format version read from the header.
    pub version: u8,
}

impl IndexReader {
    /// Checks TOC ordering, section bounds and series alignment.
    ///
    /// This is a pure metadata check: no series record is parsed and the symbol
    /// table is not walked again, so it is safe to call on every open.
    pub fn validate_layout(&self) -> Result<IndexLayout> {
        let len = self.mmap.len();
        let toc_end = len
            .checked_sub(super::toc::TOC_LEN)
            .ok_or_else(|| Error::format("index file too small"))?;

        // Sections live in the file body, before the TOC trailer. A section
        // may start exactly at the TOC when it is empty (a v1 index can leave
        // `label_indices` unused this way); a table needs at least an empty
        // content plus its CRC.
        for (name, off) in self.toc.offsets() {
            if off == 0 {
                continue;
            }
            let is_table = name.ends_with("_table");
            let limit = if is_table {
                toc_end.saturating_sub(8)
            } else {
                toc_end
            };
            if off as usize > limit {
                return Err(Error::format(format!(
                    "index {name} section offset {off} overlaps the TOC"
                )));
            }
        }

        if self.toc.symbols == 0 {
            return Err(Error::format("index has no symbol table"));
        }

        // v2 writes `label_indices`/`postings` at the same offset (and the same
        // for their tables), so only the relations below are invariant.
        let series = self.toc.series;
        if series != 0 && series < self.toc.symbols {
            return Err(Error::format(format!(
                "index series section at {series} precedes the symbol table at {}",
                self.toc.symbols
            )));
        }
        for (name, off) in [
            ("label_indices", self.toc.label_indices),
            ("postings", self.toc.postings),
        ] {
            if off != 0 && off < series {
                return Err(Error::format(format!(
                    "index {name} section at {off} precedes the series section at {series}"
                )));
            }
        }
        for (name, section, table) in [
            (
                "label_indices",
                self.toc.label_indices,
                self.toc.label_indices_table,
            ),
            ("postings", self.toc.postings, self.toc.postings_table),
        ] {
            if table != 0 && table < section {
                return Err(Error::format(format!(
                    "index {name} table at {table} precedes its section at {section}"
                )));
            }
        }

        let series_start = self.series_start() as usize;
        if series_start > toc_end || self.series_end > toc_end {
            return Err(Error::format("series section exceeds the index body"));
        }
        if self.series_end < series_start {
            return Err(Error::format("series section ends before it starts"));
        }

        // v2/v3 series references are `offset / 16`, so misaligned records are
        // unaddressable by tombstones and postings.
        if self.version != 1 && series_start % SERIES_ALIGN != 0 {
            return Err(Error::format(format!(
                "series section starts at unaligned offset {series_start}"
            )));
        }

        Ok(IndexLayout {
            series_start: series_start as u64,
            series_end: self.series_end as u64,
            version: self.version,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn fixture() -> IndexReader {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R/index");
        IndexReader::open(&path, true).unwrap()
    }

    #[test]
    fn fixture_layout_is_valid() {
        let layout = fixture().validate_layout().unwrap();
        assert_eq!(layout.version, 2);
        assert!(layout.series_end > layout.series_start);
        assert_eq!(layout.series_start % SERIES_ALIGN as u64, 0);
    }

    #[test]
    fn a_corrupt_toc_is_rejected() {
        let good = fixture();
        let mut bytes = good.bytes().to_vec();
        // Put the label index before the series section, which the reader
        // tolerates but a structural check must not.
        let toc_off = bytes.len() - super::super::toc::TOC_LEN;
        let bad = 100u64;
        bytes[toc_off + 16..toc_off + 24].copy_from_slice(&bad.to_be_bytes());
        let reader = IndexReader::from_bytes(bytes, false).unwrap();
        let error = reader.validate_layout().unwrap_err();
        assert!(
            error.to_string().contains("precedes the series"),
            "unexpected error: {error}"
        );
    }
}