1use serde::{Deserialize, Serialize};
7
8use crate::output::{Diagnostic, FunctionReport, OutcomeName, VerdictName};
9use crate::project::{Currentness, ProjectResult};
10use crate::proof::Target;
11
12pub const VERSION: u32 = 1;
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17pub struct Explanation {
18 pub version: u32,
20 pub target: Target,
22 pub establishing_run: String,
24 pub currentness: Currentness,
26 pub function: FunctionReport,
28 pub attributed_diagnostics: Vec<Diagnostic>,
30 pub run_diagnostics: Vec<Diagnostic>,
32 pub diagnostic_attribution_complete: bool,
34 pub notes: Vec<String>,
36}
37
38#[derive(Deserialize)]
41struct BaselineWire {
42 #[serde(default)]
43 contracts: Option<serde::de::IgnoredAny>,
44 version: u32,
45 name: String,
46 job_id: String,
47 result: ProjectResult,
48}
49impl TryFrom<BaselineWire> for Baseline {
50 type Error = &'static str;
51 fn try_from(wire: BaselineWire) -> Result<Self, Self::Error> {
52 if wire.contracts.is_some() {
53 return Err(crate::jobs::RETIRED_NEUTRAL_RECORD);
54 }
55 Ok(Self {
56 version: wire.version,
57 name: wire.name,
58 job_id: wire.job_id,
59 result: wire.result,
60 })
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(try_from = "BaselineWire")]
67pub struct Baseline {
68 pub version: u32,
70 pub name: String,
72 pub job_id: String,
74 pub result: ProjectResult,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum Change {
85 Unchanged,
87 Regressed,
89 BecameUnknown,
91 Recovered,
94 Added,
96 NotObserved,
98 Removed,
100 Incomparable,
102 Changed,
104}
105
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108pub struct Difference {
109 pub target: Target,
111 pub function: String,
113 pub before: Option<VerdictName>,
116 pub after: Option<VerdictName>,
119 pub change: Change,
121 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
124 pub before_passed_by_verus_totals: bool,
125 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
128 pub after_passed_by_verus_totals: bool,
129 pub obligations: Vec<ObligationDifference>,
131}
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub struct ObligationDifference {
136 pub id: String,
138 pub before: Option<OutcomeName>,
140 pub after: Option<OutcomeName>,
142 pub advisory: bool,
144 pub change: Change,
146}
147
148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct Comparison {
151 pub version: u32,
153 pub compatible: bool,
155 pub before_revision: String,
157 pub after_revision: String,
159 pub after_currentness: Currentness,
161 pub differences: Vec<Difference>,
163 pub notes: Vec<String>,
165}
166
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
170pub enum Reference {
171 Job(String),
173 Baseline(String),
175}
176
177pub fn explain(
182 result: &ProjectResult,
183 target: &Target,
184 function: &str,
185 obligation: Option<&str>,
186) -> Result<Explanation, String> {
187 let matches: Vec<_> = result
188 .targets
189 .iter()
190 .filter(|t| {
191 t.package_id == target.package_id && t.target == target.name && t.kind == target.kind
192 })
193 .collect();
194 if matches.len() != 1 {
195 return Err("SAIL0904: exact target is missing or ambiguous".into());
196 }
197 let selected = matches[0];
198 let functions: Vec<_> = selected
199 .report
200 .crates
201 .iter()
202 .flat_map(|c| &c.functions)
203 .filter(|f| f.function == function)
204 .collect();
205 if functions.len() != 1 {
206 return Err("SAIL0904: exact function is missing or ambiguous".into());
207 }
208 let mut report = functions[0].clone();
209 if let Some(id) = obligation {
210 let Some(obligations) = report.obligations.as_mut() else {
211 return Err("SAIL0904: obligation attribution is unavailable".into());
212 };
213 if !obligations.iter().any(|o| o.id == id) {
214 return Err("SAIL0904: exact obligation was not observed".into());
215 }
216 obligations.retain(|o| o.id == id);
217 }
218 Ok(Explanation {
219 version: VERSION, target: target.clone(), establishing_run: selected.establishing_run.clone(),
220 currentness: result.currentness, function: report, attributed_diagnostics: Vec::new(),
221 run_diagnostics: selected.report.diagnostics.clone(), diagnostic_attribution_complete: false,
222 notes: vec!["Run diagnostics are retained; no line-window heuristic establishes their function ownership.".into()],
223 })
224}
225
226#[derive(Debug, Clone, Copy)]
228struct Entry<'a> {
229 report: &'a FunctionReport,
230 by_totals: bool,
233}
234
235impl Entry<'_> {
236 fn verdict(self) -> VerdictName {
238 effective(self.report)
239 }
240
241 fn class(self) -> VerdictName {
245 if self.by_totals {
246 VerdictName::Verified
247 } else {
248 self.verdict()
249 }
250 }
251}
252
253type Records<'a> = std::collections::BTreeMap<(Target, String), Vec<Entry<'a>>>;
254
255fn functions(result: &ProjectResult) -> Records<'_> {
256 let mut records = Records::new();
257 for target in result.targets.iter().filter(|target| target.requested) {
258 let id = Target {
259 package_id: target.package_id.clone(),
260 name: target.target.clone(),
261 kind: target.kind.clone(),
262 };
263 for krate in &target.report.crates {
264 let cleared = krate.verus_totals_clear_unknown();
265 for function in &krate.functions {
266 records
267 .entry((id.clone(), function.function.clone()))
268 .or_default()
269 .push(Entry {
270 report: function,
271 by_totals: cleared && effective(function) == VerdictName::Unknown,
272 });
273 }
274 }
275 }
276 records
277}
278
279fn unique<'a>(entries: &[Entry<'a>]) -> Option<&'a FunctionReport> {
280 match entries {
281 [only] => Some(only.report),
282 _ => None,
283 }
284}
285
286#[derive(Debug, Default, Clone, Copy)]
288struct Side {
289 verdict: Option<VerdictName>,
291 class: Option<VerdictName>,
293 by_totals: bool,
295}
296
297fn side(entries: &[Entry<'_>]) -> Option<Side> {
299 let Some(first) = entries.first() else {
300 return Some(Side::default());
301 };
302 entries
303 .iter()
304 .all(|e| e.class() == first.class())
305 .then(|| Side {
306 verdict: entries
307 .iter()
308 .all(|e| e.verdict() == first.verdict())
309 .then(|| first.verdict()),
310 class: Some(first.class()),
311 by_totals: entries.iter().any(|e| e.by_totals),
312 })
313}
314
315fn resolve(left: &[Entry<'_>], right: &[Entry<'_>]) -> Option<(Side, Side)> {
321 let repeated = left.len() > 1 || right.len() > 1;
322 if repeated && left.len() != right.len() {
323 return None;
324 }
325 Some((side(left)?, side(right)?))
326}
327
328fn classify(before: Option<VerdictName>, after: Option<VerdictName>, removed: bool) -> Change {
330 match (before, after) {
331 (Some(a), Some(b)) if a == b => Change::Unchanged,
332 (Some(VerdictName::Verified), Some(VerdictName::Failed)) => Change::Regressed,
333 (Some(VerdictName::Verified), Some(VerdictName::Unknown | VerdictName::Provisional)) => {
334 Change::BecameUnknown
335 }
336 (Some(_), Some(VerdictName::Verified)) => Change::Recovered,
337 (None, Some(_)) => Change::Added,
338 (Some(_), None) if removed => Change::Removed,
339 (Some(_), None) => Change::NotObserved,
340 _ => Change::Changed,
341 }
342}
343
344fn scopes(result: &ProjectResult) -> Vec<(Target, String, Vec<String>)> {
345 let mut scopes: Vec<_> = result
346 .targets
347 .iter()
348 .filter(|t| t.requested)
349 .map(|target| {
350 (
351 Target {
352 package_id: target.package_id.clone(),
353 name: target.target.clone(),
354 kind: target.kind.clone(),
355 },
356 target.report.mode.clone(),
357 target.report.command.clone(),
358 )
359 })
360 .collect();
361 scopes.sort();
362 scopes
363}
364
365#[derive(Debug, Default)]
367struct Tally {
368 by_totals: usize,
370 repeated_compared: usize,
372 repeated_functions: usize,
374 repeated_incomparable: usize,
376}
377
378#[must_use]
388pub fn compare(before: &ProjectResult, after: &ProjectResult) -> Comparison {
389 let compatible = before.no_reuse.is_none()
390 && after.no_reuse.is_none()
391 && !before.context_sha256.is_empty()
392 && before.context_sha256 == after.context_sha256
393 && scopes(before) == scopes(after);
394 let after_project = after;
395 let left = functions(before);
396 let right = functions(after);
397 let ids: std::collections::BTreeSet<_> = left.keys().chain(right.keys()).cloned().collect();
398 let mut tally = Tally::default();
399 let differences = ids
400 .into_iter()
401 .map(|(target, function)| {
402 let key = (target.clone(), function.clone());
403 let l = left.get(&key).map_or(&[][..], Vec::as_slice);
404 let r = right.get(&key).map_or(&[][..], Vec::as_slice);
405 let repeated = l.len() > 1 || r.len() > 1;
406 let resolved = resolve(l, r);
407 if repeated && resolved.is_some() {
408 tally.repeated_compared += 1;
409 tally.repeated_functions += l.len().max(r.len());
410 } else if repeated {
411 tally.repeated_incomparable += 1;
412 }
413 let (old, new) = resolved.unwrap_or_default();
414 let change = if compatible && resolved.is_some() {
415 classify(old.class, new.class, inventory(after_project, &target))
416 } else {
417 Change::Incomparable
418 };
419 let classified = change != Change::Incomparable;
420 if classified {
421 let count = |entries: &[Entry<'_>]| entries.iter().filter(|e| e.by_totals).count();
422 tally.by_totals += count(l).max(count(r));
423 }
424 Difference {
425 target,
426 function,
427 before: old.verdict,
428 after: new.verdict,
429 change,
430 before_passed_by_verus_totals: classified && old.by_totals,
431 after_passed_by_verus_totals: classified && new.by_totals,
432 obligations: if repeated {
433 Vec::new()
434 } else {
435 obligations(unique(l), unique(r), compatible)
436 },
437 }
438 })
439 .collect();
440 Comparison {
441 version: VERSION,
442 compatible,
443 before_revision: before.input_revision.clone(),
444 after_revision: after.input_revision.clone(),
445 after_currentness: after.currentness,
446 differences,
447 notes: comparison_notes(compatible, &tally),
448 }
449}
450
451fn comparison_notes(compatible: bool, tally: &Tally) -> Vec<String> {
452 let mut notes = Vec::new();
453 if !compatible {
454 notes.push("Requested scope, mode or runtime context differs; transitions are descriptive, not proof regressions.".into());
455 }
456 if tally.by_totals > 0 {
457 notes.push(format!(
458 "{} function(s) reported `unknown` passed by Verus's totals (not attributed one by one); the comparison counts them as passing, as Verus did. Their verdicts stay `unknown`.",
459 tally.by_totals
460 ));
461 }
462 if tally.repeated_compared > 0 {
463 notes.push(format!(
464 "Entries are friendly function names: {} repeated name(s), shared by {} functions (VI-0010), were each compared as a group, since every function sharing the name has the same result on each side.",
465 tally.repeated_compared, tally.repeated_functions
466 ));
467 }
468 if tally.repeated_incomparable > 0 {
469 notes.push(format!(
470 "Repeated friendly function names cannot identify one implementation; {} such name(s) whose functions differ in result or number are incomparable (VI-0010).",
471 tally.repeated_incomparable
472 ));
473 }
474 notes
475}
476
477fn effective(report: &FunctionReport) -> VerdictName {
478 if report.establishment == crate::output::EstablishmentName::Provisional {
479 VerdictName::Provisional
480 } else {
481 report.verdict
482 }
483}
484
485fn inventory(project: &ProjectResult, id: &Target) -> bool {
486 project.error.is_none()
487 && project.exit_code == Some(0)
488 && project.targets.iter().any(|target| {
489 crate::acceptance::complete_target(target).is_some()
490 && target.package_id == id.package_id
491 && target.target == id.name
492 && target.kind == id.kind
493 && target.report.crates.iter().all(|report| {
494 report.verus.success == Some(true)
495 && report.verus.encountered_vir_error != Some(true)
496 })
497 })
498}
499
500fn obligations(
501 before: Option<&FunctionReport>,
502 after: Option<&FunctionReport>,
503 compatible: bool,
504) -> Vec<ObligationDifference> {
505 let index = |function: Option<&FunctionReport>| {
506 function
507 .and_then(|f| f.obligations.as_ref())
508 .into_iter()
509 .flatten()
510 .map(|obligation| (obligation.id.clone(), obligation.clone()))
511 .collect::<std::collections::BTreeMap<_, _>>()
512 };
513 let left = index(before);
514 let right = index(after);
515 left.keys()
516 .chain(right.keys())
517 .cloned()
518 .collect::<std::collections::BTreeSet<_>>()
519 .into_iter()
520 .map(|id| {
521 let old = left.get(&id);
522 let new = right.get(&id);
523 let before = old.map(|o| o.outcome);
524 let after = new.map(|o| o.outcome);
525 let advisory = new.or(old).is_some_and(|o| o.advisory);
526 let change = if compatible {
527 match (before, after) {
528 (Some(a), Some(b)) if a == b => Change::Unchanged,
529 (Some(OutcomeName::Proved), Some(OutcomeName::Failed)) if !advisory => {
530 Change::Regressed
531 }
532 (Some(OutcomeName::Proved), Some(OutcomeName::Unknown)) => {
533 Change::BecameUnknown
534 }
535 (Some(_), Some(OutcomeName::Proved)) => Change::Recovered,
536 (None, Some(_)) => Change::Added,
537 (Some(_), None) => Change::NotObserved,
538 _ => Change::Changed,
539 }
540 } else {
541 Change::Incomparable
542 };
543 ObligationDifference {
544 id,
545 before,
546 after,
547 advisory,
548 change,
549 }
550 })
551 .collect()
552}