Skip to main content

tsdb_reader/
meta.rs

1//! Block discovery and `meta.json` parsing.
2
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6#[cfg(feature = "meta")]
7use std::path::Path;
8
9#[cfg(feature = "meta")]
10use crate::error::{Error, Result};
11
12/// The only `meta.json` format version Prometheus writes.
13///
14/// This is **not** the index format version: Prometheus hardcodes this field
15/// to 1 in `writeMetaFile` while the index header independently carries
16/// version 1, 2 or 3. Code that compares the two will report false positives,
17/// so [`crate::BlockReader::validate`] only warns when the field differs.
18pub const META_VERSION: i32 = 1;
19
20fn default_version() -> i32 {
21    META_VERSION
22}
23
24/// Sample, series and chunk counters copied from `meta.json`.
25///
26/// Prometheus writes these at block creation time, so they describe the block
27/// *before* tombstones are applied. Blocks written by older versions or by
28/// custom tooling may carry zeros; use [`crate::IndexReader::scan_stats`] when
29/// an exact count matters.
30#[derive(Debug, Clone, Default, Serialize, Deserialize)]
31pub struct BlockStats {
32    /// Total samples (float plus histogram).
33    #[serde(rename = "numSamples", default)]
34    pub num_samples: u64,
35    /// Float samples.
36    #[serde(rename = "numFloatSamples", default)]
37    pub num_float_samples: u64,
38    /// Native histogram samples.
39    #[serde(rename = "numHistogramSamples", default)]
40    pub num_histogram_samples: u64,
41    /// Series in the block.
42    #[serde(rename = "numSeries", default)]
43    pub num_series: u64,
44    /// Chunks in the block.
45    #[serde(rename = "numChunks", default)]
46    pub num_chunks: u64,
47    /// Number of tombstone intervals recorded at creation time.
48    #[serde(rename = "numTombstones", default)]
49    pub num_tombstones: u64,
50}
51
52/// Compaction lineage recorded in `meta.json`.
53///
54/// Useful to tell a freshly ingested block from a compacted one, and to know
55/// whether Prometheus considers a block deletable.
56#[derive(Debug, Clone, Default, Serialize, Deserialize)]
57pub struct BlockMetaCompaction {
58    /// Compaction level; `0` means a block straight from the head.
59    #[serde(default)]
60    pub level: i32,
61    /// Blocks this one was built from, as ULIDs.
62    #[serde(default)]
63    pub sources: Vec<String>,
64    /// Time ranges that were merged into this block.
65    #[serde(default)]
66    pub parents: Vec<ParentMeta>,
67    /// Prometheus marked the block as safe to delete.
68    #[serde(default)]
69    pub deletable: bool,
70    /// The last compaction attempt failed.
71    #[serde(default)]
72    pub failed: bool,
73    /// Free-form hints written by the compactor.
74    #[serde(default)]
75    pub hints: Vec<String>,
76}
77
78/// One time range that a compacted block was built from.
79#[derive(Debug, Clone, Default, Serialize, Deserialize)]
80pub struct ParentMeta {
81    /// ULID of the source block.
82    #[serde(default)]
83    pub ulid: String,
84    /// Inclusive lower bound in milliseconds since the Unix epoch.
85    #[serde(default)]
86    pub min_time: i64,
87    /// Exclusive upper bound in milliseconds since the Unix epoch.
88    #[serde(default)]
89    pub max_time: i64,
90}
91
92/// The decoded contents of a block's `meta.json`.
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct BlockMeta {
95    /// Block ULID. [`crate::BlockReader`] fills this from the directory name
96    /// when the field is missing.
97    #[serde(default)]
98    pub ulid: String,
99    /// Inclusive lower bound of the block in milliseconds since the Unix epoch.
100    #[serde(rename = "minTime", default)]
101    pub min_time: i64,
102    /// Exclusive upper bound of the block in milliseconds since the Unix epoch.
103    #[serde(rename = "maxTime", default)]
104    pub max_time: i64,
105    /// Counters captured when the block was written.
106    #[serde(default)]
107    pub stats: BlockStats,
108    /// Compaction lineage.
109    #[serde(default)]
110    pub compaction: BlockMetaCompaction,
111    /// `meta.json` format version, not the index version.
112    ///
113    /// Prometheus always writes 1 here; the index format version lives in the
114    /// index header and is exposed as [`crate::IndexReader::version`].
115    #[serde(default = "default_version")]
116    pub version: i32,
117}
118
119impl BlockMeta {
120    /// Samples present in the block *before* tombstones are applied.
121    pub fn samples_hint(&self) -> u64 {
122        if self.stats.num_samples > 0 {
123            self.stats.num_samples
124        } else {
125            self.stats.num_float_samples + self.stats.num_histogram_samples
126        }
127    }
128}
129
130/// A discovered block: where it lives, what it claims, and how big it is.
131#[derive(Debug, Clone)]
132pub struct BlockInfo {
133    /// Local block directory (for remote sources this is the download cache).
134    pub path: PathBuf,
135    /// Mimir tenant; empty for a plain local data directory.
136    pub tenant: String,
137    /// True when the block came from an object store and was materialised locally.
138    pub remote: bool,
139    /// Decoded `meta.json`, or a caller-supplied equivalent.
140    pub meta: BlockMeta,
141    /// Size of the `index` file in bytes.
142    pub index_bytes: u64,
143    /// Size of all `chunks/` segment files in bytes.
144    pub chunks_bytes: u64,
145    /// Size of the `tombstones` file in bytes, `0` when absent.
146    pub tombstones_bytes: u64,
147    /// Non-fatal observations, e.g. overlapping time ranges.
148    pub warnings: Vec<String>,
149}
150
151impl BlockInfo {
152    /// Block ULID.
153    pub fn ulid(&self) -> &str {
154        &self.meta.ulid
155    }
156
157    /// Stable internal key: `tenant/ulid` for Mimir, `ulid` for local blocks.
158    pub fn key(&self) -> String {
159        if self.tenant.is_empty() {
160            self.meta.ulid.clone()
161        } else {
162            format!("{}/{}", self.tenant, self.meta.ulid)
163        }
164    }
165
166    /// Tenant ID, or `None` for a plain local directory.
167    pub fn tenant_opt(&self) -> Option<&str> {
168        if self.tenant.is_empty() {
169            None
170        } else {
171            Some(&self.tenant)
172        }
173    }
174
175    /// Sum of the index, chunk and tombstone sizes.
176    pub fn size_bytes(&self) -> u64 {
177        self.index_bytes + self.chunks_bytes + self.tombstones_bytes
178    }
179}
180
181/// Parses a `meta.json` file.
182#[cfg(feature = "meta")]
183pub fn read_meta(path: &Path) -> Result<BlockMeta> {
184    let data = std::fs::read(path)?;
185    serde_json::from_slice(&data)
186        .map_err(|e| Error::format(format!("parse {}: {e}", path.display())))
187}
188
189#[cfg(feature = "meta")]
190fn dir_size(path: &Path) -> u64 {
191    let Ok(rd) = std::fs::read_dir(path) else {
192        return 0;
193    };
194    let mut total = 0;
195    for entry in rd.flatten() {
196        let p = entry.path();
197        match entry.metadata() {
198            Ok(md) if md.is_file() => total += md.len(),
199            Ok(md) if md.is_dir() => total += dir_size(&p),
200            _ => {}
201        }
202    }
203    total
204}
205
206#[cfg(feature = "meta")]
207fn looks_like_block(dir: &Path) -> bool {
208    dir.join("meta.json").is_file() && dir.join("index").is_file() && dir.join("chunks").is_dir()
209}
210
211/// Discovers blocks under `root`.
212///
213/// `root` may be a Prometheus data directory (containing ULID block dirs plus
214/// `wal/` and `chunks_head/`) or a single block directory.
215#[cfg(feature = "meta")]
216pub fn discover_blocks(root: &Path) -> Result<Vec<BlockInfo>> {
217    if !root.exists() {
218        return Err(Error::format(format!(
219            "data directory does not exist: {}",
220            root.display()
221        )));
222    }
223
224    let mut dirs = Vec::new();
225    if looks_like_block(root) {
226        dirs.push(root.to_path_buf());
227    } else {
228        let rd = std::fs::read_dir(root)?;
229        for entry in rd.flatten() {
230            let p = entry.path();
231            if p.is_dir() && looks_like_block(&p) {
232                dirs.push(p);
233            }
234        }
235    }
236
237    let mut blocks = Vec::with_capacity(dirs.len());
238    for dir in dirs {
239        let meta = read_meta(&dir.join("meta.json"))?;
240        let index_bytes = std::fs::metadata(dir.join("index"))
241            .map(|m| m.len())
242            .unwrap_or(0);
243        let chunks_bytes = dir_size(&dir.join("chunks"));
244        let tombstones_bytes = std::fs::metadata(dir.join("tombstones"))
245            .map(|m| m.len())
246            .unwrap_or(0);
247        let mut warnings = Vec::new();
248        if meta.stats.num_series == 0 && meta.stats.num_samples == 0 {
249            warnings.push(
250                "meta.json has no stats; series/chunk totals require an index prepass".into(),
251            );
252        }
253        if meta.version > 3 {
254            warnings.push(format!("unknown index version {}", meta.version));
255        }
256        blocks.push(BlockInfo {
257            path: dir,
258            tenant: String::new(),
259            remote: false,
260            meta,
261            index_bytes,
262            chunks_bytes,
263            tombstones_bytes,
264            warnings,
265        });
266    }
267
268    blocks.sort_by(|a, b| {
269        a.meta
270            .min_time
271            .cmp(&b.meta.min_time)
272            .then_with(|| a.meta.ulid.cmp(&b.meta.ulid))
273    });
274
275    // Prometheus allows overlapping blocks after a crash; surface it instead of
276    // silently exporting duplicate samples.
277    for i in 1..blocks.len() {
278        let (prev_max, cur_min) = (blocks[i - 1].meta.max_time, blocks[i].meta.min_time);
279        if prev_max > cur_min {
280            let msg = format!(
281                "overlaps with block {} (prev maxTime {} > minTime {})",
282                blocks[i - 1].meta.ulid,
283                prev_max,
284                cur_min
285            );
286            blocks[i].warnings.push(msg.clone());
287            let msg2 = format!(
288                "overlaps with block {} (maxTime {} > next minTime {})",
289                blocks[i].meta.ulid, prev_max, cur_min
290            );
291            blocks[i - 1].warnings.push(msg2);
292        }
293    }
294
295    Ok(blocks)
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn stats_hint_falls_back_to_parts() {
304        let m = BlockMeta {
305            ulid: "x".into(),
306            min_time: 0,
307            max_time: 1,
308            stats: BlockStats {
309                num_float_samples: 3,
310                num_histogram_samples: 4,
311                ..Default::default()
312            },
313            compaction: Default::default(),
314            version: 2,
315        };
316        assert_eq!(m.samples_hint(), 7);
317    }
318}