tsdb-reader 0.2.0

Read-only, zero-copy Prometheus TSDB block reader: index v1-v3, all chunk encodings, integer histograms, postings lookups, tombstones
Documentation
//! Block-level consistency checks.
//!
//! Opening a block validates each file on its own. This module cross-checks
//! them: the metadata Prometheus wrote against the index that is actually on
//! disk, every chunk reference against the segment it points into, and the
//! tombstones against the index series space.
//!
//! [`BlockReader::validate`] scans the index series section without resolving
//! symbols and frames every referenced chunk record, but never decodes a
//! sample. That is cheap enough for an export that wants to fail fast on a
//! corrupt block; sample-level damage still surfaces when a chunk is decoded,
//! and [`crate::SampleIterator`] reports it with the series and chunk that
//! produced it.

use std::fmt;

use crate::block::BlockReader;
use crate::chunks::validation::SegmentReport;
use crate::index::{IndexStats, PostingsStats};
use crate::meta::META_VERSION;

/// How serious a [`Finding`] is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
    /// The block is readable but something looks off; worth logging.
    Warning,
    /// The block cannot be trusted; the reader should skip it.
    Error,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Severity::Warning => f.write_str("warning"),
            Severity::Error => f.write_str("error"),
        }
    }
}

/// One discrepancy found while validating a block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Finding {
    /// How serious the problem is.
    pub severity: Severity,
    /// Human-readable description, including the offsets involved.
    pub message: String,
}

impl Finding {
    fn warning(message: impl Into<String>) -> Self {
        Self {
            severity: Severity::Warning,
            message: message.into(),
        }
    }

    fn error(message: impl Into<String>) -> Self {
        Self {
            severity: Severity::Error,
            message: message.into(),
        }
    }
}

/// Everything validation learned about a block.
#[derive(Debug, Clone, Default)]
pub struct ValidationReport {
    /// Block ULID.
    pub block: String,
    /// Index format version read from the index header.
    pub index_version: u8,
    /// Version field of `meta.json` (the *meta* format, not the index format).
    pub meta_version: i32,
    /// Series count from scanning the index.
    pub series: u64,
    /// Chunk count from scanning the index.
    pub chunks: u64,
    /// Segment summary from walking the chunk files.
    pub segments: SegmentReport,
    /// Postings section summary, when it could be read.
    pub postings: Option<PostingsStats>,
    /// Everything that did not line up.
    pub findings: Vec<Finding>,
}

impl ValidationReport {
    /// True when no [`Severity::Error`] was recorded.
    ///
    /// Warnings do not make a block unusable, but see
    /// [`Self::into_result`] for a strict interpretation.
    pub fn is_ok(&self) -> bool {
        !self.findings.iter().any(|f| f.severity == Severity::Error)
    }

    /// Iterates the findings of a given severity.
    pub fn findings_of(&self, severity: Severity) -> impl Iterator<Item = &Finding> {
        self.findings.iter().filter(move |f| f.severity == severity)
    }

    /// Number of recorded errors.
    pub fn error_count(&self) -> usize {
        self.findings_of(Severity::Error).count()
    }

    /// Number of recorded warnings.
    pub fn warning_count(&self) -> usize {
        self.findings_of(Severity::Warning).count()
    }

    /// Fails when anything at all was reported.
    ///
    /// Use this when a single unexpected field means the block must not be
    /// exported, e.g. before a migration run that has to be restartable.
    pub fn into_result(self) -> crate::error::Result<Self> {
        if self.findings.is_empty() {
            return Ok(self);
        }
        let details: Vec<String> = self
            .findings
            .iter()
            .map(|f| format!("{}: {}", f.severity, f.message))
            .collect();
        Err(crate::error::Error::Corrupt(format!(
            "block {}: {}",
            self.block,
            details.join("; ")
        )))
    }
}

impl BlockReader {
    /// Cross-checks metadata, index, chunk segments and tombstones.
    ///
    /// Errors mean the block is corrupt (or written by something incompatible);
    /// warnings point at suspicious but readable data. Nothing here decodes
    /// samples, so a block that passes can still contain a bad chunk payload —
    /// [`crate::chunkenc::decode`] reports that when the chunk is read.
    pub fn validate(&self) -> crate::error::Result<ValidationReport> {
        let mut report = ValidationReport {
            block: self.block_id().to_string(),
            index_version: self.index().version(),
            meta_version: self.meta().version,
            ..Default::default()
        };

        let layout = self.index().validate_layout()?;
        let stats = self.index().scan_stats()?;
        report.series = stats.series;
        report.chunks = stats.chunks;
        report.segments = self.chunk_reader().validate_segments()?;

        self.check_meta(&mut report, &stats);
        self.check_series(&mut report);
        self.check_postings(&mut report);
        self.check_tombstones(&mut report);

        // An empty index section is legal only for a block without series.
        if stats.series == 0 && layout.series_end > layout.series_start + 1 {
            report.findings.push(Finding::warning(format!(
                "index series section spans {}..{} but contains no series",
                layout.series_start, layout.series_end
            )));
        }

        Ok(report)
    }

