Skip to main content

keystate_core/verify/
report.rs

1//! The verification output shapes: [`Severity`], [`IssueKind`],
2//! [`VerificationIssue`] and [`VerificationReport`].
3
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use crate::Version;
9use crate::model::EntityKind;
10
11/// Severity of a single verification issue.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum Severity {
15    /// A real completeness gap: required config state is missing.
16    Error,
17    /// Tracked state that falls short but does not block the completeness
18    /// claim (e.g. a volatile field missing purely due to null session data).
19    Warning,
20}
21
22/// The machine-readable category of a verification issue.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum IssueKind {
26    /// A `Required` entity type has no rows.
27    MissingEntity,
28    /// A required field is absent from an existing row.
29    MissingRequired,
30    /// A non-required field is absent from every row of its entity.
31    MissingOptional,
32    /// A manifest-volatile field leaked into the config body.
33    MisplacedVolatile,
34    /// A manifest-volatile field was not captured in the volatile section.
35    MissingVolatile,
36}
37
38/// A single finding from verification.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct VerificationIssue {
41    /// Severity of the finding.
42    pub severity: Severity,
43    /// Category of the finding, for machine consumers.
44    pub kind: IssueKind,
45    /// The entity kind the finding concerns.
46    pub entity: EntityKind,
47    /// Row id the finding concerns, when row-scoped.
48    pub row_id: Option<String>,
49    /// The field path the finding concerns, when field-scoped.
50    pub path: Option<String>,
51    /// Schema version that introduced the absent field, when known.
52    pub introduced_in: Option<Version>,
53    /// Human-readable explanation.
54    pub message: String,
55}
56
57impl VerificationIssue {
58    /// A concise, human-readable one-liner.
59    pub fn summary(&self) -> String {
60        match (&self.row_id, &self.path) {
61            (Some(row_id), Some(path)) => {
62                format!(
63                    "{} [{}/{}] {} -> {}",
64                    self.kind_label(),
65                    self.entity_label(),
66                    row_id,
67                    path,
68                    self.message
69                )
70            }
71            (Some(row_id), None) => {
72                format!(
73                    "{} [{}/{}] {}",
74                    self.kind_label(),
75                    self.entity_label(),
76                    row_id,
77                    self.message
78                )
79            }
80            _ => format!(
81                "{} [{}] {}",
82                self.kind_label(),
83                self.entity_label(),
84                self.message
85            ),
86        }
87    }
88
89    fn kind_label(&self) -> &'static str {
90        match self.kind {
91            IssueKind::MissingEntity => "missing-entity",
92            IssueKind::MissingRequired => "missing-required",
93            IssueKind::MissingOptional => "missing-optional",
94            IssueKind::MisplacedVolatile => "misplaced-volatile",
95            IssueKind::MissingVolatile => "missing-volatile",
96        }
97    }
98
99    fn entity_label(&self) -> &'static str {
100        super::entity_label(self.entity)
101    }
102}
103
104/// The complete result of running a manifest against an extraction.
105///
106/// Part of the output document, not a side log: completeness is a claim the
107/// tool backs with evidence every time it runs.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct VerificationReport {
110    /// Backend the report applies to.
111    pub backend: String,
112    /// Backend schema version the manifest was keyed on.
113    pub against_version: Version,
114    /// All findings, in manifest order.
115    pub issues: Vec<VerificationIssue>,
116}
117
118impl VerificationReport {
119    /// Whether the extraction is complete: no `Error`-severity findings.
120    pub fn is_complete(&self) -> bool {
121        self.issues.iter().all(|i| i.severity != Severity::Error)
122    }
123
124    /// Counts of `(errors, warnings)`.
125    pub fn counts(&self) -> (usize, usize) {
126        let errors = self
127            .issues
128            .iter()
129            .filter(|i| i.severity == Severity::Error)
130            .count();
131        (errors, self.issues.len() - errors)
132    }
133}
134
135impl fmt::Display for VerificationReport {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        let (errors, warnings) = self.counts();
138        write!(
139            f,
140            "VerificationReport({} @ {}, {} errors, {} warnings, {} issues)",
141            self.backend,
142            self.against_version,
143            errors,
144            warnings,
145            self.issues.len()
146        )
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn issue(kind: IssueKind, severity: Severity) -> VerificationIssue {
155        VerificationIssue {
156            severity,
157            kind,
158            entity: EntityKind::Client,
159            row_id: Some("c1".into()),
160            path: Some("native.secret".into()),
161            introduced_in: Some(Version::new(1, 0, 0)),
162            message: "boom".into(),
163        }
164    }
165
166    #[test]
167    fn report_counts_and_completeness() {
168        let report = VerificationReport {
169            backend: "stub".into(),
170            against_version: Version::new(1, 0, 0),
171            issues: vec![
172                issue(IssueKind::MissingRequired, Severity::Error),
173                issue(IssueKind::MissingVolatile, Severity::Warning),
174            ],
175        };
176        assert!(!report.is_complete());
177        assert_eq!(report.counts(), (1, 1));
178
179        let clean = VerificationReport {
180            issues: vec![],
181            ..report.clone()
182        };
183        assert!(clean.is_complete());
184        assert_eq!(clean.counts(), (0, 0));
185    }
186
187    #[test]
188    fn issue_summary_includes_entity_and_path() {
189        let s = issue(IssueKind::MissingRequired, Severity::Error).summary();
190        assert!(s.contains("missing-required"));
191        assert!(s.contains("client"));
192        assert!(s.contains("native.secret"));
193    }
194}