1use 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#[derive(Debug, Clone, PartialEq)]
41pub struct Report {
42 pub namespace: String,
44 pub schema: Option<Schema>,
47 pub manifest: Option<Manifest>,
49 pub wal: WalReport,
51 pub segments: Vec<SegmentReport>,
53 pub problems: Vec<String>,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Default)]
59pub struct WalReport {
60 pub objects: usize,
62 pub first: Option<u64>,
64 pub last: Option<u64>,
66 pub bytes: u64,
68 pub fenced: usize,
70 pub tail: usize,
73 pub gaps: Vec<(u64, u64)>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct SegmentReport {
81 pub id: String,
83 pub lo: u64,
85 pub hi: u64,
87 pub bytes: u64,
89 pub state: SegmentState,
94 pub index: Option<IndexInfo>,
96 pub stray_indexes: Vec<u32>,
100 pub has_sparse_data: bool,
103 pub sparse_index: Option<SparseIndexInfo>,
105 pub stray_sparse_indexes: Vec<u32>,
109 pub attr_index: Option<AttrIndexInfo>,
112 pub stray_attr_indexes: Vec<u32>,
117 pub staging_objects: usize,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct IndexInfo {
127 pub generation: u32,
129 pub kind: String,
131 pub bytes: Option<u64>,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct SparseIndexInfo {
139 pub generation: u32,
141 pub bytes: Option<u64>,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct AttrIndexInfo {
149 pub generation: u32,
151 pub bytes: Option<u64>,
154}
155
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub enum SegmentState {
159 Live,
161 Dead,
165 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
181pub 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
356fn 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
457fn 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}