Skip to main content

tsdb_reader/
validation.rs

1//! Block-level consistency checks.
2//!
3//! Opening a block validates each file on its own. This module cross-checks
4//! them: the metadata Prometheus wrote against the index that is actually on
5//! disk, every chunk reference against the segment it points into, and the
6//! tombstones against the index series space.
7//!
8//! [`BlockReader::validate`] scans the index series section without resolving
9//! symbols and frames every referenced chunk record, but never decodes a
10//! sample. That is cheap enough for an export that wants to fail fast on a
11//! corrupt block; sample-level damage still surfaces when a chunk is decoded,
12//! and [`crate::SampleIterator`] reports it with the series and chunk that
13//! produced it.
14
15use std::fmt;
16
17use crate::block::BlockReader;
18use crate::chunks::validation::SegmentReport;
19use crate::index::{IndexStats, PostingsStats};
20use crate::meta::META_VERSION;
21
22/// How serious a [`Finding`] is.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub enum Severity {
25    /// The block is readable but something looks off; worth logging.
26    Warning,
27    /// The block cannot be trusted; the reader should skip it.
28    Error,
29}
30
31impl fmt::Display for Severity {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        match self {
34            Severity::Warning => f.write_str("warning"),
35            Severity::Error => f.write_str("error"),
36        }
37    }
38}
39
40/// One discrepancy found while validating a block.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Finding {
43    /// How serious the problem is.
44    pub severity: Severity,
45    /// Human-readable description, including the offsets involved.
46    pub message: String,
47}
48
49impl Finding {
50    fn warning(message: impl Into<String>) -> Self {
51        Self {
52            severity: Severity::Warning,
53            message: message.into(),
54        }
55    }
56
57    fn error(message: impl Into<String>) -> Self {
58        Self {
59            severity: Severity::Error,
60            message: message.into(),
61        }
62    }
63}
64
65/// Everything validation learned about a block.
66#[derive(Debug, Clone, Default)]
67pub struct ValidationReport {
68    /// Block ULID.
69    pub block: String,
70    /// Index format version read from the index header.
71    pub index_version: u8,
72    /// Version field of `meta.json` (the *meta* format, not the index format).
73    pub meta_version: i32,
74    /// Series count from scanning the index.
75    pub series: u64,
76    /// Chunk count from scanning the index.
77    pub chunks: u64,
78    /// Segment summary from walking the chunk files.
79    pub segments: SegmentReport,
80    /// Postings section summary, when it could be read.
81    pub postings: Option<PostingsStats>,
82    /// Everything that did not line up.
83    pub findings: Vec<Finding>,
84}
85
86impl ValidationReport {
87    /// True when no [`Severity::Error`] was recorded.
88    ///
89    /// Warnings do not make a block unusable, but see
90    /// [`Self::into_result`] for a strict interpretation.
91    pub fn is_ok(&self) -> bool {
92        !self.findings.iter().any(|f| f.severity == Severity::Error)
93    }
94
95    /// Iterates the findings of a given severity.
96    pub fn findings_of(&self, severity: Severity) -> impl Iterator<Item = &Finding> {
97        self.findings.iter().filter(move |f| f.severity == severity)
98    }
99
100    /// Number of recorded errors.
101    pub fn error_count(&self) -> usize {
102        self.findings_of(Severity::Error).count()
103    }
104
105    /// Number of recorded warnings.
106    pub fn warning_count(&self) -> usize {
107        self.findings_of(Severity::Warning).count()
108    }
109
110    /// Fails when anything at all was reported.
111    ///
112    /// Use this when a single unexpected field means the block must not be
113    /// exported, e.g. before a migration run that has to be restartable.
114    pub fn into_result(self) -> crate::error::Result<Self> {
115        if self.findings.is_empty() {
116            return Ok(self);
117        }
118        let details: Vec<String> = self
119            .findings
120            .iter()
121            .map(|f| format!("{}: {}", f.severity, f.message))
122            .collect();
123        Err(crate::error::Error::Corrupt(format!(
124            "block {}: {}",
125            self.block,
126            details.join("; ")
127        )))
128    }
129}
130
131impl BlockReader {
132    /// Cross-checks metadata, index, chunk segments and tombstones.
133    ///
134    /// Errors mean the block is corrupt (or written by something incompatible);
135    /// warnings point at suspicious but readable data. Nothing here decodes
136    /// samples, so a block that passes can still contain a bad chunk payload —
137    /// [`crate::chunkenc::decode`] reports that when the chunk is read.
138    pub fn validate(&self) -> crate::error::Result<ValidationReport> {
139        let mut report = ValidationReport {
140            block: self.block_id().to_string(),
141            index_version: self.index().version(),
142            meta_version: self.meta().version,
143            ..Default::default()
144        };
145
146        let layout = self.index().validate_layout()?;
147        let stats = self.index().scan_stats()?;
148        report.series = stats.series;
149        report.chunks = stats.chunks;
150        report.segments = self.chunk_reader().validate_segments()?;
151
152        self.check_meta(&mut report, &stats);
153        self.check_series(&mut report);
154        self.check_postings(&mut report);
155        self.check_tombstones(&mut report);
156
157        // An empty index section is legal only for a block without series.
158        if stats.series == 0 && layout.series_end > layout.series_start + 1 {
159            report.findings.push(Finding::warning(format!(
160                "index series section spans {}..{} but contains no series",
161                layout.series_start, layout.series_end
162            )));
163        }
164
165        Ok(report)
166    }
167
168    /// Metadata-only checks: version, time range and the writer's counters.
169    fn check_meta(&self, report: &mut ValidationReport, stats: &IndexStats) {
170        let meta = self.meta();
171
172        if meta.version != META_VERSION {
173            report.findings.push(Finding::warning(format!(
174                "meta.json version is {}, expected {META_VERSION}; \
175                 this field is the meta format version, not the index version",
176                meta.version
177            )));
178        }
179        if meta.max_time <= meta.min_time {
180            report.findings.push(Finding::warning(format!(
181                "block time range is empty: minTime {} >= maxTime {}",
182                meta.min_time, meta.max_time
183            )));
184        }
185        if stats.series == 0 && meta.stats.num_series > 0 {
186            report.findings.push(Finding::error(format!(
187                "meta.json reports {} series but the index has none",
188                meta.stats.num_series
189            )));
190        }
191        if stats.series > 0 && meta.stats.num_series != stats.series {
192            report.findings.push(Finding::error(format!(
193                "meta.json reports {} series, index has {}",
194                meta.stats.num_series, stats.series
195            )));
196        }
197        if stats.series > 0 && meta.stats.num_chunks != stats.chunks {
198            report.findings.push(Finding::error(format!(
199                "meta.json reports {} chunks, index has {}",
200                meta.stats.num_chunks, stats.chunks
201            )));
202        }
203        let samples = meta.stats.num_float_samples + meta.stats.num_histogram_samples;
204        if meta.stats.num_samples != 0 && samples != 0 && meta.stats.num_samples != samples {
205            report.findings.push(Finding::warning(format!(
206                "meta.json numSamples {} does not equal numFloatSamples + numHistogramSamples ({})",
207                meta.stats.num_samples, samples
208            )));
209        }
210    }
211
212    /// Series-level checks: chunk references and time ranges.
213    fn check_series(&self, report: &mut ValidationReport) {
214        let meta = self.meta();
215        let mut max_segment = 0u32;
216        let mut outside_range = 0u64;
217        let mut bad_refs = 0u64;
218        let mut first_bad: Option<String> = None;
219
220        for series in self.series(0) {
221            let series = match series {
222                Ok(s) => s,
223                Err(e) => {
224                    report
225                        .findings
226                        .push(Finding::error(format!("series section is unreadable: {e}")));
227                    return;
228                }
229            };
230            for chunk in &series.chunks {
231                max_segment = max_segment.max(chunk.segment());
232                if chunk.min_time < meta.min_time || chunk.max_time >= meta.max_time {
233                    outside_range += 1;
234                }
235                if let Err(e) = self.chunk_reader().validate_reference(chunk.reference) {
236                    bad_refs += 1;
237                    if first_bad.is_none() {
238                        first_bad = Some(format!("{e}"));
239                    }
240                }
241            }
242        }
243
244        if bad_refs > 0 {
245            report.findings.push(Finding::error(format!(
246                "{bad_refs} chunk references do not resolve ({})",
247                first_bad.unwrap_or_default()
248            )));
249        }
250        if outside_range > 0 {
251            report.findings.push(Finding::warning(format!(
252                "{outside_range} chunks fall outside the block time range {}..{}",
253                meta.min_time, meta.max_time
254            )));
255        }
256        if self.chunk_reader().segment_count() as u32 != max_segment.saturating_add(1) {
257            report.findings.push(Finding::warning(format!(
258                "index references segments up to {max_segment} but the block has {}",
259                self.chunk_reader().segment_count()
260            )));
261        }
262    }
263
264    /// Postings checks: the offset table and every list must decode.
265    ///
266    /// A block whose label space is broken is still readable sequentially, so a
267    /// failure here is reported as a finding instead of aborting the whole
268    /// validation.
269    fn check_postings(&self, report: &mut ValidationReport) {
270        let toc = self.index().toc();
271        if toc.postings_table == 0 && toc.label_indices_table == 0 {
272            report.findings.push(Finding::warning(
273                "index has no postings offset table; label lookups are unavailable",
274            ));
275            return;
276        }
277        match self.index().validate_postings() {
278            Ok(stats) => report.postings = Some(stats),
279            Err(e) => report
280                .findings
281                .push(Finding::error(format!("postings section: {e}"))),
282        }
283    }
284
285    /// Tombstone checks: refs must be addressable and intervals well formed.
286    fn check_tombstones(&self, report: &mut ValidationReport) {
287        let tombstones = self.tombstones();
288        if tombstones.raw_count() == 0 {
289            return;
290        }
291
292        // v2/v3 series references are `offset / 16`, so they always fit in 32
293        // bits; v1 may in theory exceed that only for absurdly large indexes.
294        let max_ref = if self.index().version() == 1 {
295            u64::MAX
296        } else {
297            u32::MAX as u64
298        };
299        let mut bad_intervals = 0usize;
300        for (reference, intervals) in tombstones.iter_raw() {
301            if *reference > max_ref {
302                report.findings.push(Finding::error(format!(
303                    "tombstone series reference {reference} is not addressable in index v{}",
304                    self.index().version()
305                )));
306            }
307            for (mint, maxt) in intervals {
308                if maxt < mint {
309                    bad_intervals += 1;
310                }
311            }
312        }
313        if bad_intervals > 0 {
314            report.findings.push(Finding::error(format!(
315                "{bad_intervals} tombstone intervals have maxTime before minTime"
316            )));
317        }
318
319        // Deletes are always inside the block's time range; intervals outside
320        // it mean the file belongs to a different block.
321        let (mint, maxt) = (self.meta().min_time, self.meta().max_time);
322        for (reference, intervals) in tombstones.iter_raw() {
323            for (a, b) in intervals {
324                if *b < mint || *a >= maxt {
325                    report.findings.push(Finding::warning(format!(
326                        "tombstone interval {a}..{b} for series {reference} is outside the block range {mint}..{maxt}"
327                    )));
328                }
329            }
330        }
331    }
332}