Skip to main content

itzma_core/
inspect.rs

1//! A read-only look at one namespace: what is stored and what looks wrong.
2//!
3//! [`report`] loads the manifest and `schema.json` and lists `wal/` and
4//! `segments/`. It never writes, and unlike [`Namespace::open`] it does not
5//! heal a missing schema object, so it is safe to point at a namespace someone
6//! else is running, or at one that is damaged. Nothing it finds is repaired:
7//! a problem is a line in [`Report::problems`].
8//!
9//! The listings come after the manifest, as in [`gc`], so a segment
10//! or a WAL object written in between is past the fold point and never looks
11//! like damage. A namespace that is being written to can still show a passing
12//! problem, such as a gap while a compaction's segment is half listed. Run it
13//! again before believing it.
14//!
15//! It reads no object bodies apart from the manifest and the schema, so its
16//! cost is two listings and two small GETs however large the namespace is. That
17//! also means it cannot tell a WAL object's format version, or a segment's
18//! document count, or whether an index object decodes: it shows which index the
19//! manifest names for each segment and whether that object is there, and a
20//! query is what finds a damaged one. A WAL object of exactly 8 bytes is a
21//! fence, since every real object is longer.
22//!
23//! [`Namespace::open`]: crate::Namespace::open
24
25use std::collections::{BTreeMap, HashSet};
26use std::fmt;
27
28use futures::TryStreamExt;
29use object_store::path::Path;
30use object_store::{ObjectMeta, ObjectStore};
31
32use crate::document::Schema;
33use crate::error::{ItzmaError, Result};
34use crate::gc::{self, Found};
35use crate::manifest::{self, IndexEntry, Manifest, SparseIndexEntry};
36use crate::namespace::validate_id;
37use crate::{schema_object, segment, wal_codec};
38
39/// What [`report`] found in one namespace.
40#[derive(Debug, Clone, PartialEq)]
41pub struct Report {
42    /// The namespace id that was inspected.
43    pub namespace: String,
44    /// The schema in `schema.json`, or `None` if the object is missing or
45    /// unreadable (the second is also a problem).
46    pub schema: Option<Schema>,
47    /// The manifest, or `None` if it is missing or unreadable (also a problem).
48    pub manifest: Option<Manifest>,
49    /// The WAL objects listed under `wal/`.
50    pub wal: WalReport,
51    /// Every segment directory listed under `segments/`, oldest range first.
52    pub segments: Vec<SegmentReport>,
53    /// What looks wrong, one sentence each. Empty means nothing did.
54    pub problems: Vec<String>,
55}
56
57/// A summary of the WAL objects in a namespace.
58#[derive(Debug, Clone, PartialEq, Eq, Default)]
59pub struct WalReport {
60    /// How many WAL objects there are, fences included.
61    pub objects: usize,
62    /// The lowest seq listed.
63    pub first: Option<u64>,
64    /// The highest seq listed.
65    pub last: Option<u64>,
66    /// Total stored size of the objects.
67    pub bytes: u64,
68    /// How many are fences (8 bytes), left by garbage collection.
69    pub fenced: usize,
70    /// How many are past the manifest's fold point, so a query still reads
71    /// them. Without a manifest, all of them.
72    pub tail: usize,
73    /// Runs of missing seqs as inclusive `(from, to)` pairs, from 1 up to the
74    /// higher of the last seq listed and the fold point.
75    pub gaps: Vec<(u64, u64)>,
76}
77
78/// One directory under `segments/`.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SegmentReport {
81    /// The segment id, `<lo>-<hi>` (see [`segment`]).
82    pub id: String,
83    /// First WAL seq the segment covers.
84    pub lo: u64,
85    /// Last WAL seq the segment covers.
86    pub hi: u64,
87    /// Total stored size of the objects in the directory.
88    pub bytes: u64,
89    /// Whether the manifest lists it, and if not, whether [`Namespace::gc`]
90    /// would take it.
91    ///
92    /// [`Namespace::gc`]: crate::Namespace::gc
93    pub state: SegmentState,
94    /// The index the manifest names for this segment, if it names one.
95    pub index: Option<IndexInfo>,
96    /// Generations of index objects in the directory that the manifest does
97    /// not name, oldest first. [`Namespace::gc`](crate::Namespace::gc) deletes
98    /// them of a live segment once they are old enough.
99    pub stray_indexes: Vec<u32>,
100    /// Whether the directory has a `sparse.bin`, so some document in the
101    /// segment carries a sparse vector.
102    pub has_sparse_data: bool,
103    /// The sparse index the manifest names for this segment, if it names one.
104    pub sparse_index: Option<SparseIndexInfo>,
105    /// Generations of sparse index objects in the directory that the manifest
106    /// does not name, oldest first. [`Namespace::gc`](crate::Namespace::gc)
107    /// deletes them of a live segment once they are old enough.
108    pub stray_sparse_indexes: Vec<u32>,
109}
110
111/// An index the manifest names, and whether its object is there.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct IndexInfo {
114    /// The generation, as `index-<generation>.bin`.
115    pub generation: u32,
116    /// The algorithm's name in the manifest, such as `sq8`.
117    pub kind: String,
118    /// The object's stored size, or `None` if it is not in the directory (also
119    /// a problem).
120    pub bytes: Option<u64>,
121}
122
123/// A sparse index the manifest names, and whether its object is there.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct SparseIndexInfo {
126    /// The generation, as `sparse-idx-<generation>.bin`.
127    pub generation: u32,
128    /// The object's stored size, or `None` if it is not in the directory (also
129    /// a problem).
130    pub bytes: Option<u64>,
131}
132
133/// How a segment on disk stands against the manifest.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum SegmentState {
136    /// The manifest lists it.
137    Live,
138    /// Not live, and superseded: garbage collection deletes it once it is old
139    /// enough. The rule is the one [`Namespace::gc`](crate::Namespace::gc)
140    /// uses.
141    Dead,
142    /// Not live and not superseded. A compaction that has not published yet
143    /// looks like this, and so does one that stopped before it did. It is also
144    /// what GC leaves alone at `1-<folded>`.
145    Orphan,
146}
147
148impl fmt::Display for SegmentState {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.pad(match self {
151            Self::Live => "live",
152            Self::Dead => "dead",
153            Self::Orphan => "orphan",
154        })
155    }
156}
157
158/// Inspect the namespace `namespace` in `store`. See the module docs.
159///
160/// A manifest or schema object that is missing or cannot be decoded is
161/// reported in [`Report::problems`], not returned as an error, so the rest of
162/// the namespace still shows.
163///
164/// # Errors
165///
166/// - [`ItzmaError::InvalidNamespaceId`] for a malformed id.
167/// - [`ItzmaError::Storage`] if the store fails.
168///
169/// # Examples
170///
171/// ```
172/// # #[tokio::main]
173/// # async fn main() -> itzma_core::Result<()> {
174/// use std::sync::Arc;
175///
176/// use itzma_core::{Metric, Namespace, Schema};
177/// use object_store::memory::InMemory;
178///
179/// let store = Arc::new(InMemory::new());
180/// Namespace::create(store.clone(), "docs", Schema::new(2, Metric::L2)).await?;
181///
182/// let report = itzma_core::inspect::report(&*store, "docs").await?;
183/// assert!(report.problems.is_empty());
184/// assert_eq!(report.wal.objects, 0);
185/// # Ok(())
186/// # }
187/// ```
188pub async fn report(store: &dyn ObjectStore, namespace: &str) -> Result<Report> {
189    validate_id(namespace)?;
190    let mut problems = Vec::new();
191
192    let manifest = match manifest::load(store, namespace).await {
193        Ok((manifest, _)) => Some(manifest),
194        Err(e) => {
195            problems.push(unreadable("manifest", e)?);
196            None
197        }
198    };
199    let schema = match schema_object::read(store, namespace).await {
200        Ok(schema) => schema,
201        Err(e) => {
202            problems.push(unreadable("schema.json", e)?);
203            None
204        }
205    };
206    if let (Some(manifest), Some(schema)) = (&manifest, &schema) {
207        if &manifest.schema != schema {
208            problems.push(format!(
209                "schema.json holds {schema:?} but the manifest holds {:?}",
210                manifest.schema
211            ));
212        }
213    }
214
215    let prefix = Path::from(format!("{namespace}/segments"));
216    let listing: Vec<ObjectMeta> = store.list(Some(&prefix)).try_collect().await?;
217    let found = gc::group(&prefix, listing);
218    let wal_objects = gc::list_wal(store, namespace).await?;
219
220    let folded = manifest.as_ref().map_or(0, |m| m.wal_folded_through);
221    let wal = summarize_wal(
222        wal_objects.iter().map(|o| (o.seq, o.size)).collect(),
223        folded,
224    );
225    for &(from, to) in &wal.gaps {
226        problems.push(if from == to {
227            format!("WAL seq {from} is missing")
228        } else {
229            format!("WAL seqs {from} through {to} are missing")
230        });
231    }
232
233    let mut segments = Vec::new();
234    if let Some(manifest) = &manifest {
235        if let Err(e) = segment::validate_chain(&manifest.live_segments, folded) {
236            problems.push(e.to_string());
237        }
238        for id in &manifest.live_segments {
239            let data = segment::segment_path(namespace, id);
240            let there = found
241                .get(id)
242                .is_some_and(|f| f.objects.iter().any(|(path, _)| *path == data));
243            if !there {
244                problems.push(format!("live segment {id} has no data object"));
245            }
246        }
247        let live: HashSet<&str> = manifest.live_segments.iter().map(String::as_str).collect();
248        segments = found
249            .iter()
250            .map(|(id, f)| {
251                segment_report(
252                    id,
253                    f,
254                    folded,
255                    &live,
256                    &manifest.indexes,
257                    &manifest.sparse_indexes,
258                )
259            })
260            .collect();
261        for report in &segments {
262            if let Some(index) = &report.index {
263                if index.bytes.is_none() {
264                    problems.push(format!(
265                        "segment {} is listed with index generation {} but has no such index object",
266                        report.id, index.generation
267                    ));
268                }
269            }
270            if let Some(index) = &report.sparse_index {
271                if index.bytes.is_none() {
272                    problems.push(format!(
273                        "segment {} is listed with sparse index generation {} but has no such object",
274                        report.id, index.generation
275                    ));
276                }
277            }
278        }
279        for id in manifest.indexes.keys() {
280            if !live.contains(id.as_str()) {
281                problems.push(format!(
282                    "the manifest lists an index for {id}, which is not a live segment"
283                ));
284            }
285        }
286        for id in manifest.sparse_indexes.keys() {
287            if !live.contains(id.as_str()) {
288                problems.push(format!(
289                    "the manifest lists a sparse index for {id}, which is not a live segment"
290                ));
291            }
292        }
293    } else {
294        segments.extend(found.iter().map(|(id, f)| {
295            segment_report(
296                id,
297                f,
298                0,
299                &HashSet::new(),
300                &BTreeMap::new(),
301                &BTreeMap::new(),
302            )
303        }));
304    }
305
306    Ok(Report {
307        namespace: namespace.to_string(),
308        schema,
309        manifest,
310        wal,
311        segments,
312        problems,
313    })
314}
315
316/// A missing or undecodable object becomes a problem line. A failure of the
317/// store itself is not something to describe, so it is returned.
318fn unreadable(what: &str, err: ItzmaError) -> Result<String> {
319    match err {
320        ItzmaError::NamespaceNotFound(_) => Ok(format!("{what} is missing")),
321        ItzmaError::Serde { .. }
322        | ItzmaError::UnsupportedFormat { .. }
323        | ItzmaError::WalFormatTooNew { .. }
324        | ItzmaError::SegmentFormatTooNew { .. } => Ok(format!("{what} cannot be read: {err}")),
325        other => Err(other),
326    }
327}
328
329fn segment_report(
330    id: &str,
331    found: &Found,
332    folded: u64,
333    live: &HashSet<&str>,
334    indexes: &BTreeMap<String, IndexEntry>,
335    sparse_indexes: &BTreeMap<String, SparseIndexEntry>,
336) -> SegmentReport {
337    let state = if live.contains(id) {
338        SegmentState::Live
339    } else if gc::is_dead(folded, live, id, found) {
340        SegmentState::Dead
341    } else {
342        SegmentState::Orphan
343    };
344    let named = indexes.get(id).filter(|_| state == SegmentState::Live);
345    let index = named.map(|entry| IndexInfo {
346        generation: entry.generation,
347        kind: entry.kind.clone(),
348        bytes: found
349            .indexes
350            .iter()
351            .find(|object| object.generation == entry.generation)
352            .map(|object| object.size),
353    });
354    let mut stray_indexes: Vec<u32> = found
355        .indexes
356        .iter()
357        .map(|object| object.generation)
358        .filter(|generation| Some(*generation) != named.map(|entry| entry.generation))
359        .collect();
360    stray_indexes.sort_unstable();
361    let named_sparse = sparse_indexes
362        .get(id)
363        .filter(|_| state == SegmentState::Live);
364    let sparse_index = named_sparse.map(|entry| SparseIndexInfo {
365        generation: entry.generation,
366        bytes: found
367            .sparse_indexes
368            .iter()
369            .find(|object| object.generation == entry.generation)
370            .map(|object| object.size),
371    });
372    let mut stray_sparse_indexes: Vec<u32> = found
373        .sparse_indexes
374        .iter()
375        .map(|object| object.generation)
376        .filter(|generation| Some(*generation) != named_sparse.map(|entry| entry.generation))
377        .collect();
378    stray_sparse_indexes.sort_unstable();
379    let has_sparse_data = found
380        .objects
381        .iter()
382        .any(|(path, _)| path.filename() == Some("sparse.bin"));
383    SegmentReport {
384        id: id.to_string(),
385        lo: found.lo,
386        hi: found.hi,
387        bytes: found.objects.iter().map(|(_, size)| size).sum(),
388        state,
389        index,
390        stray_indexes,
391        has_sparse_data,
392        sparse_index,
393        stray_sparse_indexes,
394    }
395}
396
397/// Summarize `(seq, size)` pairs against the fold point. Pure: no storage.
398fn summarize_wal(mut objects: Vec<(u64, u64)>, folded: u64) -> WalReport {
399    objects.sort_unstable();
400    let mut gaps = Vec::new();
401    let mut prev = 0u64;
402    for &(seq, _) in &objects {
403        if seq > prev.saturating_add(1) {
404            gaps.push((prev + 1, seq - 1));
405        }
406        prev = prev.max(seq);
407    }
408    if folded > prev {
409        gaps.push((prev + 1, folded));
410    }
411    WalReport {
412        objects: objects.len(),
413        first: objects.first().map(|&(seq, _)| seq),
414        last: objects.last().map(|&(seq, _)| seq),
415        bytes: objects.iter().map(|&(_, size)| size).sum(),
416        fenced: objects
417            .iter()
418            .filter(|&&(_, size)| size == wal_codec::FENCE_LEN as u64)
419            .count(),
420        tail: objects.iter().filter(|&&(seq, _)| seq > folded).count(),
421        gaps,
422    }
423}
424
425impl fmt::Display for Report {
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        writeln!(f, "namespace {}", self.namespace)?;
428        match &self.schema {
429            Some(schema) => writeln!(f, "schema.json  dim {}, {:?}", schema.dim, schema.metric)?,
430            None => writeln!(f, "schema.json  none")?,
431        }
432        match &self.manifest {
433            Some(m) => writeln!(
434                f,
435                "manifest     wal_format {}, segment_format {}, folded through {}, {} live segments",
436                m.wal_format,
437                m.segment_format,
438                m.wal_folded_through,
439                m.live_segments.len()
440            )?,
441            None => writeln!(f, "manifest     none")?,
442        }
443        let wal = &self.wal;
444        write!(f, "wal          {} objects", wal.objects)?;
445        if let (Some(first), Some(last)) = (wal.first, wal.last) {
446            write!(f, ", seq {first} through {last}")?;
447        }
448        writeln!(
449            f,
450            ", {} bytes, {} fenced, {} in the tail",
451            wal.bytes, wal.fenced, wal.tail
452        )?;
453        writeln!(f, "segments     {} on disk", self.segments.len())?;
454        for s in &self.segments {
455            write!(f, "  {}  {:<6}  {} bytes", s.id, s.state, s.bytes)?;
456            if let Some(index) = &s.index {
457                match index.bytes {
458                    Some(bytes) => {
459                        write!(
460                            f,
461                            "  index {} {} {bytes} bytes",
462                            index.generation, index.kind
463                        )?;
464                    }
465                    None => write!(f, "  index {} {} missing", index.generation, index.kind)?,
466                }
467            }
468            if !s.stray_indexes.is_empty() {
469                write!(f, "  unnamed indexes {:?}", s.stray_indexes)?;
470            }
471            if s.has_sparse_data {
472                write!(f, "  sparse")?;
473            }
474            if let Some(index) = &s.sparse_index {
475                match index.bytes {
476                    Some(bytes) => write!(f, "  sparse index {} {bytes} bytes", index.generation)?,
477                    None => write!(f, "  sparse index {} missing", index.generation)?,
478                }
479            }
480            if !s.stray_sparse_indexes.is_empty() {
481                write!(f, "  unnamed sparse indexes {:?}", s.stray_sparse_indexes)?;
482            }
483            writeln!(f)?;
484        }
485        if self.problems.is_empty() {
486            writeln!(f, "problems     none")
487        } else {
488            writeln!(f, "problems     {}", self.problems.len())?;
489            for problem in &self.problems {
490                writeln!(f, "  {problem}")?;
491            }
492            Ok(())
493        }
494    }
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    fn seqs(list: &[(u64, u64)], folded: u64) -> WalReport {
502        summarize_wal(list.to_vec(), folded)
503    }
504
505    #[test]
506    fn an_empty_wal_has_no_gaps() {
507        assert_eq!(seqs(&[], 0), WalReport::default());
508    }
509
510    #[test]
511    fn a_contiguous_run_has_no_gaps() {
512        let r = seqs(&[(1, 100), (2, 50), (3, 8)], 2);
513        assert_eq!(r.objects, 3);
514        assert_eq!((r.first, r.last), (Some(1), Some(3)));
515        assert_eq!(r.bytes, 158);
516        assert_eq!(r.fenced, 1);
517        assert_eq!(r.tail, 1);
518        assert!(r.gaps.is_empty());
519    }
520
521    #[test]
522    fn the_input_order_does_not_matter() {
523        let r = seqs(&[(3, 20), (1, 20), (2, 20)], 0);
524        assert!(r.gaps.is_empty());
525        assert_eq!((r.first, r.last), (Some(1), Some(3)));
526    }
527
528    #[test]
529    fn a_missing_start_and_a_missing_middle_are_gaps() {
530        let r = seqs(&[(3, 20), (4, 20), (8, 20)], 0);
531        assert_eq!(r.gaps, vec![(1, 2), (5, 7)]);
532    }
533
534    #[test]
535    fn a_fold_point_past_the_last_object_is_a_gap() {
536        let r = seqs(&[(1, 20), (2, 20)], 5);
537        assert_eq!(r.gaps, vec![(3, 5)]);
538        assert_eq!(r.tail, 0);
539    }
540
541    #[test]
542    fn a_fold_point_at_the_last_object_is_not() {
543        assert!(seqs(&[(1, 20), (2, 20)], 2).gaps.is_empty());
544    }
545
546    #[test]
547    fn a_seq_listed_twice_is_not_a_gap() {
548        let r = seqs(&[(1, 20), (1, 20), (2, 20)], 0);
549        assert!(r.gaps.is_empty());
550    }
551}