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, AttrIndexEntry, 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    /// The attribute index the manifest names for this segment, if it names
110    /// one.
111    pub attr_index: Option<AttrIndexInfo>,
112    /// Generations of attribute index objects in the directory that the
113    /// manifest does not name, oldest first.
114    /// [`Namespace::gc`](crate::Namespace::gc) deletes them of a live segment
115    /// once they are old enough.
116    pub stray_attr_indexes: Vec<u32>,
117    /// Staging objects (`staging-<nonce>.bin`) in the directory: what a
118    /// streamed write left when it stopped before deleting one.
119    /// Not a problem; [`Namespace::gc`](crate::Namespace::gc) deletes them
120    /// once they are old enough.
121    pub staging_objects: usize,
122}
123
124/// An index the manifest names, and whether its object is there.
125#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct IndexInfo {
127    /// The generation, as `index-<generation>.bin`.
128    pub generation: u32,
129    /// The algorithm's name in the manifest, such as `sq8`.
130    pub kind: String,
131    /// The object's stored size, or `None` if it is not in the directory (also
132    /// a problem).
133    pub bytes: Option<u64>,
134}
135
136/// A sparse index the manifest names, and whether its object is there.
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct SparseIndexInfo {
139    /// The generation, as `sparse-idx-<generation>.bin`.
140    pub generation: u32,
141    /// The object's stored size, or `None` if it is not in the directory (also
142    /// a problem).
143    pub bytes: Option<u64>,
144}
145
146/// An attribute index the manifest names, and whether its object is there.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct AttrIndexInfo {
149    /// The generation, as `attr-idx-<generation>.bin`.
150    pub generation: u32,
151    /// The object's stored size, or `None` if it is not in the directory (also
152    /// a problem).
153    pub bytes: Option<u64>,
154}
155
156/// How a segment on disk stands against the manifest.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum SegmentState {
159    /// The manifest lists it.
160    Live,
161    /// Not live, and superseded: garbage collection deletes it once it is old
162    /// enough. The rule is the one [`Namespace::gc`](crate::Namespace::gc)
163    /// uses.
164    Dead,
165    /// Not live and not superseded. A compaction that has not published yet
166    /// looks like this, and so does one that stopped before it did. It is also
167    /// what GC leaves alone at `1-<folded>`.
168    Orphan,
169}
170
171impl fmt::Display for SegmentState {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.pad(match self {
174            Self::Live => "live",
175            Self::Dead => "dead",
176            Self::Orphan => "orphan",
177        })
178    }
179}
180
181/// Inspect the namespace `namespace` in `store`. See the module docs.
182///
183/// A manifest or schema object that is missing or cannot be decoded is
184/// reported in [`Report::problems`], not returned as an error, so the rest of
185/// the namespace still shows.
186///
187/// # Errors
188///
189/// - [`ItzmaError::InvalidNamespaceId`] for a malformed id.
190/// - [`ItzmaError::Storage`] if the store fails.
191///
192/// # Examples
193///
194/// ```
195/// # #[tokio::main]
196/// # async fn main() -> itzma_core::Result<()> {
197/// use std::sync::Arc;
198///
199/// use itzma_core::{Metric, Namespace, Schema};
200/// use object_store::memory::InMemory;
201///
202/// let store = Arc::new(InMemory::new());
203/// Namespace::create(store.clone(), "docs", Schema::new(2, Metric::L2)).await?;
204///
205/// let report = itzma_core::inspect::report(&*store, "docs").await?;
206/// assert!(report.problems.is_empty());
207/// assert_eq!(report.wal.objects, 0);
208/// # Ok(())
209/// # }
210/// ```
211pub async fn report(store: &dyn ObjectStore, namespace: &str) -> Result<Report> {
212    validate_id(namespace)?;
213    let mut problems = Vec::new();
214
215    let manifest = match manifest::load(store, namespace).await {
216        Ok((manifest, _)) => Some(manifest),
217        Err(e) => {
218            problems.push(unreadable("manifest", e)?);
219            None
220        }
221    };
222    let schema = match schema_object::read(store, namespace).await {
223        Ok(schema) => schema,
224        Err(e) => {
225            problems.push(unreadable("schema.json", e)?);
226            None
227        }
228    };
229    if let (Some(manifest), Some(schema)) = (&manifest, &schema) {
230        if &manifest.schema != schema {
231            problems.push(format!(
232                "schema.json holds {schema:?} but the manifest holds {:?}",
233                manifest.schema
234            ));
235        }
236    }
237
238    let prefix = Path::from(format!("{namespace}/segments"));
239    let listing: Vec<ObjectMeta> = store.list(Some(&prefix)).try_collect().await?;
240    let found = gc::group(&prefix, listing);
241    let wal_objects = gc::list_wal(store, namespace).await?;
242
243    let folded = manifest.as_ref().map_or(0, |m| m.wal_folded_through);
244    let wal = summarize_wal(
245        wal_objects.iter().map(|o| (o.seq, o.size)).collect(),
246        folded,
247    );
248    for &(from, to) in &wal.gaps {
249        problems.push(if from == to {
250            format!("WAL seq {from} is missing")
251        } else {
252            format!("WAL seqs {from} through {to} are missing")
253        });
254    }
255
256    let mut segments = Vec::new();
257    if let Some(manifest) = &manifest {
258        if let Err(e) = segment::validate_chain(&manifest.live_segments, folded) {
259            problems.push(e.to_string());
260        }
261        for id in &manifest.live_segments {
262            let data = segment::segment_path(namespace, id);
263            let there = found
264                .get(id)
265                .is_some_and(|f| f.objects.iter().any(|(path, _)| *path == data));
266            if !there {
267                problems.push(format!("live segment {id} has no data object"));
268            }
269        }
270        let live: HashSet<&str> = manifest.live_segments.iter().map(String::as_str).collect();
271        segments = found
272            .iter()
273            .map(|(id, f)| {
274                segment_report(
275                    id,
276                    f,
277                    folded,
278                    &live,
279                    &manifest.indexes,
280                    &manifest.sparse_indexes,
281                    &manifest.attr_indexes,
282                )
283            })
284            .collect();
285        for report in &segments {
286            if let Some(index) = &report.index {
287                if index.bytes.is_none() {
288                    problems.push(format!(
289                        "segment {} is listed with index generation {} but has no such index object",
290                        report.id, index.generation
291                    ));
292                }
293            }
294            if let Some(index) = &report.sparse_index {
295                if index.bytes.is_none() {
296                    problems.push(format!(
297                        "segment {} is listed with sparse index generation {} but has no such object",
298                        report.id, index.generation
299                    ));
300                }
301            }
302            if let Some(index) = &report.attr_index {
303                if index.bytes.is_none() {
304                    problems.push(format!(
305                        "segment {} is listed with attribute index generation {} but has no such object",
306                        report.id, index.generation
307                    ));
308                }
309            }
310        }
311        for id in manifest.indexes.keys() {
312            if !live.contains(id.as_str()) {
313                problems.push(format!(
314                    "the manifest lists an index for {id}, which is not a live segment"
315                ));
316            }
317        }
318        for id in manifest.sparse_indexes.keys() {
319            if !live.contains(id.as_str()) {
320                problems.push(format!(
321                    "the manifest lists a sparse index for {id}, which is not a live segment"
322                ));
323            }
324        }
325        for id in manifest.attr_indexes.keys() {
326            if !live.contains(id.as_str()) {
327                problems.push(format!(
328                    "the manifest lists an attribute index for {id}, which is not a live segment"
329                ));
330            }
331        }
332    } else {
333        segments.extend(found.iter().map(|(id, f)| {
334            segment_report(
335                id,
336                f,
337                0,
338                &HashSet::new(),
339                &BTreeMap::new(),
340                &BTreeMap::new(),
341                &BTreeMap::new(),
342            )
343        }));
344    }
345
346    Ok(Report {
347        namespace: namespace.to_string(),
348        schema,
349        manifest,
350        wal,
351        segments,
352        problems,
353    })
354}
355
356/// A missing or undecodable object becomes a problem line. A failure of the
357/// store itself is not something to describe, so it is returned.
358fn unreadable(what: &str, err: ItzmaError) -> Result<String> {
359    match err {
360        ItzmaError::NamespaceNotFound(_) => Ok(format!("{what} is missing")),
361        ItzmaError::Serde { .. }
362        | ItzmaError::UnsupportedFormat { .. }
363        | ItzmaError::WalFormatTooNew { .. }
364        | ItzmaError::SegmentFormatTooNew { .. } => Ok(format!("{what} cannot be read: {err}")),
365        other => Err(other),
366    }
367}
368
369fn segment_report(
370    id: &str,
371    found: &Found,
372    folded: u64,
373    live: &HashSet<&str>,
374    indexes: &BTreeMap<String, IndexEntry>,
375    sparse_indexes: &BTreeMap<String, SparseIndexEntry>,
376    attr_indexes: &BTreeMap<String, AttrIndexEntry>,
377) -> SegmentReport {
378    let state = if live.contains(id) {
379        SegmentState::Live
380    } else if gc::is_dead(folded, live, id, found) {
381        SegmentState::Dead
382    } else {
383        SegmentState::Orphan
384    };
385    let named = indexes.get(id).filter(|_| state == SegmentState::Live);
386    let index = named.map(|entry| IndexInfo {
387        generation: entry.generation,
388        kind: entry.kind.clone(),
389        bytes: found
390            .indexes
391            .iter()
392            .find(|object| object.generation == entry.generation)
393            .map(|object| object.size),
394    });
395    let mut stray_indexes: Vec<u32> = found
396        .indexes
397        .iter()
398        .map(|object| object.generation)
399        .filter(|generation| Some(*generation) != named.map(|entry| entry.generation))
400        .collect();
401    stray_indexes.sort_unstable();
402    let named_sparse = sparse_indexes
403        .get(id)
404        .filter(|_| state == SegmentState::Live);
405    let sparse_index = named_sparse.map(|entry| SparseIndexInfo {
406        generation: entry.generation,
407        bytes: found
408            .sparse_indexes
409            .iter()
410            .find(|object| object.generation == entry.generation)
411            .map(|object| object.size),
412    });
413    let mut stray_sparse_indexes: Vec<u32> = found
414        .sparse_indexes
415        .iter()
416        .map(|object| object.generation)
417        .filter(|generation| Some(*generation) != named_sparse.map(|entry| entry.generation))
418        .collect();
419    stray_sparse_indexes.sort_unstable();
420    let named_attr = attr_indexes.get(id).filter(|_| state == SegmentState::Live);
421    let attr_index = named_attr.map(|entry| AttrIndexInfo {
422        generation: entry.generation,
423        bytes: found
424            .attr_indexes
425            .iter()
426            .find(|object| object.generation == entry.generation)
427            .map(|object| object.size),
428    });
429    let mut stray_attr_indexes: Vec<u32> = found
430        .attr_indexes
431        .iter()
432        .map(|object| object.generation)
433        .filter(|generation| Some(*generation) != named_attr.map(|entry| entry.generation))
434        .collect();
435    stray_attr_indexes.sort_unstable();
436    let has_sparse_data = found
437        .objects
438        .iter()
439        .any(|(path, _)| path.filename() == Some("sparse.bin"));
440    SegmentReport {
441        id: id.to_string(),
442        lo: found.lo,
443        hi: found.hi,
444        bytes: found.objects.iter().map(|(_, size)| size).sum(),
445        state,
446        index,
447        stray_indexes,
448        has_sparse_data,
449        sparse_index,
450        stray_sparse_indexes,
451        attr_index,
452        stray_attr_indexes,
453        staging_objects: found.staging.len(),
454    }
455}
456
457/// Summarize `(seq, size)` pairs against the fold point. Pure: no storage.
458fn summarize_wal(mut objects: Vec<(u64, u64)>, folded: u64) -> WalReport {
459    objects.sort_unstable();
460    let mut gaps = Vec::new();
461    let mut prev = 0u64;
462    for &(seq, _) in &objects {
463        if seq > prev.saturating_add(1) {
464            gaps.push((prev + 1, seq - 1));
465        }
466        prev = prev.max(seq);
467    }
468    if folded > prev {
469        gaps.push((prev + 1, folded));
470    }
471    WalReport {
472        objects: objects.len(),
473        first: objects.first().map(|&(seq, _)| seq),
474        last: objects.last().map(|&(seq, _)| seq),
475        bytes: objects.iter().map(|&(_, size)| size).sum(),
476        fenced: objects
477            .iter()
478            .filter(|&&(_, size)| size == wal_codec::FENCE_LEN as u64)
479            .count(),
480        tail: objects.iter().filter(|&&(seq, _)| seq > folded).count(),
481        gaps,
482    }
483}
484
485impl fmt::Display for Report {
486    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487        writeln!(f, "namespace {}", self.namespace)?;
488        match &self.schema {
489            Some(schema) => writeln!(f, "schema.json  dim {}, {:?}", schema.dim, schema.metric)?,
490            None => writeln!(f, "schema.json  none")?,
491        }
492        match &self.manifest {
493            Some(m) => writeln!(
494                f,
495                "manifest     wal_format {}, segment_format {}, folded through {}, {} live segments",
496                m.wal_format,
497                m.segment_format,
498                m.wal_folded_through,
499                m.live_segments.len()
500            )?,
501            None => writeln!(f, "manifest     none")?,
502        }
503        let wal = &self.wal;
504        write!(f, "wal          {} objects", wal.objects)?;
505        if let (Some(first), Some(last)) = (wal.first, wal.last) {
506            write!(f, ", seq {first} through {last}")?;
507        }
508        writeln!(
509            f,
510            ", {} bytes, {} fenced, {} in the tail",
511            wal.bytes, wal.fenced, wal.tail
512        )?;
513        writeln!(f, "segments     {} on disk", self.segments.len())?;
514        for s in &self.segments {
515            write!(f, "  {}  {:<6}  {} bytes", s.id, s.state, s.bytes)?;
516            if let Some(index) = &s.index {
517                match index.bytes {
518                    Some(bytes) => {
519                        write!(
520                            f,
521                            "  index {} {} {bytes} bytes",
522                            index.generation, index.kind
523                        )?;
524                    }
525                    None => write!(f, "  index {} {} missing", index.generation, index.kind)?,
526                }
527            }
528            if !s.stray_indexes.is_empty() {
529                write!(f, "  unnamed indexes {:?}", s.stray_indexes)?;
530            }
531            if s.has_sparse_data {
532                write!(f, "  sparse")?;
533            }
534            if let Some(index) = &s.sparse_index {
535                match index.bytes {
536                    Some(bytes) => write!(f, "  sparse index {} {bytes} bytes", index.generation)?,
537                    None => write!(f, "  sparse index {} missing", index.generation)?,
538                }
539            }
540            if !s.stray_sparse_indexes.is_empty() {
541                write!(f, "  unnamed sparse indexes {:?}", s.stray_sparse_indexes)?;
542            }
543            if let Some(index) = &s.attr_index {
544                match index.bytes {
545                    Some(bytes) => {
546                        write!(f, "  attribute index {} {bytes} bytes", index.generation)?
547                    }
548                    None => write!(f, "  attribute index {} missing", index.generation)?,
549                }
550            }
551            if !s.stray_attr_indexes.is_empty() {
552                write!(f, "  unnamed attribute indexes {:?}", s.stray_attr_indexes)?;
553            }
554            if s.staging_objects > 0 {
555                write!(f, "  staging objects {}", s.staging_objects)?;
556            }
557            writeln!(f)?;
558        }
559        if self.problems.is_empty() {
560            writeln!(f, "problems     none")
561        } else {
562            writeln!(f, "problems     {}", self.problems.len())?;
563            for problem in &self.problems {
564                writeln!(f, "  {problem}")?;
565            }
566            Ok(())
567        }
568    }
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574
575    fn seqs(list: &[(u64, u64)], folded: u64) -> WalReport {
576        summarize_wal(list.to_vec(), folded)
577    }
578
579    #[test]
580    fn an_empty_wal_has_no_gaps() {
581        assert_eq!(seqs(&[], 0), WalReport::default());
582    }
583
584    #[test]
585    fn a_contiguous_run_has_no_gaps() {
586        let r = seqs(&[(1, 100), (2, 50), (3, 8)], 2);
587        assert_eq!(r.objects, 3);
588        assert_eq!((r.first, r.last), (Some(1), Some(3)));
589        assert_eq!(r.bytes, 158);
590        assert_eq!(r.fenced, 1);
591        assert_eq!(r.tail, 1);
592        assert!(r.gaps.is_empty());
593    }
594
595    #[test]
596    fn the_input_order_does_not_matter() {
597        let r = seqs(&[(3, 20), (1, 20), (2, 20)], 0);
598        assert!(r.gaps.is_empty());
599        assert_eq!((r.first, r.last), (Some(1), Some(3)));
600    }
601
602    #[test]
603    fn a_missing_start_and_a_missing_middle_are_gaps() {
604        let r = seqs(&[(3, 20), (4, 20), (8, 20)], 0);
605        assert_eq!(r.gaps, vec![(1, 2), (5, 7)]);
606    }
607
608    #[test]
609    fn a_fold_point_past_the_last_object_is_a_gap() {
610        let r = seqs(&[(1, 20), (2, 20)], 5);
611        assert_eq!(r.gaps, vec![(3, 5)]);
612        assert_eq!(r.tail, 0);
613    }
614
615    #[test]
616    fn a_fold_point_at_the_last_object_is_not() {
617        assert!(seqs(&[(1, 20), (2, 20)], 2).gaps.is_empty());
618    }
619
620    #[test]
621    fn a_seq_listed_twice_is_not_a_gap() {
622        let r = seqs(&[(1, 20), (1, 20), (2, 20)], 0);
623        assert!(r.gaps.is_empty());
624    }
625}