Skip to main content

sail_api/
health.rs

1//! Observed per-check proof effort; this view never changes verification verdicts.
2//!
3//! Missing measurements remain missing. No stability or fragility measurement
4//! is inferred from one run, a whole-function timing, or a cache hit count.
5
6use serde::{Deserialize, Serialize};
7
8use crate::output::ObligationReport;
9
10/// Recorded consumption of one check with a finite positive resource limit.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub struct Consumption {
13    /// Actual check effort, including values above the requested limit.
14    pub used: u64,
15    /// Requested finite positive limit, never a whole-function approximation.
16    pub limit: u64,
17}
18
19impl Consumption {
20    /// Compares exact fractions without floating point or u64 multiplication.
21    #[must_use]
22    pub fn compare(self, other: Self) -> std::cmp::Ordering {
23        (u128::from(self.used) * u128::from(other.limit))
24            .cmp(&(u128::from(other.used) * u128::from(self.limit)))
25    }
26}
27
28/// Health measurements for one original function report, not a proof tier.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct FunctionHealth {
31    /// An obligation inventory was recorded; false differs from an empty one.
32    pub attributed: bool,
33    /// Every recorded check has answer, provenance, requested limit and effort.
34    /// This says nothing about repeated-run stability or proof success.
35    pub complete: bool,
36    /// Original checks, including advisory checks.
37    pub checks: u64,
38    /// Checks with finite positive limits and actual recorded effort.
39    pub measured_checks: u64,
40    /// Checks whose measured effort exceeds half their finite limit (ADR 0009).
41    pub near_limit_checks: u64,
42    /// Checks whose original reason-unknown identifies resource exhaustion.
43    pub exhausted_checks: u64,
44    /// Checks explicitly requesting an unlimited resource budget (limit zero).
45    pub unlimited_checks: u64,
46    /// Checks missing an answer, source, requested limit or actual effort.
47    pub unrecorded_checks: u64,
48    /// Highest exact finite check-consumption fraction; absent without one.
49    pub peak: Option<Consumption>,
50}
51
52impl FunctionHealth {
53    /// Derives measurements only from original attributed per-check evidence.
54    #[must_use]
55    pub fn from_obligations(obligations: Option<&[ObligationReport]>) -> Self {
56        let mut health = Self {
57            attributed: obligations.is_some(),
58            complete: obligations.is_some(),
59            checks: 0,
60            measured_checks: 0,
61            near_limit_checks: 0,
62            exhausted_checks: 0,
63            unlimited_checks: 0,
64            unrecorded_checks: 0,
65            peak: None,
66        };
67        for check in obligations
68            .into_iter()
69            .flatten()
70            .flat_map(|item| &item.checks)
71        {
72            health.checks = health.checks.saturating_add(1);
73            let effort = sail_ledger::Effort {
74                limit: check.rlimit_limit,
75                used: check.rlimit_used,
76                reason: check.reason_unknown.clone(),
77            };
78            if effort.exhausted() {
79                health.exhausted_checks = health.exhausted_checks.saturating_add(1);
80            }
81            if check.answer.is_none()
82                || check.source.is_none()
83                || check.rlimit_limit.is_none()
84                || check.rlimit_used.is_none()
85            {
86                health.complete = false;
87                health.unrecorded_checks = health.unrecorded_checks.saturating_add(1);
88            }
89            if check.rlimit_limit == Some(0) {
90                health.unlimited_checks = health.unlimited_checks.saturating_add(1);
91            }
92            if let (Some(used), Some(limit)) = (check.rlimit_used, check.rlimit_limit)
93                && limit > 0
94            {
95                health.measured_checks = health.measured_checks.saturating_add(1);
96                if effort.near_limit() {
97                    health.near_limit_checks = health.near_limit_checks.saturating_add(1);
98                }
99                let observed = Consumption { used, limit };
100                if health
101                    .peak
102                    .is_none_or(|peak| observed.compare(peak).is_gt())
103                {
104                    health.peak = Some(observed);
105                }
106            }
107        }
108        health
109    }
110}
111
112/// One exactly identified function in a retained health view.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct Entry {
115    /// Cargo package/name/kinds, including same-named library and binary targets.
116    pub target: crate::proof::Target,
117    /// Whether the original invocation requested this target.
118    pub requested: bool,
119    /// Original invocation that established this target's report.
120    pub establishing_run: String,
121    /// Whether this job reused the original complete target report.
122    pub reused: bool,
123    /// Original qualified compiler identity.
124    pub function: String,
125    /// Original ordinary verdict, including unknown and provisional.
126    pub verdict: crate::output::VerdictName,
127    /// Original establishment; a health measurement cannot confirm a proof.
128    pub establishment: crate::output::EstablishmentName,
129    /// Original ADR 0009 instability flag.
130    pub unstable: bool,
131    /// Original answer provenance.
132    pub provenance: crate::output::ProvenanceReport,
133    /// Derived only from this report's original checks.
134    pub health: FunctionHealth,
135    /// Explicit existing replay measurement, absent when it was not measured.
136    pub fragility: Option<crate::output::Fragility>,
137}
138
139/// Bounded read-only health view, shared by CLI, JSON and MCP.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct View {
142    /// Always `sail-proof-health`.
143    pub kind: String,
144    /// Independent health-view contract version, currently one.
145    pub version: u32,
146    /// Retained job when read from the service; absent for a result file.
147    pub job_id: Option<String>,
148    /// Original producing invocation.
149    pub run_id: String,
150    /// Original workspace.
151    pub workspace: String,
152    /// Original full configuration identity, for interpreting comparisons.
153    pub context_sha256: String,
154    /// Original declared input revision.
155    pub input_revision: String,
156    /// Original result currentness; historical evidence stays historical.
157    pub currentness: crate::project::Currentness,
158    /// Original project process exit; view generation never replaces it.
159    pub exit_code: Option<i32>,
160    /// Every requested-target function, including entries omitted by the bound.
161    pub total_functions: u64,
162    /// Entries omitted from this bounded view, never silently dropped.
163    pub omitted: u64,
164    /// Ranked by exhaustion, near-limit checks, then exact finite consumption.
165    pub entries: Vec<Entry>,
166    /// Original infrastructure/setup failure, when present.
167    pub error: Option<crate::output::ErrorInfo>,
168    /// Explicit immutable baseline name when one was requested.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub baseline_name: Option<String>,
171    /// Separately labelled earlier evidence, never merged into current answers.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub baseline: Option<Box<Self>>,
174}
175
176impl View {
177    /// Reads existing per-check evidence; no solver is started and no verdict
178    /// or provisional establishment is changed. Older v2 reports need no new
179    /// measurement: their obligations supply only what was actually retained.
180    ///
181    /// # Errors
182    /// An unsupported document, duplicate identity or limit outside 1..1000.
183    pub fn of(result: &crate::project::ProjectResult, limit: usize) -> Result<Self, String> {
184        if result.kind != "sail-project-result"
185            || result.schema_version != crate::project::SCHEMA_VERSION
186            || !(1..=1000).contains(&limit)
187        {
188            return Err("health requires a supported project result and limit 1..1000".into());
189        }
190        let mut entries = Vec::new();
191        let mut seen = std::collections::BTreeSet::new();
192        let mut targets = std::collections::BTreeSet::new();
193        for target in result.targets.iter().filter(|target| target.requested) {
194            if target.report.schema_version != crate::output::SCHEMA_VERSION {
195                return Err("health does not support this embedded report version".into());
196            }
197            let identity = crate::proof::Target {
198                package_id: target.package_id.clone(),
199                name: target.target.clone(),
200                kind: target.kind.clone(),
201            };
202            if !targets.insert(identity.clone()) {
203                return Err("health cannot merge duplicate target identities".into());
204            }
205            for function in target.report.crates.iter().flat_map(|item| &item.functions) {
206                if !seen.insert((identity.clone(), &function.function)) {
207                    return Err("health cannot merge duplicate target/function identities".into());
208                }
209                entries.push(Entry {
210                    target: identity.clone(),
211                    requested: target.requested,
212                    establishing_run: target.establishing_run.clone(),
213                    reused: target.reused,
214                    function: function.function.clone(),
215                    verdict: function.verdict,
216                    establishment: function.establishment,
217                    unstable: function.unstable,
218                    provenance: function.provenance.clone(),
219                    health: FunctionHealth::from_obligations(function.obligations.as_deref()),
220                    fragility: function.fragility,
221                });
222            }
223        }
224        entries.sort_by(compare_entries);
225        let total_functions = u64::try_from(entries.len()).map_err(|error| error.to_string())?;
226        entries.truncate(limit);
227        let displayed = u64::try_from(entries.len()).map_err(|error| error.to_string())?;
228        Ok(Self {
229            kind: "sail-proof-health".into(),
230            version: 1,
231            job_id: None,
232            run_id: result.run_id.clone(),
233            workspace: result.workspace.clone(),
234            context_sha256: result.context_sha256.clone(),
235            input_revision: result.input_revision.clone(),
236            currentness: result.currentness,
237            exit_code: result.exit_code,
238            total_functions,
239            omitted: total_functions - displayed,
240            entries,
241            error: result.error.clone(),
242            baseline_name: None,
243            baseline: None,
244        })
245    }
246}
247
248fn compare_entries(left: &Entry, right: &Entry) -> std::cmp::Ordering {
249    right
250        .health
251        .exhausted_checks
252        .cmp(&left.health.exhausted_checks)
253        .then_with(|| {
254            right
255                .health
256                .near_limit_checks
257                .cmp(&left.health.near_limit_checks)
258        })
259        .then_with(|| match (left.health.peak, right.health.peak) {
260            (Some(left), Some(right)) => right.compare(left),
261            (None, Some(_)) => std::cmp::Ordering::Greater,
262            (Some(_), None) => std::cmp::Ordering::Less,
263            (None, None) => std::cmp::Ordering::Equal,
264        })
265        .then_with(|| (&left.target, &left.function).cmp(&(&right.target, &right.function)))
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use crate::output::{AnswerName, CheckReport, OutcomeName, SourceName};
272
273    fn obligation(checks: Vec<CheckReport>) -> ObligationReport {
274        ObligationReport {
275            id: "demo::f#Function-Def/0".into(),
276            kind: "Function-Def".into(),
277            ordinal: 0,
278            spinoff: None,
279            advisory: false,
280            span: None,
281            outcome: OutcomeName::Proved,
282            unstable: false,
283            checks,
284            counterexample: None,
285        }
286    }
287
288    fn check(used: Option<u64>, limit: Option<u64>) -> CheckReport {
289        CheckReport {
290            answer: Some(AnswerName::Unsat),
291            rlimit_limit: limit,
292            rlimit_used: used,
293            reason_unknown: None,
294            source: Some(SourceName::Solved),
295        }
296    }
297
298    #[test]
299    fn exact_half_threshold_and_fraction_order_survive_u64_boundaries() {
300        let maximum = u64::MAX;
301        let obligations = [obligation(vec![
302            check(Some(maximum / 2), Some(maximum)),
303            check(Some(maximum / 2 + 1), Some(maximum)),
304            check(Some(1), Some(2)),
305            check(Some(2), Some(3)),
306        ])];
307        let health = FunctionHealth::from_obligations(Some(&obligations));
308        assert_eq!(health.near_limit_checks, 2);
309        assert_eq!(health.peak, Some(Consumption { used: 2, limit: 3 }));
310        assert!(health.complete);
311        assert_eq!(
312            Consumption {
313                used: maximum,
314                limit: maximum - 1
315            }
316            .compare(Consumption {
317                used: maximum - 1,
318                limit: maximum
319            }),
320            std::cmp::Ordering::Greater
321        );
322    }
323
324    #[test]
325    fn missing_unlimited_and_empty_measurements_are_distinct() {
326        let absent = FunctionHealth::from_obligations(None);
327        let empty = FunctionHealth::from_obligations(Some(&[]));
328        assert!(!absent.attributed);
329        assert!(!absent.complete);
330        assert!(empty.attributed);
331        assert!(empty.complete);
332        let mut exhausted = check(Some(5), Some(10));
333        exhausted.answer = Some(AnswerName::Unknown);
334        exhausted.reason_unknown = Some("(:reason-unknown \"timeout\")".into());
335        let obligations = [obligation(vec![
336            check(Some(100), Some(0)),
337            check(None, Some(20)),
338            check(Some(0), None),
339            exhausted,
340        ])];
341        let health = FunctionHealth::from_obligations(Some(&obligations));
342        assert!(!health.complete);
343        assert_eq!(health.checks, 4);
344        assert_eq!(health.unrecorded_checks, 2);
345        assert_eq!(health.unlimited_checks, 1);
346        assert_eq!(health.measured_checks, 1);
347        assert_eq!(health.exhausted_checks, 1);
348        assert_eq!(health.near_limit_checks, 0);
349        assert_eq!(health.peak, Some(Consumption { used: 5, limit: 10 }));
350    }
351}