1use serde::{Deserialize, Serialize};
3
4pub const VERSION: u32 = 1;
6pub const POLICY: &str = "neutral-free-scalar-literals-v1";
8pub const MAX_MUTANTS: usize = 8;
10pub const MAX_WALL_TIME_MS: u64 = 2_700_000;
12
13#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(deny_unknown_fields)]
16pub struct Submission {
17 pub baseline_job_id: String,
19 pub max_mutants: usize,
21 pub wall_time_ms: u64,
23}
24
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Candidate {
28 pub id: String,
30 pub function: String,
32 pub requirement_id: String,
34 pub guarantee_sha256: String,
36 pub replacement: String,
38 pub body_start: usize,
40 pub body_end: usize,
42 pub source: crate::contracts::Submission,
44}
45
46#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Plan {
49 pub version: u32,
51 pub policy: String,
53 pub baseline_source_sha256: String,
55 pub candidates: Vec<Candidate>,
57 pub unsupported: Vec<String>,
59 pub omitted: usize,
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "kebab-case")]
66pub enum Outcome {
67 Killed,
69 Survived,
71 Inconclusive,
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
77#[serde(rename_all = "kebab-case")]
78pub enum State {
79 Running,
81 Completed,
83 Cancelled,
85 TimedOut,
87 Interrupted,
89}
90
91#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
94pub struct OriginalEvidence {
95 pub source: crate::contracts::Submission,
97 pub worker_stdout: String,
99 pub worker_stderr: String,
101}
102
103#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Observation {
106 pub candidate: Candidate,
108 pub job_id: String,
110 pub evidence_name: Option<String>,
112 pub backend_sha256: Option<String>,
114 pub original: Option<OriginalEvidence>,
116 pub outcome: Outcome,
118 pub reason: String,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124pub struct View {
125 pub version: u32,
127 pub id: String,
129 pub started_at_ms: u64,
131 pub baseline_original: OriginalEvidence,
133 pub submission: Submission,
135 pub baseline_source: crate::contracts::Submission,
137 pub baseline_evidence_name: String,
139 pub baseline_backend_sha256: String,
141 pub plan: Plan,
143 pub state: State,
145 pub observations: Vec<Observation>,
147 pub passed: bool,
149 pub qualifiers: Vec<String>,
151}
152
153#[must_use]
155pub fn qualifiers() -> Vec<String> {
156 vec!["bounded free scalar literal-body mutation policy; unsupported and omitted targets remain explicit".into(),"killed means authenticated conclusive SAT verifier rejection, not a concrete source counterexample".into(),"neutral translation, source admission and pinned verifier/solver remain trusted; proof verdict and tier are unchanged".into()]
157}
158
159#[must_use]
161pub fn digest(bytes: &[u8]) -> String {
162 sail_key::QueryKey(sail_key::sha256(bytes)).to_string()
163}
164
165#[must_use]
169#[allow(
170 clippy::too_many_lines,
171 reason = "One conservative decision keeps identity admission and conclusive rejection conditions together."
172)]
173pub fn classify(
174 baseline: &crate::contracts::WorkerResult,
175 mutant: &crate::contracts::WorkerResult,
176 candidate: &Candidate,
177) -> (Outcome, String) {
178 use crate::contracts::ProofState;
179 use crate::output::{
180 AnswerName, AttributionStatus, EstablishmentName, OutcomeName, VerdictName,
181 };
182 let inconclusive = |message: &str| (Outcome::Inconclusive, message.to_owned());
183 let identities = |result: &crate::contracts::WorkerResult| -> Option<Vec<String>> {
184 let mut values = Vec::new();
185 for target in &result.backend.targets {
186 let solver = target.report.solver.as_ref()?;
187 if solver.name.is_empty()
188 || solver.version.as_ref().is_none_or(String::is_empty)
189 || solver.sha256.as_ref().is_none_or(|s| {
190 s.len() != 64
191 || !s
192 .bytes()
193 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
194 })
195 {
196 return None;
197 }
198 values.push(serde_json::to_string(solver).ok()?);
199 }
200 values.sort();
201 values.dedup();
202 (!values.is_empty()).then_some(values)
203 };
204 let contract_keys = |result: &crate::contracts::WorkerResult| {
205 result
206 .contracts
207 .manifest
208 .bindings
209 .iter()
210 .map(|b| {
211 (
212 b.function.clone(),
213 b.requirement_id.clone(),
214 b.guarantee_sha256.clone(),
215 b.lowered_function.clone(),
216 )
217 })
218 .collect::<Vec<_>>()
219 };
220 if baseline.version != crate::contracts::VERSION
221 || mutant.version != crate::contracts::VERSION
222 || baseline.contracts.proof.state != ProofState::Proved
223 || baseline.contracts.manifest.contract_version
224 != mutant.contracts.manifest.contract_version
225 || mutant.contracts.manifest.contract_version != candidate.source.profile
226 || mutant.contracts.manifest.original_sha256 != candidate.source.source_sha256
227 || contract_keys(baseline) != contract_keys(mutant)
228 || baseline.contracts.translation_trust.source_policy_sha256
229 != mutant.contracts.translation_trust.source_policy_sha256
230 || identities(baseline).is_none()
231 || identities(baseline) != identities(mutant)
232 || baseline.backend.context_sha256 != mutant.backend.context_sha256
233 || baseline.backend.context_sha256.len() != 64
234 || baseline.contracts.proof
235 != crate::assurance::observed_contract_proof(
236 &baseline.contracts.manifest,
237 &baseline.backend,
238 )
239 || mutant.contracts.proof
240 != crate::assurance::observed_contract_proof(
241 &mutant.contracts.manifest,
242 &mutant.backend,
243 )
244 {
245 return inconclusive(
246 "baseline, source, contract, tool identity or original proof projection differs",
247 );
248 }
249 let Some(binding) = mutant.contracts.manifest.bindings.iter().find(|b| {
250 b.function == candidate.function
251 && b.requirement_id == candidate.requirement_id
252 && b.guarantee_sha256 == candidate.guarantee_sha256
253 }) else {
254 return inconclusive("target guarantee is not exactly bound");
255 };
256 if mutant.contracts.proof.state == ProofState::Proved {
257 return (
258 Outcome::Survived,
259 "complete original mutant proof under unchanged contract".into(),
260 );
261 }
262 let backend = &mutant.backend;
263 let counts = &mutant.contracts.proof.checks;
264 if backend.currentness != crate::project::Currentness::Current
265 || backend.error.is_some()
266 || backend.no_reuse.is_some()
267 || !matches!(backend.exit_code, Some(1 | 101))
268 || counts.unknown != 0
269 || counts.missing_answer != 0
270 || counts.missing_source != 0
271 || !backend.targets.iter().all(|t| {
272 admitted_target_completion(t)
273 && t.report.attribution.status == AttributionStatus::Complete
274 && t.report.attribution.unmatched_sessions == 0
275 && t.report.error.is_none()
276 && t.report.invariant_violations().is_empty()
277 && t.report.crates.iter().flat_map(|c| &c.functions).all(|f| {
278 !f.unstable
279 && f.provenance.checks_unrecorded == 0
280 && f.obligations
281 .as_ref()
282 .is_none_or(|os| os.iter().all(|o| !o.unstable))
283 })
284 && t.report
285 .crates
286 .iter()
287 .all(|c| c.verus.encountered_vir_error == Some(false))
288 })
289 {
290 return inconclusive(
291 "unknown, missing, frontend, currentness or attribution evidence prevents a kill",
292 );
293 }
294 if mutant
295 .contracts
296 .manifest
297 .bindings
298 .iter()
299 .filter(|b| b.function != candidate.function)
300 .any(|b| {
301 !mutant
302 .contracts
303 .proof
304 .proved_functions
305 .contains(&b.lowered_function)
306 })
307 {
308 return inconclusive("an unchanged non-target function lacks its complete proof");
309 }
310 let functions = backend
311 .targets
312 .iter()
313 .filter(|t| t.requested && t.report.exit_code == Some(1) && !t.complete)
314 .flat_map(|t| &t.report.crates)
315 .filter(|c| c.verus.success == Some(false) && c.verus.errors.is_some_and(|n| n > 0))
316 .flat_map(|c| &c.functions)
317 .filter(|f| f.function == binding.lowered_function)
318 .collect::<Vec<_>>();
319 let [function] = functions.as_slice() else {
320 return inconclusive("target function attribution is absent or ambiguous");
321 };
322 if function.verdict != VerdictName::Failed
323 || function.establishment != EstablishmentName::Confirmed
324 || function.unstable
325 || function.verus_success != Some(false)
326 || function.provenance.checks_unrecorded != 0
327 {
328 return inconclusive("target has no confirmed stable verifier failure");
329 }
330 let Some(obligations) = &function.obligations else {
331 return inconclusive("target obligations are missing");
332 };
333 let primary = obligations
334 .iter()
335 .filter(|o| !o.advisory)
336 .collect::<Vec<_>>();
337 if primary.is_empty()
338 || primary.iter().any(|o| {
339 o.unstable
340 || o.checks.is_empty()
341 || o.checks.iter().any(|c| {
342 c.source.is_none()
343 || c.reason_unknown.is_some()
344 || !matches!(c.answer, Some(AnswerName::Sat | AnswerName::Unsat))
345 })
346 })
347 {
348 return inconclusive("target checks are unknown, missing or unstable");
349 }
350 if primary.iter().any(|o| {
351 o.outcome == OutcomeName::Failed
352 && o.checks.iter().any(|c| c.answer == Some(AnswerName::Sat))
353 }) {
354 return (Outcome::Killed, "actual fully attributed SAT verifier rejection under the unchanged admitted contract; not a concrete source counterexample".into());
355 }
356 inconclusive("NotProved without an attributed conclusive SAT rejection is not killed")
357}
358
359fn admitted_target_completion(target: &crate::project::TargetResult) -> bool {
364 let report = &target.report;
365 if target.scope_reuse.is_some()
366 || report.crates.is_empty()
367 || report.summary.unknown != 0
368 || report.summary.provisional != 0
369 || report.summary.unstable != 0
370 || !report.crates.iter().all(|c| {
371 c.verus.verified.is_some()
372 && c.verus.errors.is_some()
373 && c.verus.success == c.verus.errors.map(|errors| errors == 0)
374 && c.verus.encountered_vir_error == Some(false)
375 })
376 {
377 return false;
378 }
379 match report.exit_code {
380 Some(0) => target.complete && report.crates.iter().all(|c| c.verus.success == Some(true)),
381 Some(1) => {
382 target.requested
383 && !target.complete
384 && report.crates.iter().any(|c| c.verus.success == Some(false))
385 }
386 _ => false,
387 }
388}
389
390pub fn decode_original(
395 evidence: &OriginalEvidence,
396) -> Result<crate::contracts::WorkerResult, String> {
397 evidence.source.validate()?;
398 if evidence.worker_stdout.len() > crate::contracts::MAX_STDOUT_BYTES
399 || evidence.worker_stderr.len() > crate::contracts::MAX_STDERR_BYTES
400 {
401 return Err("SAIL3144: original mutation stream exceeds retained bound".into());
402 }
403 let result: crate::contracts::WorkerResult = serde_json::from_str(&evidence.worker_stdout)
404 .map_err(|e| format!("SAIL3144: invalid original worker stream: {e}"))?;
405 if result.backend.kind != "sail-project-result"
406 || result.backend.schema_version != crate::project::SCHEMA_VERSION
407 || result.backend.error.is_some()
408 || result.backend.no_reuse.is_some()
409 || result.version != crate::contracts::VERSION
410 || result.contracts.version != crate::contracts::VERSION
411 || result.contracts.manifest.contract_version != evidence.source.profile
412 || result.contracts.manifest.original_sha256 != evidence.source.source_sha256
413 || result.contracts.manifest.crate_name != evidence.source.crate_name
414 || result.contracts.proof
415 != crate::assurance::observed_contract_proof(
416 &result.contracts.manifest,
417 &result.backend,
418 )
419 {
420 return Err("SAIL3144: original mutation worker source or proof projection differs".into());
421 }
422 Ok(result)
423}
424fn encoded_digest(value: &impl Serialize) -> Result<String, String> {
425 serde_json::to_vec(value)
426 .map(|b| digest(&b))
427 .map_err(|e| format!("SAIL3144: mutation encoding: {e}"))
428}
429fn invalid() -> String {
430 "SAIL3144: retained mutation evidence or derived view differs".into()
431}
432
433#[allow(
440 clippy::too_many_lines,
441 reason = "One bounded receipt validation keeps the original record identity, every member, and aggregate gate together."
442)]
443pub fn validate_view(view: &View) -> Result<(), String> {
444 #[derive(Serialize)]
445 struct Record<'a> {
446 version: u32,
447 submission: &'a Submission,
448 plan: &'a Plan,
449 jobs: Vec<&'a str>,
450 started_at_ms: u64,
451 }
452 let mut export_bytes = serde_json::to_vec(&view.baseline_original)
453 .map_err(|_| invalid())?
454 .len();
455 for original in view.observations.iter().filter_map(|o| o.original.as_ref()) {
456 export_bytes = export_bytes
457 .checked_add(serde_json::to_vec(original).map_err(|_| invalid())?.len())
458 .ok_or_else(invalid)?;
459 if export_bytes > crate::jobs::MAX_FRAME / 2 {
460 return Err(invalid());
461 }
462 }
463 if export_bytes > crate::jobs::MAX_FRAME / 2
464 || view.qualifiers != qualifiers()
465 || view.version != VERSION
466 || view.plan.version != VERSION
467 || view.plan.policy != POLICY
468 || !(1..=MAX_MUTANTS).contains(&view.submission.max_mutants)
469 || view.submission.wall_time_ms == 0
470 || view.submission.wall_time_ms > MAX_WALL_TIME_MS
471 || view.plan.candidates.len() > view.submission.max_mutants
472 || view.plan.candidates.len() != view.observations.len()
473 || view.baseline_source != view.baseline_original.source
474 || view.plan.baseline_source_sha256 != view.baseline_source.source_sha256
475 || !view.plan.unsupported.windows(2).all(|w| w[0] < w[1])
476 {
477 return Err(invalid());
478 }
479 let record = Record {
480 version: VERSION,
481 submission: &view.submission,
482 plan: &view.plan,
483 jobs: view
484 .observations
485 .iter()
486 .map(|o| o.job_id.as_str())
487 .collect(),
488 started_at_ms: view.started_at_ms,
489 };
490 if encoded_digest(&record)? != view.id
491 || view.baseline_evidence_name != format!("m-{}-b", view.id)
492 {
493 return Err(invalid());
494 }
495 let baseline = decode_original(&view.baseline_original)?;
496 if encoded_digest(&baseline.backend)? != view.baseline_backend_sha256 {
497 return Err(invalid());
498 }
499 let Some(binding) = baseline.contracts.manifest.bindings.first() else {
500 return Err(invalid());
501 };
502 let baseline_candidate = Candidate {
503 id: String::new(),
504 function: binding.function.clone(),
505 requirement_id: binding.requirement_id.clone(),
506 guarantee_sha256: binding.guarantee_sha256.clone(),
507 replacement: String::new(),
508 body_start: 0,
509 body_end: 0,
510 source: view.baseline_source.clone(),
511 };
512 if classify(&baseline, &baseline, &baseline_candidate).0 != Outcome::Survived {
513 return Err(invalid());
514 }
515 let mut identities = std::collections::BTreeSet::new();
516 for (index, (candidate, observation)) in view
517 .plan
518 .candidates
519 .iter()
520 .zip(&view.observations)
521 .enumerate()
522 {
523 if candidate != &observation.candidate
524 || !identities.insert(&candidate.id)
525 || candidate.id
526 != digest(
527 format!(
528 "{POLICY}:{}:{}:{}",
529 view.baseline_source.source_sha256,
530 candidate.function,
531 candidate.replacement
532 )
533 .as_bytes(),
534 )
535 || !matches!(candidate.replacement.as_str(), "false" | "true" | "0" | "1")
536 || candidate.body_start >= candidate.body_end
537 || !view
538 .baseline_source
539 .source
540 .is_char_boundary(candidate.body_start)
541 || !view
542 .baseline_source
543 .source
544 .is_char_boundary(candidate.body_end)
545 || candidate.body_end > view.baseline_source.source.len()
546 || !baseline.contracts.manifest.bindings.iter().any(|b| {
547 b.function == candidate.function
548 && b.requirement_id == candidate.requirement_id
549 && b.guarantee_sha256 == candidate.guarantee_sha256
550 })
551 {
552 return Err(invalid());
553 }
554 let mut expected = view.baseline_source.source.clone();
555 expected.replace_range(
556 candidate.body_start..candidate.body_end,
557 &format!("{{ {} }}", candidate.replacement),
558 );
559 if expected != candidate.source.source
560 || candidate.source.crate_name != view.baseline_source.crate_name
561 || expected == view.baseline_source.source
562 {
563 return Err(invalid());
564 }
565 candidate.source.validate()?;
566 if let Some(original) = &observation.original {
567 if original.source != candidate.source
568 || observation.evidence_name != Some(format!("m-{}-{index}", view.id))
569 {
570 return Err(invalid());
571 }
572 let mutant = decode_original(original)?;
573 if observation.backend_sha256 != Some(encoded_digest(&mutant.backend)?)
574 || classify(&baseline, &mutant, candidate)
575 != (observation.outcome, observation.reason.clone())
576 {
577 return Err(invalid());
578 }
579 } else if observation.evidence_name.is_some()
580 || observation.backend_sha256.is_some()
581 || observation.outcome != Outcome::Inconclusive
582 || observation.reason != "actual source job has no retained conclusive evidence"
583 {
584 return Err(invalid());
585 }
586 }
587 let passed = view.state == State::Completed
588 && !view.observations.is_empty()
589 && view.plan.unsupported.is_empty()
590 && view.plan.omitted == 0
591 && view
592 .observations
593 .iter()
594 .all(|o| o.outcome == Outcome::Killed);
595 if passed != view.passed {
596 return Err(invalid());
597 }
598 Ok(())
599}
600
601pub fn attach_assurance(
606 campaign: &View,
607 assurance: &mut crate::assurance::View,
608) -> Result<(), String> {
609 validate_view(campaign)?;
610 if assurance.version != crate::assurance::VERSION
611 || assurance.job_id != campaign.submission.baseline_job_id
612 {
613 return Err(invalid());
614 }
615 for requirement in &mut assurance.requirements {
616 for evidence in &mut requirement.evidence {
617 if evidence.source_sha256 != campaign.plan.baseline_source_sha256
618 || evidence.backend_sha256 != campaign.baseline_backend_sha256
619 {
620 return Err(invalid());
621 }
622 let observations = campaign
623 .observations
624 .iter()
625 .filter(|o| {
626 o.candidate.function == evidence.function
627 && o.candidate.requirement_id == requirement.requirement_id
628 && o.candidate.guarantee_sha256 == evidence.guarantee_sha256
629 })
630 .collect::<Vec<_>>();
631 if !observations.is_empty() {
632 evidence.mutation = crate::assurance::MutationStatus::Bounded {
633 campaign_id: campaign.id.clone(),
634 policy: campaign.plan.policy.clone(),
635 passed: campaign.passed,
636 killed: observations
637 .iter()
638 .filter(|o| o.outcome == Outcome::Killed)
639 .count(),
640 survived: observations
641 .iter()
642 .filter(|o| o.outcome == Outcome::Survived)
643 .count(),
644 inconclusive: observations
645 .iter()
646 .filter(|o| o.outcome == Outcome::Inconclusive)
647 .count(),
648 };
649 }
650 }
651 }
652 Ok(())
653}