git mv of the files and of the module directories next to them, mod declarations, #[path] attributes and the paths that name the modules, rewritten by scripts/dev/rename_mechanical.py from a reviewed name table. Two files lost one to two lines so the 400-line limit holds again (qsa_prompt_index, original_verify_expert_probe). limits-baseline.json: test fn_lines 0 -> 1 is --allow-increase for crates/deploy builtin_profiles.rs:149 (37 lines, the speed-vs-strata session's file, not touched here); the prod params census falls 108 -> 1 (w_launch, extern C ABI). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
318 lines
13 KiB
Rust
318 lines
13 KiB
Rust
//! Moved out of the parent module by STRA-338: fn cmd_alternate, fn usage.
|
|
|
|
use super::cmd_compare::mismatch_detail;
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
mod batch;
|
|
|
|
/// Where the batch writes and which executables it starts.
|
|
struct AltPaths {
|
|
out: PathBuf,
|
|
own_exe: PathBuf,
|
|
kab: PathBuf,
|
|
}
|
|
|
|
/// The schedule as written before the first run and read back from the file.
|
|
struct Planned {
|
|
schedule: Vec<(u32, Vec<Proc>)>,
|
|
text: String,
|
|
first_round: u32,
|
|
}
|
|
|
|
/// The paths, the cells of a round and the schedule.
|
|
struct AltPlan {
|
|
paths: AltPaths,
|
|
trees: Vec<&'static str>,
|
|
procs: Vec<Proc>,
|
|
planned: Planned,
|
|
}
|
|
|
|
/// Facts about the host and the output directories, fixed for the whole batch.
|
|
struct AltHost {
|
|
records_dir: PathBuf,
|
|
proc_dir: PathBuf,
|
|
parent_env: Vec<(OsString, OsString)>,
|
|
sibling_at_start: bool,
|
|
machine_role: String,
|
|
rust_tool: Tool,
|
|
}
|
|
|
|
/// One `alternate` batch.
|
|
struct AltRun {
|
|
a: AltArgs,
|
|
verified: Verified,
|
|
case: CaseEntry,
|
|
started: String,
|
|
plan: AltPlan,
|
|
host: AltHost,
|
|
}
|
|
|
|
/// The C++ driver: `--kab`, else `$KAB`, else the build directory of the end-to-end root.
|
|
fn kab_path(a: &AltArgs) -> PathBuf {
|
|
a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| {
|
|
PathBuf::from(
|
|
std::env::var("E2E_ROOT")
|
|
.unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default())),
|
|
)
|
|
.join("build/kernel-ab/kab")
|
|
})
|
|
}
|
|
|
|
/// The output directory, the two executables and the checks that keep generated files out of Git and out of the run
|
|
/// directory.
|
|
fn alt_paths(a: &AltArgs) -> Result<AltPaths, String> {
|
|
let out = a.out.clone().unwrap_or_else(|| {
|
|
let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned());
|
|
a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case))
|
|
});
|
|
let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
|
|
if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) {
|
|
return Err("--out must not contain or lie inside the KAB1 directory".to_owned());
|
|
}
|
|
if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) {
|
|
return Err(
|
|
"--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned()
|
|
);
|
|
}
|
|
let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
|
|
let kab = kab_path(a);
|
|
if !kab.is_file() {
|
|
return Err(format!(
|
|
"the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)",
|
|
kab.display()
|
|
));
|
|
}
|
|
Ok(AltPaths { out, own_exe, kab })
|
|
}
|
|
|
|
/// The schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch.
|
|
fn write_schedule(a: &AltArgs, out: &Path, procs: &[Proc]) -> Result<Planned, String> {
|
|
let first_round = (a.batch - 1) * a.rounds + 1;
|
|
let planned = make_schedule(a.seed, a.batch, a.rounds, procs);
|
|
let header = ScheduleHeader { seed: a.seed, batch: a.batch, rounds: a.rounds, case: &a.case, pin: a.pin };
|
|
let text = schedule_text(header, first_round, &planned);
|
|
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
|
if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) {
|
|
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
|
}
|
|
create_new_file(&a.schedule, text.as_bytes())?;
|
|
let schedule =
|
|
parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?;
|
|
println!(
|
|
"schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes",
|
|
a.schedule.display(),
|
|
sha_hex(text.as_bytes()),
|
|
schedule.len(),
|
|
procs.len()
|
|
);
|
|
Ok(Planned { schedule, text, first_round })
|
|
}
|
|
|
|
fn plan_run(a: &AltArgs, verified: &Verified) -> Result<AltPlan, String> {
|
|
let paths = alt_paths(a)?;
|
|
// a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there)
|
|
let trees: Vec<&'static str> =
|
|
TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect();
|
|
let procs = procs_for(&trees);
|
|
let planned = write_schedule(a, &paths.out, &procs)?;
|
|
Ok(AltPlan { paths, trees, procs, planned })
|
|
}
|
|
|
|
fn probe_host(a: &AltArgs, out: &Path) -> Result<AltHost, String> {
|
|
let (records_dir, proc_dir) = (out.join("records"), out.join("processes"));
|
|
for d in [&records_dir, &proc_dir] {
|
|
fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
|
|
}
|
|
let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect();
|
|
let sibling_at_start = sibling_idle(a.pin);
|
|
let machine_role = a
|
|
.machine_role
|
|
.clone()
|
|
.or_else(|| std::env::var("HOSTNAME").ok())
|
|
.or_else(|| std::env::var("COMPUTERNAME").ok())
|
|
.unwrap_or_else(|| "unknown".to_owned());
|
|
let (version, triple) = rustc_info();
|
|
let rust_tool = Tool { compiler: "rustc".to_owned(), version, triple, flags: ours_flags() };
|
|
Ok(AltHost { records_dir, proc_dir, parent_env, sibling_at_start, machine_role, rust_tool })
|
|
}
|
|
|
|
impl AltRun {
|
|
fn prepare(a: AltArgs, verified: Verified, started: String) -> Result<Self, String> {
|
|
let case = verified
|
|
.cases
|
|
.iter()
|
|
.find(|c| c.id == a.case)
|
|
.ok_or_else(|| format!("case {} is not in the manifest", a.case))?
|
|
.clone();
|
|
let plan = plan_run(&a, &verified)?;
|
|
let host = probe_host(&a, &plan.paths.out)?;
|
|
Ok(Self { a, verified, case, started, plan, host })
|
|
}
|
|
|
|
/// Our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by
|
|
/// timing).
|
|
fn equality_phase(&self) -> Result<BTreeMap<&'static str, Outcome>, String> {
|
|
let eq_dir = self.plan.paths.out.join(format!("equality-b{:04}", self.a.batch));
|
|
let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new();
|
|
for tree in self.plan.trees.iter().copied() {
|
|
equality.insert(tree, self.equality_for(tree, &eq_dir)?);
|
|
}
|
|
Ok(equality)
|
|
}
|
|
|
|
fn equality_for(&self, tree: &'static str, eq_dir: &Path) -> Result<Outcome, String> {
|
|
let (a, case) = (&self.a, &self.case);
|
|
let p = Proc { imp: Impl::Rust, tree, rep: 'a' };
|
|
let mut cmd = scrubbed_command(&self.plan.paths.own_exe, &self.host.parent_env, &cell_env(&p));
|
|
cmd.arg("run-tree")
|
|
.arg(&a.dir)
|
|
.args(["--tree", tree, "--case", &a.case, "--out"])
|
|
.arg(eq_dir)
|
|
.args(["--pin", &a.pin.to_string()]);
|
|
run_cell(&mut cmd, &format!("{}/equality", p.name()))?;
|
|
let ours_name = format!("case-{}.rust-{tree}.out", a.case);
|
|
let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?;
|
|
let o = case.outs.iter().find(|o| o.tree == tree).ok_or("missing reference out")?;
|
|
let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes)))
|
|
.map_err(|e| e.to_string())?;
|
|
let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref());
|
|
let verdict = if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" };
|
|
println!("EQUALITY {} [{tree}] {verdict}{}", a.case, mismatch_detail(&outcome));
|
|
Ok(outcome)
|
|
}
|
|
|
|
fn batch_ctx<'a>(&'a self, equality: &'a BTreeMap<&'static str, Outcome>) -> BatchCtx<'a> {
|
|
let (a, tool) = (&self.a, &self.host.rust_tool);
|
|
BatchCtx {
|
|
verified: &self.verified,
|
|
case: &self.case,
|
|
pin: a.pin,
|
|
machine_role: self.host.machine_role.clone(),
|
|
os: host_os(),
|
|
cpu_model: String::new(),
|
|
started_utc: self.started.clone(),
|
|
rust_tool: tool.clone(),
|
|
batch: a.batch,
|
|
equality,
|
|
}
|
|
}
|
|
|
|
/// Every round of the schedule; returns the names of the records written.
|
|
fn rounds(&self, equality: &BTreeMap<&'static str, Outcome>) -> Result<Vec<String>, String> {
|
|
let mut ctx = self.batch_ctx(equality);
|
|
let mut written = Vec::new();
|
|
for (round_no, order) in &self.plan.planned.schedule {
|
|
let done = self.run_round(order, *round_no)?;
|
|
if ctx.cpu_model.is_empty() {
|
|
ctx.cpu_model =
|
|
done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned());
|
|
let path = self.plan.paths.out.join(format!("batch-{:04}.json", self.a.batch));
|
|
create_new_file(&path, self.batch_json(&ctx.cpu_model, equality)?.as_bytes())?;
|
|
}
|
|
for (name, json) in round_records(&ctx, *round_no, &done)? {
|
|
create_new_file(&self.host.records_dir.join(&name), json.as_bytes())?;
|
|
written.push(name);
|
|
}
|
|
println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::<Vec<_>>().join(" "));
|
|
}
|
|
Ok(written)
|
|
}
|
|
|
|
fn run_round(&self, order: &[Proc], round_no: u32) -> Result<Vec<ProcOut>, String> {
|
|
let mut done: Vec<ProcOut> = Vec::new();
|
|
for p in order {
|
|
done.push(self.run_proc(p, round_no)?);
|
|
}
|
|
Ok(done)
|
|
}
|
|
|
|
/// The `time` command of one cell, writing its JSON to `file`.
|
|
fn cell_command(&self, p: &Proc, file: &Path) -> Command {
|
|
let (a, paths) = (&self.a, &self.plan.paths);
|
|
let mut cmd = scrubbed_command(
|
|
if p.imp == Impl::Cpp { &paths.kab } else { &paths.own_exe },
|
|
&self.host.parent_env,
|
|
&cell_env(p),
|
|
);
|
|
cmd.arg("time")
|
|
.args(["--run-dir"])
|
|
.arg(&a.dir)
|
|
.args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"])
|
|
.arg(file);
|
|
if let Some(ms) = a.slice_ms {
|
|
cmd.args(["--slice-ms", &ms.to_string()]);
|
|
}
|
|
if let Some(b) = a.llc_bytes {
|
|
cmd.args(["--llc-bytes", &b.to_string()]);
|
|
}
|
|
cmd
|
|
}
|
|
|
|
fn run_proc(&self, p: &Proc, round_no: u32) -> Result<ProcOut, String> {
|
|
let name = p.name();
|
|
let file = self.host.proc_dir.join(format!("r{round_no:05}-{name}.json"));
|
|
let res = run_cell(&mut self.cell_command(p, &file), &name)?;
|
|
fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat())
|
|
.map_err(|e| format!("{}: {e}", file.display()))?;
|
|
let bytes =
|
|
fs::read(&file).map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?;
|
|
let expect = Expect {
|
|
manifest_sha: &self.verified.manifest_sha256,
|
|
input_sha: &self.case.in_sha256,
|
|
case: &self.a.case,
|
|
pin: self.a.pin,
|
|
};
|
|
parse_proc_json(p, &bytes, &expect)
|
|
}
|
|
|
|
fn summarize(&self, written: &[String], equality: &BTreeMap<&'static str, Outcome>) {
|
|
let a = &self.a;
|
|
println!(
|
|
"ALTERNATE OK batch={} rounds={} records={} dir={}",
|
|
a.batch,
|
|
a.rounds,
|
|
written.len(),
|
|
self.host.records_dir.display()
|
|
);
|
|
for (t, o) in equality {
|
|
println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" });
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn cmd_alternate(args: &[String]) -> Result<ExitCode, String> {
|
|
let a = parse_alt_args(args)?;
|
|
let started = now_utc();
|
|
let verified = match verify_dir(&a.dir) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
println!("{e}");
|
|
return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 }));
|
|
}
|
|
};
|
|
let run = AltRun::prepare(a, verified, started)?;
|
|
let equality = run.equality_phase()?;
|
|
let written = run.rounds(&equality)?;
|
|
run.summarize(&written, &equality);
|
|
Ok(ExitCode::SUCCESS)
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------ main
|
|
|
|
pub(super) fn usage() -> ExitCode {
|
|
eprintln!(
|
|
"usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | \
|
|
run-tree D --tree T --out R [--pin CPU] [--case ID]"
|
|
);
|
|
eprintln!(
|
|
" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime \
|
|
both|resident|streamed] [--llc-bytes B]"
|
|
);
|
|
eprintln!(
|
|
" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] \
|
|
[--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]"
|
|
);
|
|
ExitCode::from(64)
|
|
}
|