tsdb_reader/
validation.rs1use std::fmt;
16
17use crate::block::BlockReader;
18use crate::chunks::validation::SegmentReport;
19use crate::index::{IndexStats, PostingsStats};
20use crate::meta::META_VERSION;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub enum Severity {
25 Warning,
27 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#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Finding {
43 pub severity: Severity,
45 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#[derive(Debug, Clone, Default)]
67pub struct ValidationReport {
68 pub block: String,
70 pub index_version: u8,
72 pub meta_version: i32,
74 pub series: u64,
76 pub chunks: u64,
78 pub segments: SegmentReport,
80 pub postings: Option<PostingsStats>,
82 pub findings: Vec<Finding>,
84}
85
86impl ValidationReport {
87 pub fn is_ok(&self) -> bool {
92 !self.findings.iter().any(|f| f.severity == Severity::Error)
93 }
94
95 pub fn findings_of(&self, severity: Severity) -> impl Iterator<Item = &Finding> {
97 self.findings.iter().filter(move |f| f.severity == severity)
98 }
99
100 pub fn error_count(&self) -> usize {
102 self.findings_of(Severity::Error).count()
103 }
104
105 pub fn warning_count(&self) -> usize {
107 self.findings_of(Severity::Warning).count()
108 }
109
110 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 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 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 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 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 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 fn check_tombstones(&self, report: &mut ValidationReport) {
287 let tombstones = self.tombstones();
288 if tombstones.raw_count() == 0 {
289 return;
290 }
291
292 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 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}