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(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct Baseline {
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub contracts: Option<Box<crate::contracts::Evidence>>,
44 pub version: u32,
46 pub name: String,
48 pub job_id: String,
50 pub result: ProjectResult,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum Change {
61 Unchanged,
63 Regressed,
65 BecameUnknown,
67 Recovered,
70 Added,
72 NotObserved,
74 Removed,
76 Incomparable,
78 Changed,
80}
81
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84pub struct Difference {
85 pub target: Target,
87 pub function: String,
89 pub before: Option<VerdictName>,
92 pub after: Option<VerdictName>,
95 pub change: Change,
97 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
100 pub before_passed_by_verus_totals: bool,
101 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104 pub after_passed_by_verus_totals: bool,
105 pub obligations: Vec<ObligationDifference>,
107}
108
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct ObligationDifference {
112 pub id: String,
114 pub before: Option<OutcomeName>,
116 pub after: Option<OutcomeName>,
118 pub advisory: bool,
120 pub change: Change,
122}
123
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126pub struct Comparison {
127 pub version: u32,
129 pub compatible: bool,
131 pub before_revision: String,
133 pub after_revision: String,
135 pub after_currentness: Currentness,
137 pub differences: Vec<Difference>,
139 pub notes: Vec<String>,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
146pub enum Reference {
147 Job(String),
149 Baseline(String),
151}
152
153pub fn explain(
158 result: &ProjectResult,
159 target: &Target,
160 function: &str,
161 obligation: Option<&str>,
162) -> Result<Explanation, String> {
163 let matches: Vec<_> = result
164 .targets
165 .iter()
166 .filter(|t| {
167 t.package_id == target.package_id && t.target == target.name && t.kind == target.kind
168 })
169 .collect();
170 if matches.len() != 1 {
171 return Err("SAIL0904: exact target is missing or ambiguous".into());
172 }
173 let selected = matches[0];
174 let functions: Vec<_> = selected
175 .report
176 .crates
177 .iter()
178 .flat_map(|c| &c.functions)
179 .filter(|f| f.function == function)
180 .collect();
181 if functions.len() != 1 {
182 return Err("SAIL0904: exact function is missing or ambiguous".into());
183 }
184 let mut report = functions[0].clone();
185 if let Some(id) = obligation {
186 let Some(obligations) = report.obligations.as_mut() else {
187 return Err("SAIL0904: obligation attribution is unavailable".into());
188 };
189 if !obligations.iter().any(|o| o.id == id) {
190 return Err("SAIL0904: exact obligation was not observed".into());
191 }
192 obligations.retain(|o| o.id == id);
193 }
194 Ok(Explanation {
195 version: VERSION, target: target.clone(), establishing_run: selected.establishing_run.clone(),
196 currentness: result.currentness, function: report, attributed_diagnostics: Vec::new(),
197 run_diagnostics: selected.report.diagnostics.clone(), diagnostic_attribution_complete: false,
198 notes: vec!["Run diagnostics are retained; no line-window heuristic establishes their function ownership.".into()],
199 })
200}
201
202#[derive(Debug, Clone, Copy)]
204struct Entry<'a> {
205 report: &'a FunctionReport,
206 by_totals: bool,
209}
210
211impl Entry<'_> {
212 fn verdict(self) -> VerdictName {
214 effective(self.report)
215 }
216
217 fn class(self) -> VerdictName {
221 if self.by_totals {
222 VerdictName::Verified
223 } else {
224 self.verdict()
225 }
226 }
227}
228
229type Records<'a> = std::collections::BTreeMap<(Target, String), Vec<Entry<'a>>>;
230
231fn functions(result: &ProjectResult) -> Records<'_> {
232 let mut records = Records::new();
233 for target in result.targets.iter().filter(|target| target.requested) {
234 let id = Target {
235 package_id: target.package_id.clone(),
236 name: target.target.clone(),
237 kind: target.kind.clone(),
238 };
239 for krate in &target.report.crates {
240 let cleared = krate.verus_totals_clear_unknown();
241 for function in &krate.functions {
242 records
243 .entry((id.clone(), function.function.clone()))
244 .or_default()
245 .push(Entry {
246 report: function,
247 by_totals: cleared && effective(function) == VerdictName::Unknown,
248 });
249 }
250 }
251 }
252 records
253}
254
255fn unique<'a>(entries: &[Entry<'a>]) -> Option<&'a FunctionReport> {
256 match entries {
257 [only] => Some(only.report),
258 _ => None,
259 }
260}
261
262#[derive(Debug, Default, Clone, Copy)]
264struct Side {
265 verdict: Option<VerdictName>,
267 class: Option<VerdictName>,
269 by_totals: bool,
271}
272
273fn side(entries: &[Entry<'_>]) -> Option<Side> {
275 let Some(first) = entries.first() else {
276 return Some(Side::default());
277 };
278 entries
279 .iter()
280 .all(|e| e.class() == first.class())
281 .then(|| Side {
282 verdict: entries
283 .iter()
284 .all(|e| e.verdict() == first.verdict())
285 .then(|| first.verdict()),
286 class: Some(first.class()),
287 by_totals: entries.iter().any(|e| e.by_totals),
288 })
289}
290
291fn resolve(left: &[Entry<'_>], right: &[Entry<'_>]) -> Option<(Side, Side)> {
297 let repeated = left.len() > 1 || right.len() > 1;
298 if repeated && left.len() != right.len() {
299 return None;
300 }
301 Some((side(left)?, side(right)?))
302}
303
304fn classify(before: Option<VerdictName>, after: Option<VerdictName>, removed: bool) -> Change {
306 match (before, after) {
307 (Some(a), Some(b)) if a == b => Change::Unchanged,
308 (Some(VerdictName::Verified), Some(VerdictName::Failed)) => Change::Regressed,
309 (Some(VerdictName::Verified), Some(VerdictName::Unknown | VerdictName::Provisional)) => {
310 Change::BecameUnknown
311 }
312 (Some(_), Some(VerdictName::Verified)) => Change::Recovered,
313 (None, Some(_)) => Change::Added,
314 (Some(_), None) if removed => Change::Removed,
315 (Some(_), None) => Change::NotObserved,
316 _ => Change::Changed,
317 }
318}
319
320fn scopes(result: &ProjectResult) -> Vec<(Target, String, Vec<String>)> {
321 let mut scopes: Vec<_> = result
322 .targets
323 .iter()
324 .filter(|t| t.requested)
325 .map(|target| {
326 (
327 Target {
328 package_id: target.package_id.clone(),
329 name: target.target.clone(),
330 kind: target.kind.clone(),
331 },
332 target.report.mode.clone(),
333 target.report.command.clone(),
334 )
335 })
336 .collect();
337 scopes.sort();
338 scopes
339}
340
341#[derive(Debug, Default)]
343struct Tally {
344 by_totals: usize,
346 repeated_compared: usize,
348 repeated_functions: usize,
350 repeated_incomparable: usize,
352}
353
354#[must_use]
364pub fn compare(before: &ProjectResult, after: &ProjectResult) -> Comparison {
365 let compatible = before.no_reuse.is_none()
366 && after.no_reuse.is_none()
367 && !before.context_sha256.is_empty()
368 && before.context_sha256 == after.context_sha256
369 && scopes(before) == scopes(after);
370 let after_project = after;
371 let left = functions(before);
372 let right = functions(after);
373 let ids: std::collections::BTreeSet<_> = left.keys().chain(right.keys()).cloned().collect();
374 let mut tally = Tally::default();
375 let differences = ids
376 .into_iter()
377 .map(|(target, function)| {
378 let key = (target.clone(), function.clone());
379 let l = left.get(&key).map_or(&[][..], Vec::as_slice);
380 let r = right.get(&key).map_or(&[][..], Vec::as_slice);
381 let repeated = l.len() > 1 || r.len() > 1;
382 let resolved = resolve(l, r);
383 if repeated && resolved.is_some() {
384 tally.repeated_compared += 1;
385 tally.repeated_functions += l.len().max(r.len());
386 } else if repeated {
387 tally.repeated_incomparable += 1;
388 }
389 let (old, new) = resolved.unwrap_or_default();
390 let change = if compatible && resolved.is_some() {
391 classify(old.class, new.class, inventory(after_project, &target))
392 } else {
393 Change::Incomparable
394 };
395 let classified = change != Change::Incomparable;
396 if classified {
397 let count = |entries: &[Entry<'_>]| entries.iter().filter(|e| e.by_totals).count();
398 tally.by_totals += count(l).max(count(r));
399 }
400 Difference {
401 target,
402 function,
403 before: old.verdict,
404 after: new.verdict,
405 change,
406 before_passed_by_verus_totals: classified && old.by_totals,
407 after_passed_by_verus_totals: classified && new.by_totals,
408 obligations: if repeated {
409 Vec::new()
410 } else {
411 obligations(unique(l), unique(r), compatible)
412 },
413 }
414 })
415 .collect();
416 Comparison {
417 version: VERSION,
418 compatible,
419 before_revision: before.input_revision.clone(),
420 after_revision: after.input_revision.clone(),
421 after_currentness: after.currentness,
422 differences,
423 notes: comparison_notes(compatible, &tally),
424 }
425}
426
427fn comparison_notes(compatible: bool, tally: &Tally) -> Vec<String> {
428 let mut notes = Vec::new();
429 if !compatible {
430 notes.push("Requested scope, mode or runtime context differs; transitions are descriptive, not proof regressions.".into());
431 }
432 if tally.by_totals > 0 {
433 notes.push(format!(
434 "{} 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`.",
435 tally.by_totals
436 ));
437 }
438 if tally.repeated_compared > 0 {
439 notes.push(format!(
440 "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.",
441 tally.repeated_compared, tally.repeated_functions
442 ));
443 }
444 if tally.repeated_incomparable > 0 {
445 notes.push(format!(
446 "Repeated friendly function names cannot identify one implementation; {} such name(s) whose functions differ in result or number are incomparable (VI-0010).",
447 tally.repeated_incomparable
448 ));
449 }
450 notes
451}
452
453fn effective(report: &FunctionReport) -> VerdictName {
454 if report.establishment == crate::output::EstablishmentName::Provisional {
455 VerdictName::Provisional
456 } else {
457 report.verdict
458 }
459}
460
461fn inventory(project: &ProjectResult, id: &Target) -> bool {
462 project.error.is_none()
463 && project.exit_code == Some(0)
464 && project.targets.iter().any(|target| {
465 crate::acceptance::complete_target(target).is_some()
466 && target.package_id == id.package_id
467 && target.target == id.name
468 && target.kind == id.kind
469 && target.report.crates.iter().all(|report| {
470 report.verus.success == Some(true)
471 && report.verus.encountered_vir_error != Some(true)
472 })
473 })
474}
475
476fn obligations(
477 before: Option<&FunctionReport>,
478 after: Option<&FunctionReport>,
479 compatible: bool,
480) -> Vec<ObligationDifference> {
481 let index = |function: Option<&FunctionReport>| {
482 function
483 .and_then(|f| f.obligations.as_ref())
484 .into_iter()
485 .flatten()
486 .map(|obligation| (obligation.id.clone(), obligation.clone()))
487 .collect::<std::collections::BTreeMap<_, _>>()
488 };
489 let left = index(before);
490 let right = index(after);
491 left.keys()
492 .chain(right.keys())
493 .cloned()
494 .collect::<std::collections::BTreeSet<_>>()
495 .into_iter()
496 .map(|id| {
497 let old = left.get(&id);
498 let new = right.get(&id);
499 let before = old.map(|o| o.outcome);
500 let after = new.map(|o| o.outcome);
501 let advisory = new.or(old).is_some_and(|o| o.advisory);
502 let change = if compatible {
503 match (before, after) {
504 (Some(a), Some(b)) if a == b => Change::Unchanged,
505 (Some(OutcomeName::Proved), Some(OutcomeName::Failed)) if !advisory => {
506 Change::Regressed
507 }
508 (Some(OutcomeName::Proved), Some(OutcomeName::Unknown)) => {
509 Change::BecameUnknown
510 }
511 (Some(_), Some(OutcomeName::Proved)) => Change::Recovered,
512 (None, Some(_)) => Change::Added,
513 (Some(_), None) => Change::NotObserved,
514 _ => Change::Changed,
515 }
516 } else {
517 Change::Incomparable
518 };
519 ObligationDifference {
520 id,
521 before,
522 after,
523 advisory,
524 change,
525 }
526 })
527 .collect()
528}