1use serde::{Deserialize, Serialize};
7
8use crate::output::ObligationReport;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12pub struct Consumption {
13 pub used: u64,
15 pub limit: u64,
17}
18
19impl Consumption {
20 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct FunctionHealth {
31 pub attributed: bool,
33 pub complete: bool,
36 pub checks: u64,
38 pub measured_checks: u64,
40 pub near_limit_checks: u64,
42 pub exhausted_checks: u64,
44 pub unlimited_checks: u64,
46 pub unrecorded_checks: u64,
48 pub peak: Option<Consumption>,
50}
51
52impl FunctionHealth {
53 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub struct Entry {
115 pub target: crate::proof::Target,
117 pub requested: bool,
119 pub establishing_run: String,
121 pub reused: bool,
123 pub function: String,
125 pub verdict: crate::output::VerdictName,
127 pub establishment: crate::output::EstablishmentName,
129 pub unstable: bool,
131 pub provenance: crate::output::ProvenanceReport,
133 pub health: FunctionHealth,
135 pub fragility: Option<crate::output::Fragility>,
137}
138
139#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub struct View {
142 pub kind: String,
144 pub version: u32,
146 pub job_id: Option<String>,
148 pub run_id: String,
150 pub workspace: String,
152 pub context_sha256: String,
154 pub input_revision: String,
156 pub currentness: crate::project::Currentness,
158 pub exit_code: Option<i32>,
160 pub total_functions: u64,
162 pub omitted: u64,
164 pub entries: Vec<Entry>,
166 pub error: Option<crate::output::ErrorInfo>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub baseline_name: Option<String>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub baseline: Option<Box<Self>>,
174}
175
176impl View {
177 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}