Skip to main content

tsdb_reader/chunks/
validation.rs

1//! Structural checks for chunk segments.
2//!
3//! `ChunkReader::open` already rejects a header that is not a chunk segment and
4//! a file list with gaps. These checks go further and verify that the records
5//! tile the segment exactly (no gaps, no overlaps, no trailing bytes) and that
6//! every reference the index hands out points at a decodable record.
7
8use crate::chunkenc;
9use crate::error::{Error, Result};
10
11use super::segment::{
12    check_header, record_bounds, RecordBounds, MAX_LEN_FIELD, SEGMENT_HEADER_SIZE,
13};
14use super::ChunkReader;
15
16/// Prepends context to a format error without nesting the `invalid format:`
17/// prefix twice.
18fn contextual(prefix: String, err: Error) -> Error {
19    match err {
20        Error::Format(msg) => Error::Format(format!("{prefix}: {msg}")),
21        other => other,
22    }
23}
24
25/// What a segment walk found.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct SegmentReport {
28    /// Number of segment files.
29    pub segments: usize,
30    /// Number of chunk records across all segments.
31    pub records: u64,
32    /// Total bytes of all segments.
33    pub bytes: u64,
34}
35
36impl ChunkReader {
37    /// Walks every record of every segment, validating the framing.
38    ///
39    /// This reads only headers: no chunk body is decoded and no CRC is
40    /// computed, so it stays cheap even for multi-gigabyte blocks. A segment
41    /// must be tiled exactly by its records; Prometheus never pads a segment,
42    /// so leftover bytes mean corruption or a mismatched file.
43    pub fn validate_segments(&self) -> Result<SegmentReport> {
44        let mut report = SegmentReport {
45            segments: self.segment_count(),
46            records: 0,
47            bytes: self.bytes(),
48        };
49        for seq in 0..self.segment_count() {
50            let seg = self.segment(seq).ok_or_else(|| {
51                Error::format(format!("chunk segment {seq} disappeared from the reader"))
52            })?;
53            check_header(seg, seq as u64)?;
54            let mut pos = SEGMENT_HEADER_SIZE;
55            while pos < seg.len() {
56                if seg.len() - pos < MAX_LEN_FIELD {
57                    return Err(Error::format(format!(
58                        "chunk segment {seq}: {} trailing bytes at {pos}",
59                        seg.len() - pos
60                    )));
61                }
62                let offset = u32::try_from(pos)
63                    .map_err(|_| Error::format(format!("segment {seq} is larger than 4 GiB")))?;
64                let bounds = record_bounds(seg, offset)
65                    .map_err(|e| contextual(format!("chunk segment {seq} at offset {pos}"), e))?;
66                let enc = seg[bounds.encoding];
67                if !chunkenc::is_known_encoding(enc) {
68                    return Err(Error::format(format!(
69                        "chunk segment {seq} at offset {pos}: unknown encoding {enc}"
70                    )));
71                }
72                report.records += 1;
73                pos = bounds.crc_end;
74            }
75            if pos != seg.len() {
76                return Err(Error::format(format!(
77                    "chunk segment {seq}: records end at {pos}, file has {} bytes",
78                    seg.len()
79                )));
80            }
81        }
82        Ok(report)
83    }
84
85    /// Checks that `reference` points at a framed record with a known encoding.
86    ///
87    /// Mirrors what [`ChunkReader::chunk`] enforces, minus the CRC and without
88    /// handing out a slice, so a whole index can be validated cheaply.
89    pub fn validate_reference(&self, reference: u64) -> Result<()> {
90        let segment = (reference >> 32) as u32;
91        let offset = reference as u32;
92        let seg = self.segment(segment as usize).ok_or_else(|| {
93            Error::format(format!(
94                "chunk reference {reference:#x}: segment {segment} out of range ({})",
95                self.segment_count()
96            ))
97        })?;
98        let bounds: RecordBounds = record_bounds(seg, offset)?;
99        let enc = seg[bounds.encoding];
100        if !chunkenc::is_known_encoding(enc) {
101            return Err(Error::format(format!(
102                "chunk reference {reference:#x}: unknown encoding {enc}"
103            )));
104        }
105        Ok(())
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::chunkenc::ENC_XOR;
113    use std::path::PathBuf;
114
115    fn segment_with(encoding: u8, data: &[u8]) -> Vec<u8> {
116        let mut body = Vec::new();
117        body.push(encoding);
118        body.extend_from_slice(data);
119
120        let mut seg = Vec::new();
121        seg.extend_from_slice(&0x85BD_40DDu32.to_be_bytes());
122        seg.push(1);
123        seg.extend_from_slice(&[0, 0, 0]);
124        let mut len = Vec::new();
125        let mut v = data.len() as u64;
126        loop {
127            let mut b = (v & 0x7f) as u8;
128            v >>= 7;
129            if v != 0 {
130                b |= 0x80;
131            }
132            len.push(b);
133            if v == 0 {
134                break;
135            }
136        }
137        seg.extend_from_slice(&len);
138        seg.extend_from_slice(&body);
139        seg.extend_from_slice(&crc32c::crc32c(&body).to_be_bytes());
140        seg
141    }
142
143    fn reader(files: &[Vec<u8>]) -> ChunkReader {
144        ChunkReader::from_segments(files.to_vec(), true).unwrap()
145    }
146
147    #[test]
148    fn a_clean_segment_tiles_exactly() {
149        let r = reader(&[segment_with(ENC_XOR, &[1, 2, 3])]);
150        let report = r.validate_segments().unwrap();
151        assert_eq!(report.segments, 1);
152        assert_eq!(report.records, 1);
153        assert!(report.bytes > 0);
154        r.validate_reference(SEGMENT_HEADER_SIZE as u64).unwrap();
155    }
156
157    #[test]
158    fn trailing_bytes_are_reported() {
159        let mut seg = segment_with(ENC_XOR, &[1, 2, 3]);
160        seg.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
161        let r = reader(&[seg]);
162        // Six zero bytes are too short for a length prefix, so the walk stops
163        // on them rather than silently accepting a padded segment.
164        let error = r.validate_segments().unwrap_err();
165        assert!(error.to_string().contains("chunk segment 0"), "{error}");
166    }
167
168    #[test]
169    fn unknown_encodings_are_reported() {
170        let r = reader(&[segment_with(99, &[1, 2, 3])]);
171        let error = r.validate_segments().unwrap_err();
172        assert!(error.to_string().contains("unknown encoding 99"), "{error}");
173        let error = r
174            .validate_reference(SEGMENT_HEADER_SIZE as u64)
175            .unwrap_err();
176        assert!(error.to_string().contains("unknown encoding"), "{error}");
177    }
178
179    #[test]
180    fn references_into_the_header_are_rejected() {
181        let r = reader(&[segment_with(ENC_XOR, &[1])]);
182        assert!(r.validate_reference(0).is_err());
183        assert!(r.validate_reference(1 << 32).is_err());
184    }
185
186    #[test]
187    fn the_vendored_block_walks_cleanly() {
188        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
189            .join("tests/data/block/01M70C8VV61N5H5VWXB17HQQ1R/chunks");
190        let r = ChunkReader::open(&dir, true, false).unwrap();
191        let report = r.validate_segments().unwrap();
192        assert_eq!(report.segments, 1);
193        assert!(report.records > 0);
194    }
195}