Files
leleka/crates/native-cpu-expert/examples/kernel_ab/describe_cpp_tree_fn.rs
T

199 lines
7.8 KiB
Rust

//! 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::<Vec<_>>()
.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<ProcOut, String> {
let j = parse_json(bytes)?;
let name = p.name();
let fail = |what: String| format!("cell {name}: {what}");
if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 {
return Err(fail("the output is not KAB1-time version 1".to_owned()));
}
if j.str("writer").map_err(fail)? != p.imp.name() {
return Err(fail(format!(
"the output's writer is {:?}, expected {}",
j.str("writer").unwrap_or("?"),
p.imp.name()
)));
}
if j.str("tree").map_err(fail)? != p.tree {
return Err(fail(format!(
"the process ran the {} tree, the cell asks for {}",
j.str("tree").unwrap_or("?"),
p.tree
)));
}
if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha {
return Err(fail("manifest_sha256 differs from the run directory's".to_owned()));
}
let c = j.req("case").map_err(fail)?;
if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha {
return Err(fail("the case id or its input hash differs from the manifest's".to_owned()));
}
let pin = j.req("pin").map_err(fail)?;
if pin.uint("cpu").map_err(fail)? as usize != expect.pin {
return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin)));
}
let want_env: BTreeMap<String, String> = cell_env(p).into_iter().collect();
let mut seen_env = BTreeMap::new();
if let Json::Obj(items) = j.req("effective_env").map_err(fail)? {
for (k, v) in items {
seen_env.insert(
k.clone(),
match v {
Json::Str(s) => s.clone(),
Json::Num(n) => n.clone(),
_ => "?".to_owned(),
},
);
}
}
if seen_env != want_env {
return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}")));
}
let mut regimes = BTreeMap::new();
for r in j.array("regimes").map_err(fail)? {
let label = r.str("regime").map_err(fail)?.to_owned();
regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?);
}
for want in ["RESIDENT", "STREAMED"] {
if !regimes.contains_key(want) {
return Err(fail(format!("regime {want} is missing")));
}
}
let clock = j.req("clock_calibration").map_err(fail)?;
let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? {
Json::Null => Some(true),
_ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT),
};
let detail = j.req("tree_detail").map_err(fail)?;
let (tree_text, cpu_report) = if p.imp == Impl::Rust {
let report: Vec<String> = detail
.array("cpu_report")
.map_err(fail)?
.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(|| fail("no process kernel family line".to_owned()))?;
(format!("leleka-serve {line}"), report)
} else {
(describe_cpp_tree(detail), Vec::new())
};
let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report));
Ok(ProcOut {
proc: *p,
regimes,
ghz_start: clock.float("ghz_at_start").map_err(fail)?,
ghz_end: clock.float("ghz_at_end").map_err(fail)?,
sibling_idle,
final_unchanged: j.flag("final_output_unchanged").map_err(fail)?,
output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }),
tree_text,
cpu_model,
})
}
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())
}