//! Moved out of the parent module by STRA-338: fn describe_cpp_tree, fn parse_proc_json, impl Kind, fn side_stat, fn //! stat_json, fn tool_json .... #[allow(unused_imports)] use super::*; pub(super) fn describe_cpp_tree(d: &Json) -> String { let b = |k: &str| { d.get(k).map_or("?".to_owned(), |v| match v { Json::Bool(x) => x.to_string(), Json::Num(n) => n.clone(), _ => "?".to_owned(), }) }; let env = match d.get("strata_env") { Some(Json::Obj(items)) if !items.is_empty() => items .iter() .map(|(k, v)| format!("{k}={}", if let Json::Str(s) = v { s.as_str() } else { "?" })) .collect::>() .join(" "), _ => "no STRATA_* variable set (STRATA_NO_IQ512, STRATA_NO_IQ256 and STRATA_IQ_GATHER unset)".to_owned(), }; format!( "avx2_ok={} avx512_ok={} iq512_gather_on={} iq256_gather_setting={}; {env}", b("avx2_ok"), b("avx512_ok"), b("iq512_gather_on"), b("iq256_gather_setting") ) } /// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input /// hashes, case, pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's. pub(super) fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result { let j = parse_json(bytes)?; let name = p.name(); proc_out(&j, p, expect).map_err(|what| format!("cell {name}: {what}")) } /// The body of `parse_proc_json`; every error text is still to be prefixed with the cell name by the caller. fn proc_out(j: &Json, p: &Proc, expect: &Expect) -> Result { let pin = check_proc_json(j, p, expect)?; let (regimes, clock) = read_regimes_and_clock(j, p)?; let sibling_idle = sibling_idle_of(pin)?; let (tree_text, cpu_model) = tree_report(j.req("tree_detail")?, p)?; Ok(ProcOut { proc: *p, regimes, ghz_start: clock.float("ghz_at_start")?, ghz_end: clock.float("ghz_at_end")?, sibling_idle, final_unchanged: j.flag("final_output_unchanged")?, output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }), tree_text, cpu_model, }) } /// The identity of the output against the cell and the run; returns the `pin` object for the later reads. fn check_proc_json<'j>(j: &'j Json, p: &Proc, expect: &Expect) -> Result<&'j Json, String> { check_identity(j, p)?; check_manifest_case(j, expect)?; check_pin_env(j, p, expect) } fn check_identity(j: &Json, p: &Proc) -> Result<(), String> { if j.str("format")? != "KAB1-time" || j.uint("version")? != 1 { return Err("the output is not KAB1-time version 1".to_owned()); } if j.str("writer")? != p.imp.name() { return Err(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name())); } if j.str("tree")? != p.tree { return Err(format!("the process ran the {} tree, the cell asks for {}", j.str("tree").unwrap_or("?"), p.tree)); } Ok(()) } fn check_manifest_case(j: &Json, expect: &Expect) -> Result<(), String> { if j.str("manifest_sha256")? != expect.manifest_sha { return Err("manifest_sha256 differs from the run directory's".to_owned()); } let c = j.req("case")?; if c.str("id")? != expect.case || c.str("input_sha256")? != expect.input_sha { return Err("the case id or its input hash differs from the manifest's".to_owned()); } Ok(()) } fn check_pin_env<'j>(j: &'j Json, p: &Proc, expect: &Expect) -> Result<&'j Json, String> { let pin = j.req("pin")?; if pin.uint("cpu")? as usize != expect.pin { return Err(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin)); } let want_env: BTreeMap = cell_env(p).into_iter().collect(); let seen_env = effective_env(j)?; if seen_env != want_env { return Err(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")); } Ok(pin) } fn effective_env(j: &Json) -> Result, String> { let mut seen_env = BTreeMap::new(); if let Json::Obj(items) = j.req("effective_env")? { for (k, v) in items { seen_env.insert( k.clone(), match v { Json::Str(s) => s.clone(), Json::Num(n) => n.clone(), _ => "?".to_owned(), }, ); } } Ok(seen_env) } /// The per-regime statistics (both regimes must be present) and the `clock_calibration` object. fn read_regimes_and_clock<'j>(j: &'j Json, p: &Proc) -> Result<(BTreeMap, &'j Json), String> { let mut regimes = BTreeMap::new(); for r in j.array("regimes")? { let label = r.str("regime")?.to_owned(); regimes.insert(label, parse_regime(r, p.imp)?); } for want in ["RESIDENT", "STREAMED"] { if !regimes.contains_key(want) { return Err(format!("regime {want} is missing")); } } Ok((regimes, j.req("clock_calibration")?)) } fn sibling_idle_of(pin: &Json) -> Result, String> { Ok(match pin.req("sibling_cpu")? { Json::Null => Some(true), _ => pin.float_or_null("sibling_busy_fraction_during_run")?.map(|f| f < SIBLING_BUSY_LIMIT), }) } /// The tree text of the record and the CPU model (only a Rust process reports one). fn tree_report(detail: &Json, p: &Proc) -> Result<(String, Option), String> { let (tree_text, cpu_report) = if p.imp == Impl::Rust { rust_tree_report(detail)? } else { (describe_cpp_tree(detail), Vec::new()) }; let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report)); Ok((tree_text, cpu_model)) } fn rust_tree_report(detail: &Json) -> Result<(String, Vec), String> { let report: Vec = detail .array("cpu_report")? .iter() .filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None }) .collect(); let line = report .iter() .find(|l| l.starts_with("cpu: process kernel family")) .cloned() .ok_or_else(|| "no process kernel family line".to_owned())?; Ok((format!("leleka-serve {line}"), report)) } impl Kind { pub(super) fn slug(self) -> &'static str { match self { Kind::Ab => "ab", Kind::AaCpp => "aa-cpp", Kind::AaRust => "aa-rust", } } } pub(super) fn side_stat(r: &RegimeStat, cycles: bool) -> SideStat { let v = if cycles { &r.cycles } else { &r.ns }; SideStat { median: if cycles { r.median_cycles } else { r.median_ns }, p05: percentile_of(v, 0.05), p95: percentile_of(v, 0.95), } } pub(super) fn stat_json(s: &SideStat) -> String { format!("{{\"median\": {}, \"p05\": {}, \"p95\": {}}}", jnum(s.median, 6), jnum(s.p05, 6), jnum(s.p95, 6)) } pub(super) fn tool_json(t: &Tool) -> String { format!( "{{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}", jstr(&t.compiler), jstr(&t.version), jstr(&t.triple), jstr(&t.flags) ) } pub(super) fn equality_block(c: &CaseEntry, o: &Outcome) -> String { let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { format!( ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", t.value, jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), jstr(&t.basis_written_utc) ) }); format!( "{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": \ {}{tolerance}\n }}", if c.tolerance.is_some() { "tolerance" } else { "bitwise" }, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, o.compared, o.mismatches ) } /// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes /// (and each one's selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit /// (selfcheck), which is the same function. pub(super) fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { let compared = rows * H; let selfchecks = a.regimes.values().chain(b.regimes.values()).all(|r| r.selfcheck) && a.final_unchanged && b.final_unchanged; let same = selfchecks && (a.proc.imp == Impl::Cpp || (a.output_sha.is_some() && a.output_sha == b.output_sha)); let note = if a.proc.imp == Impl::Cpp { "selfcheck of both processes against compose_expert()" } else { "output sha256 of both processes" }; let outcome = Outcome { compared, mismatches: usize::from(!same), differing_bits: usize::from(!same), max_abs_error: 0.0, first_mismatch: None, }; (outcome, note.to_owned()) }