//! Offline regression gates for the versioned OpenAPI support matrix and corpus. use crank_import::rest::model::CoverageDisposition; use crank_import::rest::model::{CanonicalSourceNode, CanonicalSourceValue}; use crank_import::rest::{ ImportParseError, NormalizationConfig, SourceDigest, normalize_verified_document, preview_from_ir, validate_normalized_ir, }; use serde::Deserialize; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use std::{ fs, path::{Path, PathBuf}, }; #[path = "corpus/matrix.rs"] mod matrix; fn tests_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests") } fn hex(bytes: impl AsRef<[u8]>) -> String { Sha256::digest(bytes) .iter() .map(|b| format!("{b:02x}")) .collect() } fn canonical_json(value: &Value) -> Vec { serde_json::to_vec(value).expect("JSON values serialize") } fn escape_pointer(value: &str) -> String { value.replace('~', "~0").replace('/', "~1") } fn source_ledger( value: &Value, pointer: &str, ledger: &mut std::collections::BTreeMap, ) { assert!(ledger.insert(pointer.to_owned(), value.clone()).is_none()); match value { Value::Array(items) => { for (index, item) in items.iter().enumerate() { source_ledger(item, &format!("{pointer}/{index}"), ledger); } } Value::Object(fields) => { for (key, item) in fields { source_ledger(item, &format!("{pointer}/{}", escape_pointer(key)), ledger); } } _ => {} } } fn canonical_source_ledger( node: &CanonicalSourceNode, ledger: &mut std::collections::BTreeMap, ) -> Value { let value = match &node.value { CanonicalSourceValue::Null => Value::Null, CanonicalSourceValue::Boolean(value) => json!(value), CanonicalSourceValue::Number(value) => { serde_json::from_str(value).expect("canonical number") } CanonicalSourceValue::String(value) => json!(value), CanonicalSourceValue::Array(items) => Value::Array( items .iter() .map(|item| canonical_source_ledger(item, ledger)) .collect(), ), CanonicalSourceValue::Object(items) => { let mut fields = serde_json::Map::new(); for (key, item) in items { fields.insert(key.clone(), canonical_source_ledger(item, ledger)); } Value::Object(fields) } }; assert!( ledger .insert(node.location.pointer.clone(), value.clone()) .is_none() ); value } #[derive(Debug, Deserialize)] struct Manifest { corpus_version: String, matrix_version: String, compatibility_impact: String, documents: Vec, } #[derive(Debug, Deserialize)] struct Document { id: String, file: String, sha256: String, canonical_digest: Option, origin: String, license: String, specification_version: String, classification: String, expected_preview: Value, } fn manifest() -> Manifest { serde_json::from_slice( &fs::read(tests_root().join("corpus/manifest.json")).expect("manifest exists"), ) .expect("manifest JSON is valid") } fn normalize(source: &str) -> Result { let source_digest = SourceDigest::parse(hex(source.as_bytes())).expect("sha256 is valid"); normalize_verified_document(source, source_digest, &NormalizationConfig::default()) } #[test] fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() { let manifest = manifest(); assert_eq!(manifest.corpus_version, "1.0.3"); assert_eq!(manifest.matrix_version, "1.0.2"); assert!(!manifest.compatibility_impact.trim().is_empty()); assert!(manifest.documents.len() >= 50); let root = tests_root().join("corpus"); let mut versions = std::collections::BTreeSet::new(); let mut representative_count = 0; for document in &manifest.documents { assert!(!document.id.is_empty()); assert!( document.origin.starts_with("synthetic:"), "{} lacks provenance", document.id ); assert!( document.license.contains("CC0"), "{} lacks license", document.id ); assert_eq!(document.sha256.len(), 64); versions.insert(document.specification_version.as_str()); let source = fs::read(root.join(&document.file)) .unwrap_or_else(|e| panic!("{}: {e}", document.file)); assert_eq!( hex(&source), document.sha256, "checksum mismatch for {}", document.file ); if let Ok(value) = serde_json::from_slice::(&source) { let digest = hex(canonical_json(&value)); assert_eq!( document.canonical_digest.as_deref(), Some(digest.as_str()), "canonical digest mismatch for {}", document.file ); } else { assert!( document.canonical_digest.is_none(), "malformed JSON has no canonical digest" ); } if document.classification == "representative" { representative_count += 1; let text = std::str::from_utf8(&source).expect("fixtures are UTF-8"); let ir = normalize(text).unwrap_or_else(|e| panic!("{} failed parser: {e}", document.file)); validate_normalized_ir(&ir).expect("normalized IR has explicit source coverage"); let preview = preview_from_ir(&ir); let repeated_preview = preview_from_ir(&normalize(text).expect("repeat normalization succeeds")); assert_eq!( serde_json::to_value(&preview).unwrap(), serde_json::to_value(&repeated_preview).unwrap(), "deterministic preview diff for {}:\nexpected={}\nactual={}", document.file, serde_json::to_string_pretty(&preview).unwrap(), serde_json::to_string_pretty(&repeated_preview).unwrap(), ); let candidates = preview .groups .iter() .flat_map(|g| &g.operations) .collect::>(); assert_eq!( candidates.len(), document.expected_preview["operation_count"] .as_u64() .unwrap() as usize, "operation count in {}", document.file ); assert_eq!( candidates.len(), 1, "corpus fixtures are single-operation exact oracles" ); let expected = &document.expected_preview["operations"][0]; let actual_candidate = serde_json::to_value(candidates[0]).unwrap(); assert_eq!( actual_candidate, expected["candidate"], "frozen candidate diff for {}:\nexpected={}\nactual={}", document.file, serde_json::to_string_pretty(&expected["candidate"]).unwrap(), serde_json::to_string_pretty(&actual_candidate).unwrap(), ); let blocking_codes = candidates[0] .findings .iter() .filter(|finding| { finding.severity == crank_import::rest::ImportFindingSeverity::Error }) .map(|finding| finding.code.clone()) .collect::>(); assert_eq!(json!(blocking_codes), expected["blocker_codes"]); assert_eq!( blocking_codes.is_empty(), expected["actionable"].as_bool().unwrap() ); assert_eq!( hex(canonical_json(&actual_candidate)), expected["candidate_digest"], "candidate canonical digest in {}", document.file ); assert_eq!( hex(canonical_json(&serde_json::to_value(&preview).unwrap())), document.expected_preview["canonical_preview_digest"], "preview canonical digest in {}", document.file ); let actual_preview = serde_json::to_value(&preview).unwrap(); assert_eq!( actual_preview, document.expected_preview["canonical_preview"], "frozen readable preview diff for {}:\nexpected={}\nactual={}", document.file, serde_json::to_string_pretty(&document.expected_preview["canonical_preview"]) .unwrap(), serde_json::to_string_pretty(&actual_preview).unwrap(), ); assert_eq!( serde_json::to_value(candidates[0].method).unwrap().as_str(), expected["method"].as_str() ); assert_eq!(candidates[0].path, expected["path"].as_str().unwrap()); assert_eq!( candidates[0].operation_id.as_deref(), expected["operation_id"].as_str() ); assert!( preview.findings.is_empty(), "unexpected preview findings in {}: {:?}", document.file, preview.findings ); let mut actual_findings = candidates[0] .findings .iter() .map(|f| f.code.as_str()) .collect::>(); let mut expected_findings = document.expected_preview["finding_codes"] .as_array() .unwrap() .iter() .map(|v| v.as_str().unwrap()) .collect::>(); actual_findings.sort_unstable(); expected_findings.sort_unstable(); assert_eq!( actual_findings, expected_findings, "finding codes in {}", document.file ); } else { assert_eq!(document.classification, "hostile"); let text = std::str::from_utf8(&source).unwrap(); let parsed = normalize(text); assert_eq!( parsed, normalize(text), "hostile parser result changed on deterministic rerun for {}", document.file ); if [ "hostile-empty.json", "hostile-malformed.json", "hostile-oversized.json", "hostile-deep.json", "hostile-aliases.yaml", ] .contains(&document.file.as_str()) { if [ "hostile-oversized.json", "hostile-deep.json", "hostile-aliases.yaml", ] .contains(&document.file.as_str()) { assert!( matches!(parsed, Err(ImportParseError::LimitExceeded)), "{} must fail within configured bounds: {parsed:?}", document.file ); } else { assert!(parsed.is_err(), "{} must be rejected", document.file); } } else if document.file == "hostile-trace.json" { let ir = parsed.expect("TRACE is reported instead of silently discarded"); assert!( ir.findings .iter() .any(|f| f.code == "unsupported_http_method") ); assert!(ir.coverage.iter().any(|c| c.construct_id.contains("trace") && c.disposition == CoverageDisposition::Finding)); } else if document.file == "hostile-xml.json" { let ir = parsed.expect("XML is represented by an explicit finding"); let preview = preview_from_ir(&ir); let codes = preview .groups .iter() .flat_map(|g| &g.operations) .flat_map(|o| &o.findings) .map(|f| f.code.as_str()) .collect::>(); assert!( codes .iter() .any(|code| code.contains("xml") || code.contains("media")), "XML findings: {codes:?}" ); } else if document.file == "hostile-secret.json" { let ir = parsed.expect("secret-like examples remain inspectable"); let evidence = serde_json::to_string(&preview_from_ir(&ir)).unwrap(); assert!( !evidence.contains("sk_test_corpus_secret_canary"), "secret canary leaked into preview evidence" ); } else { let ir = parsed.unwrap_or_else(|error| { panic!( "{} must have an explicit finding or bounded rejection: {error}", document.file ) }); validate_normalized_ir(&ir).expect("hostile construct coverage remains explicit"); assert!( !ir.coverage.is_empty(), "{} has no construct ledger", document.file ); let preview = preview_from_ir(&ir); match document.file.as_str() { "hostile-cycle.json" => { assert_eq!( ir.operations.len(), 1, "recursive schema must not drop the source operation" ); assert!( ir.findings .iter() .chain(ir.operations.iter().flat_map(|op| &op.findings)) .all(|finding| { finding.severity != crank_import::rest::ImportFindingSeverity::Error }), "bounded cycle policy must not yield an unexplained blocker: {:?} {:?}", ir.findings, ir.operations.iter().map(|op| &op.findings) ); assert!( ir.unresolved_references.is_empty(), "resolved recursion must not be reported as unresolvable: {:?}", ir.unresolved_references ); let cycle_edge = |recursive: bool| { ir.reference_graph.edges.iter().any(|edge| { edge.recursive == recursive && edge.source.location.pointer == "/components/schemas/Node/properties/next/$ref" && edge.target.location.pointer == "/components/schemas/Node" }) }; assert!( cycle_edge(false) && cycle_edge(true), "Node.next must resolve through both bounded and recursive edges: {:?}", ir.reference_graph.edges ); let response = ir.operations[0] .response_variants .iter() .find(|variant| variant.status_code == 200) .expect("200 response is retained"); assert!( matches!( &response.schema, Some(schema) if matches!( &schema.kind, crank_import::rest::NormalizedSchemaKind::Object { properties, .. } if properties.contains_key("next") ) ), "recursive node schema must be projected: {:?}", response.schema ); assert!( ir.coverage.iter().any(|entry| { entry.location.pointer == "/components/schemas/Node/properties/next/properties/next" && entry.disposition == CoverageDisposition::Mapped }), "bounded recursion must remain Mapped in the resolved source ledger: {:?}", ir.coverage ); assert_eq!( document.expected_preview["mapped_recursive_pointer"].as_str(), Some("/components/schemas/Node/properties/next/properties/next") ); assert_eq!( ir.findings .iter() .map(|f| (f.code.clone(), f.severity.clone())) .collect::>(), vec![( "missing_servers".to_owned(), crank_import::rest::ImportFindingSeverity::Warning )], "cycle fixture must expose only the exact bounded warning set: {:?}", ir.findings ); assert_eq!( document.expected_preview["operation_count"].as_u64(), Some(1) ); assert_eq!( document.expected_preview["recursive_edge"]["source"].as_str(), Some("/components/schemas/Node/properties/next/$ref") ); assert_eq!( document.expected_preview["recursive_edge"]["target"].as_str(), Some("/components/schemas/Node") ); assert_eq!(document.expected_preview["blocker_findings"], json!([])); assert_eq!( document.expected_preview["unresolved_references"], json!([]) ); assert_eq!( document.expected_preview["warning_findings"], json!([{"code":"missing_servers","severity":"Warning","operation_key":null}]) ); } "hostile-external-ref.json" => assert!( ir.findings.iter() .chain(ir.operations.iter().flat_map(|op| &op.findings)) .any(|finding| finding.code == "external_reference_disabled" && finding.location.pointer == "/paths/~1hostile/get/responses/200/content/application~1json/schema/$ref"), "external ref must be denied at its source: {:?}", ir.findings ), "hostile-duplicate-ids.json" => assert_eq!( ir.operations.len(), 2, "duplicate IDs must not drop a source operation" ), "hostile-composition-conflict.json" => { assert_eq!( ir.operations.len(), 1, "conflicting allOf must keep the source operation explicit" ); let conflict = ir.operations[0] .findings .iter() .find(|finding| finding.code == "all_of_conflict") .unwrap_or_else(|| { panic!( "allOf conflict must be named: {:?}", ir.operations[0].findings ) }); assert_eq!( conflict.severity, crank_import::rest::ImportFindingSeverity::Error, "allOf conflict must block the candidate: {:?}", conflict ); assert_eq!( conflict.operation_key.as_deref(), Some("GET /hostile"), "conflict must belong to the affected candidate: {:?}", conflict ); assert_eq!( conflict.location.pointer, "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf", "conflict must point at the conflicting allOf: {:?}", conflict ); assert!( ir.coverage .iter() .any(|entry| { entry.location .pointer == "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf" }) && ir .operations[0] .findings .iter() .any(|finding| finding.code == "all_of_conflict" && finding.location.pointer == "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"), "conflicting allOf must stay in the source ledger bound to the explicit finding: {:?}", ir.coverage ); let response = ir.operations[0] .response_variants .iter() .find(|variant| variant.status_code == 200) .expect("200 response is retained"); assert!( matches!( &response.schema, Some(schema) if matches!( &schema.kind, crank_import::rest::NormalizedSchemaKind::Composition { operator, variants } if operator == "allOf" && variants.len() == 2 ) ), "conflict branches must be preserved verbatim: {:?}", response.schema ); assert_eq!( ir.findings .iter() .map(|f| (f.code.clone(), f.severity.clone())) .collect::>(), vec![( "missing_servers".to_owned(), crank_import::rest::ImportFindingSeverity::Warning )], "composition conflict fixture must keep the exact warning set: {:?}", ir.findings ); assert_eq!( document.expected_preview["operation_count"].as_u64(), Some(1) ); assert_eq!( document.expected_preview["blocker_findings"], json!([{"code":"all_of_conflict","severity":"Error", "operation_key":"GET /hostile", "location":"/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"}]) ); assert_eq!( document.expected_preview["composition"], json!({"operator":"allOf","branch_count":2}) ); assert_eq!( document.expected_preview["warning_findings"], json!([{"code":"missing_servers","severity":"Warning","operation_key":null}]) ); } "hostile-security-scope.json" => { assert_eq!( ir.operations.len(), 2, "security-scope fixture must keep both candidates explicit: {:?}", ir.operations.iter().map(|op| &op.key).collect::>() ); let requirements = ir .findings .iter() .filter(|finding| finding.code == "unsupported_security_requirement") .collect::>(); assert_eq!( requirements.len(), 1, "exactly the inherited requirement must produce a blocker: {:?}", ir.findings ); let requirement = &requirements[0]; assert_eq!( requirement.severity, crank_import::rest::ImportFindingSeverity::Error, "security requirement must block its candidate: {:?}", requirement ); assert_eq!( requirement.operation_key.as_deref(), Some("GET /secure"), "blocker must belong only to the inherited secured candidate: {:?}", requirement ); assert_eq!( requirement.location.pointer, "/security/0", "inherited requirement must point at the document root requirement: {:?}", requirement ); let mut by_key = std::collections::BTreeMap::new(); for group in &preview.groups { for candidate in &group.operations { by_key.insert(candidate.key.clone(), candidate); } } let public = by_key.get("GET /public").expect("public candidate present"); assert!( public.findings.iter().all(|finding| finding.severity != crank_import::rest::ImportFindingSeverity::Error), "public operation with security: [] must stay actionable: {:?}", public.findings ); assert!( by_key .get("GET /secure") .expect("secured candidate present") .findings .iter() .any(|finding| finding.code == "unsupported_security_requirement" && finding.severity == crank_import::rest::ImportFindingSeverity::Error), "inherited requirement must block the secured candidate: {:?}", by_key.get("GET /secure").unwrap().findings ); assert!( preview .findings .iter() .all(|finding| finding.operation_key.is_some()), "no document-global blocker may be produced: {:?}", preview.findings ); assert!( ir.coverage .iter() .any(|entry| entry.location.pointer == "/security/0" && entry.disposition == CoverageDisposition::Finding), "inherited requirement must stay in the source ledger bound to the finding: {:?}", ir.coverage ); let mut actual_operation_keys = preview .groups .iter() .flat_map(|group| &group.operations) .map(|op| op.key.clone()) .collect::>(); actual_operation_keys.sort(); assert_eq!( json!(actual_operation_keys), document.expected_preview["operation_keys"], "security-scope operation oracle for {}", document.file ); let actual_blockers = requirements .iter() .map(|finding| { json!({"code": finding.code.clone(), "severity": "Error", "operation_key": finding.operation_key.clone(), "location": finding.location.pointer.clone()}) }) .collect::>(); assert_eq!( actual_blockers, document.expected_preview["blocker_findings"] .as_array() .unwrap() .clone(), "security-scope blocker oracle for {}: actual {actual_blockers:?}", document.file ); let actual_warnings = ir .findings .iter() .filter(|finding| { finding.severity == crank_import::rest::ImportFindingSeverity::Warning }) .map(|finding| { json!({"code": finding.code.clone(), "severity": "Warning", "operation_key": finding.operation_key.clone()}) }) .collect::>(); assert_eq!( actual_warnings, document.expected_preview["warning_findings"] .as_array() .unwrap() .clone(), "security-scope warning oracle for {}: actual {actual_warnings:?}", document.file ); } _ => unreachable!("hostile fixture must have a dedicated expectation"), } } } } // Exact file set: manifest rows are unique and every corpus data file is // accounted exactly once, so duplicates or orphan fixtures cannot inflate // or hide coverage. let mut ids = std::collections::BTreeSet::new(); let mut files = std::collections::BTreeSet::new(); for document in &manifest.documents { assert!( ids.insert(document.id.clone()), "duplicate manifest document id {}", document.id ); assert!( files.insert(document.file.clone()), "duplicate manifest file {}", document.file ); } let expected_files = files .into_iter() .chain(std::iter::once("manifest.json".to_owned())) .chain(std::iter::once("matrix.rs".to_owned())) .collect::>(); let actual_files = fs::read_dir(&root) .expect("corpus directory exists") .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) .collect::>(); assert_eq!( actual_files, expected_files, "corpus directory must equal the manifest file set exactly" ); assert_eq!(representative_count, 50); assert!( versions .iter() .any(|version| version.starts_with("OpenAPI 3.0")) && versions .iter() .any(|version| version.starts_with("OpenAPI 3.1")) && versions.contains("Swagger 2.0") ); } #[test] fn ac_3_evidence_reports_actionable_denominator_exclusions_and_zero_silent_loss() { let manifest = manifest(); let mut denominator = 0_u64; let mut actionable_count = 0_u64; let mut operation_count = 0_u64; let mut source_construct_count = 0_u64; let mut covered_source_construct_count = 0_u64; let mut semantic_coverage_count = 0_u64; let mut silent_loss = Vec::new(); let mut exclusions = Vec::new(); let mut finding_count = 0_u64; for document in &manifest.documents { if document.classification != "representative" { continue; } let source_bytes = fs::read(tests_root().join("corpus").join(&document.file)).unwrap(); let source: Value = serde_json::from_slice(&source_bytes).expect("representative corpus source is JSON"); let mut raw_ledger = std::collections::BTreeMap::new(); source_ledger(&source, "", &mut raw_ledger); let source_text = std::str::from_utf8(&source_bytes).unwrap(); let ir = normalize(source_text).unwrap(); validate_normalized_ir(&ir).unwrap(); let mut normalized_ledger = std::collections::BTreeMap::new(); let _ = canonical_source_ledger(&ir.source_tree, &mut normalized_ledger); assert_eq!( normalized_ledger, raw_ledger, "normalizer source-tree ledger differs from raw document for {}", document.file ); source_construct_count += raw_ledger.len() as u64; let coverage_by_id = ir .coverage .iter() .map(|entry| (entry.construct_id.as_str(), entry)) .collect::>(); for pointer in raw_ledger.keys() { let source_id = format!("source:{pointer}"); match coverage_by_id.get(source_id.as_str()) { Some(entry) if entry.location.pointer == *pointer && entry.disposition == CoverageDisposition::Mapped => { covered_source_construct_count += 1; } _ => silent_loss.push(json!({"document":document.id,"source_pointer":pointer,"coverage_id":source_id})), } } let findings = ir .findings .iter() .chain( ir.operations .iter() .flat_map(|operation| &operation.findings), ) .collect::>(); for entry in ir .coverage .iter() .filter(|entry| !entry.construct_id.starts_with("source:")) { semantic_coverage_count += 1; assert!( raw_ledger.contains_key(&entry.location.pointer), "coverage {} points outside raw source tree for {}", entry.construct_id, document.file ); match entry.disposition { CoverageDisposition::Mapped => {} CoverageDisposition::Finding => assert!( findings .iter() .any(|finding| finding.construct_id == entry.construct_id && finding.location == entry.location), "finding coverage {} has no matching finding in {}", entry.construct_id, document.file ), } } for operation in &ir.operations { denominator += 1; operation_count += 1; if operation .findings .iter() .all(|f| f.severity != crank_import::rest::ImportFindingSeverity::Error) { actionable_count += 1; } else { exclusions.push(json!({"document":document.id,"operation":operation.key,"reason":"blocking_finding","findings":operation.findings.iter().map(|f| &f.code).collect::>()})); } } finding_count += ir.findings.len() as u64; } assert!(denominator > 0); assert!( actionable_count * 100 >= denominator * 95, "actionable {actionable_count}/{denominator}; exclusions={exclusions:?}" ); let silent_loss_count = silent_loss.len() as u64; assert_eq!( source_construct_count, covered_source_construct_count, "independently enumerated raw source constructs lack coverage: {silent_loss:?}" ); let mut reversed_counts = (0_u64, 0_u64, 0_u64); for document in manifest .documents .iter() .rev() .filter(|document| document.classification == "representative") { let source = fs::read_to_string(tests_root().join("corpus").join(&document.file)).unwrap(); let ir = normalize(&source).unwrap(); reversed_counts.0 += ir.operations.len() as u64; reversed_counts.1 += ir .operations .iter() .filter(|operation| { operation.findings.iter().all(|finding| { finding.severity != crank_import::rest::ImportFindingSeverity::Error }) }) .count() as u64; reversed_counts.2 += ir.findings.len() as u64; } assert_eq!( reversed_counts, (operation_count, actionable_count, finding_count), "aggregate evidence must not depend on manifest order" ); let manifest_bytes = fs::read(tests_root().join("corpus/manifest.json")).unwrap(); let manifest_digest = hex(&manifest_bytes); let matrix_bytes = fs::read(tests_root().join("support-matrix.yaml")).unwrap(); let matrix_digest = hex(&matrix_bytes); let matrix_value: serde_yaml::Value = serde_yaml::from_slice(&matrix_bytes).unwrap(); let matrix_row_count = matrix_value["constructs"].as_sequence().unwrap().len(); let evidence_identity = hex(format!( "{}\n{}\n{}\n{}", manifest.corpus_version, manifest.matrix_version, manifest_digest, matrix_digest )); let mut evidence = json!({ "evidence_version":"1.0.0", "corpus_version":manifest.corpus_version, "matrix_version":manifest.matrix_version, "evidence_identity":evidence_identity, "content_digest_algorithm":"sha256", "content_digest_definition":"SHA-256 of compact key-sorted JSON before the content_digest field is added.", "manifest_digest":manifest_digest, "matrix_digest":matrix_digest, "denominator":denominator, "actionable_count":actionable_count, "exclusions":exclusions, "raw_counts":{"documents":manifest.documents.len(),"representative_operations":operation_count,"findings":finding_count,"source_constructs":source_construct_count,"covered_source_constructs":covered_source_construct_count,"semantic_coverage_entries":semantic_coverage_count}, "matrix_contract":{"construct_rows":matrix_row_count,"semantic_probes":"AC-1 runs a generated normalizer probe for every matrix row, including every 2xx status in all three formats."}, "uncovered_source_constructs":silent_loss, "silent_loss_count":silent_loss_count, "method":"real normalize_verified_document + preview_from_ir; every NormalizedIr passed validate_normalized_ir" }); let content_digest = hex(canonical_json(&evidence)); evidence["content_digest"] = json!(content_digest); let artifact = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!( "target/openapi-corpus/evidence-{evidence_identity}.json" )); let target_dir = artifact.parent().unwrap(); fs::create_dir_all(target_dir).unwrap(); let bytes = serde_json::to_vec_pretty(&evidence).unwrap(); // Each process needs its own temp file: concurrent corpus runs must not // truncate each other's pending evidence before atomic publication. let mut nonce = 0u32; let (publish, mut file) = loop { let path = target_dir.join(format!( "evidence.json.tmp-{}-{}-{nonce}", &evidence_identity[..16], std::process::id() )); match fs::OpenOptions::new() .write(true) .create_new(true) .open(&path) { Ok(file) => break (path, file), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && nonce < 1024 => { nonce += 1; } Err(error) => panic!( "cannot create evidence temp file {}: {error}", path.display() ), } }; { use std::io::Write; file.write_all(&bytes).unwrap(); file.sync_all().unwrap(); } // hard_link fails atomically when the final identity already exists. // Rename would silently overwrite after an exists-check race, while // create_new on the final path would expose partial bytes after a crash. let published = match fs::hard_link(&publish, &artifact) { Ok(()) => true, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false, Err(error) => panic!( "cannot publish immutable evidence artifact {}: {error}", artifact.display() ), }; fs::remove_file(&publish).ok(); if !published { let existing = fs::read(&artifact).unwrap(); assert_eq!( existing, bytes, "immutable evidence identity {evidence_identity} already has conflicting contents at {}", artifact.display() ); } if let Ok(directory) = fs::File::open(target_dir) { let _ = directory.sync_all(); } let reread: Value = serde_json::from_slice(&fs::read(artifact).unwrap()).unwrap(); assert_eq!(reread, evidence); assert_eq!(reread["silent_loss_count"], 0); assert_eq!(source_construct_count, covered_source_construct_count); assert_eq!(reread["denominator"], denominator); assert_eq!(reread["actionable_count"], actionable_count); }