use serde_json::Value;
use super::config::{normalize_output, print_diff};
use crate::db;
pub fn verify_sla(
case_name: &str,
runtime: &str,
then: &Value,
elapsed_ms: i64,
peak_rss_val: i64,
fork_count: i64,
) -> Result<(), String> {
let sla = then.get("performance_sla");
let max_duration_ms = sla.and_then(|s| s.get("max_duration_ms")).and_then(|v| v.as_i64());
let max_rss_kb = sla.and_then(|s| s.get("max_rss_kb")).and_then(|v| v.as_i64());
let max_forks = sla.and_then(|s| s.get("max_forks")).and_then(|v| v.as_i64());
if let Some(max_dur) = max_duration_ms
&& elapsed_ms > max_dur {
return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_duration_ms: {}ms > {}ms", case_name, runtime, elapsed_ms, max_dur));
}
if let Some(max_rss) = max_rss_kb
&& peak_rss_val > max_rss {
return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_rss_kb: {}KB > {}KB", case_name, runtime, peak_rss_val, max_rss));
}
if let Some(max_f) = max_forks
&& fork_count > max_f {
return Err(format!("❌ [SLA_VIOLATION] Case '{}' runtime '{}' exceeded max_forks: {} > {}", case_name, runtime, fork_count, max_f));
}
Ok(())
}
pub fn record_exec_mcard(
_case_name: &str,
runtime: &str,
inputs: &serde_json::Map<String, Value>,
stdout_data: &str,
run_status: i32,
active_a_hash: &str,
active_c_hash: &str,
clm_root: &str,
) -> Result<String, String> {
let runtime_facts = crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_RUNTIME_FACTS).unwrap_or_default();
let clean_out = stdout_data.trim_end();
let exec_hash_input = format!(
"inputs: {} | outputs: {} | exit_code: {} | runtime: {} | runtime_facts: {}",
Value::Object(inputs.clone()), clean_out, run_status, runtime, runtime_facts
);
let exec_hash = crate::fs_utils::compute_content_hash(&exec_hash_input);
let mut extra_fields = format!(
"exit_code: {}\noutputs:\n result: \"{}\"\ninputs:\n",
run_status, clean_out.replace('\"', "\\\"")
);
for (k, v) in inputs {
let val_str = match v {
Value::String(s) => s.clone(),
other => other.to_string(),
};
extra_fields.push_str(&format!(" {}: {}\n", k, val_str));
}
let mcard_path = db::emit_exec_mcard(
&format!("polyglot_execution_{}", runtime),
&exec_hash,
&extra_fields,
active_a_hash,
active_c_hash,
clm_root,
).map_err(|e| e.to_string())?;
eprintln!("[PAL:polyglot] ✅ Execution MCard ({}) registered: {}", runtime, mcard_path);
Ok(exec_hash)
}
pub fn verify_parity_and_record_consensus(
case_name: &str,
executed_runtimes: &[String],
runtime_outputs: &[String],
runtime_exit_codes: &[i32],
runtime_exec_hashes: &[String],
active_a_hash: &str,
active_c_hash: &str,
clm_root: &str,
) -> Result<(i32, String), String> {
let exec_count = executed_runtimes.len();
if exec_count == 0 {
return Err(format!("No runtimes were successfully executed for case '{}'.", case_name));
}
let first_out = &runtime_outputs[0];
let first_code = runtime_exit_codes[0];
let first_norm = normalize_output(first_out);
let mut parity_failed = false;
let mut mismatch_rt = "";
let mut mismatch_out = String::new();
for i in 1..exec_count {
let r_name = &executed_runtimes[i];
let r_out = &runtime_outputs[i];
let r_code = runtime_exit_codes[i];
let r_norm = normalize_output(r_out);
if r_code != first_code {
parity_failed = true;
mismatch_rt = r_name;
mismatch_out = format!("Exit code mismatch: {}={} vs {}={}", executed_runtimes[0], first_code, r_name, r_code);
break;
}
if r_norm != first_norm {
parity_failed = true;
mismatch_rt = r_name;
mismatch_out = r_out.clone();
break;
}
}
if parity_failed {
let err_msg = format!(
"COHOMOLOGICAL OBSTRUCTION: Cross-Runtime Parity Fail\n\
❌ [PARITY_ERR] Polyglot execution mismatch between '{}' and '{}' in case '{}'!\n\
--- Outputs:\n\
1. {}: {}\n\
2. {}: {}\n\
--- Diff:\n",
executed_runtimes[0], mismatch_rt, case_name,
executed_runtimes[0], first_out.trim(),
mismatch_rt, mismatch_out.trim()
);
print_diff(&first_norm, &normalize_output(&mismatch_out));
return Err(err_msg);
}
if exec_count > 1 {
let mut sorted_hashes = runtime_exec_hashes.to_vec();
sorted_hashes.sort();
let fold_input = sorted_hashes.join("");
let parity_hash = crate::fs_utils::compute_sha256_hex(fold_input.as_bytes());
let clean_first_out = first_out.trim_end();
let mut parity_fields = format!(
"consensus_exit_code: {}\nconsensus_result: \"{}\"\nactive_runtimes:\n",
first_code, clean_first_out.replace('\"', "\\\"")
);
for r in executed_runtimes {
parity_fields.push_str(&format!(" - {}\n", r));
}
let parity_file = db::emit_exec_mcard(
"polyglot_parity",
&parity_hash,
&parity_fields,
active_a_hash,
active_c_hash,
clm_root,
).map_err(|e| e.to_string())?;
eprintln!("[PAL:polyglot] ✅ Consensus Parity MCard registered: {}", parity_file);
}
let shared_points = if exec_count > 1 { 1 } else { 0 };
let cross_confirmed = exec_count.saturating_sub(1);
eprintln!(
"[EPIPLEXITY] Metrics for case '{}': runtimes={}, shared_test_points={}, cross_confirmed_assertions={}",
case_name, exec_count, shared_points, cross_confirmed
);
Ok((first_code, first_out.clone()))
}