#![allow(unused_imports)]
use super::*;
use crate::layer1::bisimulation_ast::preserve_json_numeric_tokens;
pub fn assess_equivalence(clm_root: &str, clm_file: &str) -> Result<(i32, String), String> {
use std::fs;
use std::path::{Path, PathBuf};
let content = fs::read_to_string(clm_file)
.map_err(|e| format!("Failed to read equivalence spec: {}", e))?;
if content.trim_start().starts_with('{') {
let is_bisim = serde_json::from_str::<serde_json::Value>(&preserve_json_numeric_tokens(&content))
.ok()
.and_then(|v| v.get("mode")?.as_str().map(|s| s == "bialgebraic_bisimulation"));
if is_bisim == Some(true) {
return evaluate_bisimulation_spec_rs(&content);
}
}
let parsed: serde_yaml::Value = serde_yaml::from_str(&content)
.map_err(|e| format!("Failed to parse equivalence YAML: {}", e))?;
let clm_val = parsed.get("clm").unwrap_or(&parsed);
let process_val = clm_val.get("concrete_impl")
.and_then(|v| v.get("process"))
.or_else(|| clm_val.get("process"))
.ok_or_else(|| "No process block found in equivalence spec".to_string())?;
let ref_pcard = process_val.get("process_ref")
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing process_ref in spec".to_string())?;
let cand_pcard = process_val.get("process_cand")
.and_then(|v| v.as_str())
.ok_or_else(|| "Missing process_cand in spec".to_string())?;
let relation_type = process_val.get("relation_type")
.and_then(|v| v.as_str())
.unwrap_or("identity");
let domain_val = process_val.get("domain")
.ok_or_else(|| "Missing domain in spec".to_string())?;
let mut inputs = Vec::new();
if let Some(arr) = domain_val.as_sequence() {
for item in arr {
if let Some(s) = item.as_str() {
inputs.push(s.to_string());
} else if let Some(n) = item.as_i64() {
inputs.push(n.to_string());
} else if let Some(b) = item.as_bool() {
inputs.push(b.to_string());
}
}
}
if inputs.is_empty() {
return Err("Equivalence domain cannot be empty".to_string());
}
let mut opts = RelationOptions::default();
if let Some(ro) = process_val.get("relation_options") {
opts.normalize_newlines = ro.get("normalize_newlines").and_then(|v| v.as_bool()).unwrap_or(false);
opts.trim_whitespace = ro.get("trim_whitespace").and_then(|v| v.as_bool()).unwrap_or(false);
opts.ignore_ansi = ro.get("ignore_ansi").and_then(|v| v.as_bool()).unwrap_or(false);
opts.ignore_case = ro.get("ignore_case").and_then(|v| v.as_bool()).unwrap_or(false);
opts.stop_on_first_mismatch = ro.get("stop_on_first_mismatch").and_then(|v| v.as_bool()).unwrap_or(false);
opts.required_degree = ro.get("required_degree").and_then(|v| v.as_f64());
}
let ref_path = if Path::new(ref_pcard).is_absolute() {
PathBuf::from(ref_pcard)
} else {
Path::new(clm_root).join(ref_pcard)
};
let cand_path = if Path::new(cand_pcard).is_absolute() {
PathBuf::from(cand_pcard)
} else {
Path::new(clm_root).join(cand_pcard)
};
let ref_hash = crate::fs_utils::compute_stripped_file_hash(&ref_path)
.unwrap_or_else(|_| format!("{}unknown_ref", crate::hash::DEFAULT_HASH_PREFIX));
let cand_hash = crate::fs_utils::compute_stripped_file_hash(&cand_path)
.unwrap_or_else(|_| format!("{}unknown_cand", crate::hash::DEFAULT_HASH_PREFIX));
let domain_json = serde_json::to_string(&inputs).unwrap_or_default();
let domain_hash = crate::fs_utils::compute_content_hash(&domain_json);
let mut matched = 0;
let mut total = 0;
let mut witness_lines = Vec::new();
let mut ref_total_ms = 0;
let mut cand_total_ms = 0;
let mut thread_results = Vec::new();
std::thread::scope(|s| {
let mut handles = Vec::new();
for input in &inputs {
let handle_ref = s.spawn(|| {
let start = std::time::Instant::now();
let res = execute_pcard(clm_root, ref_pcard, input);
let elapsed = start.elapsed().as_millis() as u64;
(res, elapsed)
});
let handle_cand = s.spawn(|| {
let start = std::time::Instant::now();
let res = execute_pcard(clm_root, cand_pcard, input);
let elapsed = start.elapsed().as_millis() as u64;
(res, elapsed)
});
handles.push((input, handle_ref, handle_cand));
}
for (input, h_ref, h_cand) in handles {
let (out_ref_res, ref_elapsed) = h_ref.join().unwrap();
let (out_cand_res, cand_elapsed) = h_cand.join().unwrap();
thread_results.push((input, out_ref_res, ref_elapsed, out_cand_res, cand_elapsed));
}
});
for (input, out_ref_res, ref_elapsed, out_cand_res, cand_elapsed) in thread_results {
total += 1;
ref_total_ms += ref_elapsed;
cand_total_ms += cand_elapsed;
let (out_ref, ref_err) = match out_ref_res {
Ok(s) => (s, None),
Err(e) => (String::new(), Some(e)),
};
let (out_cand, cand_err) = match out_cand_res {
Ok(s) => (s, None),
Err(e) => (String::new(), Some(e)),
};
let norm_ref = normalize_output(&out_ref, &opts);
let norm_cand = normalize_output(&out_cand, &opts);
let mut result = "fail";
let mut comp_made = false;
if ref_err.is_none() && cand_err.is_none() {
comp_made = true;
match relation_type {
"identity" => {
if norm_ref == norm_cand {
result = "pass";
matched += 1;
}
}
"structural" => {
if let (Ok(ref_v), Ok(cand_v)) = (parse_json_or_yaml(&norm_ref), parse_json_or_yaml(&norm_cand)) {
let clean_ref = canonical_value(&clean_data(&ref_v));
let clean_cand = canonical_value(&clean_data(&cand_v));
if clean_ref == clean_cand {
result = "pass";
matched += 1;
}
}
}
"numerical" => {
if compare_numerical(&norm_ref, &norm_cand) {
result = "pass";
matched += 1;
}
}
"hash_invariant" => {
if norm_ref == norm_cand {
result = "pass";
matched += 1;
} else {
if let Ok(eq) = check_content_equivalent(clm_root, &norm_ref, &norm_cand)
&& eq {
result = "pass";
matched += 1;
}
}
}
"invariant" => {
if norm_ref == norm_cand {
result = "pass";
matched += 1;
}
}
_ => return Err(format!("Unknown comparison relation: {}", relation_type)),
}
} else {
result = "error";
}
let ref_trunc = if out_ref.len() > 64 { &out_ref[0..64] } else { &out_ref };
let cand_trunc = if out_cand.len() > 64 { &out_cand[0..64] } else { &out_cand };
let mut witness_parts = vec![
format!("\"input\":\"{}\"", input.replace('"', "\\\"")),
format!("\"ref\":\"{}\"", ref_trunc.trim().replace('"', "\\\"").replace('\n', " ")),
format!("\"cand\":\"{}\"", cand_trunc.trim().replace('"', "\\\"").replace('\n', " ")),
format!("\"result\":\"{}\"", result),
];
if let Some(ref_e) = &ref_err {
witness_parts.push(format!("\"ref_error\":\"{}\"", ref_e.replace('"', "\\\"").replace('\n', " ")));
}
if let Some(cand_e) = &cand_err {
witness_parts.push(format!("\"cand_error\":\"{}\"", cand_e.replace('"', "\\\"").replace('\n', " ")));
}
if result == "fail" && comp_made
&& let Some((idx, ac, bc)) = find_divergence(&norm_ref, &norm_cand) {
witness_parts.push(format!("\"diff_at\":{},\"expected_char\":\"{}\",\"actual_char\":\"{}\"", idx, ac, bc));
}
let witness = format!("{{{}}}", witness_parts.join(","));
witness_lines.push(witness);
if opts.stop_on_first_mismatch && result == "fail" {
break;
}
}
let degree = (matched as f64) / (total as f64);
let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
let agent_did = std::env::var("CLM_AGENT_DID").unwrap_or_else(|_| "did:clm:bootstrap".to_string());
let vcard_yaml = format!(
"clm:\n equivalence_vcard:\n process_ref_hash: \"{}\"\n process_cand_hash: \"{}\"\n domain_hash: \"{}\"\n relation_type: \"{}\"\n degree_of_equivalence: {:.4}\n witness_trail: [{}]\n performance_differential:\n ref_total_ms: {}\n cand_total_ms: {}\n timestamp: \"{}\"\n agent_did: \"{}\"",
ref_hash,
cand_hash,
domain_hash,
relation_type,
degree,
witness_lines.join(","),
ref_total_ms,
cand_total_ms,
timestamp,
agent_did
);
let vcard_hash = crate::fs_utils::compute_content_hash(&vcard_yaml);
let g_time = crate::fs_utils::compute_g_time();
if let Ok(conn) = crate::db::get_connection("content_memory", clm_root) {
let _ = conn.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?);",
rusqlite::params![vcard_hash, vcard_yaml, g_time],
);
let handle_name = format!("vcard:equivalence:{}", vcard_hash);
let _ = conn.execute(
"INSERT OR IGNORE INTO handle_registry (handle, current_hash, updated_at) VALUES (?, ?, ?);",
rusqlite::params![handle_name, vcard_hash, timestamp],
);
}
let handle_name = format!("vcard:equivalence:{}", vcard_hash);
crate::cache::setter_mcard_cache_handle(&handle_name, &vcard_hash);
crate::cache::setter_mcard_cache(&vcard_hash, &vcard_yaml);
let zero_fs = crate::utils::is_zero_fs();
if !zero_fs {
let logs_dir = Path::new(clm_root).join("data").join("execution_logs");
let _ = fs::create_dir_all(&logs_dir);
let file_path = logs_dir.join(format!("equiv_{}.yaml", &vcard_hash[0..8]));
let _ = fs::write(&file_path, &vcard_yaml);
}
let threshold = opts.required_degree.unwrap_or(1.0);
let exit_code = if degree >= threshold { 0 } else { 1 };
Ok((exit_code, format!("{}\n", vcard_hash)))
}
pub use crate::layer1::bisimulation::{CanonNum, evaluate_bisimulation_spec_rs};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_invariants_equivalence_boundary() {
let spec = r#"{"mode":"bialgebraic_bisimulation","cases":[
{"id":"i64_exact_2p53p1","left":{"tag":"AddZero","expr":{"tag":"Lit","value":9007199254740993}},"right":{"tag":"Lit","value":"9007199254740993"},"expected_verdict":"EQUIVALENT"},
{"id":"i64_overflow","left":{"tag":"Add","left":{"tag":"Lit","value":9223372036854775807},"right":{"tag":"Lit","value":1}},"right":{"tag":"Lit","value":-9223372036854775808},"expected_verdict":"DIVERGENT"},
{"id":"nan_diverge","left":{"tag":"Add","left":{"tag":"Lit","value":"NaN"},"right":{"tag":"Lit","value":0}},"right":{"tag":"Lit","value":0},"expected_verdict":"DIVERGENT"},
{"id":"signed_zero","left":{"tag":"Lit","value":-0.0},"right":{"tag":"Lit","value":0},"expected_verdict":"DIVERGENT"},
{"id":"tape_eutt","left":{"tag":"Seq","first":{"tag":"MCardPut","handle":"h","expr":{"tag":"AddZero","expr":{"tag":"Lit","value":7}}},"second":{"tag":"MCardGet","handle":"h"}},"right":{"tag":"Seq","first":{"tag":"MCardPut","handle":"h","expr":{"tag":"Lit","value":7}},"second":{"tag":"AddZero","expr":{"tag":"MCardGet","handle":"h"}}},"expected_verdict":"EQUIVALENT"},
{"id":"tape_order_fault","left":{"tag":"Seq","first":{"tag":"MCardPut","handle":"a","expr":{"tag":"Lit","value":1}},"second":{"tag":"MCardPut","handle":"b","expr":{"tag":"Lit","value":2}}},"right":{"tag":"Seq","first":{"tag":"MCardPut","handle":"b","expr":{"tag":"Lit","value":2}},"second":{"tag":"MCardPut","handle":"a","expr":{"tag":"Lit","value":1}}},"expected_verdict":"DIVERGENT"},
{"id":"bound_open_frontier","max_steps":1,"bound_name":"stepCap","left":{"tag":"AddZero","expr":{"tag":"AddZero","expr":{"tag":"Lit","value":7}}},"right":{"tag":"Lit","value":7},"expected_verdict":"UNDECIDED_WITHIN_BOUND"}
]}"#;
let (rc, out) = evaluate_bisimulation_spec_rs(spec).expect("spec evaluation must succeed");
assert_eq!(rc, 0);
let parsed: serde_json::Value = serde_json::from_str(&out).expect("valid output json");
let res = parsed["results"].as_array().expect("results array");
assert_eq!(res.len(), 7);
assert_eq!(res[0]["certificateVerified"], serde_json::Value::Bool(true));
assert_eq!(res[1]["counterexampleTrace"][0], "RET_MISMATCH:left=OVERFLOW_I64|right=FINITE_I64:-9223372036854775808");
assert_eq!(res[2]["counterexampleTrace"][0], "RET_MISMATCH:left=NAN|right=SIGNED_ZERO:+0");
assert_eq!(res[3]["counterexampleTrace"][0], "RET_MISMATCH:left=SIGNED_ZERO:-0|right=SIGNED_ZERO:+0");
assert_eq!(res[4]["certificate"].as_array().unwrap().len(), 3);
assert_eq!(res[5]["counterexampleTrace"][0], "VIS_MISMATCH:left=PUT:a:FINITE_I64:1|right=PUT:b:FINITE_I64:2");
assert_eq!(res[6]["verdict"], "UNDECIDED_WITHIN_BOUND");
}
}