use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Verdict {
Matched,
Diverged,
NoResult,
InfrastructureError,
}
impl std::fmt::Display for Verdict {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Matched => "matched",
Self::Diverged => "diverged",
Self::NoResult => "no_result",
Self::InfrastructureError => "infrastructure_error",
})
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum NoResultReason {
NotRun,
FirstRunRejected {
exit_code: Option<i32>,
signal: Option<i32>,
stdout_bytes: u64,
stderr_bytes: u64,
},
ComparisonRefused { detail: String },
ContainerFailed(ContainerFailure),
RunFailed {
run: VerificationRun,
failure: RunFailure,
detail: String,
},
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RunFailure {
BackendFailure,
DeterminismLoss,
PolicyRefusal,
Deadlock,
}
impl RunFailure {
pub fn as_str(self) -> &'static str {
match self {
Self::BackendFailure => "backend_failure",
Self::DeterminismLoss => "determinism_loss",
Self::PolicyRefusal => "policy_refusal",
Self::Deadlock => "deadlock",
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum VerificationRun {
Run1,
Run2,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
pub enum ContainerDisposition {
Exited {
code: i32,
},
Signaled {
signal: i32,
core_dumped: bool,
},
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ContainerFailure {
pub run: VerificationRun,
pub disposition: ContainerDisposition,
}
impl ContainerFailure {
pub fn require_reporter_exit(
&self,
status: Option<i32>,
signal: Option<i32>,
timed_out: bool,
) -> Result<(), String> {
if status == Some(125) && signal.is_none() && !timed_out {
Ok(())
} else {
Err(format!(
"container_failed contradicts Hermit process disposition: status={status:?} signal={signal:?} timed_out={timed_out} (expected exit 125 without timeout)"
))
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum InfrastructureError {
SkidOvershoot { count: u64 },
HostInputChanged {
run: VerificationRun,
path: String,
before: detcore_model::host_input::HostFileIdentity,
after: detcore_model::host_input::HostFileIdentity,
},
}
impl std::fmt::Display for InfrastructureError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SkidOvershoot { count } => {
write!(f, "{count} precise-timer skid overshoot(s)")
}
Self::HostInputChanged {
run,
path,
before,
after,
} => write!(
f,
"host input changed during run {}: {path} ({before} -> {after})",
match run {
VerificationRun::Run1 => 1,
VerificationRun::Run2 => 2,
}
),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RuntimeStats {
pub scheduler_turns: u64,
pub virtual_nanoseconds: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub syscalls: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dispatch: Option<detcore_model::summary::DispatchStats>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct VerificationRuntime {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run1: Option<RuntimeStats>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub run2: Option<RuntimeStats>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct DbtCountedBranchComparison {
pub left: u64,
pub right: u64,
}
impl DbtCountedBranchComparison {
#[allow(dead_code)] pub fn matched(self) -> bool {
self.left == self.right
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LogCompareStrictness {
Stripped,
Canonical,
}
impl std::fmt::Display for LogCompareStrictness {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
Self::Stripped => "stripped",
Self::Canonical => "canonical",
})
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ComparedLogScope {
Deterministic,
Info,
FullTrace,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordEnvelopeReport {
AllRecordsV1,
DbtEvidenceTransportV1,
CrossBackendDetcoreV1,
CallerDefined,
}
impl RecordEnvelopeReport {
pub fn is_canonical(self) -> bool {
matches!(self, Self::AllRecordsV1 | Self::DbtEvidenceTransportV1)
}
pub fn as_str(self) -> &'static str {
match self {
Self::AllRecordsV1 => "all_records_v1",
Self::DbtEvidenceTransportV1 => "dbt_evidence_transport_v1",
Self::CrossBackendDetcoreV1 => "cross_backend_detcore_v1",
Self::CallerDefined => "caller_defined",
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ComparisonReport {
pub strictness: LogCompareStrictness,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
pub compare_logs: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compare_io_buffers: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub log_scope: Option<ComparedLogScope>,
pub record_envelope: RecordEnvelopeReport,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub virtualize_time: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strip_lines: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonicalize_addresses: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub full_trace: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exact_remainder: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stripped_prefixes: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub canonicalizations: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ignore_lines: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_commit: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skip_detlog: Option<bool>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ComparedLogMessages {
pub left: u64,
pub right: u64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComparedOutput {
pub exit_code: Option<i32>,
pub signal: Option<i32>,
pub stdout_sha256: String,
pub stdout_bytes: u64,
pub stderr_sha256: String,
pub stderr_bytes: u64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ComparedOutputs {
pub left: ComparedOutput,
pub right: ComparedOutput,
}
impl ComparedOutputs {
pub fn require_exact_match(&self) -> Result<(), String> {
if self.left == self.right {
Ok(())
} else {
Err("verification operands differ in status, stdout, or stderr".into())
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct VerificationReport {
pub verified: bool,
pub bitwise_parity: bool,
pub verdict: Verdict,
#[serde(default)]
pub no_result_reason: Option<NoResultReason>,
#[serde(default)]
pub infrastructure_error: Option<InfrastructureError>,
#[serde(deserialize_with = "present_but_nullable_comparison")]
pub comparison: Option<ComparisonReport>,
pub compared_log_messages: Option<ComparedLogMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compared_outputs: Option<ComparedOutputs>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dbt_counted_branches: Option<DbtCountedBranchComparison>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub runtime: Option<VerificationRuntime>,
#[serde(default)]
pub guest_exit_code: Option<i32>,
#[serde(default)]
pub guest_signal: Option<i32>,
#[serde(default)]
pub first_divergent_scheduler_turn: Option<u64>,
#[serde(default)]
pub first_divergent_virtual_nanoseconds: Option<u64>,
#[serde(default)]
pub first_divergent_record: Option<u64>,
#[serde(default)]
pub first_divergent_syscall: Option<u64>,
#[serde(default)]
pub first_divergent_left_message: Option<String>,
#[serde(default)]
pub first_divergent_right_message: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exact_branch_counter: Option<BranchCounterVerdict>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct BranchCounterVerdict {
pub present: bool,
pub evidence: String,
}
fn present_but_nullable_comparison<'de, D>(
deserializer: D,
) -> Result<Option<ComparisonReport>, D::Error>
where
D: serde::Deserializer<'de>,
{
Option::<ComparisonReport>::deserialize(deserializer)
}
impl VerificationReport {
#[allow(dead_code)] pub fn no_result() -> Self {
Self {
verified: false,
bitwise_parity: false,
verdict: Verdict::NoResult,
no_result_reason: Some(NoResultReason::NotRun),
infrastructure_error: None,
comparison: None,
compared_log_messages: None,
compared_outputs: None,
dbt_counted_branches: None,
runtime: None,
guest_exit_code: None,
guest_signal: None,
first_divergent_scheduler_turn: None,
first_divergent_virtual_nanoseconds: None,
first_divergent_record: None,
first_divergent_syscall: None,
first_divergent_left_message: None,
first_divergent_right_message: None,
exact_branch_counter: None,
}
}
fn require_consistent_outcome_fields(self) -> Result<Self, String> {
if let Some(NoResultReason::RunFailed { detail, .. }) = &self.no_result_reason {
if detail.trim().is_empty() {
return Err("incomplete verification report: run_failed omitted its detail".into());
}
if self.verdict != Verdict::NoResult
|| self.verified
|| self.bitwise_parity
|| self.infrastructure_error.is_some()
|| self.comparison.is_some()
|| self.compared_log_messages.is_some()
|| self.compared_outputs.is_some()
|| self.dbt_counted_branches.is_some()
|| self.runtime.is_some()
|| self.guest_exit_code.is_some()
|| self.guest_signal.is_some()
|| self.first_divergent_scheduler_turn.is_some()
|| self.first_divergent_virtual_nanoseconds.is_some()
|| self.first_divergent_record.is_some()
|| self.first_divergent_syscall.is_some()
|| self.first_divergent_left_message.is_some()
|| self.first_divergent_right_message.is_some()
{
return Err(
"run_failed contradicts its no-comparison, unknown-guest outcome".into(),
);
}
}
if let Some(NoResultReason::ContainerFailed(failure)) = &self.no_result_reason {
let valid_status = match failure.disposition {
ContainerDisposition::Exited { code } => {
const DEADLINE_EXIT: i32 = 124;
(0..=255).contains(&code)
&& code != detcore_model::HERMIT_POLICY_REFUSAL_EXIT
&& code != DEADLINE_EXIT
&& detcore_model::signal_from_exit_status(code).is_none()
}
ContainerDisposition::Signaled { signal, .. } => (1..=64).contains(&signal),
};
if !valid_status {
return Err("invalid container_failed disposition".into());
}
if self.verdict != Verdict::NoResult
|| self.verified
|| self.bitwise_parity
|| self.infrastructure_error.is_some()
|| self.comparison.is_some()
|| self.compared_log_messages.is_some()
|| self.compared_outputs.is_some()
|| self.dbt_counted_branches.is_some()
|| self.runtime.is_some()
|| self.guest_exit_code.is_some()
|| self.guest_signal.is_some()
|| self.first_divergent_scheduler_turn.is_some()
|| self.first_divergent_virtual_nanoseconds.is_some()
|| self.first_divergent_record.is_some()
|| self.first_divergent_syscall.is_some()
|| self.first_divergent_left_message.is_some()
|| self.first_divergent_right_message.is_some()
{
return Err(
"container_failed contradicts its no-comparison, unknown-guest outcome".into(),
);
}
}
if self.comparison.is_none()
&& !matches!(
self.verdict,
Verdict::NoResult | Verdict::InfrastructureError
)
{
return Err(format!(
"incomplete verification report: comparison is null but verdict is {}; null is legal only for no_result or infrastructure_error",
self.verdict
));
}
match (&self.verdict, &self.infrastructure_error) {
(Verdict::InfrastructureError, Some(InfrastructureError::SkidOvershoot { count }))
if *count > 0 => {}
(Verdict::InfrastructureError, Some(InfrastructureError::SkidOvershoot { .. })) => {
return Err(
"incomplete verification report: skid_overshoot count must be positive".into(),
);
}
(Verdict::InfrastructureError, Some(InfrastructureError::HostInputChanged { .. }))
if self.comparison.is_some() => {}
(Verdict::InfrastructureError, Some(InfrastructureError::HostInputChanged { .. })) => {
return Err(
"incomplete verification report: host_input_changed requires the comparison that found the divergence"
.into(),
);
}
(Verdict::InfrastructureError, None) => {
return Err(
"incomplete verification report: infrastructure_error verdict omitted infrastructure_error"
.into(),
);
}
(_, Some(_)) => {
return Err(format!(
"inconsistent verification report: verdict={} carries infrastructure_error",
self.verdict
));
}
(_, None) => {}
}
Ok(self)
}
#[allow(dead_code)] pub fn from_json_slice(bytes: &[u8]) -> Result<Self, String> {
serde_json::from_slice::<Self>(bytes)
.map_err(|error| format!("incomplete verification report: {error}"))?
.require_consistent_outcome_fields()
}
#[allow(dead_code)] pub fn from_json_value(value: serde_json::Value) -> Result<Self, String> {
serde_json::from_value::<Self>(value)
.map_err(|error| format!("incomplete verification report: {error}"))?
.require_consistent_outcome_fields()
}
#[allow(dead_code)] pub fn from_current_json_slice(bytes: &[u8]) -> Result<Self, String> {
let report = Self::from_json_slice(bytes)?;
let value = serde_json::from_slice(bytes)
.map_err(|error| format!("incomplete verification report: {error}"))?;
Self::from_current_json_value(value)?;
Ok(report)
}
#[allow(dead_code)] pub fn from_current_json_value(value: serde_json::Value) -> Result<Self, String> {
Self::from_producer_json_value(value, true)
}
#[allow(dead_code)] pub fn from_retained_cell_json_slice(bytes: &[u8]) -> Result<Self, String> {
let report = Self::from_json_slice(bytes)?;
let value = serde_json::from_slice(bytes)
.map_err(|error| format!("incomplete verification report: {error}"))?;
Self::from_producer_json_value(value, false)?;
Ok(report)
}
fn from_producer_json_value(
value: serde_json::Value,
require_outputs: bool,
) -> Result<Self, String> {
let object = value
.as_object()
.ok_or_else(|| "incomplete verification report: expected an object".to_string())?;
for field in [
"verified",
"bitwise_parity",
"verdict",
"infrastructure_error",
"comparison",
"no_result_reason",
"compared_log_messages",
"guest_exit_code",
"guest_signal",
"first_divergent_scheduler_turn",
"first_divergent_virtual_nanoseconds",
"first_divergent_record",
"first_divergent_syscall",
"first_divergent_left_message",
"first_divergent_right_message",
] {
if !object.contains_key(field) {
return Err(format!(
"incomplete verification report: missing current producer field `{field}`"
));
}
}
let verdict = object.get("verdict").and_then(serde_json::Value::as_str);
if require_outputs
&& matches!(verdict, Some("matched" | "diverged"))
&& object
.get("compared_outputs")
.is_none_or(serde_json::Value::is_null)
{
return Err(
"incomplete verification report: missing current producer field `compared_outputs`"
.into(),
);
}
if let Some(comparison) = object
.get("comparison")
.and_then(serde_json::Value::as_object)
{
for field in [
"strictness",
"display_name",
"compare_logs",
"compare_io_buffers",
"log_scope",
"record_envelope",
"virtualize_time",
"strip_lines",
"canonicalize_addresses",
"full_trace",
"exact_remainder",
"stripped_prefixes",
"canonicalizations",
"ignore_lines",
"skip_commit",
"skip_detlog",
] {
if !comparison.contains_key(field) {
return Err(format!(
"incomplete verification report: missing current comparison field `{field}`"
));
}
}
}
let report = Self::from_json_value(value)?;
if report.verdict == Verdict::Matched && report.compared_outputs.is_some() {
report.require_exact_output_match()?;
}
if report.verdict == Verdict::NoResult && report.compared_outputs.is_some() {
return Err(
"inconsistent verification report: no_result carries compared_outputs".into(),
);
}
match (&report.verdict, &report.no_result_reason) {
(Verdict::NoResult, Some(NoResultReason::ComparisonRefused { detail }))
if detail.trim().is_empty() =>
{
Err("incomplete verification report: comparison_refused omitted its detail".into())
}
(Verdict::NoResult, Some(_)) => Ok(report),
(Verdict::NoResult, None) => Ok(report),
(_, Some(_)) => Err(format!(
"inconsistent verification report: verdict={} carries no_result_reason",
report.verdict
)),
(_, None) => Ok(report),
}
}
pub fn require_canonical_comparison(&self) -> Result<(), String> {
let counts = self.compared_log_messages.as_ref();
let Some(comparison) = self.comparison.as_ref() else {
return Err(format!(
"verification recorded no comparison at all (verdict={}), so there is no canonical INFO evidence to admit",
self.verdict
));
};
if comparison.strictness == LogCompareStrictness::Canonical
&& comparison.compare_logs
&& comparison.record_envelope.is_canonical()
&& counts.is_some_and(|counts| counts.left > 0 && counts.right > 0)
{
Ok(())
} else {
Err(format!(
"verification did not compare canonical non-vacuous INFO evidence: strictness={} compare_logs={} record_envelope={} messages={}/{}",
comparison.strictness,
comparison.compare_logs,
comparison.record_envelope.as_str(),
counts.map_or(0, |counts| counts.left),
counts.map_or(0, |counts| counts.right),
))
}
}
pub fn require_exact_output_match(&self) -> Result<(), String> {
let outputs = self
.compared_outputs
.as_ref()
.ok_or("same-backend verification omitted exact output evidence")?;
outputs.require_exact_match()?;
let output = &outputs.left;
for (field, digest) in [
("stdout_sha256", output.stdout_sha256.as_str()),
("stderr_sha256", output.stderr_sha256.as_str()),
] {
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Err(format!("{field} is not a SHA-256 digest"));
}
}
if output.exit_code.is_some() == output.signal.is_some() {
return Err(
"output must record exactly one guest disposition (exit code or signal)".into(),
);
}
if self.guest_exit_code != output.exit_code || self.guest_signal != output.signal {
return Err("output disposition contradicts its verification result".into());
}
Ok(())
}
pub fn require_canonical_match(&self) -> Result<(), String> {
self.require_canonical_comparison()?;
if self.compared_outputs.is_some() {
self.require_exact_output_match()?;
}
if self.verified && self.verdict == Verdict::Matched && self.bitwise_parity {
Ok(())
} else {
Err(format!(
"canonical verification did not match: verified={} verdict={} bitwise_parity={}",
self.verified, self.verdict, self.bitwise_parity
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_exact_branch_counter_verdict_is_optional_and_strictly_typed() {
let report = VerificationReport::no_result();
let bytes = serde_json::to_vec(&report).unwrap();
let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(value.get("exact_branch_counter").is_none(), "{value}");
assert_eq!(
VerificationReport::from_current_json_slice(&bytes)
.unwrap()
.exact_branch_counter,
None
);
let mut report = VerificationReport::no_result();
report.exact_branch_counter = Some(BranchCounterVerdict {
present: false,
evidence: "fixture CPU: Reverie performance-counter validation failed \
(AmdSpecLockMapShouldBeDisabled)"
.into(),
});
let bytes = serde_json::to_vec(&report).unwrap();
assert_eq!(
VerificationReport::from_current_json_slice(&bytes)
.unwrap()
.exact_branch_counter,
report.exact_branch_counter
);
let mut value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
value["exact_branch_counter"]["measured_counts"] = serde_json::json!(91);
assert!(VerificationReport::from_json_slice(value.to_string().as_bytes()).is_err());
}
fn failed_container_report(
run: VerificationRun,
disposition: ContainerDisposition,
) -> VerificationReport {
let mut report = VerificationReport::no_result();
report.no_result_reason = Some(NoResultReason::ContainerFailed(ContainerFailure {
run,
disposition,
}));
report
}
#[test]
fn run_failure_round_trips_and_names_no_guest_disposition() {
for run in [VerificationRun::Run1, VerificationRun::Run2] {
for failure in [
RunFailure::BackendFailure,
RunFailure::DeterminismLoss,
RunFailure::PolicyRefusal,
RunFailure::Deadlock,
] {
let mut report = VerificationReport::no_result();
report.no_result_reason = Some(NoResultReason::RunFailed {
run,
failure,
detail: "drrun started and the DBT run then failed".into(),
});
let bytes = serde_json::to_vec(&report).unwrap();
let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(value["no_result_reason"]["kind"], "run_failed");
assert_eq!(value["no_result_reason"]["failure"], failure.as_str());
assert_eq!(
VerificationReport::from_current_json_slice(&bytes).unwrap(),
report
);
assert!(report.require_canonical_comparison().is_err());
let mut guest = report.clone();
guest.guest_exit_code = Some(0);
let bytes = serde_json::to_vec(&guest).unwrap();
assert!(VerificationReport::from_current_json_slice(&bytes).is_err());
let mut blank = report.clone();
blank.no_result_reason = Some(NoResultReason::RunFailed {
run,
failure,
detail: " ".into(),
});
let bytes = serde_json::to_vec(&blank).unwrap();
assert!(VerificationReport::from_current_json_slice(&bytes).is_err());
}
}
}
#[test]
fn container_failure_requires_exact_actor_and_absent_comparison_fields() {
for run in [VerificationRun::Run1, VerificationRun::Run2] {
for disposition in [
ContainerDisposition::Exited { code: 0 },
ContainerDisposition::Exited { code: 101 },
ContainerDisposition::Signaled {
signal: 14,
core_dumped: false,
},
ContainerDisposition::Signaled {
signal: 11,
core_dumped: true,
},
] {
let report = failed_container_report(run, disposition);
let bytes = serde_json::to_vec(&report).unwrap();
assert_eq!(
VerificationReport::from_current_json_slice(&bytes).unwrap(),
report
);
assert!(report.require_canonical_comparison().is_err());
assert!(report.require_canonical_match().is_err());
let NoResultReason::ContainerFailed(failure) =
report.no_result_reason.as_ref().unwrap()
else {
unreachable!()
};
failure
.require_reporter_exit(Some(125), None, false)
.unwrap();
for (status, signal, timeout) in [
(Some(0), None, false),
(Some(122), None, false),
(None, Some(14), false),
(Some(125), None, true),
] {
assert!(
failure
.require_reporter_exit(status, signal, timeout)
.is_err()
);
}
let value = serde_json::to_value(&report).unwrap();
for (field, invented) in [
("verified", serde_json::json!(true)),
("bitwise_parity", serde_json::json!(true)),
("verdict", serde_json::json!("matched")),
("guest_exit_code", serde_json::json!(0)),
("guest_signal", serde_json::json!(14)),
(
"runtime",
serde_json::json!({"run1":{"scheduler_turns":1,"virtual_nanoseconds":2}}),
),
(
"compared_log_messages",
serde_json::json!({"left":1,"right":1}),
),
("first_divergent_record", serde_json::json!(1)),
("first_divergent_syscall", serde_json::json!(1)),
("first_divergent_scheduler_turn", serde_json::json!(1)),
("first_divergent_virtual_nanoseconds", serde_json::json!(1)),
(
"first_divergent_left_message",
serde_json::json!("invented"),
),
(
"first_divergent_right_message",
serde_json::json!("invented"),
),
(
"dbt_counted_branches",
serde_json::json!({"left":1,"right":1}),
),
(
"infrastructure_error",
serde_json::json!({"kind":"skid_overshoot","count":1}),
),
] {
let mut bad = value.clone();
bad[field] = invented;
let bytes = serde_json::to_vec(&bad).unwrap();
assert!(
VerificationReport::from_current_json_slice(&bytes).is_err(),
"{field}"
);
assert!(
VerificationReport::from_retained_cell_json_slice(&bytes).is_err(),
"{field}"
);
}
}
}
}
#[test]
fn container_failure_rejects_malformed_duplicate_and_reserved_dispositions() {
let report = failed_container_report(
VerificationRun::Run1,
ContainerDisposition::Exited { code: 0 },
);
let value = serde_json::to_value(report).unwrap();
for code in [-1, 122, 124, 129, 142, 192, 256] {
let mut bad = value.clone();
bad["no_result_reason"]["disposition"]["code"] = code.into();
assert!(
VerificationReport::from_current_json_value(bad).is_err(),
"{code}"
);
}
for replacement in [
serde_json::json!({"kind":"container_failed","disposition":{"kind":"exited","code":1}}),
serde_json::json!({"kind":"container_failed","run":"run3","disposition":{"kind":"exited","code":1}}),
serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"exited","code":1,"signal":14}}),
serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":14}}),
serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":0,"core_dumped":false}}),
serde_json::json!({"kind":"container_failed","run":"run1","disposition":{"kind":"signaled","signal":65,"core_dumped":false}}),
serde_json::json!({"kind":"container_failed","run":"run1","extra":true,"disposition":{"kind":"exited","code":1}}),
] {
let mut bad = value.clone();
bad["no_result_reason"] = replacement;
assert!(VerificationReport::from_current_json_value(bad).is_err());
}
let raw = serde_json::to_string(&value).unwrap();
for (needle, replacement) in [
(r#""run":"run1""#, r#""run":"run1","run":"run2""#),
(r#""code":0"#, r#""code":0,"code":0"#),
] {
assert!(raw.contains(needle));
let bad = raw.replacen(needle, replacement, 1);
assert!(
VerificationReport::from_current_json_slice(bad.as_bytes())
.unwrap_err()
.contains("duplicate field")
);
}
}
#[test]
fn divergence_position_survives_the_parse() {
let json = br#"{"verified":false,"bitwise_parity":false,"verdict":"diverged",
"comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180},
"first_divergent_scheduler_turn":4,
"first_divergent_virtual_nanoseconds":1767225600002825515,
"first_divergent_record":108,
"first_divergent_syscall":37,
"first_divergent_left_message":"INFO detcore: left event",
"first_divergent_right_message":"INFO detcore: right event"}"#;
let report = VerificationReport::from_json_slice(json).expect("diverged report parses");
assert_eq!(report.first_divergent_scheduler_turn, Some(4));
assert_eq!(
report.first_divergent_virtual_nanoseconds,
Some(1_767_225_600_002_825_515)
);
assert_eq!(report.first_divergent_record, Some(108));
assert_eq!(report.first_divergent_syscall, Some(37));
assert_eq!(
report.first_divergent_left_message.as_deref(),
Some("INFO detcore: left event")
);
assert_eq!(
report.first_divergent_right_message.as_deref(),
Some("INFO detcore: right event")
);
}
#[test]
fn a_located_record_does_not_require_its_bounding_siblings() {
let json = br#"{"verified":false,"bitwise_parity":false,"verdict":"diverged",
"comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},
"compared_log_messages":{"left":180,"right":180},
"first_divergent_record":3}"#;
let report = VerificationReport::from_json_slice(json).expect("report parses");
assert_eq!(report.first_divergent_record, Some(3));
assert_eq!(report.first_divergent_scheduler_turn, None);
assert_eq!(report.first_divergent_virtual_nanoseconds, None);
assert_eq!(report.first_divergent_left_message, None);
assert_eq!(report.first_divergent_right_message, None);
assert_eq!(report.first_divergent_syscall, None);
}
#[test]
fn an_earlier_divergence_reports_a_smaller_position() {
let parse = |turn: u64, nanos: u64| {
let json = format!(
r#"{{"verified":false,"bitwise_parity":false,"verdict":"diverged",
"comparison":{{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"}},"compared_log_messages":{{"left":180,"right":180}},
"first_divergent_scheduler_turn":{turn},
"first_divergent_virtual_nanoseconds":{nanos}}}"#
);
VerificationReport::from_json_slice(json.as_bytes()).expect("report parses")
};
let late = parse(4, 1_767_225_600_002_825_515);
let early = parse(1, 1_767_225_600_000_500_000);
assert!(
early.first_divergent_scheduler_turn < late.first_divergent_scheduler_turn,
"an earlier divergence must order before a later one in scheduler turns"
);
assert!(
early.first_divergent_virtual_nanoseconds < late.first_divergent_virtual_nanoseconds,
"and in virtual nanoseconds"
);
}
#[test]
fn a_report_without_the_divergence_position_still_parses() {
let json = br#"{"verified":true,"bitwise_parity":true,"verdict":"matched",
"comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180}}"#;
let report = VerificationReport::from_json_slice(json);
let report = report.expect("a pre-field report is not malformed");
assert_eq!(report.first_divergent_scheduler_turn, None);
assert_eq!(report.first_divergent_virtual_nanoseconds, None);
}
#[test]
fn runtime_totals_survive_the_typed_report_parse() {
let json = br#"{"verified":true,"bitwise_parity":true,"verdict":"matched",
"comparison":{"strictness":"canonical","compare_logs":true,"record_envelope":"all_records_v1"},"compared_log_messages":{"left":180,"right":180},
"runtime":{"run1":{"scheduler_turns":12,"virtual_nanoseconds":34,"syscalls":5},
"run2":{"scheduler_turns":13,"virtual_nanoseconds":35,"syscalls":6}}}"#;
let report = VerificationReport::from_json_slice(json).expect("runtime report parses");
let runtime = report.runtime.expect("runtime retained");
assert_eq!(runtime.run1.expect("run1").syscalls, Some(5));
assert_eq!(runtime.run2.expect("run2").scheduler_turns, 13);
}
fn report(
strictness: LogCompareStrictness,
compare_logs: bool,
left: u64,
right: u64,
) -> VerificationReport {
VerificationReport {
verified: true,
bitwise_parity: true,
verdict: Verdict::Matched,
no_result_reason: None,
infrastructure_error: None,
comparison: Some(ComparisonReport {
strictness,
display_name: None,
compare_logs,
compare_io_buffers: None,
log_scope: None,
record_envelope: RecordEnvelopeReport::AllRecordsV1,
virtualize_time: None,
strip_lines: None,
canonicalize_addresses: None,
full_trace: None,
exact_remainder: None,
stripped_prefixes: None,
canonicalizations: None,
ignore_lines: None,
skip_commit: None,
skip_detlog: None,
}),
compared_log_messages: Some(ComparedLogMessages { left, right }),
compared_outputs: None,
dbt_counted_branches: None,
runtime: None,
guest_exit_code: None,
guest_signal: None,
first_divergent_scheduler_turn: None,
first_divergent_virtual_nanoseconds: None,
first_divergent_record: None,
first_divergent_syscall: None,
first_divergent_left_message: None,
first_divergent_right_message: None,
exact_branch_counter: None,
}
}
#[test]
fn brackets_every_canonical_match_requirement() {
assert!(
report(LogCompareStrictness::Canonical, true, 1, 1)
.require_canonical_match()
.is_ok()
);
let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
weak.verified = false;
assert!(weak.require_canonical_match().is_err());
let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
weak.verdict = Verdict::Diverged;
assert!(weak.require_canonical_match().is_err());
let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
weak.bitwise_parity = false;
assert!(weak.require_canonical_match().is_err());
assert!(
report(LogCompareStrictness::Stripped, true, 1, 1)
.require_canonical_match()
.is_err()
);
assert!(
report(LogCompareStrictness::Canonical, false, 1, 1)
.require_canonical_match()
.is_err()
);
assert!(
report(LogCompareStrictness::Canonical, true, 0, 1)
.require_canonical_match()
.is_err()
);
let mut weak = report(LogCompareStrictness::Canonical, true, 1, 1);
weak.comparison.as_mut().unwrap().record_envelope = RecordEnvelopeReport::CallerDefined;
assert!(weak.require_canonical_match().is_err());
}
const REAL_NO_RESULT_REPORT: &str = concat!(
r#"{"verified":false,"bitwise_parity":false,"verdict":"no_result","#,
r#""comparison":null,"compared_log_messages":null,"guest_exit_code":null,"#,
r#""guest_signal":null,"first_divergent_scheduler_turn":null,"#,
r#""first_divergent_virtual_nanoseconds":null,"first_divergent_record":null,"#,
r#""first_divergent_syscall":null}"#,
);
#[test]
fn a_real_no_result_report_parses_instead_of_reading_as_unreadable() {
let parsed = VerificationReport::from_json_slice(REAL_NO_RESULT_REPORT.as_bytes())
.expect("a documented no-result report must parse");
assert_eq!(parsed.verdict, Verdict::NoResult);
assert!(parsed.comparison.is_none());
}
#[test]
fn a_no_result_report_is_still_inadmissible_and_names_the_real_reason() {
let parsed = VerificationReport::from_json_slice(REAL_NO_RESULT_REPORT.as_bytes())
.expect("a documented no-result report must parse");
let refusal = parsed
.require_canonical_comparison()
.expect_err("a report with no comparison must never be admitted");
assert!(
refusal.contains("recorded no comparison at all"),
"refusal must name the missing comparison, got: {refusal}"
);
assert!(
refusal.contains("no_result"),
"refusal must carry the verdict, got: {refusal}"
);
assert!(parsed.require_canonical_match().is_err());
}
#[test]
fn a_missing_comparison_field_is_refused_rather_than_defaulting_to_none() {
let absent = r#"{"verified":false,"bitwise_parity":false,"verdict":"no_result","compared_log_messages":null}"#;
assert!(VerificationReport::from_json_slice(absent.as_bytes()).is_err());
}
#[test]
fn a_malformed_comparison_object_is_still_refused_at_parse() {
let malformed = REAL_NO_RESULT_REPORT.replace(r#""comparison":null"#, r#""comparison":7"#);
assert!(VerificationReport::from_json_slice(malformed.as_bytes()).is_err());
let missing_field = REAL_NO_RESULT_REPORT.replace(
r#""comparison":null"#,
r#""comparison":{"compare_logs":true,"record_envelope":"all_records_v1"}"#,
);
assert!(VerificationReport::from_json_slice(missing_field.as_bytes()).is_err());
}
#[test]
fn comparison_record_envelope_is_required_and_unknown_values_are_refused() {
let missing = serde_json::json!({
"verified": true,
"bitwise_parity": true,
"verdict": "matched",
"infrastructure_error": null,
"comparison": {"strictness": "canonical", "compare_logs": true},
"compared_log_messages": {"left": 1, "right": 1}
});
let error = VerificationReport::from_json_value(missing)
.expect_err("a comparison that never states its record envelope is not admissible")
.to_string();
assert!(
error.contains("record_envelope"),
"the refusal must name the missing field so an operator can tell a producer that \
predates the envelope from a corrupt report; got: {error}"
);
let unknown = serde_json::json!({
"verified": true,
"bitwise_parity": true,
"verdict": "matched",
"infrastructure_error": null,
"comparison": {
"strictness": "canonical",
"compare_logs": true,
"record_envelope": "unknown_v9"
},
"compared_log_messages": {"left": 1, "right": 1}
});
assert!(VerificationReport::from_json_value(unknown).is_err());
}
#[test]
fn readable_object_with_unreadable_nested_predicate_is_refused() {
let malformed = serde_json::json!({
"verified": true,
"bitwise_parity": true,
"verdict": "matched",
"comparison": null,
"compared_log_messages": {"left": 1, "right": 1}
});
assert!(VerificationReport::from_json_value(malformed).is_err());
}
#[test]
fn typed_no_result_reason_round_trips_and_unknown_values_are_refused() {
let current = serde_json::to_value(VerificationReport::no_result()).unwrap();
let parsed = VerificationReport::from_current_json_value(current.clone())
.expect("the typed not-run reason must round-trip");
assert_eq!(parsed.no_result_reason, Some(NoResultReason::NotRun));
let mut rejected = VerificationReport::no_result();
rejected.no_result_reason = Some(NoResultReason::FirstRunRejected {
exit_code: Some(9),
signal: None,
stdout_bytes: 0,
stderr_bytes: 0,
});
rejected.guest_exit_code = Some(9);
let mut rejected_value = serde_json::to_value(&rejected).unwrap();
for include_null in [false, true] {
if include_null {
rejected_value["compared_outputs"] = serde_json::Value::Null;
} else {
rejected_value
.as_object_mut()
.unwrap()
.remove("compared_outputs");
}
let parsed = VerificationReport::from_current_json_slice(
&serde_json::to_vec(&rejected_value).unwrap(),
)
.expect("a first-run rejection has no comparison output evidence");
assert_eq!(parsed, rejected);
}
let output = ComparedOutput {
exit_code: Some(9),
signal: None,
stdout_sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
.into(),
stdout_bytes: 0,
stderr_sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
.into(),
stderr_bytes: 0,
};
rejected.compared_outputs = Some(ComparedOutputs {
left: output.clone(),
right: output,
});
let error =
VerificationReport::from_current_json_slice(&serde_json::to_vec(&rejected).unwrap())
.expect_err("a first-run rejection cannot carry comparison output evidence");
assert!(
error.contains("no_result") && error.contains("compared_outputs"),
"{error}"
);
let mut missing = current.clone();
missing.as_object_mut().unwrap().remove("no_result_reason");
let error = VerificationReport::from_current_json_value(missing)
.expect_err("a current no-result must state the nullable reason field");
assert!(error.contains("no_result_reason"), "{error}");
let mut absent = current.clone();
absent["no_result_reason"] = serde_json::Value::Null;
let parsed = VerificationReport::from_current_json_value(absent)
.expect("explicit null records that the producer has no exact cause");
assert_eq!(parsed.no_result_reason, None);
let mut comparator_refusal = current.clone();
comparator_refusal["no_result_reason"] = serde_json::json!({
"kind": "comparison_refused",
"detail": "the first log was truncated"
});
let parsed = VerificationReport::from_current_json_value(comparator_refusal)
.expect("a comparator refusal carries the producer's exact cause");
assert_eq!(
parsed.no_result_reason,
Some(NoResultReason::ComparisonRefused {
detail: "the first log was truncated".into()
})
);
let mut unknown = current;
unknown["no_result_reason"] = serde_json::json!({"kind": "never_ran"});
let error = VerificationReport::from_current_json_value(unknown)
.expect_err("an unknown no-result reason must be refused");
assert!(
error.contains("unknown variant"),
"refusal must identify the unknown typed reason: {error}"
);
}
#[test]
fn current_comparison_requires_every_producer_field_by_name() {
let mut current = serde_json::json!({
"verified": true,
"bitwise_parity": true,
"verdict": "matched",
"no_result_reason": null,
"infrastructure_error": null,
"comparison": {
"strictness": "canonical",
"display_name": "BitwiseInfoV1",
"compare_logs": true,
"compare_io_buffers": true,
"log_scope": "info",
"record_envelope": "all_records_v1",
"virtualize_time": true,
"strip_lines": false,
"canonicalize_addresses": true,
"full_trace": true,
"exact_remainder": true,
"stripped_prefixes": ["real-wall-clock-prefix/v1"],
"canonicalizations": ["host-address-to-first-appearance-ordinal/v1"],
"ignore_lines": false,
"skip_commit": false,
"skip_detlog": false
},
"compared_log_messages": {"left": 1, "right": 1},
"compared_outputs": {
"left": {
"exit_code": 0,
"signal": null,
"stdout_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"stdout_bytes": 4,
"stderr_sha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
"stderr_bytes": 0
},
"right": {
"exit_code": 0,
"signal": null,
"stdout_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"stdout_bytes": 4,
"stderr_sha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",
"stderr_bytes": 0
}
},
"guest_exit_code": 0,
"guest_signal": null,
"first_divergent_scheduler_turn": null,
"first_divergent_virtual_nanoseconds": null,
"first_divergent_record": null,
"first_divergent_syscall": null,
"first_divergent_left_message": null,
"first_divergent_right_message": null
});
let parsed = VerificationReport::from_current_json_value(current.clone())
.expect("the complete current producer shape must parse");
let comparison = parsed.comparison.expect("matched report has comparison");
assert_eq!(comparison.compare_io_buffers, Some(true));
assert_eq!(comparison.log_scope, Some(ComparedLogScope::Info));
assert_eq!(parsed.guest_exit_code, Some(0));
let mut missing_outputs = current.clone();
missing_outputs
.as_object_mut()
.unwrap()
.remove("compared_outputs");
let error = VerificationReport::from_current_json_value(missing_outputs)
.expect_err("a completed current report must carry exact output evidence");
assert!(error.contains("compared_outputs"), "{error}");
let mut null_outputs = current.clone();
null_outputs["compared_outputs"] = serde_json::Value::Null;
let error = VerificationReport::from_current_json_value(null_outputs)
.expect_err("null is not output evidence for a completed current report");
assert!(error.contains("compared_outputs"), "{error}");
current["comparison"]
.as_object_mut()
.unwrap()
.remove("compare_io_buffers");
let error = VerificationReport::from_current_json_value(current)
.expect_err("current comparison missing a producer field must be refused");
assert!(
error.contains("compare_io_buffers"),
"refusal must name the missing comparison field: {error}"
);
}
#[test]
fn current_raw_reports_reject_duplicates_and_preserve_required_fields() {
let mut current = serde_json::json!({
"verified": true,
"bitwise_parity": true,
"verdict": "matched",
"no_result_reason": null,
"infrastructure_error": null,
"comparison": {
"strictness": "canonical",
"display_name": "BitwiseInfoV1",
"compare_logs": true,
"compare_io_buffers": true,
"log_scope": "info",
"record_envelope": "all_records_v1",
"virtualize_time": true,
"strip_lines": false,
"canonicalize_addresses": true,
"full_trace": true,
"exact_remainder": true,
"stripped_prefixes": ["real-wall-clock-prefix/v1"],
"canonicalizations": ["host-address-to-first-appearance-ordinal/v1"],
"ignore_lines": false,
"skip_commit": false,
"skip_detlog": false
},
"compared_log_messages": {"left": 1, "right": 1},
"guest_exit_code": 0,
"guest_signal": null,
"first_divergent_scheduler_turn": null,
"first_divergent_virtual_nanoseconds": null,
"first_divergent_record": null,
"first_divergent_syscall": null,
"first_divergent_left_message": null,
"first_divergent_right_message": null
});
let output = serde_json::json!({
"exit_code": 0, "signal": null,
"stdout_sha256": "a".repeat(64), "stdout_bytes": 0,
"stderr_sha256": "b".repeat(64), "stderr_bytes": 0
});
current["compared_outputs"] = serde_json::json!({"left": output, "right": output});
for mutation in [
"unequal",
"bad-digest",
"two-dispositions",
"wrong-disposition",
] {
let mut bad = current.clone();
match mutation {
"unequal" => {
bad["compared_outputs"]["right"]["stdout_sha256"] = "c".repeat(64).into()
}
"bad-digest" => {
for side in ["left", "right"] {
bad["compared_outputs"][side]["stdout_sha256"] = "invalid".into();
}
}
"two-dispositions" => {
for side in ["left", "right"] {
bad["compared_outputs"][side]["signal"] = 9.into();
}
}
"wrong-disposition" => bad["guest_exit_code"] = 7.into(),
_ => unreachable!(),
}
let bytes = serde_json::to_vec(&bad).unwrap();
assert!(
VerificationReport::from_current_json_slice(&bytes).is_err(),
"{mutation}"
);
assert!(
VerificationReport::from_retained_cell_json_slice(&bytes).is_err(),
"{mutation}"
);
assert!(
VerificationReport::from_json_slice(&bytes)
.unwrap()
.require_canonical_match()
.is_err(),
"{mutation}"
);
}
let mut historical = current.clone();
historical
.as_object_mut()
.unwrap()
.remove("compared_outputs");
let bytes = serde_json::to_vec(&historical).unwrap();
VerificationReport::from_retained_cell_json_slice(&bytes)
.unwrap()
.require_canonical_match()
.unwrap();
assert!(VerificationReport::from_current_json_slice(&bytes).is_err());
let mut diverged = current.clone();
diverged["verdict"] = "diverged".into();
diverged["verified"] = false.into();
diverged["bitwise_parity"] = false.into();
diverged["compared_outputs"]["right"]["stdout_sha256"] = "c".repeat(64).into();
VerificationReport::from_current_json_value(diverged).unwrap();
let mut relaxed = current.clone();
relaxed["comparison"]["strictness"] = "stripped".into();
relaxed["bitwise_parity"] = false.into();
VerificationReport::from_current_json_value(relaxed).unwrap();
let raw = serde_json::to_string(¤t).unwrap();
VerificationReport::from_current_json_slice(raw.as_bytes())
.unwrap()
.require_canonical_match()
.unwrap();
for (needle, replacement) in [
(r#""verified":true"#, r#""verified":false,"verified":true"#),
(r#""verified":true"#, r#""verified":true,"verified":true"#),
(
r#""no_result_reason":null"#,
r#""no_result_reason":{"kind":"not_run"},"no_result_reason":null"#,
),
(
r#""no_result_reason":null"#,
r#""no_result_reason":null,"no_result_reason":null"#,
),
(r#""left":1"#, r#""left":0,"left":1"#),
(r#""left":1"#, r#""left":1,"left":1"#),
] {
assert_eq!(raw.matches(needle).count(), 1);
let duplicated = raw.replacen(needle, replacement, 1);
let collapsed: serde_json::Value = serde_json::from_str(&duplicated).unwrap();
assert_eq!(
collapsed, current,
"the last-value map loses this contradiction"
);
let error =
VerificationReport::from_current_json_slice(duplicated.as_bytes()).unwrap_err();
assert!(error.contains("duplicate field"), "{replacement}: {error}");
}
for field in ["no_result_reason", "guest_signal"] {
let mut missing = current.clone();
missing.as_object_mut().unwrap().remove(field);
let error =
VerificationReport::from_current_json_slice(&serde_json::to_vec(&missing).unwrap())
.unwrap_err();
assert!(error.contains(field), "{error}");
}
let mut missing = current;
missing["comparison"]
.as_object_mut()
.unwrap()
.remove("compare_io_buffers");
assert!(
VerificationReport::from_current_json_slice(&serde_json::to_vec(&missing).unwrap())
.unwrap_err()
.contains("compare_io_buffers")
);
let mut refused = serde_json::to_value(VerificationReport::no_result()).unwrap();
refused["no_result_reason"] = serde_json::json!({"kind":"comparison_refused","detail":"the second log was truncated"});
VerificationReport::from_current_json_slice(&serde_json::to_vec(&refused).unwrap())
.unwrap();
refused["no_result_reason"]["detail"] = serde_json::json!("");
assert!(
VerificationReport::from_current_json_slice(&serde_json::to_vec(&refused).unwrap())
.unwrap_err()
.contains("detail")
);
}
#[test]
fn unknown_verdict_is_refused_by_the_shared_type() {
let unknown = serde_json::json!({
"verified": false,
"bitwise_parity": false,
"verdict": "partly_matched",
"comparison": null,
"compared_log_messages": null
});
let error = VerificationReport::from_json_value(unknown)
.expect_err("an unknown verdict must not become a product failure");
assert!(
error.contains("unknown variant"),
"unexpected error: {error}"
);
}
#[test]
fn infrastructure_error_is_distinct_from_no_result_and_requires_a_positive_count() {
let mut report =
serde_json::to_value(report(LogCompareStrictness::Canonical, true, 1, 1)).unwrap();
report["verified"] = serde_json::json!(false);
report["bitwise_parity"] = serde_json::json!(false);
report["verdict"] = serde_json::json!("infrastructure_error");
report["infrastructure_error"] = serde_json::json!({"kind": "skid_overshoot", "count": 2});
let parsed = VerificationReport::from_json_value(report.clone()).unwrap();
assert_eq!(parsed.verdict, Verdict::InfrastructureError);
assert_eq!(
parsed.infrastructure_error,
Some(InfrastructureError::SkidOvershoot { count: 2 })
);
assert!(parsed.comparison.is_some());
report["infrastructure_error"]["count"] = serde_json::json!(0);
let error = VerificationReport::from_json_value(report)
.expect_err("zero cannot describe an observed skid overshoot");
assert!(error.contains("count must be positive"), "{error}");
}
}