    /// Metadata-only checks: version, time range and the writer's counters.
    fn check_meta(&self, report: &mut ValidationReport, stats: &IndexStats) {
        let meta = self.meta();

        if meta.version != META_VERSION {
            report.findings.push(Finding::warning(format!(
                "meta.json version is {}, expected {META_VERSION}; \
                 this field is the meta format version, not the index version",
                meta.version
            )));
        }
        if meta.max_time <= meta.min_time {
            report.findings.push(Finding::warning(format!(
                "block time range is empty: minTime {} >= maxTime {}",
                meta.min_time, meta.max_time
            )));
        }
        if stats.series == 0 && meta.stats.num_series > 0 {
            report.findings.push(Finding::error(format!(
                "meta.json reports {} series but the index has none",
                meta.stats.num_series
            )));
        }
        if stats.series > 0 && meta.stats.num_series != stats.series {
            report.findings.push(Finding::error(format!(
                "meta.json reports {} series, index has {}",
                meta.stats.num_series, stats.series
            )));
        }
        if stats.series > 0 && meta.stats.num_chunks != stats.chunks {
            report.findings.push(Finding::error(format!(
                "meta.json reports {} chunks, index has {}",
                meta.stats.num_chunks, stats.chunks
            )));
        }
        let samples = meta.stats.num_float_samples + meta.stats.num_histogram_samples;
        if meta.stats.num_samples != 0 && samples != 0 && meta.stats.num_samples != samples {
            report.findings.push(Finding::warning(format!(
                "meta.json numSamples {} does not equal numFloatSamples + numHistogramSamples ({})",
                meta.stats.num_samples, samples
            )));
        }
    }

    /// Series-level checks: chunk references and time ranges.
    fn check_series(&self, report: &mut ValidationReport) {
        let meta = self.meta();
        let mut max_segment = 0u32;
        let mut outside_range = 0u64;
        let mut bad_refs = 0u64;
        let mut first_bad: Option<String> = None;

        for series in self.series(0) {
            let series = match series {
                Ok(s) => s,
                Err(e) => {
                    report
                        .findings
                        .push(Finding::error(format!("series section is unreadable: {e}")));
                    return;
                }
            };
            for chunk in &series.chunks {
                max_segment = max_segment.max(chunk.segment());
                if chunk.min_time < meta.min_time || chunk.max_time >= meta.max_time {
                    outside_range += 1;
                }
                if let Err(e) = self.chunk_reader().validate_reference(chunk.reference) {
                    bad_refs += 1;
                    if first_bad.is_none() {
                        first_bad = Some(format!("{e}"));
                    }
                }
            }
        }

        if bad_refs > 0 {
            report.findings.push(Finding::error(format!(
                "{bad_refs} chunk references do not resolve ({})",
                first_bad.unwrap_or_default()
            )));
        }
        if outside_range > 0 {
            report.findings.push(Finding::warning(format!(
                "{outside_range} chunks fall outside the block time range {}..{}",
                meta.min_time, meta.max_time
            )));
        }
        if self.chunk_reader().segment_count() as u32 != max_segment.saturating_add(1) {
            report.findings.push(Finding::warning(format!(
                "index references segments up to {max_segment} but the block has {}",
                self.chunk_reader().segment_count()
            )));
        }
    }

    /// Postings checks: the offset table and every list must decode.
    ///
    /// A block whose label space is broken is still readable sequentially, so a
    /// failure here is reported as a finding instead of aborting the whole
    /// validation.
    fn check_postings(&self, report: &mut ValidationReport) {
        let toc = self.index().toc();
        if toc.postings_table == 0 && toc.label_indices_table == 0 {
            report.findings.push(Finding::warning(
                "index has no postings offset table; label lookups are unavailable",
            ));
            return;
        }
        match self.index().validate_postings() {
            Ok(stats) => report.postings = Some(stats),
            Err(e) => report
                .findings
                .push(Finding::error(format!("postings section: {e}"))),
        }
    }

    /// Tombstone checks: refs must be addressable and intervals well formed.
    fn check_tombstones(&self, report: &mut ValidationReport) {
        let tombstones = self.tombstones();
        if tombstones.raw_count() == 0 {
            return;
        }

        // v2/v3 series references are `offset / 16`, so they always fit in 32
        // bits; v1 may in theory exceed that only for absurdly large indexes.
        let max_ref = if self.index().version() == 1 {
            u64::MAX
        } else {
            u32::MAX as u64
        };
        let mut bad_intervals = 0usize;
        for (reference, intervals) in tombstones.iter_raw() {
            if *reference > max_ref {
                report.findings.push(Finding::error(format!(
                    "tombstone series reference {reference} is not addressable in index v{}",
                    self.index().version()
                )));
            }
            for (mint, maxt) in intervals {
                if maxt < mint {
                    bad_intervals += 1;
                }
            }
        }
        if bad_intervals > 0 {
            report.findings.push(Finding::error(format!(
                "{bad_intervals} tombstone intervals have maxTime before minTime"
            )));
        }

        // Deletes are always inside the block's time range; intervals outside
        // it mean the file belongs to a different block.
        let (mint, maxt) = (self.meta().min_time, self.meta().max_time);
        for (reference, intervals) in tombstones.iter_raw() {
            for (a, b) in intervals {
                if *b < mint || *a >= maxt {
                    report.findings.push(Finding::warning(format!(
                        "tombstone interval {a}..{b} for series {reference} is outside the block range {mint}..{maxt}"
                    )));
                }
            }
        }
    }
}