diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs new file mode 100644 index 00000000..ed568144 --- /dev/null +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -0,0 +1,124 @@ +//! `approxbench benchmark-external`: run one engine over a run directory, or join +//! every engine run's cells into the report. +//! +//! Example: `approxbench benchmark-external run --run-directory R --engine fake`, then +//! `approxbench benchmark-external report --run-directory R --truth fake/v1`. + +use std::path::PathBuf; + +use anyhow::{bail, Context, Result}; +use aqpbm_core::harness::benchmark_external::{report, run_engine, write_report, EngineRunSetup}; +use aqpbm_core::harness::engine::EngineUnderTest; +use aqpbm_core::harness::fake::FakeEngine; +use aqpbm_core::harness::protocol::{ + load_probe_for, MeasurementClocks, OsCpuClock, ProcessCpuFiles, Protocol, +}; +use aqpbm_core::harness::run_directory::RunDirectory; +use clap::{Parser, Subcommand}; + +/// The engines this binary can run. +pub const ENGINES: [&str; 1] = ["fake"]; + +#[derive(Parser, Debug)] +pub struct BenchmarkExternalArgs { + #[command(subcommand)] + pub command: BenchmarkExternalCmd, +} + +#[derive(Subcommand, Debug)] +pub enum BenchmarkExternalCmd { + /// Run every (workload, variant) cell of the run directory on one engine. + Run(RunArgs), + /// Join every engine run's cells into summary.csv, summary.md and accuracy.csv. + Report(ReportArgs), +} + +#[derive(Parser, Debug)] +pub struct RunArgs { + /// The run directory: workloads/, plans//, results/. + #[arg(long)] + pub run_directory: PathBuf, + /// The engine: `fake` (the harness's own fake engine). + #[arg(long)] + pub engine: String, + /// Only these variants (repeatable); every variant under plans/ by default. + #[arg(long = "variant")] + pub variants: Vec, + /// The core the harness pins each step to. + #[arg(long, default_value_t = 0)] + pub core: usize, + /// Runs discarded before measuring, per step. + #[arg(long, default_value_t = Protocol::default().warmup_runs)] + pub warmup: u32, + /// Runs measured per step; odd. + #[arg(long, default_value_t = Protocol::default().measured_runs)] + pub runs: u32, + /// A core busier than this fraction before a step refuses it. + #[arg(long, default_value_t = Protocol::default().max_core_busy_fraction)] + pub max_core_busy: f64, +} + +#[derive(Parser, Debug)] +pub struct ReportArgs { + #[arg(long)] + pub run_directory: PathBuf, + /// The cells answers are compared with: `/`. + #[arg(long)] + pub truth: String, +} + +pub fn run(args: BenchmarkExternalArgs) -> Result<()> { + match args.command { + BenchmarkExternalCmd::Run(args) => run_engine_cmd(args), + BenchmarkExternalCmd::Report(args) => report_cmd(args), + } +} + +fn run_engine_cmd(args: RunArgs) -> Result<()> { + let engine: Box = match args.engine.as_str() { + "fake" => Box::new(FakeEngine::default()), + other => bail!( + "unknown engine '{other}'; known engines: {}", + ENGINES.join(", ") + ), + }; + let run_directory = RunDirectory::open(&args.run_directory)?; + let protocol = Protocol { + warmup_runs: args.warmup, + measured_runs: args.runs, + max_core_busy_fraction: args.max_core_busy, + }; + let clocks = MeasurementClocks::with_calling_thread(&OsCpuClock); + // The idle check watches the server's cores for an external server, the + // harness core for an in-process engine. + let mut probe = load_probe_for(&engine.cpu_accounting(), &ProcessCpuFiles::os())?; + let only = (!args.variants.is_empty()).then_some(args.variants.as_slice()); + let cells = run_engine( + &run_directory, + engine.as_ref(), + only, + EngineRunSetup { + protocol: &protocol, + core: args.core, + probe: probe.as_mut(), + clocks: &clocks, + args: std::env::args().collect(), + }, + )?; + for cell in cells { + println!("{} {} {:?}", cell.workload, cell.variant, cell.outcome); + } + Ok(()) +} + +fn report_cmd(args: ReportArgs) -> Result<()> { + let (engine, variant) = args + .truth + .split_once('/') + .context("--truth must be /")?; + let run_directory = RunDirectory::open(&args.run_directory)?; + let report = report(&run_directory, engine, variant)?; + write_report(&run_directory, &report)?; + print!("{}", report.summary_markdown()); + Ok(()) +} diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index d68577b4..fb88c46b 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -8,6 +8,7 @@ use clap::builder::TypedValueParser; use clap::{Parser, Subcommand}; use crate::atomic_costs_cmd; +use crate::benchmark_external_cmd; use crate::flatten_cmd; #[derive(Parser, Debug)] @@ -37,6 +38,8 @@ pub enum Cmd { /// records that came from several invocations of the same cell rather /// than one. Flatten(flatten_cmd::FlattenArgs), + /// Run one engine of a comparison over a run directory, or report all engine runs. + BenchmarkExternal(benchmark_external_cmd::BenchmarkExternalArgs), } /// One target of the sketch bundle: one variant, one library, one construction diff --git a/aqpbm-cli/src/lib.rs b/aqpbm-cli/src/lib.rs index 66017708..0fa085f3 100644 --- a/aqpbm-cli/src/lib.rs +++ b/aqpbm-cli/src/lib.rs @@ -1,5 +1,6 @@ pub mod atomic_costs; pub mod atomic_costs_cmd; +pub mod benchmark_external_cmd; pub mod cli; pub mod external; pub mod flatten_cmd; diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 999bbb27..c98a21d5 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -22,7 +22,7 @@ static GLOBAL: aqpbm_core::metrics::heap_track::TrackingAllocator Result<()> { @@ -31,5 +31,6 @@ fn main() -> Result<()> { Cmd::Sketchbench(args) => sketchbench::run_sketchbench(args), Cmd::AtomicCosts(args) => atomic_costs_cmd::run(args), Cmd::Flatten(args) => flatten_cmd::run(args), + Cmd::BenchmarkExternal(args) => benchmark_external_cmd::run(args), } } diff --git a/aqpbm-cli/tests/benchmark_external_cli.rs b/aqpbm-cli/tests/benchmark_external_cli.rs new file mode 100644 index 00000000..8f2de042 --- /dev/null +++ b/aqpbm-cli/tests/benchmark_external_cli.rs @@ -0,0 +1,164 @@ +//! `approxbench benchmark-external run` and `report` on the fake engine. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use aqpbm_core::harness::data::DataRecord; +use aqpbm_core::harness::engine::{QueryLanguage, QueryText, WorkloadQuery, WorkloadSpec}; +use aqpbm_core::harness::run_directory::RunDirectory; +use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; + +fn workload(name: &str) -> WorkloadSpec { + WorkloadSpec { + name: name.into(), + queries: vec![WorkloadQuery { + id: "sum".into(), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: "sum_over_time(m[10s])".into(), + }], + window_ms: 10_000, + evaluation_interval_ms: 10_000, + }], + data: vec![DataRecord { + metric: "m".into(), + description: TimeSeriesDescription { + labels: vec![SeriesLabelSpec { + name: "s".into(), + cardinality: 2, + skewness: 0.0, + }], + series_num: 2, + start_ms: 0, + sample_interval_ms: 1_000, + duration_ms: 60_000, + value_distribution: DataDistribution::Uniform(UniformParameter { + lower_bound: 0.0, + upper_bound: 10.0, + seed: 0, + }), + counter: false, + seed: 1, + }, + }], + } +} + +fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); +} + +fn fixture(test: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!( + "approxbench-benchmark-external-{}-{test}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&root); + let run = RunDirectory::create_at(&root.join("run")).unwrap(); + for name in ["w1", "w2"] { + write( + &run.path().join(format!("workloads/{name}.json")), + &serde_json::to_string(&workload(name)).unwrap(), + ); + } + let plans = run.path().join("plans"); + write( + &plans.join("v1/variant.json"), + r#"{"substitutions_allowed": false}"#, + ); + write(&plans.join("v1/w1.plan.json"), "{}"); + write( + &plans.join("v1/w2.no-plan.json"), + r#"{"reason": "ExcludedByDeployment"}"#, + ); + write( + &plans.join("v2/variant.json"), + r#"{"substitutions_allowed": true}"#, + ); + write(&plans.join("v2/w1.plan.json"), "{}"); + write(&plans.join("v2/w2.plan.json"), "{}"); + run.path().to_path_buf() +} + +fn approxbench(args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(args) + .output() + .unwrap() +} + +/// X1: a fake engine runs every cell, and the report has one row per cell. +#[test] +fn a_fake_engine_runs_and_reports() { + let run = fixture("x1"); + let run_directory = run.to_str().unwrap(); + let out = approxbench(&[ + "benchmark-external", + "run", + "--run-directory", + run_directory, + "--engine", + "fake", + "--warmup", + "0", + "--runs", + "1", + "--max-core-busy", + "1.0", + ]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let out = approxbench(&[ + "benchmark-external", + "report", + "--run-directory", + run_directory, + "--truth", + "fake/v2", + ]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let summary = std::fs::read_to_string(run.join("summary.csv")).unwrap(); + assert_eq!(summary.lines().count(), 5, "{summary}"); + assert!( + summary + .lines() + .any(|line| line.starts_with("w1,fake,v1,ok,thread,")), + "{summary}" + ); + assert!( + summary + .lines() + .any(|line| line.starts_with("w2,fake,v1,no plan: ExcludedByDeployment")), + "{summary}" + ); + let _ = std::fs::remove_dir_all(run.parent().unwrap()); +} + +/// X2: an unknown engine names the known ones. +#[test] +fn an_unknown_engine_names_the_known_engines() { + let run = fixture("x2"); + let out = approxbench(&[ + "benchmark-external", + "run", + "--run-directory", + run.to_str().unwrap(), + "--engine", + "clickhouse", + ]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("clickhouse") && stderr.contains("fake"), + "{stderr}" + ); + let _ = std::fs::remove_dir_all(run.parent().unwrap()); +} diff --git a/aqpbm-core/Cargo.toml b/aqpbm-core/Cargo.toml index 01b62327..960b9c70 100644 --- a/aqpbm-core/Cargo.toml +++ b/aqpbm-core/Cargo.toml @@ -53,8 +53,8 @@ tikv-jemalloc-ctl = { workspace = true, optional = true } [target.'cfg(unix)'.dependencies] libc.workspace = true -# Runs on the process's main thread (no libtest harness), where a pinned -# thread is also the thread whose affinity `getpid()` names. +# Runs on the process's main thread (no libtest harness), so the thread the +# test pins is the one whose affinity it then reads. [[test]] name = "harness_pin_main_thread" harness = false diff --git a/aqpbm-core/src/harness/arm_run.rs b/aqpbm-core/src/harness/arm_run.rs index 1f9be853..f497b601 100644 --- a/aqpbm-core/src/harness/arm_run.rs +++ b/aqpbm-core/src/harness/arm_run.rs @@ -4,7 +4,8 @@ use crate::harness::data::{workload_chunks, DataError}; use crate::harness::engine::{ - Answers, ArmSpec, EngineError, EngineUnderTest, InstalledArm, MeasuredUsage, WorkloadSpec, + Answers, ArmSpec, CpuAccounting, EngineError, EngineUnderTest, InstalledArm, MeasuredUsage, + WorkloadSpec, }; use crate::harness::protocol::{ CoreLoad, EngineClock, JobRecord, LoadProbe, MeasurementClocks, Protocol, ProtocolError, @@ -20,6 +21,126 @@ pub struct ArmSchedule { pub evaluate_at_ms: Vec, } +impl ArmSchedule { + /// The schedule every engine run uses for `workload`: refresh every evaluation + /// interval, and evaluate at every multiple of the interval + /// (`t mod interval = 0`) from the data start plus the longest window + /// through the data end. + /// The data start must be a multiple of the interval, so each evaluation + /// time is a chunk end. + /// Example: windows 30 s and 20 s, every 10 s, data from 0 ms for + /// 120 s: refresh 10 s, evaluations at 30,000, 40,000, ..., 120,000 ms. + pub fn for_workload(workload: &WorkloadSpec) -> Result { + let first = workload.queries.first().ok_or(ScheduleError::NoQueries { + workload: workload.name.clone(), + })?; + let interval_ms = first.evaluation_interval_ms; + if interval_ms == 0 { + return Err(ScheduleError::ZeroInterval { + query: first.id.clone(), + }); + } + if let Some(other) = workload + .queries + .iter() + .find(|query| query.evaluation_interval_ms != interval_ms) + { + return Err(ScheduleError::MixedEvaluationIntervals { + workload: workload.name.clone(), + first_ms: interval_ms, + other_ms: other.evaluation_interval_ms, + other_query: other.id.clone(), + }); + } + let longest_window_ms = workload + .queries + .iter() + .map(|q| q.window_ms) + .max() + .unwrap_or(0); + let start_ms = workload + .data + .iter() + .map(|record| record.description.start_ms) + .min() + .ok_or(ScheduleError::NoData { + workload: workload.name.clone(), + })?; + let end_ms = workload + .data + .iter() + .map(|record| record.description.start_ms + record.description.duration_ms as i64) + .max() + .unwrap_or(start_ms); + let interval = interval_ms as i64; + // Chunks end at `start + k * refresh`; with an unaligned start an + // evaluation would run after a chunk holding later samples. + if start_ms.rem_euclid(interval) != 0 { + return Err(ScheduleError::UnalignedStart { + workload: workload.name.clone(), + start_ms, + interval_ms, + }); + } + let earliest_ms = start_ms + longest_window_ms as i64; + let first_ms = earliest_ms.div_euclid(interval) * interval + + if earliest_ms.rem_euclid(interval) == 0 { + 0 + } else { + interval + }; + let evaluate_at_ms: Vec = (0..) + .map(|k| first_ms + k * interval) + .take_while(|&at_ms| at_ms <= end_ms) + .collect(); + if evaluate_at_ms.is_empty() { + return Err(ScheduleError::NoEvaluationTime { + workload: workload.name.clone(), + longest_window_ms, + data_ms: (end_ms - start_ms) as u64, + }); + } + Ok(ArmSchedule { + refresh_ms: interval_ms, + evaluate_at_ms, + }) + } +} + +/// A workload no schedule fits. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ScheduleError { + #[error("workload {workload} has no queries")] + NoQueries { workload: String }, + #[error("workload {workload} has no data")] + NoData { workload: String }, + #[error("query {query} has an evaluation interval of 0 ms")] + ZeroInterval { query: String }, + /// Every query of a workload is evaluated at every evaluation time, so + /// one interval per workload; split the workload instead. + #[error("workload {workload}: query {other_query} runs every {other_ms} ms but the first query every {first_ms} ms; one interval per workload")] + MixedEvaluationIntervals { + workload: String, + first_ms: u64, + other_ms: u64, + other_query: String, + }, + /// The data must start on a multiple of the evaluation interval, so + /// every evaluation time is a chunk end. + #[error("workload {workload}: data starts at {start_ms} ms, not a multiple of the evaluation interval {interval_ms} ms")] + UnalignedStart { + workload: String, + start_ms: i64, + interval_ms: u64, + }, + #[error("workload {workload}: the longest window ({longest_window_ms} ms) leaves no evaluation time inside {data_ms} ms of data")] + NoEvaluationTime { + workload: String, + longest_window_ms: u64, + data_ms: u64, + }, +} + /// Runs `arm` of `workload` on `engine` pinned to `core`. Each measured run /// installs the arm afresh, so ingest stays a first ingest; the answers come /// from the last measured run. @@ -76,11 +197,20 @@ pub fn run_arm( } let clock = clocks.clock_for(&engine.cpu_accounting())?; let runs = (protocol.warmup_runs + protocol.measured_runs) as usize; + let server_cgroup = match engine.cpu_accounting() { + CpuAccounting::Cgroup(source) => Some(source), + _ => None, + }; + let server_before = server_cgroup + .as_ref() + .map(|source| Ok::<_, ProtocolError>((source.cpu()?.usage_ns, source.memory()?))) + .transpose()?; let mut installs: Vec> = (0..runs) .map(|_| engine.install(workload, arm)) .collect::>()?; let mut ingest = Vec::new(); + let mut ingested_samples: u64 = 0; let mut evaluate = Vec::new(); let mut answers = Vec::new(); // The after-sample of the last job, the before-sample of the next. @@ -108,6 +238,7 @@ pub fn run_arm( }; for chunk in workload_chunks(&workload.data, schedule.refresh_ms)? { let chunk = chunk?; + ingested_samples += chunk.samples.len() as u64; let mut call = 0; let job = protocol.run_next_job(core, probe, load, &clock, &mut || { let report = installs[call].ingest(&chunk); @@ -126,6 +257,10 @@ pub fn run_arm( let last = installs.last_mut().expect("at least one measured run"); let footprint = last.footprint()?; + let server_after = server_cgroup + .as_ref() + .map(|source| Ok::<_, ProtocolError>((source.cpu()?.usage_ns, source.memory()?))) + .transpose()?; let data_seconds = data_ms as f64 / 1_000.0; let usage = MeasuredUsage { ingest_cpu_ns_per_second: median_cpu_ns(&ingest, &clock) / data_seconds, @@ -144,6 +279,14 @@ pub fn run_arm( evaluate, answers, footprint, + ingested_samples, + server_memory_before: server_before.map(|(_, memory)| memory), + server_memory_after: server_after.map(|(_, memory)| memory), + server_cpu_ns_whole_arm: server_before + .zip(server_after) + .map(|((before_ns, _), (after_ns, _))| after_ns.saturating_sub(before_ns)), + cpu_source: clock.cpu_source(), + installs_held: runs as u32, }) } diff --git a/aqpbm-core/src/harness/benchmark_external.rs b/aqpbm-core/src/harness/benchmark_external.rs new file mode 100644 index 00000000..aaebb4ae --- /dev/null +++ b/aqpbm-core/src/harness/benchmark_external.rs @@ -0,0 +1,887 @@ +//! Engine runs over one run directory, and the report that joins them. +//! +//! An engine run is one engine under test run as its own process over a run +//! directory another step prepared: +//! +//! ```text +//! workloads/.json harness WorkloadSpec +//! plans//variant.json {"substitutions_allowed": false} +//! plans//.plan.json a plan file, opaque to the harness +//! plans//.no-plan.json {"reason": "ExcludedByDeployment"} +//! ``` +//! +//! [`run_engine`] runs every (workload, variant) cell on the engine and writes +//! `results//__.cell.json` (always) and the +//! `ArmResult` beside it (when the cell ran). [`report`] joins every engine run's +//! cells into one row per cell, with absolute CPU, memory and accuracy +//! against a truth engine run, and [`write_report`] writes `summary.csv`, +//! `summary.md` and `accuracy.csv`. +//! +//! Example: engine `clickhouse` over variants `clickhouse.equivalent-only` and +//! `clickhouse.with-substitutes`, engine `asap` over both, report with truth +//! `asap/exact`. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use chrono::Utc; +use serde::{Deserialize, Serialize}; + +use crate::harness::arm_run::{run_arm, ArmSchedule}; +use crate::harness::engine::{ + ArmSpec, CpuAccounting, EngineDescription, EngineUnderTest, WorkloadSpec, +}; +use crate::harness::protocol::{LoadProbe, MeasurementClocks, Protocol}; +use crate::harness::records::ArmResult; +use crate::harness::run_directory::{ + check_result_name, write_json, RunDirectory, RunDirectoryError, +}; + +/// `plans//variant.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct VariantRecord { + /// `false` for a plan restricted to functions equivalent to the + /// planner's: an engine that reports a substitution then disagrees with + /// the capability file the plan was made under, and the cell fails. + pub substitutions_allowed: bool, +} + +/// `plans//.no-plan.json`: why the planner wrote no plan. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NoPlanRecord { + pub reason: String, +} + +/// What a variant holds for one workload. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PlanEntry { + PlanFile(PathBuf), + NoPlan { reason: String }, +} + +/// One variant of the run directory. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Variant { + pub name: String, + pub record: VariantRecord, + /// Per workload. + pub entries: BTreeMap, +} + +/// One (workload, variant) cell of one engine: `__.cell.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EngineRunCell { + pub engine: String, + pub workload: String, + pub variant: String, + pub outcome: CellOutcome, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum CellOutcome { + /// The arm ran; its `ArmResult` is beside the cell. + Ran, + /// The planner wrote no plan for this workload in this variant. + NoPlan { reason: String }, + /// Installing or running failed, such as a translator refusal. + NotRun { error: String }, +} + +/// `results//engine-run-.json`: one engine run and how it measured. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EngineRunRecord { + pub engine: EngineDescription, + pub cpu_accounting: CpuAccounting, + pub protocol: Protocol, + pub core: usize, + /// The command line. + pub args: Vec, +} + +/// The workloads of a run directory, by name (the file stem, which must +/// equal the spec's `name`). +pub fn read_workloads( + run_directory: &RunDirectory, +) -> Result, BenchmarkExternalError> { + let mut workloads = BTreeMap::new(); + for path in sorted_files(&run_directory.path().join("workloads"))? { + let stem = file_stem_with_suffix(&path, ".json")?; + // Refused here, before any cell runs, not when its result is written. + check_result_name("workload", &stem, true)?; + let spec: WorkloadSpec = read_json(&path)?; + if spec.name != stem { + return Err(BenchmarkExternalError::Layout(format!( + "{} holds workload '{}'; the file must be named after it", + path.display(), + spec.name + ))); + } + workloads.insert(stem, spec); + } + Ok(workloads) +} + +/// The variants under `plans/`, each with one entry per workload. +pub fn read_variants( + run_directory: &RunDirectory, + workloads: &BTreeMap, +) -> Result, BenchmarkExternalError> { + let mut variants = Vec::new(); + for dir in sorted_entries(&run_directory.path().join("plans"))? { + if !dir.is_dir() { + return Err(BenchmarkExternalError::Layout(format!( + "{} is not a variant directory", + dir.display() + ))); + } + let name = file_name(&dir); + check_result_name("variant", &name, true)?; + let mut record = None; + let mut entries = BTreeMap::new(); + for path in sorted_files(&dir)? { + let file = file_name(&path); + let (workload, entry) = if file == "variant.json" { + record = Some(read_json::(&path)?); + continue; + } else if let Some(workload) = file.strip_suffix(".plan.json") { + (workload.to_string(), PlanEntry::PlanFile(absolute(&path)?)) + } else if let Some(workload) = file.strip_suffix(".no-plan.json") { + let NoPlanRecord { reason } = read_json(&path)?; + (workload.to_string(), PlanEntry::NoPlan { reason }) + } else { + return Err(BenchmarkExternalError::Layout(format!( + "{} is neither variant.json, .plan.json nor .no-plan.json", + path.display() + ))); + }; + if !workloads.contains_key(&workload) { + return Err(BenchmarkExternalError::Layout(format!( + "{} names workload '{workload}', which is not in workloads/", + path.display() + ))); + } + if entries.insert(workload.clone(), entry).is_some() { + return Err(BenchmarkExternalError::Layout(format!( + "variant {name} has both {workload}.plan.json and {workload}.no-plan.json" + ))); + } + } + let record = record.ok_or_else(|| { + BenchmarkExternalError::Layout(format!("variant {name} has no variant.json")) + })?; + if let Some(missing) = workloads.keys().find(|w| !entries.contains_key(*w)) { + return Err(BenchmarkExternalError::Layout(format!( + "variant {name} has neither {missing}.plan.json nor {missing}.no-plan.json" + ))); + } + variants.push(Variant { + name, + record, + entries, + }); + } + Ok(variants) +} + +/// How one engine run measures. +pub struct EngineRunSetup<'a> { + pub protocol: &'a Protocol, + pub core: usize, + pub probe: &'a mut dyn LoadProbe, + pub clocks: &'a MeasurementClocks<'a>, + pub args: Vec, +} + +/// Runs every (workload, variant) cell of `run_directory` on `engine`, the +/// variants limited to `only_variants` when given. A cell whose +/// `.cell.json` exists is refused before anything runs, so an engine run can go +/// variant by variant but never overwrites a result. A cell that fails is +/// written as `NotRun` and the next one runs. +pub fn run_engine( + run_directory: &RunDirectory, + engine: &dyn EngineUnderTest, + only_variants: Option<&[String]>, + mut setup: EngineRunSetup, +) -> Result, BenchmarkExternalError> { + let workloads = read_workloads(run_directory)?; + let mut variants = read_variants(run_directory, &workloads)?; + if let Some(only) = only_variants { + if let Some(unknown) = only + .iter() + .find(|v| !variants.iter().any(|x| &x.name == *v)) + { + return Err(BenchmarkExternalError::Layout(format!( + "no variant {unknown} under plans/" + ))); + } + variants.retain(|variant| only.contains(&variant.name)); + } + let engine_id = engine.description().id; + let engine_directory = run_directory.path().join("results").join(&engine_id); + for variant in &variants { + for workload in workloads.keys() { + let cell = cell_path(&engine_directory, workload, &variant.name); + if cell.exists() { + return Err(BenchmarkExternalError::CellExists(cell)); + } + } + } + std::fs::create_dir_all(&engine_directory).map_err(|e| io(&engine_directory, e))?; + write_json( + &engine_directory.join(format!( + "engine-run-{}.json", + Utc::now().format("%Y%m%dT%H%M%S%.3fZ") + )), + &EngineRunRecord { + engine: engine.description(), + cpu_accounting: engine.cpu_accounting(), + protocol: setup.protocol.clone(), + core: setup.core, + args: setup.args.clone(), + }, + )?; + + let mut cells = Vec::new(); + for variant in &variants { + for (workload_name, workload) in &workloads { + let outcome = match &variant.entries[workload_name] { + PlanEntry::NoPlan { reason } => CellOutcome::NoPlan { + reason: reason.clone(), + }, + PlanEntry::PlanFile(plan_file) => { + match run_cell( + run_directory, + engine, + workload, + variant, + plan_file, + &mut setup, + ) { + Ok(()) => CellOutcome::Ran, + Err(error) => CellOutcome::NotRun { error }, + } + } + }; + let cell = EngineRunCell { + engine: engine_id.clone(), + workload: workload_name.clone(), + variant: variant.name.clone(), + outcome, + }; + write_json( + &cell_path(&engine_directory, workload_name, &variant.name), + &cell, + )?; + cells.push(cell); + } + } + Ok(cells) +} + +/// Runs one cell and writes its `ArmResult`; the error text otherwise. +fn run_cell( + run_directory: &RunDirectory, + engine: &dyn EngineUnderTest, + workload: &WorkloadSpec, + variant: &Variant, + plan_file: &Path, + setup: &mut EngineRunSetup, +) -> Result<(), String> { + let schedule = ArmSchedule::for_workload(workload).map_err(|e| e.to_string())?; + let arm = ArmSpec { + name: variant.name.clone(), + raw_data_retained: true, + engine_options: serde_json::json!({ "plan_file": plan_file }), + }; + let result = run_arm( + engine, + workload, + &arm, + &schedule, + setup.protocol, + setup.core, + setup.probe, + setup.clocks, + ) + .map_err(|e| e.to_string())?; + if !variant.record.substitutions_allowed { + if let Some(first) = result.plan.substitutions.first() { + return Err(format!( + "variant {} allows no substitutions, but the engine substituted: {first}", + variant.name + )); + } + } + run_directory + .write_arm(&result) + .map_err(|e| e.to_string())?; + Ok(()) +} + +/// One row of `summary.csv`: one cell of one engine. Every number is absolute; +/// `None` is an empty field (the cell did not run, or the engine has no such +/// counter). +#[derive(Debug, Clone, PartialEq)] +pub struct ReportRow { + pub workload: String, + pub engine: String, + pub variant: String, + /// `ok`, `no plan: ` or `not run: `. + pub status: String, + /// `thread` (in-process, the calling thread's CPU), `processes` or + /// `cgroup` (a server's whole process or group, background threads included). + pub cpu_accounting: Option<&'static str>, + /// Sum over refresh chunks of the median ingest CPU, per ingested sample. + pub ingest_cpu_ns_per_sample: Option, + /// Mean over evaluation times of the median evaluation CPU, in ms. + pub query_cpu_ms_per_evaluation: Option, + /// The same for the engine's own per-query CPU counter; `None` when any + /// step lacks it. + pub engine_counter_cpu_ms_per_evaluation: Option, + /// A `cgroup` server's CPU over the whole arm, steps and the work between + /// them, over every install, in ms. + pub server_cpu_ms_whole_arm: Option, + /// A `cgroup` server's `memory.current` before the installs. + pub server_memory_before_bytes: Option, + /// A `cgroup` server's `memory.current` after the run, every install held. + pub server_memory_after_bytes: Option, + /// A `cgroup` server's `memory.peak` over the container's whole life. + pub server_lifetime_peak_bytes: Option, + pub installs_held: Option, + /// View plus raw bytes the last install holds. + pub stored_bytes_last_install: Option, + /// The truth has no answers for this workload (its cell did not run). + pub no_truth: bool, + pub accuracy: Option, + pub substitutions: Vec, + pub sharing_lost: Vec, +} + +/// Relative errors of answers against the truth over a set of points. +#[derive(Debug, Clone, PartialEq)] +pub struct PointErrors { + pub max_relative_error: Option, + pub median_relative_error: Option, + /// Points both answered. + pub points: u64, + /// Truth points the answer lacks. + pub missing_points: u64, + /// Answer points the truth lacks. + pub extra_points: u64, +} + +/// One row of `accuracy.csv`: one query of one cell. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryAccuracy { + pub workload: String, + pub engine: String, + pub variant: String, + pub query: String, + pub errors: PointErrors, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Report { + /// `engine/variant` of the truth. + pub truth: String, + pub rows: Vec, + pub accuracy: Vec, +} + +/// `|a - t| / |t|`; equal values (0 and 0, the same infinity) 0; both NaN +/// 0; one NaN, `t = 0` with `a != 0`, or an infinity on one side only (or +/// opposite infinities), infinite. +pub fn relative_error(answer: f64, truth: f64) -> f64 { + if answer.is_nan() && truth.is_nan() { + 0.0 + } else if answer.is_nan() || truth.is_nan() { + f64::INFINITY + } else if answer == truth { + 0.0 + } else if truth == 0.0 || truth.is_infinite() || answer.is_infinite() { + f64::INFINITY + } else { + (answer - truth).abs() / truth.abs() + } +} + +/// The middle value; the mean of the two middle values for an even count. +fn median_of(values: &[f64]) -> Option { + if values.is_empty() { + return None; + } + let mut sorted = values.to_vec(); + sorted.sort_by(f64::total_cmp); + let n = sorted.len(); + Some(if n % 2 == 1 { + sorted[n / 2] + } else { + (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0 + }) +} + +fn point_errors(errors: &[f64], missing_points: u64, extra_points: u64) -> PointErrors { + PointErrors { + max_relative_error: errors.iter().copied().reduce(f64::max), + median_relative_error: median_of(errors), + points: errors.len() as u64, + missing_points, + extra_points, + } +} + +/// One query's errors against the truth, before they are summarized. +#[derive(Debug, Default)] +struct QueryErrors { + /// One relative error per point both answered. + errors: Vec, + missing_points: u64, + extra_points: u64, +} + +/// Per query, the errors of `result`'s answers against `truth`'s. The two +/// must answer at the same times. +fn errors_against( + result: &ArmResult, + truth: &ArmResult, +) -> Result, String> { + let times = |r: &ArmResult| r.answers.iter().map(|(t, _)| *t).collect::>(); + if times(result) != times(truth) { + return Err(format!( + "workload {}: {}/{} answered at {:?} but the truth at {:?}", + result.workload, + result.engine, + result.arm, + times(result), + times(truth) + )); + } + let mut per_query: BTreeMap = BTreeMap::new(); + for ((_, answers), (_, truth_answers)) in result.answers.iter().zip(&truth.answers) { + let queries: std::collections::BTreeSet<&String> = + answers.0.keys().chain(truth_answers.0.keys()).collect(); + for query in queries { + let entry = per_query.entry(query.clone()).or_default(); + let empty = BTreeMap::new(); + let got = answers.0.get(query).unwrap_or(&empty); + let want = truth_answers.0.get(query).unwrap_or(&empty); + for (series, truth_value) in want { + match got.get(series) { + Some(value) => entry.errors.push(relative_error(*value, *truth_value)), + None => entry.missing_points += 1, + } + } + entry.extra_points += got + .keys() + .filter(|series| !want.contains_key(*series)) + .count() as u64; + } + } + Ok(per_query) +} + +/// Joins every engine run's cells into the report, with accuracy against the +/// cells of `truth_engine`/`truth_variant`. Refuses a truth with no cell, and +/// a workload whose ran cells ingested different numbers of samples (the +/// engine runs did not read the same data). +pub fn report( + run_directory: &RunDirectory, + truth_engine: &str, + truth_variant: &str, +) -> Result { + let results = run_directory.path().join("results"); + let mut cells: Vec<(EngineRunCell, Option)> = Vec::new(); + for engine_directory in sorted_entries(&results)? { + for path in sorted_entries(&engine_directory)? { + if !file_name(&path).ends_with(".cell.json") { + continue; + } + let cell: EngineRunCell = read_json(&path)?; + let result = match cell.outcome { + CellOutcome::Ran => Some(read_json::( + &engine_directory.join(format!("{}__{}.json", cell.workload, cell.variant)), + )?), + _ => None, + }; + cells.push((cell, result)); + } + } + if !cells + .iter() + .any(|(cell, _)| cell.engine == truth_engine && cell.variant == truth_variant) + { + return Err(BenchmarkExternalError::Report(format!( + "the truth {truth_engine}/{truth_variant} has no cells under results/" + ))); + } + let mut samples_per_workload: BTreeMap<&str, (u64, String)> = BTreeMap::new(); + for (cell, result) in &cells { + let Some(result) = result else { continue }; + let here = format!("{}/{}", cell.engine, cell.variant); + let (samples, first) = samples_per_workload + .entry(&cell.workload) + .or_insert((result.ingested_samples, here.clone())); + if *samples != result.ingested_samples { + return Err(BenchmarkExternalError::Report(format!( + "workload {}: {first} ingested {samples} samples but {here} {}; the engine runs did not read the same data", + cell.workload, result.ingested_samples + ))); + } + } + let truth_of = |workload: &str| { + cells.iter().find_map(|(cell, result)| { + (cell.engine == truth_engine + && cell.variant == truth_variant + && cell.workload == workload) + .then_some(result.as_ref()) + .flatten() + }) + }; + let mut rows = Vec::new(); + let mut accuracy = Vec::new(); + for (cell, result) in &cells { + let status = match &cell.outcome { + CellOutcome::Ran => "ok".to_string(), + CellOutcome::NoPlan { reason } => format!("no plan: {reason}"), + CellOutcome::NotRun { error } => format!("not run: {error}"), + }; + let mut row = ReportRow { + workload: cell.workload.clone(), + engine: cell.engine.clone(), + variant: cell.variant.clone(), + status, + cpu_accounting: None, + ingest_cpu_ns_per_sample: None, + query_cpu_ms_per_evaluation: None, + engine_counter_cpu_ms_per_evaluation: None, + server_cpu_ms_whole_arm: None, + server_memory_before_bytes: None, + server_memory_after_bytes: None, + server_lifetime_peak_bytes: None, + installs_held: None, + stored_bytes_last_install: None, + no_truth: false, + accuracy: None, + substitutions: Vec::new(), + sharing_lost: Vec::new(), + }; + if let Some(result) = result { + fill_measurements(&mut row, result); + if let Some(truth) = truth_of(&cell.workload) { + let per_query = + errors_against(result, truth).map_err(BenchmarkExternalError::Report)?; + let (mut all, mut missing, mut extra) = (Vec::new(), 0, 0); + for (query, errors) in per_query { + all.extend_from_slice(&errors.errors); + missing += errors.missing_points; + extra += errors.extra_points; + accuracy.push(QueryAccuracy { + workload: cell.workload.clone(), + engine: cell.engine.clone(), + variant: cell.variant.clone(), + query, + errors: point_errors( + &errors.errors, + errors.missing_points, + errors.extra_points, + ), + }); + } + row.accuracy = Some(point_errors(&all, missing, extra)); + } else { + row.no_truth = true; + } + } + rows.push(row); + } + Ok(Report { + truth: format!("{truth_engine}/{truth_variant}"), + rows, + accuracy, + }) +} + +fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { + let step_cpu_ns = + |cost: &crate::harness::engine::StepCost| cost.thread_cpu_ns.unwrap_or(cost.process_cpu_ns); + row.cpu_accounting = Some(match result.cpu_source.as_str() { + "calling-thread" => "thread", + "schedstat" => "processes", + _ => "cgroup", + }); + let ingest_ns: u64 = result + .ingest + .iter() + .map(|job| step_cpu_ns(&job.median)) + .sum(); + row.ingest_cpu_ns_per_sample = + (result.ingested_samples > 0).then(|| ingest_ns as f64 / result.ingested_samples as f64); + let evaluations = result.evaluate.len(); + if evaluations > 0 { + let query_ns: u64 = result + .evaluate + .iter() + .map(|job| step_cpu_ns(&job.median)) + .sum(); + row.query_cpu_ms_per_evaluation = Some(query_ns as f64 / 1e6 / evaluations as f64); + row.engine_counter_cpu_ms_per_evaluation = result + .evaluate + .iter() + .map(|job| job.median.report.engine_reported_cpu_ns) + .sum::>() + .map(|ns| ns as f64 / 1e6 / evaluations as f64); + } + row.server_cpu_ms_whole_arm = result.server_cpu_ns_whole_arm.map(|ns| ns as f64 / 1e6); + row.server_memory_before_bytes = result + .server_memory_before + .map(|memory| memory.current_bytes); + row.server_memory_after_bytes = result + .server_memory_after + .map(|memory| memory.current_bytes); + row.server_lifetime_peak_bytes = result + .server_memory_after + .and_then(|memory| memory.lifetime_peak_bytes); + row.installs_held = Some(result.installs_held); + row.stored_bytes_last_install = + Some(result.footprint.view_bytes + result.footprint.raw_retained_bytes); + row.substitutions = result.plan.substitutions.clone(); + row.sharing_lost = result.plan.sharing_lost.clone(); +} + +/// The `summary.csv` header. +pub const SUMMARY_CSV_HEADER: &str = "workload,engine,variant,status,cpu_accounting,ingest_cpu_ns_per_sample,query_cpu_ms_per_evaluation,engine_counter_cpu_ms_per_evaluation,server_cpu_ms_whole_arm,server_memory_before_bytes,server_memory_after_bytes,server_lifetime_peak_bytes,installs_held,stored_bytes_last_install,max_relative_error,median_relative_error,points,missing_points,extra_points,substitutions,sharing_lost"; + +/// The `accuracy.csv` header. +pub const ACCURACY_CSV_HEADER: &str = + "workload,engine,variant,query,max_relative_error,median_relative_error,points,missing_points,extra_points"; + +fn field(value: Option) -> String { + value.map(|v| v.to_string()).unwrap_or_default() +} + +/// A CSV field: quoted when it holds a comma, quote or newline. +fn csv_text(text: &str) -> String { + if text.contains([',', '"', '\n']) { + format!("\"{}\"", text.replace('"', "\"\"")) + } else { + text.to_string() + } +} + +fn error_fields(errors: Option<&PointErrors>) -> String { + match errors { + Some(e) => format!( + "{},{},{},{},{}", + field(e.max_relative_error), + field(e.median_relative_error), + e.points, + e.missing_points, + e.extra_points + ), + None => ",,,,".to_string(), + } +} + +impl Report { + /// `summary.csv`: the header and one line per row. + pub fn summary_csv(&self) -> String { + let mut text = format!("{SUMMARY_CSV_HEADER}\n"); + for row in &self.rows { + text.push_str(&format!( + "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n", + csv_text(&row.workload), + csv_text(&row.engine), + csv_text(&row.variant), + csv_text(&row.status), + field(row.cpu_accounting), + field(row.ingest_cpu_ns_per_sample), + field(row.query_cpu_ms_per_evaluation), + field(row.engine_counter_cpu_ms_per_evaluation), + field(row.server_cpu_ms_whole_arm), + field(row.server_memory_before_bytes), + field(row.server_memory_after_bytes), + field(row.server_lifetime_peak_bytes), + field(row.installs_held), + field(row.stored_bytes_last_install), + error_fields(row.accuracy.as_ref()), + csv_text(&row.substitutions.join(";")), + csv_text(&row.sharing_lost.join(";")), + )); + } + text + } + + /// `accuracy.csv`: one line per query of every ran cell with a truth. + pub fn accuracy_csv(&self) -> String { + let mut text = format!("{ACCURACY_CSV_HEADER}\n"); + for row in &self.accuracy { + text.push_str(&format!( + "{},{},{},{},{}\n", + csv_text(&row.workload), + csv_text(&row.engine), + csv_text(&row.variant), + csv_text(&row.query), + error_fields(Some(&row.errors)) + )); + } + text + } + + /// `summary.md`: rows = workloads, columns = `engine/variant`, sorted. + /// A ran cell reads `q 2.000 ms, i 2000.0 ns/sample, err 0.100 [cgroup]`. + pub fn summary_markdown(&self) -> String { + let columns: std::collections::BTreeSet = self + .rows + .iter() + .map(|row| format!("{}/{}", row.engine, row.variant)) + .collect(); + let workloads: std::collections::BTreeSet<&str> = + self.rows.iter().map(|row| row.workload.as_str()).collect(); + let mut text = format!( + "Absolute CPU per engine: `q` = query CPU per evaluation, `i` = ingest CPU per sample, `err` = max relative error against {}. `[thread]` engine runs count the calling thread only; `[cgroup]` engine runs count the whole server.\n\n| workload |", + self.truth + ); + for column in &columns { + text.push_str(&format!(" {column} |")); + } + text.push_str("\n|---|"); + text.push_str(&"---|".repeat(columns.len())); + text.push('\n'); + for workload in workloads { + text.push_str(&format!("| {workload} |")); + for column in &columns { + let row = self.rows.iter().find(|row| { + row.workload == workload && format!("{}/{}", row.engine, row.variant) == *column + }); + let cell = match row { + None => String::new(), + Some(row) if row.status == "ok" => format!( + "q {} ms, i {} ns/sample, err {} [{}]", + row.query_cpu_ms_per_evaluation + .map_or("-".into(), |v| format!("{v:.3}")), + row.ingest_cpu_ns_per_sample + .map_or("-".into(), |v| format!("{v:.1}")), + if row.no_truth { + "- (no truth)".to_string() + } else { + row.accuracy + .as_ref() + .and_then(|e| e.max_relative_error) + .map_or("-".into(), |v| format!("{v:.3}")) + }, + row.cpu_accounting.unwrap_or("-"), + ), + Some(row) => { + let first_line = row.status.lines().next().unwrap_or(""); + first_line + .chars() + .take(80) + .collect::() + .replace('|', "/") + } + }; + text.push_str(&format!(" {cell} |")); + } + text.push('\n'); + } + text + } +} + +/// Writes `summary.csv`, `summary.md` and `accuracy.csv` in the run +/// directory, replacing earlier reports (a report is derived, never a result). +pub fn write_report( + run_directory: &RunDirectory, + report: &Report, +) -> Result<(), BenchmarkExternalError> { + for (name, text) in [ + ("summary.csv", report.summary_csv()), + ("summary.md", report.summary_markdown()), + ("accuracy.csv", report.accuracy_csv()), + ] { + let path = run_directory.path().join(name); + std::fs::write(&path, text).map_err(|e| io(&path, e))?; + } + Ok(()) +} + +fn cell_path(engine_directory: &Path, workload: &str, variant: &str) -> PathBuf { + engine_directory.join(format!("{workload}__{variant}.cell.json")) +} + +fn sorted_entries(dir: &Path) -> Result, BenchmarkExternalError> { + let mut paths: Vec = std::fs::read_dir(dir) + .map_err(|e| io(dir, e))? + .map(|entry| entry.map(|entry| entry.path()).map_err(|e| io(dir, e))) + .collect::>()?; + paths.sort(); + Ok(paths) +} + +fn sorted_files(dir: &Path) -> Result, BenchmarkExternalError> { + let paths = sorted_entries(dir)?; + if let Some(sub) = paths.iter().find(|path| !path.is_file()) { + return Err(BenchmarkExternalError::Layout(format!( + "{} is not a file", + sub.display() + ))); + } + Ok(paths) +} + +fn file_name(path: &Path) -> String { + path.file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +fn file_stem_with_suffix(path: &Path, suffix: &str) -> Result { + file_name(path) + .strip_suffix(suffix) + .map(str::to_string) + .ok_or_else(|| { + BenchmarkExternalError::Layout(format!("{} does not end in {suffix}", path.display())) + }) +} + +fn absolute(path: &Path) -> Result { + std::path::absolute(path).map_err(|e| io(path, e)) +} + +fn read_json(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| io(path, e))?; + serde_json::from_str(&text).map_err(|error| BenchmarkExternalError::Json { + path: path.to_path_buf(), + message: error.to_string(), + }) +} + +fn io(path: &Path, error: std::io::Error) -> BenchmarkExternalError { + BenchmarkExternalError::Io { + path: path.to_path_buf(), + message: error.to_string(), + } +} + +#[derive(Debug, thiserror::Error)] +pub enum BenchmarkExternalError { + /// The run directory does not have the layout of the module docs. + #[error("{0}")] + Layout(String), + /// A cell already has a result; results are never overwritten. + #[error("{} exists; results are never overwritten", .0.display())] + CellExists(PathBuf), + #[error("{path}: {message}")] + Io { path: PathBuf, message: String }, + #[error("{path}: {message}")] + Json { path: PathBuf, message: String }, + #[error(transparent)] + RunDirectory(#[from] RunDirectoryError), + /// Inputs the report cannot join, such as engine runs that ingested different data. + #[error("{0}")] + Report(String), +} diff --git a/aqpbm-core/src/harness/cgroup.rs b/aqpbm-core/src/harness/cgroup.rs new file mode 100644 index 00000000..2dc2ed75 --- /dev/null +++ b/aqpbm-core/src/harness/cgroup.rs @@ -0,0 +1,267 @@ +//! CPU and memory of an external server that runs in its own cgroup v2 +//! group, such as a docker container's +//! `/sys/fs/cgroup/system.slice/docker-.scope`. +//! +//! The group's files are read either from a local directory or, when the +//! server runs on another host than the harness, over SSH with `cat` on the +//! server host. Only [`CGROUP_FILES`] and the host's `/proc/stat` +//! ([`PROC_STAT`]) are read. +//! +//! Example: `cpu.stat` with `usage_usec 2500` reads 2,500,000 ns; a group +//! whose `nr_throttled` grows during a step was throttled by a CPU quota, +//! and that step is not a sample. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use serde::{Deserialize, Serialize}; + +/// The group files the harness reads: CPU, current and peak memory, memory +/// breakdown, and the cores the group may run on. +pub const CGROUP_FILES: [&str; 5] = [ + "cpu.stat", + "memory.current", + "memory.peak", + "memory.stat", + "cpuset.cpus.effective", +]; + +/// The name under which [`CgroupSource::read`] reads the server host's +/// `/proc/stat`, so the harness can check the server's cores are idle +/// around a step. +pub const PROC_STAT: &str = "proc-stat"; + +/// Where a server's cgroup v2 files are read. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum CgroupSource { + /// The group's directory on this host. + Local(PathBuf), + /// The group's directory on the server host, read over SSH. Reads to one + /// host share one connection, so a read costs one round trip. + Remote { + /// The SSH client, normally `ssh`. + ssh_program: String, + /// The SSH destination, such as `bench@10.0.0.2`. + host: String, + /// The group's directory on that host, such as + /// `/sys/fs/cgroup/system.slice/docker-.scope`. + cgroup_directory: PathBuf, + }, +} + +impl CgroupSource { + /// The current text of one of [`CGROUP_FILES`], or of the server + /// host's `/proc/stat` for [`PROC_STAT`]. + pub fn read(&self, file: &str) -> Result { + if !CGROUP_FILES.contains(&file) && file != PROC_STAT { + return Err(CgroupError::NotACgroupFile(file.into())); + } + match self { + CgroupSource::Local(dir) => { + let path = if file == PROC_STAT { + PathBuf::from("/proc/stat") + } else { + dir.join(file) + }; + std::fs::read_to_string(&path).map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + CgroupError::NotFound(path.display().to_string()) + } else { + CgroupError::Read { + file: path.display().to_string(), + message: error.to_string(), + } + } + }) + } + CgroupSource::Remote { + ssh_program, + host, + cgroup_directory, + } => { + let path = if file == PROC_STAT { + PathBuf::from("/proc/stat") + } else { + cgroup_directory.join(file) + }; + ssh_read(ssh_program, host, &path) + } + } + } + + /// `cpu.stat` read once. + pub fn cpu(&self) -> Result { + CgroupCpu::parse(&self.read("cpu.stat")?) + } + + /// The memory files read once; `memory.peak` is absent before Linux 5.19. + pub fn memory(&self) -> Result { + let current_bytes = parse_number("memory.current", self.read("memory.current")?.trim())?; + let lifetime_peak_bytes = match self.read("memory.peak") { + Ok(text) => Some(parse_number("memory.peak", text.trim())?), + Err(CgroupError::NotFound(_)) => None, + Err(error) => return Err(error), + }; + let stat = self.read("memory.stat")?; + Ok(CgroupMemory { + current_bytes, + anon_bytes: stat_field("memory.stat", &stat, "anon")?, + file_bytes: stat_field("memory.stat", &stat, "file")?, + lifetime_peak_bytes, + }) + } +} + +/// The CPU counters of `cpu.stat`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CgroupCpu { + /// `usage_usec` in ns: CPU of every thread and child of the group. + pub usage_ns: u64, + /// `nr_throttled`: periods a CPU quota stopped the group (0 without a + /// `--cpus` quota; absent when the cpu controller is off, read as 0). + pub nr_throttled: u64, +} + +impl CgroupCpu { + pub fn parse(cpu_stat: &str) -> Result { + let usage_usec = stat_field("cpu.stat", cpu_stat, "usage_usec")?; + let nr_throttled = match stat_field("cpu.stat", cpu_stat, "nr_throttled") { + Ok(value) => value, + Err(CgroupError::MissingField { .. }) => 0, + Err(error) => return Err(error), + }; + Ok(CgroupCpu { + usage_ns: usage_usec * 1_000, + nr_throttled, + }) + } +} + +/// A group's memory, read at one moment. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CgroupMemory { + /// `memory.current`: every page the group holds, page cache included. + pub current_bytes: u64, + /// `memory.stat` `anon`: heap and stacks, without page cache. + pub anon_bytes: u64, + /// `memory.stat` `file`: page cache. + pub file_bytes: u64, + /// `memory.peak`: the most `memory.current` has been since the group + /// started. Before Linux 6.12 it cannot be reset, so it spans the + /// container's whole life, every earlier arm included. `None` before 5.19. + pub lifetime_peak_bytes: Option, +} + +fn parse_number(file: &str, text: &str) -> Result { + text.parse().map_err(|_| CgroupError::Parse { + file: file.into(), + message: format!("'{text}' is not a number"), + }) +} + +/// The value of the ` ` line of a flat-keyed cgroup file. +fn stat_field(file: &str, text: &str, field: &str) -> Result { + let value = text + .lines() + .find_map(|line| { + let (key, value) = line.split_once(' ')?; + (key == field).then_some(value) + }) + .ok_or_else(|| CgroupError::MissingField { + file: file.into(), + field: field.into(), + })?; + parse_number(file, value.trim()) +} + +/// Options of every SSH read: never prompt for a password; share one +/// connection per host, kept open 60 s after the last read; give up on a +/// host that does not answer within 5 s, and on a connection that stops +/// answering within about 15 s. The control socket is in the user's own +/// `~/.ssh`, so no other local user can reach or pre-create it; `%C` (a +/// hash of the hosts, port and remote user) keeps the path under the +/// 104 bytes macOS allows for a socket. +const SSH_OPTIONS: [&str; 12] = [ + "-o", + "BatchMode=yes", + "-o", + "ControlMaster=auto", + "-o", + "ControlPath=~/.ssh/aqpbm-%C", + "-o", + "ControlPersist=60", + "-o", + "ConnectTimeout=5", + "-o", + "ServerAliveInterval=5", +]; + +/// The exit status of the remote command when the file does not exist. +const MISSING_FILE_EXIT_STATUS: i32 = 3; + +/// The text of `path` on `host`: +/// ` -- "test -e '' || exit 3; exec cat -- ''"`. +/// `--` keeps a host that starts with `-` from being read as an option. +/// Exit status 255 is SSH's own failure (no connection, refused key); 3 is +/// a missing file ([`CgroupError::NotFound`]), decided by the status, not by +/// the server's locale-dependent error text; any other failure is `cat`'s. +fn ssh_read(ssh_program: &str, host: &str, path: &Path) -> Result { + let shown = format!("{host}:{}", path.display()); + let quoted = shell_quoted(&path.to_string_lossy()); + let output = Command::new(ssh_program) + .args(SSH_OPTIONS) + .arg("--") + .arg(host) + .arg(format!( + "test -e {quoted} || exit {MISSING_FILE_EXIT_STATUS}; exec cat -- {quoted}" + )) + .stdin(Stdio::null()) + .output() + .map_err(|error| CgroupError::Remote { + host: host.into(), + message: format!("cannot start {ssh_program}: {error}"), + })?; + if output.status.success() { + return String::from_utf8(output.stdout).map_err(|_| CgroupError::Parse { + file: shown, + message: "not UTF-8".into(), + }); + } + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + match output.status.code() { + Some(255) | None => Err(CgroupError::Remote { + host: host.into(), + message: stderr, + }), + // Such as `memory.peak` before Linux 5.19. + Some(MISSING_FILE_EXIT_STATUS) => Err(CgroupError::NotFound(shown)), + _ => Err(CgroupError::Read { + file: shown, + message: stderr, + }), + } +} + +/// `text` in single quotes for the server host's shell, each `'` as `'\''`. +fn shell_quoted(text: &str) -> String { + format!("'{}'", text.replace('\'', r"'\''")) +} + +/// A cgroup file that cannot be read or parsed. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CgroupError { + #[error("cannot read {file}: {message}")] + Read { file: String, message: String }, + #[error("{file} has no '{field}' line")] + MissingField { file: String, field: String }, + #[error("cannot parse {file}: {message}")] + Parse { file: String, message: String }, + #[error("SSH to {host}: {message}")] + Remote { host: String, message: String }, + /// The file does not exist, such as `memory.peak` before Linux 5.19. + #[error("{0} does not exist")] + NotFound(String), + #[error("{0} is not one of the cgroup files the harness reads")] + NotACgroupFile(String), +} diff --git a/aqpbm-core/src/harness/engine.rs b/aqpbm-core/src/harness/engine.rs index 218fc3e7..d78a1226 100644 --- a/aqpbm-core/src/harness/engine.rs +++ b/aqpbm-core/src/harness/engine.rs @@ -55,6 +55,10 @@ pub enum CpuAccounting { /// around each step (their own cgroup's `cpu.stat`, or their threads' /// `schedstat`; see [`crate::harness::protocol::ProcessesCpuClock`]). Processes(Vec), + /// An external server in its own cgroup v2 group (a container), whose + /// `cpu.stat` and memory files the harness reads, on this host or over + /// SSH on the server host ([`crate::harness::cgroup::CgroupSource`]). + Cgroup(crate::harness::cgroup::CgroupSource), } /// One arm of a workload: how the engine is asked to run it. @@ -159,11 +163,13 @@ pub struct StepCost { } /// The answers of one evaluation: per query id, one value per output series. -/// An output series keeps its input labels; the query id is the outer key, -/// so two queries over one metric never share a key and no label name is -/// reserved. Example: `sum_over_time(probe[10s])` with id `sum` over the -/// series `probe{instance="instance_0"}` answers under -/// `"sum" -> {__name__="probe", instance="instance_0"}`. +/// An output series carries PromQL's output labels: a function or an +/// aggregation drops `__name__`, and only a bare selector keeps it; every +/// engine uses this convention so the report can join engine runs by label set. The +/// query id is the outer key, so two queries over one metric never share a +/// key and no label name is reserved. Example: `sum_over_time(probe[10s])` +/// with id `sum` over the series `probe{instance="instance_0"}` answers +/// under `"sum" -> {instance="instance_0"}`. #[derive(Debug, Clone, Default, PartialEq)] pub struct Answers(pub BTreeMap>); @@ -228,6 +234,14 @@ pub struct PlanSummary { pub node_kinds: Vec, /// Outputs the arm stores between evaluations (views, sketches). pub stored_outputs: Vec, + /// Rules of a translating engine whose answers differ from the plan's + /// guarantee, such as `quantileDD for Kll at node 3`. + #[serde(default)] + pub substitutions: Vec, + /// Shared query-time nodes the engine recomputes for each reader, such + /// as `node 4 for nodes 6, 7`. + #[serde(default)] + pub sharing_lost: Vec, } /// The engine's own predicted cost of an arm, recorded in each diff --git a/aqpbm-core/src/harness/fake.rs b/aqpbm-core/src/harness/fake.rs index 5a7bf4ae..2fd54dbb 100644 --- a/aqpbm-core/src/harness/fake.rs +++ b/aqpbm-core/src/harness/fake.rs @@ -19,10 +19,11 @@ use std::cell::Cell; use std::collections::BTreeMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; +use crate::harness::cgroup::CgroupSource; use crate::harness::data::{SampleChunk, SeriesLabels}; use crate::harness::engine::{ Answers, ArmSpec, Calibratable, CostTarget, CpuAccounting, EngineDescription, EngineError, @@ -90,6 +91,9 @@ pub struct FakeServer { /// The fake `/proc` (and an empty cgroup mount beside it). pub cpu_files: ProcessCpuFiles, cpu_ns: Rc>, + /// Set by [`FakeServer::start_in_cgroup`]: the group directory whose + /// `cpu.stat` the fake rewrites after every charge. + pub cgroup_dir: Option, } impl FakeServer { @@ -108,17 +112,40 @@ impl FakeServer { cgroup_root: root.join("cgroup"), }, cpu_ns: Rc::default(), + cgroup_dir: None, }; server.write_schedstat()?; Ok(server) } + /// A server in its own cgroup v2 group at `cgroup_dir`: after every + /// charge its `cpu.stat` reads `usage_usec` = CPU in whole µs (rounded + /// down, as the kernel reports it) and `nr_throttled 0`; the memory files + /// read `memory.current` 3,145,728 bytes, `memory.peak` 5,242,880, + /// `memory.stat` `anon` 2,097,152 and `file` 1,048,576. The engine then reports + /// `CpuAccounting::Cgroup(Local(cgroup_dir))`. + pub fn start_in_cgroup(root: &Path, pid: u32, cgroup_dir: &Path) -> std::io::Result { + let mut server = FakeServer::start(root, pid)?; + std::fs::create_dir_all(cgroup_dir)?; + std::fs::write(cgroup_dir.join("memory.current"), "3145728\n")?; + std::fs::write(cgroup_dir.join("memory.peak"), "5242880\n")?; + std::fs::write( + cgroup_dir.join("memory.stat"), + "anon 2097152\nfile 1048576\nkernel 4096\n", + )?; + server.cgroup_dir = Some(cgroup_dir.to_path_buf()); + server.write_schedstat()?; + Ok(server) + } + /// The server's CPU so far, in ns. pub fn cpu_ns(&self) -> u64 { self.cpu_ns.get() } - fn charge(&self, ns: u64) { + /// Charges `ns` of server CPU, as work between steps does (such as a + /// background merge). + pub fn charge(&self, ns: u64) { self.cpu_ns.set(self.cpu_ns.get() + ns); self.write_schedstat() .unwrap_or_else(|error| panic!("fake server {} schedstat: {error}", self.pid)); @@ -130,6 +157,20 @@ impl FakeServer { /// some file systems (ext4) flush it on close, about 100 ms per write. fn write_schedstat(&self) -> std::io::Result<()> { use std::io::Write; + if let Some(dir) = &self.cgroup_dir { + std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(dir.join("cpu.stat"))? + .write_all( + format!( + "usage_usec {:020}\nnr_periods 0\nnr_throttled 0\nthrottled_usec 0\n", + self.cpu_ns.get() / 1_000 + ) + .as_bytes(), + )?; + } let path = self .cpu_files .proc_root @@ -167,6 +208,9 @@ pub struct FakeEngine { pub ns_per_sample: u64, pub ns_per_series: u64, pub ns_per_call: u64, + /// Charged at every install, outside every step (0 by default), as a + /// server's setup work. + pub ns_per_install: u64, /// Reported in every `StepReport`, like an external engine's own counter. pub engine_reported_cpu_ns: Option, pub cpu_accounting: CpuAccounting, @@ -187,6 +231,7 @@ impl Default for FakeEngine { ns_per_sample: 50, ns_per_series: 150, ns_per_call: 10_000, + ns_per_install: 0, engine_reported_cpu_ns: None, cpu_accounting: CpuAccounting::CallingThread, faults: Vec::new(), @@ -222,7 +267,10 @@ impl EngineUnderTest for FakeEngine { fn cpu_accounting(&self) -> CpuAccounting { match &self.server { - Some(server) => CpuAccounting::Processes(vec![server.pid]), + Some(server) => match &server.cgroup_dir { + Some(dir) => CpuAccounting::Cgroup(CgroupSource::Local(dir.clone())), + None => CpuAccounting::Processes(vec![server.pid]), + }, None => self.cpu_accounting.clone(), } } @@ -234,8 +282,12 @@ impl EngineUnderTest for FakeEngine { workload: &WorkloadSpec, arm: &ArmSpec, ) -> Result, EngineError> { - let _ = arm; self.installs.set(self.installs.get() + 1); + let plan = FakePlanFile::read(arm)?; + match &self.server { + Some(server) => server.charge(self.ns_per_install), + None => self.clock.charge_thread(self.ns_per_install), + } let mut queries = Vec::new(); let mut scanned_metrics: Vec = Vec::new(); for query in &workload.queries { @@ -273,6 +325,7 @@ impl EngineUnderTest for FakeEngine { }, queries, scanned_metrics, + plan, stored: BTreeMap::new(), node_cpu_ns_per_batch: BTreeMap::new(), })) @@ -349,6 +402,44 @@ fn parse_over_time(text: &str) -> Result<(OverTime, String), EngineError> { Ok((function, metric.to_string())) } +/// The plan file an arm names in `engine_options.plan_file`, as the fake +/// reads it: `{}` installs normally, `{"refuse": ""}` fails the +/// install with that message, and `{"substitutions": ["..."]}` reports +/// those substitutions, as a translating engine would. +#[derive(Debug, Clone, Default)] +struct FakePlanFile { + path: Option, + substitutions: Vec, +} + +impl FakePlanFile { + fn read(arm: &ArmSpec) -> Result { + let Some(path) = arm.engine_options.get("plan_file").and_then(|p| p.as_str()) else { + return Ok(FakePlanFile::default()); + }; + let text = std::fs::read_to_string(path) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; + let json: serde_json::Value = serde_json::from_str(&text) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; + if let Some(message) = json.get("refuse").and_then(|m| m.as_str()) { + return Err(EngineError(message.to_string())); + } + let substitutions = json + .get("substitutions") + .and_then(|list| list.as_array()) + .map(|list| { + list.iter() + .filter_map(|s| s.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + Ok(FakePlanFile { + path: Some(path.to_string()), + substitutions, + }) + } +} + /// One installed query. #[derive(Debug, Clone)] struct FakeQuery { @@ -377,6 +468,7 @@ struct FakeArm { queries: Vec, /// The metrics the shared `scan` node reads. scanned_metrics: Vec, + plan: FakePlanFile, /// Per metric, per series, its `(ts_ms, value)` samples in time order /// (chunks arrive in time order). stored: BTreeMap, @@ -433,10 +525,15 @@ impl InstalledArm for FakeArm { )); node_kinds.push(kind.to_string()); } + if let Some(path) = &self.plan.path { + lines.push(format!("plan_file = {path}")); + } PlanSummary { text: lines.join("\n"), node_kinds, stored_outputs: Vec::new(), + substitutions: self.plan.substitutions.clone(), + sharing_lost: Vec::new(), } } @@ -485,10 +582,13 @@ impl InstalledArm for FakeArm { OverTime::Sum => values.iter().sum(), OverTime::Count => values.len() as f64, }; + // A range function drops the metric name (PromQL's output labels). + let mut output_labels = SeriesLabels::clone(labels); + output_labels.remove("__name__"); answers .entry(query.id.clone()) .or_default() - .insert(SeriesLabels::clone(labels), value + self.answer_offset); + .insert(output_labels, value + self.answer_offset); } self.charge_node(&query.id, self.ns_per_series * answered_series); } diff --git a/aqpbm-core/src/harness/mod.rs b/aqpbm-core/src/harness/mod.rs index 42ec95f8..1b6c5d12 100644 --- a/aqpbm-core/src/harness/mod.rs +++ b/aqpbm-core/src/harness/mod.rs @@ -19,6 +19,8 @@ //! [`crate::metrics`] (`ThreadCpuTime`, `CpuTimeSampler`) rather than its own. pub mod arm_run; +pub mod benchmark_external; +pub mod cgroup; pub mod conformance; pub mod data; pub mod data_stats; @@ -30,5 +32,5 @@ pub mod gate; pub mod machine; pub mod protocol; pub mod records; -pub mod rundir; +pub mod run_directory; pub mod sweep; diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index d14b16d9..0cf7da7c 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -14,6 +14,7 @@ use crate::metrics::{CpuTimeSampler, ThreadCpuTime}; use serde::{Deserialize, Serialize}; +use crate::harness::cgroup::{CgroupCpu, CgroupError, CgroupSource, PROC_STAT}; use crate::harness::engine::{CpuAccounting, EngineError, StepCost, StepReport}; use crate::harness::fit::FitPoint; @@ -109,6 +110,14 @@ pub struct ProcessesCpuClock { } impl ProcessesCpuClock { + /// Where the CPU is read: `cgroup ` or `schedstat`. + pub fn cpu_source(&self) -> String { + match &self.cgroup_cpu_stat { + Some(cpu_stat) => format!("cgroup {}", cpu_stat.display()), + None => "schedstat".into(), + } + } + /// Picks the source and reads the pids once, so a missing or exited /// server fails here, before any job. pub fn new(pids: Vec, files: ProcessCpuFiles) -> Result { @@ -161,6 +170,67 @@ impl CpuClock for ProcessesCpuClock { } } +/// The clock of a [`CpuAccounting::Cgroup`] engine: an external server in +/// its own cgroup v2 group, read locally or over SSH on the server host. Process CPU is the group's `cpu.stat` `usage_usec` (µs resolution, +/// every thread and child of the group); thread CPU is 0; wall time is the +/// OS monotonic clock. A reading whose `nr_throttled` is above the one at +/// creation is [`ProtocolError::CgroupThrottled`]: a CPU quota stopped the +/// server, so the step's CPU is not the work's. +#[derive(Debug)] +pub struct CgroupCpuClock { + source: CgroupSource, + nr_throttled_at_start: u64, + last_process_cpu_ns: Cell, + read_error: RefCell>, +} + +impl CgroupCpuClock { + /// Reads `cpu.stat` once, so an unreachable group fails before any job. + pub fn new(source: CgroupSource) -> Result { + let cpu = source.cpu()?; + Ok(CgroupCpuClock { + source, + nr_throttled_at_start: cpu.nr_throttled, + last_process_cpu_ns: Cell::new(cpu.usage_ns), + read_error: RefCell::new(None), + }) + } + + fn read_cpu_ns(&self) -> Result { + let cpu = self.source.cpu()?; + if cpu.nr_throttled > self.nr_throttled_at_start { + return Err(ProtocolError::CgroupThrottled { + nr_throttled: cpu.nr_throttled - self.nr_throttled_at_start, + }); + } + Ok(cpu.usage_ns) + } +} + +impl CpuClock for CgroupCpuClock { + fn thread_cpu_ns(&self) -> u64 { + 0 + } + fn process_cpu_ns(&self) -> u64 { + match self.read_cpu_ns() { + Ok(ns) => { + self.last_process_cpu_ns.set(ns); + ns + } + Err(error) => { + self.read_error.borrow_mut().get_or_insert(error); + self.last_process_cpu_ns.get() + } + } + } + fn wall_ns(&self) -> u64 { + OsCpuClock.wall_ns() + } + fn take_read_error(&self) -> Option { + self.read_error.borrow_mut().take() + } +} + /// The cgroup v2 path of `//cgroup` (its `0::` line), such /// as `/system.slice/docker-1a2b.scope`; `None` when unreadable or v1 only. fn cgroup_v2_path(proc_root: &Path, pid: &str) -> Option { @@ -172,7 +242,12 @@ fn cgroup_v2_path(proc_root: &Path, pid: &str) -> Option { /// The `cpu.stat` of the cgroup all of `pids` are in, when that group is /// their own: one group for every pid, not the root, not the harness's own -/// group (`/self`), and its `cpu.stat` readable. +/// group (`/self`), every process in its `cgroup.procs` one of +/// `pids` or a descendant of one, and its `cpu.stat` readable. Otherwise the +/// group's CPU would count a foreign process, so the clock reads `schedstat`. +/// Example: a container with the server (pid 40) and its child (pid 41, +/// parent 40) is the server's own; with an unrelated pid 99 (parent 1) it +/// is not. fn own_cgroup_cpu_stat(files: &ProcessCpuFiles, pids: &[u32]) -> Option { let group = cgroup_v2_path(&files.proc_root, &pids.first()?.to_string())?; let shared = pids @@ -181,28 +256,68 @@ fn own_cgroup_cpu_stat(files: &ProcessCpuFiles, pids: &[u32]) -> Option if !shared || group == "/" || cgroup_v2_path(&files.proc_root, "self") == Some(group.clone()) { return None; } - let cpu_stat = files - .cgroup_root - .join(group.trim_start_matches('/')) - .join("cpu.stat"); + let group_dir = files.cgroup_root.join(group.trim_start_matches('/')); + if !group_holds_only(&group_dir, &files.proc_root, pids)? { + return None; + } + let cpu_stat = group_dir.join("cpu.stat"); cgroup_usage_ns(&cpu_stat).ok().map(|_| cpu_stat) } -/// `usage_usec` of a cgroup v2 `cpu.stat`, in ns. +/// Whether every process in `group_dir` and its child groups (whose CPU +/// the group's `cpu.stat` also counts) is one of `pids` or a descendant; +/// `None` when a `cgroup.procs` cannot be read. +fn group_holds_only(group_dir: &Path, proc_root: &Path, pids: &[u32]) -> Option { + let procs = std::fs::read_to_string(group_dir.join("cgroup.procs")).ok()?; + for member in procs.split_whitespace() { + let member: u32 = member.parse().ok()?; + if !descends_from(proc_root, member, pids) { + return Some(false); + } + } + for entry in std::fs::read_dir(group_dir).ok()? { + let child = entry.ok()?.path(); + if child.is_dir() && !group_holds_only(&child, proc_root, pids)? { + return Some(false); + } + } + Some(true) +} + +/// Whether `pid` is one of `ancestors` or a descendant of one, by its parent +/// pids (field 4 of `//stat`). An unreadable stat (a process +/// that just exited) is not a descendant. +fn descends_from(proc_root: &Path, pid: u32, ancestors: &[u32]) -> bool { + let mut current = pid; + // A pid chain is at most as long as the pid space; 4096 steps is far + // above any real process tree and stops a malformed (cyclic) fake. + for _ in 0..4096 { + if ancestors.contains(¤t) { + return true; + } + let Ok(stat) = std::fs::read_to_string(proc_root.join(current.to_string()).join("stat")) + else { + return false; + }; + let parent = stat + .rfind(')') + .and_then(|end| stat[end + 1..].split_whitespace().nth(1)) + .and_then(|ppid| ppid.parse::().ok()); + match parent { + Some(parent) if parent > 0 && parent != current => current = parent, + _ => return false, + } + } + false +} + +/// `usage_usec` of a cgroup v2 `cpu.stat`, in ns ([`CgroupCpu::parse`]). fn cgroup_usage_ns(cpu_stat: &Path) -> Result { - let parse_error = |message: String| ProtocolError::Parse { + let text = std::fs::read_to_string(cpu_stat).map_err(|error| ProtocolError::Parse { what: cpu_stat.display().to_string(), - message, - }; - let text = std::fs::read_to_string(cpu_stat).map_err(|error| parse_error(error.to_string()))?; - let usage_usec: u64 = text - .lines() - .find_map(|line| line.strip_prefix("usage_usec ")) - .ok_or_else(|| parse_error("no usage_usec line".into()))? - .trim() - .parse() - .map_err(|_| parse_error("usage_usec is not a number".into()))?; - Ok(usage_usec * 1_000) + message: error.to_string(), + })?; + Ok(CgroupCpu::parse(&text)?.usage_ns) } /// The state (field 3) of one `/proc//stat` line, such as `S` or `Z`. @@ -293,6 +408,9 @@ impl<'a> MeasurementClocks<'a> { pids.clone(), self.process_cpu_files.clone(), )?), + CpuAccounting::Cgroup(source) => { + EngineClock::Cgroup(CgroupCpuClock::new(source.clone())?) + } }) } } @@ -303,6 +421,7 @@ impl<'a> MeasurementClocks<'a> { pub enum EngineClock<'a> { CallingThread(&'a dyn CpuClock), Processes(ProcessesCpuClock), + Cgroup(CgroupCpuClock), } impl EngineClock<'_> { @@ -310,6 +429,28 @@ impl EngineClock<'_> { match self { EngineClock::CallingThread(clock) => *clock, EngineClock::Processes(clock) => clock, + EngineClock::Cgroup(clock) => clock, + } + } + + /// Where this clock reads CPU, recorded in every arm result: + /// `calling-thread`, `cgroup `, `schedstat` or + /// `cgroup : over SSH`. + pub fn cpu_source(&self) -> String { + match self { + EngineClock::CallingThread(_) => "calling-thread".into(), + EngineClock::Processes(clock) => clock.cpu_source(), + EngineClock::Cgroup(clock) => match &clock.source { + CgroupSource::Local(dir) => format!("cgroup {}", dir.join("cpu.stat").display()), + CgroupSource::Remote { + host, + cgroup_directory, + .. + } => format!( + "cgroup {host}:{} over SSH", + cgroup_directory.join("cpu.stat").display() + ), + }, } } @@ -318,7 +459,7 @@ impl EngineClock<'_> { pub fn engine_cpu_ns(&self, cost: &StepCost) -> u64 { match self { EngineClock::CallingThread(_) => cost.thread_cpu_ns.unwrap_or(0), - EngineClock::Processes(_) => cost.process_cpu_ns, + EngineClock::Processes(_) | EngineClock::Cgroup(_) => cost.process_cpu_ns, } } } @@ -515,6 +656,200 @@ impl LoadProbe for OsLoadProbe { } } +/// The cores of a cpu list such as `2,22` or `0-3,8` (cgroup +/// `cpuset.cpus.effective`, `/proc//status` `Cpus_allowed_list`). +pub fn parse_cpu_list(text: &str) -> Result, ProtocolError> { + let parse_error = || ProtocolError::Parse { + what: "cpu list".into(), + message: format!("'{}' is not a list like 2,22 or 0-3,8", text.trim()), + }; + let mut cores = Vec::new(); + for part in text.trim().split(',').filter(|part| !part.is_empty()) { + let (first, last) = part.split_once('-').unwrap_or((part, part)); + let first: usize = first.parse().map_err(|_| parse_error())?; + let last: usize = last.parse().map_err(|_| parse_error())?; + if last < first { + return Err(parse_error()); + } + cores.extend(first..=last); + } + if cores.is_empty() { + return Err(parse_error()); + } + Ok(cores) +} + +/// The busy fraction of `cores` between two `/proc/stat` texts that is not +/// the server's own work: busy ticks over the cores, minus the server's CPU +/// over the same interval (`server_cpu_ns`), over all ticks of the cores. +/// A server pinned to these cores runs only on them, so its own merges and +/// flushes never count as foreign load. +/// `/proc/stat` counts whole ticks while the server's CPU is read in µs, and +/// the two are read by separate requests, so up to two ticks per core of +/// the busy time are rounding, not load: they are forgiven. +/// Example: cores 2 and 22 over 10 ticks each (`tick_ns` 10 ms, 200 ms in +/// all), 10 busy ticks (100 ms) of which the server used 40 ms: 60 ms, less +/// 40 ms of rounding allowance, is 20 ms of 200 ms, 0.1. +pub fn foreign_busy_fraction( + cores: &[usize], + before: &str, + after: &str, + server_cpu_ns: u64, + tick_ns: u64, +) -> Result { + let (mut busy_ticks, mut total_ticks) = (0_u64, 0_u64); + for &core in cores { + let before = core_ticks(core, before)?; + let after = core_ticks(core, after)?; + let delta = |field: usize| after[field].saturating_sub(before[field]); + let total: u64 = (0..8).map(delta).sum(); + total_ticks += total; + busy_ticks += total - (delta(3) + delta(4)); + } + if total_ticks == 0 { + return Err(ProtocolError::IdleUnmeasurable { + core: cores.first().copied().unwrap_or(0), + }); + } + let rounding_allowance_ns = 2 * tick_ns * cores.len() as u64; + let foreign_ns = (busy_ticks * tick_ns) + .saturating_sub(server_cpu_ns) + .saturating_sub(rounding_allowance_ns); + Ok(foreign_ns as f64 / (total_ticks * tick_ns) as f64) +} + +/// The length of one `/proc/stat` tick, in ns (`USER_HZ`, 100 per second on +/// Linux). +fn proc_stat_tick_ns() -> u64 { + #[cfg(unix)] + { + // SAFETY: `sysconf` reads a constant and takes no pointers. + let per_second = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + if per_second > 0 { + return 1_000_000_000 / per_second as u64; + } + } + 10_000_000 +} + +/// Where a [`ServerCoresProbe`] reads `/proc/stat`, the load average and +/// the server's own CPU. +#[derive(Debug, Clone)] +enum ServerHost { + /// This host: its proc root, and the server's pids (their threads' + /// `schedstat`). + Local { proc_root: PathBuf, pids: Vec }, + /// The server host's cgroup source: its `/proc/stat` and the group's + /// `cpu.stat`. + Cgroup(CgroupSource), +} + +/// The idle check of an external server: over one sampling interval, the +/// busy fraction of the cores the server may run on (its container's +/// cpuset) that is not the server's own work ([`foreign_busy_fraction`]), +/// not the harness's core. The `core` the protocol passes is the harness's +/// and is ignored; a `CoreBusy` error names it. +#[derive(Debug, Clone)] +pub struct ServerCoresProbe { + pub cores: Vec, + pub sample_interval: std::time::Duration, + host: ServerHost, +} + +impl ServerCoresProbe { + /// `/proc/stat` and the server's CPU in ns, read together. + fn read(&self) -> Result<(String, u64), ProtocolError> { + match &self.host { + ServerHost::Local { proc_root, pids } => { + let path = proc_root.join("stat"); + let stat = + std::fs::read_to_string(&path).map_err(|error| ProtocolError::Parse { + what: path.display().to_string(), + message: error.to_string(), + })?; + Ok((stat, processes_cpu_ns(proc_root, pids)?)) + } + ServerHost::Cgroup(source) => Ok((source.read(PROC_STAT)?, source.cpu()?.usage_ns)), + } + } +} + +impl LoadProbe for ServerCoresProbe { + fn core_busy_fraction(&mut self, _harness_core: usize) -> Result { + let (before, server_before_ns) = self.read()?; + std::thread::sleep(self.sample_interval); + let (after, server_after_ns) = self.read()?; + foreign_busy_fraction( + &self.cores, + &before, + &after, + server_after_ns.saturating_sub(server_before_ns), + proc_stat_tick_ns(), + ) + } + + /// The server host's load average on this host; `NaN` (recorded `None`) + /// for a cgroup source, which does not read it. + fn loadavg(&mut self) -> f64 { + match &self.host { + ServerHost::Local { proc_root, .. } => { + std::fs::read_to_string(proc_root.join("loadavg")) + .ok() + .and_then(|text| text.split_whitespace().next()?.parse().ok()) + .unwrap_or(f64::NAN) + } + ServerHost::Cgroup(_) => f64::NAN, + } + } +} + +/// The idle probe for an engine with `accounting`: the harness core +/// ([`OsLoadProbe`]) for `CallingThread`; the server's cores for +/// `Processes` (the first pid's `Cpus_allowed_list` under +/// `files.proc_root`) and `Cgroup` (the group's `cpuset.cpus.effective`, +/// `/proc/stat` through the source). +pub fn load_probe_for( + accounting: &CpuAccounting, + files: &ProcessCpuFiles, +) -> Result, ProtocolError> { + let sample_interval = OsLoadProbe::default().sample_interval; + Ok(match accounting { + CpuAccounting::CallingThread => Box::new(OsLoadProbe::default()), + CpuAccounting::Processes(pids) => { + let pid = pids.first().ok_or_else(|| ProtocolError::Parse { + what: "Processes accounting".into(), + message: "no pids".into(), + })?; + let path = files.proc_root.join(pid.to_string()).join("status"); + let status = + std::fs::read_to_string(&path).map_err(|_| ProtocolError::MissingProcess { + pid: *pid, + path: path.display().to_string(), + })?; + let list = status + .lines() + .find_map(|line| line.strip_prefix("Cpus_allowed_list:")) + .ok_or_else(|| ProtocolError::Parse { + what: path.display().to_string(), + message: "no Cpus_allowed_list line".into(), + })?; + Box::new(ServerCoresProbe { + cores: parse_cpu_list(list)?, + sample_interval, + host: ServerHost::Local { + proc_root: files.proc_root.clone(), + pids: pids.clone(), + }, + }) + } + CpuAccounting::Cgroup(source) => Box::new(ServerCoresProbe { + cores: parse_cpu_list(&source.read("cpuset.cpus.effective")?)?, + sample_interval, + host: ServerHost::Cgroup(source.clone()), + }), + }) +} + /// The protocol of a run, recorded in `run.json`. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -553,6 +888,8 @@ pub struct JobRecord { /// The sample with the median thread CPU (process CPU for a `Processes` /// engine). pub median: StepCost, + /// The index of `median` in `samples`: the measured run it came from. + pub median_run: usize, } impl JobRecord { @@ -673,7 +1010,8 @@ impl Protocol { busy_fraction: after.busy_fraction, }); } - let median = median_sample(&samples, clock); + let median_run = median_run(&samples, clock); + let median = samples[median_run].clone(); Ok(JobRecord { core, busy_before: before.busy_fraction, @@ -682,6 +1020,7 @@ impl Protocol { marks, samples, median, + median_run, }) } @@ -697,10 +1036,10 @@ impl Protocol { /// The sample in the middle of an odd number of samples, ordered by the CPU /// `clock` measures the engine by; ties keep run order, so the choice is /// deterministic. -fn median_sample(samples: &[StepCost], clock: &EngineClock) -> StepCost { - let mut order: Vec<&StepCost> = samples.iter().collect(); - order.sort_by_key(|sample| clock.engine_cpu_ns(sample)); - order[order.len() / 2].clone() +fn median_run(samples: &[StepCost], clock: &EngineClock) -> usize { + let mut order: Vec = (0..samples.len()).collect(); + order.sort_by_key(|&run| clock.engine_cpu_ns(&samples[run])); + order[order.len() / 2] } /// Times `run(size)` at each size as one protocol job pinned to `core` @@ -733,14 +1072,9 @@ pub fn measure_sizes( })?; load = Some(job.load_after()); let measured_units = &units_per_call[protocol.warmup_runs as usize..]; - let median_run = job - .samples - .iter() - .position(|sample| *sample == job.median) - .expect("the median is one of the samples"); points.push(FitPoint { setting: size.to_string(), - terms: vec![measured_units[median_run] as f64, 1.0], + terms: vec![measured_units[job.median_run] as f64, 1.0], measured: clock.engine_cpu_ns(&job.median) as f64, }); } @@ -829,6 +1163,13 @@ pub enum ProtocolError { /// Pinning failed in the OS. #[error("pinning to core {core} failed: {message}")] Pin { core: usize, message: String }, + /// A server's cgroup file that cannot be read. + #[error(transparent)] + Cgroup(#[from] CgroupError), + /// The server's cgroup was throttled by a CPU quota during the run + /// (`nr_throttled` grew by this many periods); start it without `--cpus`. + #[error("the server's cgroup was throttled {nr_throttled} times by a CPU quota: start it without --cpus")] + CgroupThrottled { nr_throttled: u64 }, /// The job's engine call failed. #[error("the job failed: {0}")] Job(#[from] EngineError), diff --git a/aqpbm-core/src/harness/records.rs b/aqpbm-core/src/harness/records.rs index a191bdc3..6fdc2b3e 100644 --- a/aqpbm-core/src/harness/records.rs +++ b/aqpbm-core/src/harness/records.rs @@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize}; +use crate::harness::cgroup::CgroupMemory; use crate::harness::engine::{ Answers, EngineDescription, Footprint, NodeProfile, PlanSummary, PredictedCost, }; @@ -39,6 +40,25 @@ pub struct ArmResult { /// The answers at each evaluation time. pub answers: Vec<(i64, Answers)>, pub footprint: Footprint, + /// Samples ingested by one install: the sum over refresh chunks. + pub ingested_samples: u64, + /// For a [`crate::harness::engine::CpuAccounting::Cgroup`] engine, the server's + /// memory before the installs. + pub server_memory_before: Option, + /// The same after the last step. The server then holds every install of + /// the arm at once (`installs_held` of them), so this is not one + /// install's memory. + pub server_memory_after: Option, + /// For a `Cgroup` engine, the server's CPU from before the installs to + /// after the footprint, in ns: the steps plus work between them, such + /// as background merges, over every install. + pub server_cpu_ns_whole_arm: Option, + /// Where the engine's CPU was read ([`crate::harness::protocol::EngineClock::cpu_source`]), + /// such as `cgroup /sys/fs/cgroup/system.slice/docker-1a2b.scope/cpu.stat` + /// or `schedstat`. + pub cpu_source: String, + /// Installs held at once while the arm ran: warm-up plus measured runs. + pub installs_held: u32, /// The usage the harness measured, priced at the engine's own prices /// ([`crate::harness::engine::InstalledArm::price`]); `None` for an engine without /// a cost model. Compare with the engine's own prediction, diff --git a/aqpbm-core/src/harness/rundir.rs b/aqpbm-core/src/harness/run_directory.rs similarity index 64% rename from aqpbm-core/src/harness/rundir.rs rename to aqpbm-core/src/harness/run_directory.rs index 96f06d3a..369cb608 100644 --- a/aqpbm-core/src/harness/rundir.rs +++ b/aqpbm-core/src/harness/run_directory.rs @@ -13,13 +13,13 @@ use crate::harness::records::{ArmResult, RunRecord}; /// A created run directory. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct RunDir { - /// Private: only [`RunDir::create`] makes one, so every `RunDir` names a +pub struct RunDirectory { + /// Private: only [`RunDirectory::create`] makes one, so every `RunDirectory` names a /// directory this run created. path: PathBuf, } -impl RunDir { +impl RunDirectory { /// Creates the directory and its subdirectories. Refuses an existing /// directory and a label or subcommand outside `[a-z0-9-]`. pub fn create( @@ -28,7 +28,7 @@ impl RunDir { utc: DateTime, subcommand: &str, label: &str, - ) -> Result { + ) -> Result { check_name("machine key", machine_key, MACHINE_KEY_CHARSET, |c| { c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_' })?; @@ -37,25 +37,50 @@ impl RunDir { c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' })?; } - let parent = root.join("runs").join(machine_key); - std::fs::create_dir_all(&parent).map_err(|source| io(&parent, source))?; - let path = parent.join(format!( + let path = root.join("runs").join(machine_key).join(format!( "{}-{subcommand}-{label}", utc.format("%Y%m%dT%H%M%SZ") )); - // `create_dir` fails on an existing directory, so two runs never share one. - match std::fs::create_dir(&path) { + RunDirectory::create_at(&path) + } + + /// Creates the run directory at `path` and its subdirectories, for a + /// run whose engine runs are separate processes over one directory + /// (`benchmark-external --run-directory`). Refuses an existing `path`. + pub fn create_at(path: &Path) -> Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|source| io(parent, source))?; + } + match std::fs::create_dir(path) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - return Err(RunDirError::RunDirExists(path)); + return Err(RunDirectoryError::RunDirectoryExists(path.to_path_buf())); } - Err(source) => return Err(io(&path, source)), + Err(source) => return Err(io(path, source)), } - for sub in ["workloads", "data", "plans", "results"] { + for sub in RUN_SUBDIRECTORIES { let sub = path.join(sub); std::fs::create_dir(&sub).map_err(|source| io(&sub, source))?; } - Ok(RunDir { path }) + Ok(RunDirectory { + path: path.to_path_buf(), + }) + } + + /// Opens a run directory another process created: every subdirectory + /// must exist. + pub fn open(path: &Path) -> Result { + for sub in RUN_SUBDIRECTORIES { + if !path.join(sub).is_dir() { + return Err(RunDirectoryError::NotARunDirectory { + path: path.to_path_buf(), + missing: sub.into(), + }); + } + } + Ok(RunDirectory { + path: path.to_path_buf(), + }) } /// The directory. @@ -64,12 +89,12 @@ impl RunDir { } /// Writes `run.json`. - pub fn write_run(&self, run: &RunRecord) -> Result<(), RunDirError> { + pub fn write_run(&self, run: &RunRecord) -> Result<(), RunDirectoryError> { write_json(&self.path.join("run.json"), run) } /// Writes `data/.datagen.json` and returns its path. - pub fn write_data(&self, data: &DataRecord) -> Result { + pub fn write_data(&self, data: &DataRecord) -> Result { check_name("metric", &data.metric, METRIC_CHARSET, |c| { c.is_ascii_alphanumeric() || c == '_' || c == ':' })?; @@ -84,31 +109,10 @@ impl RunDir { /// Writes `results//__.json` and returns its path. /// A workload or arm name containing `__` is refused: the file name would /// be ambiguous. - pub fn write_arm(&self, result: &ArmResult) -> Result { - for (what, name) in [ - ("engine", &result.engine), - ("workload", &result.workload), - ("arm", &result.arm), - ] { - check_name(what, name, FILE_NAME_CHARSET, |c| { - c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' - })?; - if name.starts_with('.') { - return Err(RunDirError::BadName { - what: what.into(), - name: name.clone(), - allowed: FILE_NAME_CHARSET, - }); - } - } - for (what, name) in [("workload", &result.workload), ("arm", &result.arm)] { - if name.contains("__") { - return Err(RunDirError::AmbiguousName { - what: what.into(), - name: name.clone(), - }); - } - } + pub fn write_arm(&self, result: &ArmResult) -> Result { + check_result_name("engine", &result.engine, false)?; + check_result_name("workload", &result.workload, true)?; + check_result_name("arm", &result.arm, true)?; let dir = self.path.join("results").join(&result.engine); std::fs::create_dir_all(&dir).map_err(|source| io(&dir, source))?; let path = dir.join(format!("{}__{}.json", result.workload, result.arm)); @@ -120,7 +124,7 @@ impl RunDir { /// after, load average and marks (such as `busy-after 0.35`). /// Example: `ingest-0 core 3 busy-before 0.02 busy-after 0.03 loadavg 0.5 0.75`; /// an unreadable load average is written `unknown`. - pub fn append_status(&self, job: &str, record: &JobRecord) -> Result<(), RunDirError> { + pub fn append_status(&self, job: &str, record: &JobRecord) -> Result<(), RunDirectoryError> { let mut line = format!( "{job} core {} busy-before {:.2} busy-after {:.2} loadavg {} {}", record.core, @@ -147,6 +151,37 @@ impl RunDir { } } +/// Refuses a name that cannot be part of a result file name: outside +/// `[a-zA-Z0-9._-]`, starting with `.`, or, for a workload or arm +/// (`separated`), containing `__`, which separates them in +/// `__.json`. +pub(crate) fn check_result_name( + what: &str, + name: &str, + separated: bool, +) -> Result<(), RunDirectoryError> { + check_name(what, name, FILE_NAME_CHARSET, |c| { + c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' + })?; + if name.starts_with('.') { + return Err(RunDirectoryError::BadName { + what: what.into(), + name: name.into(), + allowed: FILE_NAME_CHARSET, + }); + } + if separated && name.contains("__") { + return Err(RunDirectoryError::AmbiguousName { + what: what.into(), + name: name.into(), + }); + } + Ok(()) +} + +/// The subdirectories of every run directory. +const RUN_SUBDIRECTORIES: [&str; 4] = ["workloads", "data", "plans", "results"]; + fn loadavg_text(loadavg: Option) -> String { loadavg.map_or_else(|| "unknown".to_string(), |value| value.to_string()) } @@ -166,9 +201,9 @@ fn check_name( name: &str, allowed: &'static str, allowed_char: impl Fn(char) -> bool, -) -> Result<(), RunDirError> { +) -> Result<(), RunDirectoryError> { if name.is_empty() || !name.chars().all(allowed_char) { - return Err(RunDirError::BadName { + return Err(RunDirectoryError::BadName { what: what.into(), name: name.into(), allowed, @@ -177,8 +212,8 @@ fn check_name( Ok(()) } -fn io(path: &Path, source: std::io::Error) -> RunDirError { - RunDirError::Io { +fn io(path: &Path, source: std::io::Error) -> RunDirectoryError { + RunDirectoryError::Io { path: path.to_path_buf(), source, } @@ -186,11 +221,15 @@ fn io(path: &Path, source: std::io::Error) -> RunDirError { /// Writes `value` as pretty JSON with a final newline to a new file; an /// existing file is refused (`create_new`), so a result is never overwritten. -fn write_json(path: &Path, value: &T) -> Result<(), RunDirError> { - let mut text = serde_json::to_string_pretty(value).map_err(|source| RunDirError::Json { - path: path.to_path_buf(), - source, - })?; +pub(crate) fn write_json( + path: &Path, + value: &T, +) -> Result<(), RunDirectoryError> { + let mut text = + serde_json::to_string_pretty(value).map_err(|source| RunDirectoryError::Json { + path: path.to_path_buf(), + source, + })?; text.push('\n'); std::fs::OpenOptions::new() .write(true) @@ -202,10 +241,10 @@ fn write_json(path: &Path, value: &T) -> Result<(), RunDirE /// A run directory that cannot be created or written. #[derive(Debug, thiserror::Error)] -pub enum RunDirError { +pub enum RunDirectoryError { /// The directory exists; runs are never overwritten. #[error("run directory {0} exists; runs are never overwritten")] - RunDirExists(PathBuf), + RunDirectoryExists(PathBuf), /// A name outside its character set, such as a label outside `[a-z0-9-]`. #[error("{what} '{name}' must match {allowed}+")] BadName { @@ -218,6 +257,9 @@ pub enum RunDirError { "{what} '{name}' contains '__', which separates workload and arm in result file names" )] AmbiguousName { what: String, name: String }, + /// A directory without one of the run subdirectories. + #[error("{path} is not a run directory: it has no {missing}/")] + NotARunDirectory { path: PathBuf, missing: String }, #[error("{path}: {source}")] Io { path: PathBuf, diff --git a/aqpbm-core/tests/harness_arm_schedule.rs b/aqpbm-core/tests/harness_arm_schedule.rs new file mode 100644 index 00000000..cdc3b7b5 --- /dev/null +++ b/aqpbm-core/tests/harness_arm_schedule.rs @@ -0,0 +1,110 @@ +//! The schedule every engine run uses for a workload. + +use aqpbm_core::harness::arm_run::{ArmSchedule, ScheduleError}; +use aqpbm_core::harness::data::DataRecord; +use aqpbm_core::harness::engine::{QueryLanguage, QueryText, WorkloadQuery, WorkloadSpec}; +use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; + +fn query(id: &str, window_ms: u64, evaluation_interval_ms: u64) -> WorkloadQuery { + WorkloadQuery { + id: id.into(), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: format!("sum_over_time(m[{window_ms}ms])"), + }], + window_ms, + evaluation_interval_ms, + } +} + +fn workload(queries: Vec, start_ms: i64, duration_ms: u64) -> WorkloadSpec { + WorkloadSpec { + name: "w".into(), + queries, + data: vec![DataRecord { + metric: "m".into(), + description: TimeSeriesDescription { + labels: vec![SeriesLabelSpec { + name: "s".into(), + cardinality: 1, + skewness: 0.0, + }], + series_num: 1, + start_ms, + sample_interval_ms: 1_000, + duration_ms, + value_distribution: DataDistribution::Uniform(UniformParameter { + lower_bound: 0.0, + upper_bound: 1.0, + seed: 0, + }), + counter: false, + seed: 1, + }, + }], + } +} + +/// Windows 30 s and 20 s every 10 s over data from 0 ms for 120 s: the +/// multiples of 10 s from 30,000 ms (start + longest window) to 120,000 ms. +#[test] +fn evaluations_are_the_interval_multiples_after_the_longest_window() { + let spec = workload( + vec![query("a", 30_000, 10_000), query("b", 20_000, 10_000)], + 0, + 120_000, + ); + let schedule = ArmSchedule::for_workload(&spec).unwrap(); + assert_eq!(schedule.refresh_ms, 10_000); + assert_eq!( + schedule.evaluate_at_ms, + (3..=12).map(|k| k * 10_000).collect::>() + ); + // 125 s of data: the last multiple inside the data is still 120,000. + let longer = workload(vec![query("a", 30_000, 10_000)], 0, 125_000); + assert_eq!( + ArmSchedule::for_workload(&longer) + .unwrap() + .evaluate_at_ms + .last(), + Some(&120_000) + ); +} + +#[test] +fn workloads_no_schedule_fits_are_refused() { + let mixed = workload( + vec![query("a", 30_000, 10_000), query("b", 30_000, 15_000)], + 0, + 120_000, + ); + assert!(matches!( + ArmSchedule::for_workload(&mixed), + Err(ScheduleError::MixedEvaluationIntervals { + first_ms: 10_000, + other_ms: 15_000, + .. + }) + )); + let empty = workload(Vec::new(), 0, 120_000); + assert!(matches!( + ArmSchedule::for_workload(&empty), + Err(ScheduleError::NoQueries { .. }) + )); + // Data from 1,000 ms: chunks end at 11,000, 21,000, ..., so an + // evaluation at 40,000 would run after a chunk holding later samples. + let unaligned = workload(vec![query("a", 30_000, 10_000)], 1_000, 120_000); + assert!(matches!( + ArmSchedule::for_workload(&unaligned), + Err(ScheduleError::UnalignedStart { + start_ms: 1_000, + interval_ms: 10_000, + .. + }) + )); + let too_long = workload(vec![query("a", 200_000, 10_000)], 0, 120_000); + assert!(matches!( + ArmSchedule::for_workload(&too_long), + Err(ScheduleError::NoEvaluationTime { .. }) + )); +} diff --git a/aqpbm-core/tests/harness_benchmark_external.rs b/aqpbm-core/tests/harness_benchmark_external.rs new file mode 100644 index 00000000..be02f848 --- /dev/null +++ b/aqpbm-core/tests/harness_benchmark_external.rs @@ -0,0 +1,648 @@ +//! Engine runs over one run directory and the report that joins them. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use aqpbm_core::harness::benchmark_external::{ + read_variants, read_workloads, report, run_engine, write_report, CellOutcome, EngineRunCell, + EngineRunSetup, SUMMARY_CSV_HEADER, +}; +use aqpbm_core::harness::cgroup::CgroupMemory; +use aqpbm_core::harness::data::{DataRecord, SeriesLabels}; +use aqpbm_core::harness::engine::{ + Answers, Footprint, PlanSummary, QueryLanguage, QueryText, StepCost, StepReport, WorkloadQuery, + WorkloadSpec, +}; +use aqpbm_core::harness::fake::FakeEngine; +use aqpbm_core::harness::protocol::{ + JobRecord, LoadProbe, MeasurementClocks, Protocol, ProtocolError, +}; +use aqpbm_core::harness::records::ArmResult; +use aqpbm_core::harness::run_directory::RunDirectory; +use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; + +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "aqpbm-core-harness-benchmark-external-{}-{test}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + TempDir(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct IdleProbe; + +impl LoadProbe for IdleProbe { + fn core_busy_fraction(&mut self, _core: usize) -> Result { + Ok(0.0) + } + fn loadavg(&mut self) -> f64 { + 0.0 + } +} + +/// `sum_over_time(m[10s])` every 10 s over 2 series, 1 sample per second +/// for 60 s. +fn workload(name: &str) -> WorkloadSpec { + WorkloadSpec { + name: name.into(), + queries: vec![WorkloadQuery { + id: "sum".into(), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: "sum_over_time(m[10s])".into(), + }], + window_ms: 10_000, + evaluation_interval_ms: 10_000, + }], + data: vec![DataRecord { + metric: "m".into(), + description: TimeSeriesDescription { + labels: vec![SeriesLabelSpec { + name: "s".into(), + cardinality: 2, + skewness: 0.0, + }], + series_num: 2, + start_ms: 0, + sample_interval_ms: 1_000, + duration_ms: 60_000, + value_distribution: DataDistribution::Uniform(UniformParameter { + lower_bound: 0.0, + upper_bound: 10.0, + seed: 0, + }), + counter: false, + seed: 1, + }, + }], + } +} + +fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); +} + +/// Workloads w1 and w2; variant v1 (no substitutions allowed) with a plan +/// for w1 and none for w2; variant v2 (substitutions allowed) with the +/// given plan texts for w1 and w2. +fn fixture(temp: &TempDir, v2_w1: &str, v2_w2: &str) -> RunDirectory { + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + for name in ["w1", "w2"] { + write( + &run.path().join("workloads").join(format!("{name}.json")), + &serde_json::to_string(&workload(name)).unwrap(), + ); + } + let plans = run.path().join("plans"); + write( + &plans.join("v1/variant.json"), + r#"{"substitutions_allowed": false}"#, + ); + write(&plans.join("v1/w1.plan.json"), "{}"); + write( + &plans.join("v1/w2.no-plan.json"), + r#"{"reason": "ExcludedByDeployment"}"#, + ); + write( + &plans.join("v2/variant.json"), + r#"{"substitutions_allowed": true}"#, + ); + write(&plans.join("v2/w1.plan.json"), v2_w1); + write(&plans.join("v2/w2.plan.json"), v2_w2); + run +} + +fn protocol() -> Protocol { + Protocol { + warmup_runs: 0, + measured_runs: 1, + max_core_busy_fraction: 1.0, + } +} + +fn run_fake(run: &RunDirectory, only: Option<&[String]>) -> Result, String> { + let engine = FakeEngine::default(); + let clocks = MeasurementClocks::with_calling_thread(&engine.clock); + let protocol = protocol(); + run_engine( + run, + &engine, + only, + EngineRunSetup { + protocol: &protocol, + core: 0, + probe: &mut IdleProbe, + clocks: &clocks, + args: vec!["test".into()], + }, + ) + .map_err(|error| error.to_string()) +} + +fn outcomes(cells: &[EngineRunCell]) -> Vec<(String, String, CellOutcome)> { + cells + .iter() + .map(|cell| { + ( + cell.workload.clone(), + cell.variant.clone(), + cell.outcome.clone(), + ) + }) + .collect() +} + +fn read_result(run: &RunDirectory, workload: &str, variant: &str) -> ArmResult { + let path = run + .path() + .join(format!("results/fake/{workload}__{variant}.json")); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +/// L1: every cell is written; ran cells got the absolute plan file path. +#[test] +fn an_engine_run_runs_every_cell_and_passes_the_plan_file() { + let temp = TempDir::new("l1"); + let run = fixture(&temp, "{}", "{}"); + let cells = run_fake(&run, None).unwrap(); + assert_eq!( + outcomes(&cells), + vec![ + ("w1".into(), "v1".into(), CellOutcome::Ran), + ( + "w2".into(), + "v1".into(), + CellOutcome::NoPlan { + reason: "ExcludedByDeployment".into() + } + ), + ("w1".into(), "v2".into(), CellOutcome::Ran), + ("w2".into(), "v2".into(), CellOutcome::Ran), + ] + ); + for (workload, variant) in [("w1", "v1"), ("w1", "v2"), ("w2", "v2")] { + let result = read_result(&run, workload, variant); + let plan = std::path::absolute( + run.path() + .join(format!("plans/{variant}/{workload}.plan.json")), + ) + .unwrap(); + assert!( + result + .plan + .text + .contains(&format!("plan_file = {}", plan.display())), + "{}", + result.plan.text + ); + assert_eq!(result.ingested_samples, 120); + assert!(run + .path() + .join(format!("results/fake/{workload}__{variant}.cell.json")) + .is_file()); + } + assert!(!run.path().join("results/fake/w2__v1.json").exists()); + let engine_run_records = std::fs::read_dir(run.path().join("results/fake")) + .unwrap() + .filter(|e| { + e.as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("engine-run-") + }) + .count(); + assert_eq!(engine_run_records, 1); +} + +/// L2 + L5: an engine run can go variant by variant; a cell is never rerun. +#[test] +fn an_engine_run_goes_variant_by_variant_and_never_reruns_a_cell() { + let temp = TempDir::new("l5"); + let run = fixture(&temp, "{}", "{}"); + let v2 = run_fake(&run, Some(&["v2".to_string()])).unwrap(); + assert_eq!(v2.len(), 2); + assert!(v2.iter().all(|cell| cell.variant == "v2")); + assert_eq!(run_fake(&run, Some(&["v1".to_string()])).unwrap().len(), 2); + let error = run_fake(&run, Some(&["v1".to_string()])).unwrap_err(); + assert!( + error.contains("w1__v1.cell.json") && error.contains("never overwritten"), + "{error}" + ); + let unknown = run_fake(&run, Some(&["v9".to_string()])).unwrap_err(); + assert!(unknown.contains("v9"), "{unknown}"); +} + +/// L3 + L7: an install error, and a substitution under a variant that +/// allows none, are `NotRun` cells; the other cells still run. +#[test] +fn failed_cells_are_written_and_the_engine_run_goes_on() { + let temp = TempDir::new("l3"); + let run = fixture( + &temp, + r#"{"refuse": "refused: UnsupportedShape filter@node 3"}"#, + "{}", + ); + write( + &run.path().join("plans/v1/w1.plan.json"), + r#"{"substitutions": ["quantileDD for Kll at node 2"]}"#, + ); + let cells = run_fake(&run, None).unwrap(); + let by_cell: BTreeMap<(String, String), CellOutcome> = outcomes(&cells) + .into_iter() + .map(|(w, v, o)| ((w, v), o)) + .collect(); + assert_eq!( + by_cell[&("w1".into(), "v2".into())], + CellOutcome::NotRun { + error: "refused: UnsupportedShape filter@node 3".into() + } + ); + match &by_cell[&("w1".into(), "v1".into())] { + CellOutcome::NotRun { error } => { + assert!(error.contains("quantileDD for Kll at node 2"), "{error}") + } + other => panic!("expected NotRun, got {other:?}"), + } + assert_eq!(by_cell[&("w2".into(), "v2".into())], CellOutcome::Ran); + assert!(!run.path().join("results/fake/w1__v1.json").exists()); +} + +/// L4 + L6: an ambiguous or unknown file in a variant is refused before +/// anything runs. +#[test] +fn a_bad_variant_layout_is_refused_before_any_cell() { + let temp = TempDir::new("l4"); + let run = fixture(&temp, "{}", "{}"); + write( + &run.path().join("plans/v2/w2.no-plan.json"), + r#"{"reason": "x"}"#, + ); + let error = run_fake(&run, None).unwrap_err(); + assert!( + error.contains("w2.plan.json") && error.contains("w2.no-plan.json"), + "{error}" + ); + assert!(!run.path().join("results/fake").exists()); + + let temp = TempDir::new("l6"); + let run = fixture(&temp, "{}", "{}"); + write(&run.path().join("plans/v1/w1.txt"), ""); + let error = run_fake(&run, None).unwrap_err(); + assert!(error.contains("w1.txt"), "{error}"); + + let temp = TempDir::new("l6b"); + let run = fixture(&temp, "{}", "{}"); + std::fs::remove_file(run.path().join("plans/v2/variant.json")).unwrap(); + let workloads = read_workloads(&run).unwrap(); + let error = read_variants(&run, &workloads).unwrap_err().to_string(); + assert!(error.contains("variant.json"), "{error}"); +} + +fn series(name: &str) -> SeriesLabels { + [("s".to_string(), name.to_string())].into_iter().collect() +} + +fn answers(values: &[(&str, f64)]) -> Answers { + let mut per_series = BTreeMap::new(); + for (name, value) in values { + per_series.insert(series(name), *value); + } + Answers([("q".to_string(), per_series)].into_iter().collect()) +} + +fn job(cost: StepCost) -> JobRecord { + JobRecord { + core: 0, + busy_before: 0.0, + busy_after: 0.0, + loadavg: [None, None], + marks: Vec::new(), + samples: vec![cost.clone()], + median: cost, + median_run: 0, + } +} + +fn thread_job(ns: u64) -> JobRecord { + job(StepCost { + thread_cpu_ns: Some(ns), + process_cpu_ns: ns, + wall_ns: ns, + report: StepReport::default(), + }) +} + +fn server_job(ns: u64, counter_ns: Option) -> JobRecord { + job(StepCost { + thread_cpu_ns: None, + process_cpu_ns: ns, + wall_ns: ns, + report: StepReport { + scanned_bytes: None, + engine_reported_cpu_ns: counter_ns, + }, + }) +} + +fn result(engine: &str, workload: &str, variant: &str, answers: Vec<(i64, Answers)>) -> ArmResult { + ArmResult { + engine: engine.into(), + workload: workload.into(), + arm: variant.into(), + plan: PlanSummary::default(), + predicted: None, + ingest: vec![thread_job(1_000)], + evaluate: vec![thread_job(1_000)], + answers, + footprint: Footprint::default(), + measured_engine_cost_per_second: None, + node_profiles: None, + ingested_samples: 4, + server_memory_before: None, + server_memory_after: None, + server_cpu_ns_whole_arm: None, + cpu_source: "calling-thread".into(), + installs_held: 1, + } +} + +/// Writes a cell, and its result when it ran. +fn put( + run: &RunDirectory, + engine: &str, + workload: &str, + variant: &str, + outcome: CellOutcome, + arm: Option, +) { + if let Some(arm) = arm { + run.write_arm(&arm).unwrap(); + } + let cell = EngineRunCell { + engine: engine.into(), + workload: workload.into(), + variant: variant.into(), + outcome, + }; + write( + &run.path() + .join(format!("results/{engine}/{workload}__{variant}.cell.json")), + &serde_json::to_string(&cell).unwrap(), + ); +} + +fn truth_answers() -> Vec<(i64, Answers)> { + vec![ + (10, answers(&[("s1", 10.0), ("s2", 0.0)])), + (20, answers(&[])), + ] +} + +/// The P1 fixture: truth `a/v1`, `b/v1` a cgroup engine that ran, `b/v2` no +/// plan, `c/v1` not run, and workload w2 where the truth has no plan. +fn report_fixture(temp: &TempDir) -> RunDirectory { + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + put( + &run, + "a", + "w1", + "v1", + CellOutcome::Ran, + Some(result("a", "w1", "v1", truth_answers())), + ); + let mut b = result( + "b", + "w1", + "v1", + vec![ + (10, answers(&[("s1", 11.0), ("s2", 0.0), ("s3", 7.0)])), + (20, answers(&[])), + ], + ); + b.ingest = vec![server_job(3_000, None), server_job(5_000, None)]; + b.evaluate = vec![ + server_job(1_500_000, Some(1_000_000)), + server_job(2_500_000, Some(3_000_000)), + ]; + b.server_cpu_ns_whole_arm = Some(9_000_000); + b.cpu_source = + "cgroup bench@192.0.2.1:/sys/fs/cgroup/system.slice/docker-1a2b.scope/cpu.stat over SSH" + .into(); + let memory = CgroupMemory { + current_bytes: 3 * 1_048_576, + anon_bytes: 0, + file_bytes: 0, + lifetime_peak_bytes: Some(5 * 1_048_576), + }; + b.server_memory_before = Some(memory); + b.server_memory_after = Some(memory); + b.installs_held = 6; + b.footprint = Footprint { + view_bytes: 100, + raw_retained_bytes: 20, + peak_bytes: None, + }; + b.plan.substitutions = vec!["quantileDD for Kll at node 3".into(), "x".into()]; + b.plan.sharing_lost = vec!["node 4 for nodes 6, 7".into()]; + put(&run, "b", "w1", "v1", CellOutcome::Ran, Some(b)); + put( + &run, + "b", + "w1", + "v2", + CellOutcome::NoPlan { + reason: "ExcludedByDeployment".into(), + }, + None, + ); + put( + &run, + "c", + "w1", + "v1", + CellOutcome::NotRun { + error: "refused: filter@node 3".into(), + }, + None, + ); + put( + &run, + "a", + "w2", + "v1", + CellOutcome::NoPlan { + reason: "ExcludedByDeployment".into(), + }, + None, + ); + put( + &run, + "b", + "w2", + "v1", + CellOutcome::Ran, + Some(result("b", "w2", "v1", truth_answers())), + ); + run +} + +/// P1, P2, P5, P6: the summary rows, by hand. +#[test] +fn the_summary_has_absolute_numbers_and_errors_against_the_truth() { + let temp = TempDir::new("p1"); + let run = report_fixture(&temp); + let report = report(&run, "a", "v1").unwrap(); + let csv = report.summary_csv(); + let lines: Vec<&str> = csv.lines().collect(); + assert_eq!(lines[0], SUMMARY_CSV_HEADER); + assert_eq!(SUMMARY_CSV_HEADER.split(',').count(), 21); + let empty_after_status = ",".repeat(17); + let expected = [ + "w1,a,v1,ok,thread,250,0.001,,,,,,1,0,0,0,2,0,0,,".to_string(), + "w2,a,v1,no plan: ExcludedByDeployment".to_string() + &empty_after_status, + "w1,b,v1,ok,cgroup,2000,2,2,9,3145728,3145728,5242880,6,120,0.1,0.05,2,0,1,quantileDD for Kll at node 3;x,\"node 4 for nodes 6, 7\"".to_string(), + "w1,b,v2,no plan: ExcludedByDeployment".to_string() + &empty_after_status, + "w2,b,v1,ok,thread,250,0.001,,,,,,1,0,,,,,,,".to_string(), + "w1,c,v1,not run: refused: filter@node 3".to_string() + &empty_after_status, + ]; + assert_eq!( + lines[1..].to_vec(), + expected.iter().map(String::as_str).collect::>() + ); + + let accuracy = report.accuracy_csv(); + assert!( + accuracy + .lines() + .any(|line| line == "w1,b,v1,q,0.1,0.05,2,0,1"), + "{accuracy}" + ); + + let markdown = report.summary_markdown(); + assert!( + markdown.contains("| q 2.000 ms, i 2000.0 ns/sample, err 0.100 [cgroup] |"), + "{markdown}" + ); + assert!( + markdown.contains("| not run: refused: filter@node 3 |"), + "{markdown}" + ); + assert!( + markdown.contains("| no plan: ExcludedByDeployment |"), + "{markdown}" + ); + + write_report(&run, &report).unwrap(); + for file in ["summary.csv", "summary.md", "accuracy.csv"] { + assert!(run.path().join(file).is_file(), "{file}"); + } + assert!(report_error(&run, "a", "v9").contains("a/v9")); +} + +fn report_error(run: &RunDirectory, engine: &str, variant: &str) -> String { + report(run, engine, variant).unwrap_err().to_string() +} + +/// P2: the relative-error rules. +#[test] +fn relative_errors_follow_the_stated_rules() { + use aqpbm_core::harness::benchmark_external::relative_error; + assert_eq!(relative_error(11.0, 10.0), 0.1); + assert_eq!(relative_error(0.0, 0.0), 0.0); + assert_eq!(relative_error(1.0, 0.0), f64::INFINITY); + assert_eq!(relative_error(f64::NAN, f64::NAN), 0.0); + assert_eq!(relative_error(f64::NAN, 1.0), f64::INFINITY); + assert_eq!(relative_error(1.0, f64::NAN), f64::INFINITY); + assert_eq!(relative_error(1.0, f64::INFINITY), f64::INFINITY); + assert_eq!(relative_error(f64::INFINITY, 1.0), f64::INFINITY); + assert_eq!( + relative_error(f64::NEG_INFINITY, f64::INFINITY), + f64::INFINITY + ); + assert_eq!(relative_error(f64::INFINITY, f64::INFINITY), 0.0); +} + +/// Review items 5 and 7: engine runs that read different data, or answered at +/// other times than the truth, are refused by the report. +#[test] +fn the_report_refuses_engine_runs_that_did_not_run_the_same_data_or_times() { + let temp = TempDir::new("p7"); + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + put( + &run, + "a", + "w1", + "v1", + CellOutcome::Ran, + Some(result("a", "w1", "v1", truth_answers())), + ); + put( + &run, + "b", + "w1", + "v1", + CellOutcome::Ran, + Some(result("b", "w1", "v1", vec![(10, answers(&[]))])), + ); + let error = report_error(&run, "a", "v1"); + assert!( + error.contains("[10]") && error.contains("[10, 20]"), + "{error}" + ); + + let temp = TempDir::new("p8"); + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + put( + &run, + "a", + "w1", + "v1", + CellOutcome::Ran, + Some(result("a", "w1", "v1", truth_answers())), + ); + let mut other = result("b", "w1", "v1", truth_answers()); + other.ingested_samples = 5; + put(&run, "b", "w1", "v1", CellOutcome::Ran, Some(other)); + let error = report_error(&run, "a", "v1"); + assert!( + error.contains("4") && error.contains("5") && error.contains("same data"), + "{error}" + ); +} + +/// A workload or variant name that cannot be part of a result file name is +/// refused before any cell runs, not after its arm ran. +#[test] +fn result_file_names_are_checked_before_any_cell_runs() { + let temp = TempDir::new("names"); + let run = fixture(&temp, "{}", "{}"); + let workloads = run.path().join("workloads"); + let spec = workload("w__3"); + write( + &workloads.join("w__3.json"), + &serde_json::to_string(&spec).unwrap(), + ); + for variant in ["v1", "v2"] { + write( + &run.path().join(format!("plans/{variant}/w__3.plan.json")), + "{}", + ); + } + let error = run_fake(&run, None).unwrap_err(); + assert!(error.contains("w__3") && error.contains("__"), "{error}"); + assert!(!run.path().join("results/fake").exists()); +} diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs new file mode 100644 index 00000000..47c31c3e --- /dev/null +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -0,0 +1,449 @@ +//! A server's cgroup v2 files: CPU from `cpu.stat`, memory, reading them +//! over SSH from the server host, the clock over them and a whole arm run +//! on a fake server in its own group. + +use std::path::{Path, PathBuf}; + +use aqpbm_core::harness::arm_run::{run_arm, ArmSchedule}; +use aqpbm_core::harness::cgroup::{CgroupCpu, CgroupError, CgroupMemory, CgroupSource}; +use aqpbm_core::harness::data::DataRecord; +use aqpbm_core::harness::engine::{ + ArmSpec, CpuAccounting, EngineUnderTest, QueryLanguage, QueryText, StepReport, WorkloadQuery, + WorkloadSpec, +}; +use aqpbm_core::harness::fake::{FakeEngine, FakeServer}; +use aqpbm_core::harness::protocol::{ + LoadProbe, MeasurementClocks, OsCpuClock, Protocol, ProtocolError, +}; +use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; + +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "aqpbm-core-harness-cgroup-{}-{test}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + TempDir(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct IdleProbe; + +impl LoadProbe for IdleProbe { + fn core_busy_fraction(&mut self, _core: usize) -> Result { + Ok(0.0) + } + fn loadavg(&mut self) -> f64 { + 0.0 + } +} + +fn cpu_stat(usage_usec: u64, nr_throttled: u64) -> String { + format!("usage_usec {usage_usec}\nuser_usec 0\nsystem_usec 0\nnr_periods 0\nnr_throttled {nr_throttled}\nthrottled_usec 0\n") +} + +/// A group directory with `cpu.stat` and the memory files of C2. +fn group(dir: &Path, usage_usec: u64) { + std::fs::write(dir.join("cpu.stat"), cpu_stat(usage_usec, 0)).unwrap(); + std::fs::write(dir.join("memory.current"), "1048576\n").unwrap(); + std::fs::write(dir.join("memory.peak"), "2097152\n").unwrap(); + std::fs::write( + dir.join("memory.stat"), + "anon 524288\nfile 262144\nkernel 4096\n", + ) + .unwrap(); +} + +/// C1: `usage_usec` in ns; no `usage_usec` line names the field. +#[test] +fn cpu_stat_reads_usage_in_ns() { + let cpu = CgroupCpu::parse(&cpu_stat(2500, 0)).unwrap(); + assert_eq!(cpu.usage_ns, 2_500_000); + assert_eq!(cpu.nr_throttled, 0); + let error = CgroupCpu::parse("user_usec 1\n").unwrap_err(); + assert!(error.to_string().contains("usage_usec"), "{error}"); +} + +/// C2: memory files; no `memory.peak` (kernel < 5.19) reads `None`. +#[test] +fn memory_files_read_current_anon_file_and_lifetime_peak() { + let temp = TempDir::new("memory"); + group(&temp.0, 0); + let source = CgroupSource::Local(temp.0.clone()); + assert_eq!( + source.memory().unwrap(), + CgroupMemory { + current_bytes: 1_048_576, + anon_bytes: 524_288, + file_bytes: 262_144, + lifetime_peak_bytes: Some(2_097_152), + } + ); + std::fs::remove_file(temp.0.join("memory.peak")).unwrap(); + assert_eq!(source.memory().unwrap().lifetime_peak_bytes, None); +} + +/// An executable shell script named `name` in `dir`. +#[cfg(unix)] +fn script(dir: &Path, name: &str, body: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.display().to_string() +} + +/// A stand-in for `ssh`: records its arguments in `ssh-arguments`, drops +/// the options and the host, and runs the remote command on this host. +#[cfg(unix)] +fn fake_ssh(dir: &Path) -> String { + script( + dir, + "fake-ssh", + "printf '%s\\n' \"$@\" > \"$(dirname \"$0\")/ssh-arguments\"\nfor last; do :; done\nexec sh -c \"$last\"\n", + ) +} + +/// A remote source reads the same values as the local directory, afresh +/// per read, over one shared SSH connection; a path with a quote reaches +/// `cat` intact; files outside the cgroup set are refused. +#[cfg(unix)] +#[test] +fn ssh_reads_the_same_values_as_the_directory_and_nothing_else() { + let temp = TempDir::new("ssh-'quoted'"); + group(&temp.0, 2500); + let local = CgroupSource::Local(temp.0.clone()); + let remote = CgroupSource::Remote { + ssh_program: fake_ssh(&temp.0), + host: "bench@192.0.2.1".into(), + cgroup_directory: temp.0.clone(), + }; + assert_eq!(remote.cpu().unwrap(), local.cpu().unwrap()); + assert_eq!(remote.memory().unwrap(), local.memory().unwrap()); + let arguments = std::fs::read_to_string(temp.0.join("ssh-arguments")).unwrap(); + assert!(arguments.contains("ControlMaster=auto"), "{arguments}"); + assert!(arguments.contains("BatchMode=yes"), "{arguments}"); + // `--` ends the options, so a host can never be read as one. + assert!(arguments.contains("--\nbench@192.0.2.1\n"), "{arguments}"); + std::fs::write(temp.0.join("cpu.stat"), cpu_stat(9000, 0)).unwrap(); + assert_eq!(remote.cpu().unwrap().usage_ns, 9_000_000); + // Without `memory.peak` (an older kernel) the remote command exits 3, + // whatever language the server host's error messages are in. + std::fs::remove_file(temp.0.join("memory.peak")).unwrap(); + assert_eq!(remote.memory().unwrap().lifetime_peak_bytes, None); + if Path::new("/proc/stat").exists() { + assert!(remote.read("proc-stat").unwrap().starts_with("cpu")); + } + for file in ["cgroup.procs", "../cpu.stat"] { + let error = remote.read(file).unwrap_err(); + assert!(error.to_string().contains(file), "{error}"); + } +} + +/// SSH's own failure (exit status 255) names the host and SSH's message. +#[cfg(unix)] +#[test] +fn an_unreachable_host_is_an_ssh_error() { + let temp = TempDir::new("ssh-unreachable"); + let remote = CgroupSource::Remote { + ssh_program: script( + &temp.0, + "refused-ssh", + "echo 'ssh: connect to host 192.0.2.1 port 22: Connection refused' >&2\nexit 255\n", + ), + host: "bench@192.0.2.1".into(), + cgroup_directory: PathBuf::from("/sys/fs/cgroup/system.slice/docker-1a2b.scope"), + }; + match remote.cpu().unwrap_err() { + CgroupError::Remote { host, message } => { + assert_eq!(host, "bench@192.0.2.1"); + assert!(message.contains("Connection refused"), "{message}"); + } + other => panic!("expected an SSH error, got {other:?}"), + } +} + +/// C4: the clock reads `usage_usec` around a step; thread CPU 0. An +/// unreadable group fails when the clock is made. +#[test] +fn cgroup_clock_reads_usage_and_fails_early_on_a_missing_group() { + let temp = TempDir::new("clock"); + group(&temp.0, 1000); + let clocks = MeasurementClocks::with_calling_thread(&OsCpuClock); + let clock = clocks + .clock_for(&CpuAccounting::Cgroup(CgroupSource::Local(temp.0.clone()))) + .unwrap(); + let cpu = clock.as_clock(); + let before = cpu.process_cpu_ns(); + std::fs::write(temp.0.join("cpu.stat"), cpu_stat(3500, 0)).unwrap(); + assert_eq!(cpu.process_cpu_ns() - before, 2_500_000); + assert_eq!(cpu.thread_cpu_ns(), 0); + assert!(clocks + .clock_for(&CpuAccounting::Cgroup(CgroupSource::Local( + temp.0.join("gone") + ))) + .is_err()); +} + +/// C5: `nr_throttled` above its value at clock creation fails the job. +#[test] +fn a_throttled_group_fails_the_job() { + let temp = TempDir::new("throttled"); + group(&temp.0, 1000); + let clocks = MeasurementClocks::with_calling_thread(&OsCpuClock); + let clock = clocks + .clock_for(&CpuAccounting::Cgroup(CgroupSource::Local(temp.0.clone()))) + .unwrap(); + let protocol = Protocol { + warmup_runs: 0, + measured_runs: 1, + max_core_busy_fraction: 1.0, + }; + let dir = temp.0.clone(); + let result = protocol.run_job(0, &mut IdleProbe, &clock, &mut || { + std::fs::write(dir.join("cpu.stat"), cpu_stat(2000, 1)).unwrap(); + Ok(StepReport::default()) + }); + assert_eq!( + result.unwrap_err(), + ProtocolError::CgroupThrottled { nr_throttled: 1 } + ); +} + +/// C6: `cpu.stat` has µs resolution: 1,500 ns twice reads 1 µs then 3 µs, +/// so the steps measure 1,000 and 2,000 ns. +#[test] +fn cgroup_cpu_is_quantized_to_whole_microseconds() { + let temp = TempDir::new("quantized"); + let server = + FakeServer::start_in_cgroup(&temp.0.join("proc"), 4242, &temp.0.join("group")).unwrap(); + let clocks = MeasurementClocks::with_calling_thread(&OsCpuClock); + let clock = clocks + .clock_for(&CpuAccounting::Cgroup(CgroupSource::Local( + temp.0.join("group"), + ))) + .unwrap(); + let cpu = clock.as_clock(); + let mut steps = Vec::new(); + for _ in 0..2 { + let before = cpu.process_cpu_ns(); + server.charge(1_500); + steps.push(cpu.process_cpu_ns() - before); + } + assert_eq!(steps, vec![1_000, 2_000]); +} + +/// 2 series, one sample per second for 60 s from 1,000 ms; one +/// `sum_over_time` query over 10 s every 10 s. +fn two_series_workload() -> WorkloadSpec { + WorkloadSpec { + name: "two".into(), + queries: vec![WorkloadQuery { + id: "sum".into(), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: "sum_over_time(m[10s])".into(), + }], + window_ms: 10_000, + evaluation_interval_ms: 10_000, + }], + data: vec![DataRecord { + metric: "m".into(), + description: TimeSeriesDescription { + labels: vec![SeriesLabelSpec { + name: "s".into(), + cardinality: 2, + skewness: 0.0, + }], + series_num: 2, + start_ms: 1_000, + sample_interval_ms: 1_000, + duration_ms: 60_000, + value_distribution: DataDistribution::Uniform(UniformParameter { + lower_bound: 0.0, + upper_bound: 10.0, + seed: 0, + }), + counter: false, + seed: 1, + }, + }], + } +} + +/// A1: a whole arm on a fake server in its own group. Ingesting a chunk of +/// `n` samples charges 10 µs + 50 ns·n (whole µs for n = 20: 11 µs); +/// medians come from process CPU and carry no thread CPU; the record has +/// the sample count, the memory before and after, and the whole-arm CPU, +/// which also counts 500 µs the fake charges at each install. +#[test] +fn an_arm_on_a_cgroup_server_records_cpu_memory_and_samples() { + let temp = TempDir::new("arm"); + let server = + FakeServer::start_in_cgroup(&temp.0.join("proc"), 4243, &temp.0.join("group")).unwrap(); + let engine = FakeEngine { + server: Some(server), + ns_per_install: 500_000, + ..FakeEngine::default() + }; + assert_eq!( + engine.cpu_accounting(), + CpuAccounting::Cgroup(CgroupSource::Local(temp.0.join("group"))) + ); + let workload = two_series_workload(); + let schedule = ArmSchedule { + refresh_ms: 10_000, + evaluate_at_ms: vec![61_000], + }; + let protocol = Protocol { + warmup_runs: 0, + measured_runs: 3, + max_core_busy_fraction: 1.0, + }; + let clocks = MeasurementClocks::with_calling_thread(&OsCpuClock); + let arm = ArmSpec { + name: "exact".into(), + raw_data_retained: true, + engine_options: serde_json::Value::Null, + }; + let result = run_arm( + &engine, + &workload, + &arm, + &schedule, + &protocol, + 0, + &mut IdleProbe, + &clocks, + ) + .unwrap(); + assert_eq!(result.ingested_samples, 120); + assert_eq!( + result.cpu_source, + format!("cgroup {}", temp.0.join("group").join("cpu.stat").display()) + ); + assert_eq!(result.installs_held, 3); + assert_eq!(result.ingest.len(), 6); + for job in &result.ingest { + assert_eq!(job.median.thread_cpu_ns, None); + // 10,000 + 50 * 20 = 11,000 ns, a whole number of µs. + assert_eq!(job.median.process_cpu_ns, 11_000); + } + let memory = CgroupMemory { + current_bytes: 3 * 1_048_576, + anon_bytes: 2 * 1_048_576, + file_bytes: 1_048_576, + lifetime_peak_bytes: Some(5 * 1_048_576), + }; + assert_eq!(result.server_memory_before, Some(memory)); + assert_eq!(result.server_memory_after, Some(memory)); + let steps_ns: u64 = result + .ingest + .iter() + .chain(&result.evaluate) + .flat_map(|job| &job.samples) + .map(|cost| cost.process_cpu_ns) + .sum(); + assert_eq!(result.server_cpu_ns_whole_arm, Some(steps_ns + 3 * 500_000)); +} + +/// The server's cores come from its cpu list; the idle check takes the +/// busiest of them. +#[test] +fn the_idle_check_watches_the_server_cores() { + use aqpbm_core::harness::protocol::{ + foreign_busy_fraction, load_probe_for, parse_cpu_list, ProcessCpuFiles, + }; + assert_eq!(parse_cpu_list("2,22\n").unwrap(), vec![2, 22]); + assert_eq!(parse_cpu_list("0-3,8").unwrap(), vec![0, 1, 2, 3, 8]); + assert!(parse_cpu_list("3-1").is_err()); + // core 2: 1 busy tick of 10; core 22: 5 of 10. + let before = "cpu2 0 0 0 0 0 0 0 0\ncpu22 0 0 0 0 0 0 0 0\n"; + let after = "cpu2 1 0 0 9 0 0 0 0\ncpu22 5 0 0 5 0 0 0 0\n"; + // No server CPU: 6 busy ticks of 20, less 4 ticks of rounding. + assert_eq!( + foreign_busy_fraction(&[2, 22], before, after, 0, 10_000_000).unwrap(), + 0.1 + ); + // The server's own work is not foreign load: 6 busy ticks (60 ms at + // 10 ms a tick) of 20, the server used 10 ms, 2 ticks per core (40 ms) + // are rounding → 10 ms of 200 ms. + assert_eq!( + foreign_busy_fraction(&[2, 22], before, after, 10_000_000, 10_000_000).unwrap(), + 0.05 + ); + // A server busier than the ticks show (tick rounding) is never negative. + assert_eq!( + foreign_busy_fraction(&[2, 22], before, after, 90_000_000, 10_000_000).unwrap(), + 0.0 + ); + + let temp = TempDir::new("probe"); + let proc_root = temp.0.join("proc"); + std::fs::create_dir_all(proc_root.join("40")).unwrap(); + std::fs::write( + proc_root.join("40/status"), + "Name:\tserver\nCpus_allowed_list:\t2,22\n", + ) + .unwrap(); + let files = ProcessCpuFiles { + proc_root: proc_root.clone(), + cgroup_root: temp.0.join("cgroup"), + }; + assert!(load_probe_for(&CpuAccounting::Processes(vec![40]), &files).is_ok()); + let group_dir = temp.0.join("group"); + std::fs::create_dir_all(&group_dir).unwrap(); + std::fs::write(group_dir.join("cpuset.cpus.effective"), "4-5\n").unwrap(); + assert!(load_probe_for( + &CpuAccounting::Cgroup(CgroupSource::Local(group_dir)), + &files + ) + .is_ok()); + assert!(load_probe_for(&CpuAccounting::Processes(vec![41]), &files).is_err()); +} + +/// A `Processes` engine's group is read only when every process in it is +/// the server or its descendant; a foreign process makes the clock read +/// `schedstat`. +#[test] +fn a_group_with_a_foreign_process_is_not_the_server_cpu() { + let temp = TempDir::new("foreign"); + let server = FakeServer::start(&temp.0, 40).unwrap(); + let group = server.cpu_files.cgroup_root.join("srv.scope"); + std::fs::create_dir_all(&group).unwrap(); + std::fs::write(group.join("cpu.stat"), cpu_stat(400_000, 0)).unwrap(); + std::fs::write(temp.0.join("40/cgroup"), "0::/srv.scope\n").unwrap(); + // The server's child, pid 41 (parent 40), in the same group. + std::fs::create_dir_all(temp.0.join("41")).unwrap(); + std::fs::write(temp.0.join("41/stat"), "41 (child) S 40 1 1 0\n").unwrap(); + std::fs::write(group.join("cgroup.procs"), "40\n41\n").unwrap(); + let clocks = MeasurementClocks { + calling_thread: &OsCpuClock, + process_cpu_files: server.cpu_files.clone(), + }; + let own = clocks + .clock_for(&CpuAccounting::Processes(vec![40])) + .unwrap(); + assert_eq!( + own.cpu_source(), + format!("cgroup {}", group.join("cpu.stat").display()) + ); + // An unrelated pid 99 (parent 1) joins the group. + std::fs::create_dir_all(temp.0.join("99")).unwrap(); + std::fs::write(temp.0.join("99/stat"), "99 (other) S 1 1 1 0\n").unwrap(); + std::fs::write(group.join("cgroup.procs"), "40\n41\n99\n").unwrap(); + let shared = clocks + .clock_for(&CpuAccounting::Processes(vec![40])) + .unwrap(); + assert_eq!(shared.cpu_source(), "schedstat"); +} diff --git a/aqpbm-core/tests/harness_conformance.rs b/aqpbm-core/tests/harness_conformance.rs index 718e54ec..e7ae8ee9 100644 --- a/aqpbm-core/tests/harness_conformance.rs +++ b/aqpbm-core/tests/harness_conformance.rs @@ -58,7 +58,7 @@ fn a_fake_with_nondeterministic_answers_fails_and_shows_the_differing_answer() { )), "{message}" ); - assert!(series.contains("probe"), "{series}"); + assert!(series.contains("instance_0"), "{series}"); } /// A fake that counts the sample on the window start answers 2 for diff --git a/aqpbm-core/tests/harness_fake.rs b/aqpbm-core/tests/harness_fake.rs index afe26faf..2ec71d7a 100644 --- a/aqpbm-core/tests/harness_fake.rs +++ b/aqpbm-core/tests/harness_fake.rs @@ -389,8 +389,8 @@ fn consecutive_jobs_share_one_idle_sample() { /// A series that already carries a `query` label keeps it: answers are keyed /// by query id outside the labels, so no label name is reserved. Query `q` -/// over `m{query="x", s="s_0"}` answers under `"q" -> {__name__="m", -/// query="x", s="s_0"}`. +/// over `m{query="x", s="s_0"}` answers under `"q" -> {query="x", +/// s="s_0"}` (a range function drops `__name__`). #[test] fn a_series_label_named_query_is_kept() { let engine = FakeEngine::default(); @@ -414,7 +414,9 @@ fn a_series_label_named_query_is_kept() { }; installed.ingest(&samples).unwrap(); let (answers, _) = installed.evaluate(10_000).unwrap(); - assert_eq!(answers.get("q", &labels), Some(2.5)); + let mut output_labels = labels.clone(); + output_labels.remove("__name__"); + assert_eq!(answers.get("q", &output_labels), Some(2.5)); assert_eq!(answers.iter().count(), 1); } diff --git a/aqpbm-core/tests/harness_fit.rs b/aqpbm-core/tests/harness_fit.rs index aa3bd6c8..db9115c8 100644 --- a/aqpbm-core/tests/harness_fit.rs +++ b/aqpbm-core/tests/harness_fit.rs @@ -532,3 +532,33 @@ fn no_scored_fold_has_no_rms_log_error() { loso ); } + +/// Runs of equal CPU keep their own units: the point takes the units of the +/// median run by its index, not of the first sample equal to the median. +/// Three runs each charge 1,000 ns and process 10, 20 and 30 units; the +/// middle run (index 1, 20 units) is the median. +#[test] +fn equal_cost_runs_take_the_median_runs_units() { + let clock = FakeClock::default(); + let kernel_clock = clock.clone(); + let protocol = Protocol { + warmup_runs: 0, + measured_runs: 3, + max_core_busy_fraction: 1.0, + }; + let mut calls = 0; + let points = measure_sizes( + &protocol, + 0, + &mut IdleProbe, + &EngineClock::CallingThread(&clock), + &[7], + &mut |_size| { + kernel_clock.charge_thread(1_000); + calls += 1; + Ok(calls * 10) + }, + ) + .unwrap(); + assert_eq!(points[0].terms, vec![20.0, 1.0]); +} diff --git a/aqpbm-core/tests/harness_protocol.rs b/aqpbm-core/tests/harness_protocol.rs index 395b92e8..6a7d0cff 100644 --- a/aqpbm-core/tests/harness_protocol.rs +++ b/aqpbm-core/tests/harness_protocol.rs @@ -13,7 +13,7 @@ use aqpbm_core::harness::protocol::{ processes_cpu_ns, Comparison, CpuClock, EngineClock, JobMark, LoadProbe, MeasurementClocks, OsCpuClock, ProcessCpuFiles, ProcessesCpuClock, Protocol, ProtocolError, }; -use aqpbm_core::harness::rundir::RunDir; +use aqpbm_core::harness::run_directory::RunDirectory; use chrono::{TimeZone, Utc}; /// A load probe that returns `busy` fractions in order (the last one @@ -202,9 +202,10 @@ fn a_core_that_turns_busy_during_the_job_marks_it() { let tmp = TempDir::new("busy-after"); let utc = Utc.with_ymd_and_hms(2026, 11, 16, 0, 0, 0).unwrap(); - let run_dir = RunDir::create(&tmp.0, "test-machine", utc, "test", "busy-after").unwrap(); - run_dir.append_status("ingest", &record).unwrap(); - let status = std::fs::read_to_string(run_dir.path().join("status.log")).unwrap(); + let run_directory = + RunDirectory::create(&tmp.0, "test-machine", utc, "test", "busy-after").unwrap(); + run_directory.append_status("ingest", &record).unwrap(); + let status = std::fs::read_to_string(run_directory.path().join("status.log")).unwrap(); assert!(status.contains("busy-after 0.35"), "{status}"); } @@ -481,13 +482,16 @@ fn server_cpu_is_the_sum_of_its_threads_schedstat() { } /// Puts `pids` in the cgroup v2 group `group` (their `/cgroup` reads -/// `0::`) and writes the group's `cpu.stat` with `usage_usec`. +/// `0::`, the group's `cgroup.procs` lists them) and writes the +/// group's `cpu.stat` with `usage_usec`. fn write_fake_cgroup(root: &std::path::Path, pids: &[u32], group: &str, usage_usec: u64) { for pid in pids { std::fs::write(root.join(format!("{pid}/cgroup")), format!("0::{group}\n")).unwrap(); } let dir = root.join("cgroup").join(group.trim_start_matches('/')); std::fs::create_dir_all(&dir).unwrap(); + let procs: String = pids.iter().map(|pid| format!("{pid}\n")).collect(); + std::fs::write(dir.join("cgroup.procs"), procs).unwrap(); std::fs::write( dir.join("cpu.stat"), format!("usage_usec {usage_usec}\nuser_usec {usage_usec}\nsystem_usec 0\n"), diff --git a/aqpbm-core/tests/harness_rundir.rs b/aqpbm-core/tests/harness_run_directory.rs similarity index 83% rename from aqpbm-core/tests/harness_rundir.rs rename to aqpbm-core/tests/harness_run_directory.rs index 4a4f50eb..5ccc037e 100644 --- a/aqpbm-core/tests/harness_rundir.rs +++ b/aqpbm-core/tests/harness_run_directory.rs @@ -7,7 +7,7 @@ use aqpbm_core::harness::engine::{EngineDescription, Footprint, PlanSummary, Ste use aqpbm_core::harness::machine::MachineDescription; use aqpbm_core::harness::protocol::{JobRecord, Protocol}; use aqpbm_core::harness::records::{calibration_staleness, ArmResult, RunRecord}; -use aqpbm_core::harness::rundir::{RunDir, RunDirError}; +use aqpbm_core::harness::run_directory::{RunDirectory, RunDirectoryError}; use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; use chrono::{DateTime, TimeZone, Utc}; @@ -20,7 +20,7 @@ struct TempDir(PathBuf); impl TempDir { fn new(test: &str) -> Self { let path = std::env::temp_dir().join(format!( - "aqpbm-core-harness-rundir-{}-{test}", + "aqpbm-core-harness-run_directory-{}-{test}", std::process::id() )); let _ = std::fs::remove_dir_all(&path); @@ -40,8 +40,8 @@ fn utc() -> DateTime { Utc.with_ymd_and_hms(2026, 11, 16, 20, 15, 0).unwrap() } -fn create(root: &Path) -> Result { - RunDir::create(root, E5_KEY, utc(), "sweep", "sketch-benefit") +fn create(root: &Path) -> Result { + RunDirectory::create(root, E5_KEY, utc(), "sweep", "sketch-benefit") } fn fake_engine(version: &str, version_dirty: bool) -> EngineDescription { @@ -92,6 +92,12 @@ fn arm_result(workload: &str) -> ArmResult { footprint: Footprint::default(), measured_engine_cost_per_second: None, node_profiles: None, + ingested_samples: 0, + server_memory_before: None, + server_memory_after: None, + server_cpu_ns_whole_arm: None, + cpu_source: "calling-thread".into(), + installs_held: 1, } } @@ -104,6 +110,7 @@ fn job(core: usize, busy_before: f64, busy_after: f64, loadavg: [f64; 2]) -> Job marks: Vec::new(), samples: vec![StepCost::default()], median: StepCost::default(), + median_run: 0, } } @@ -137,9 +144,10 @@ fn run_dir_is_machine_key_utc_subcommand_label() { #[test] fn a_label_outside_the_slug_charset_is_refused() { let root = TempDir::new("a_label_outside_the_slug_charset_is_refused"); - let error = RunDir::create(&root.0, E5_KEY, utc(), "sweep", "Sketch Benefit/1").unwrap_err(); + let error = + RunDirectory::create(&root.0, E5_KEY, utc(), "sweep", "Sketch Benefit/1").unwrap_err(); assert!( - matches!(&error, RunDirError::BadName { name, .. } if name == "Sketch Benefit/1"), + matches!(&error, RunDirectoryError::BadName { name, .. } if name == "Sketch Benefit/1"), "{error:?}" ); let message = error.to_string(); @@ -148,7 +156,7 @@ fn a_label_outside_the_slug_charset_is_refused() { assert!(!root.0.join("runs").exists()); } -/// Creating the same run directory twice fails with `RunDirExists` naming +/// Creating the same run directory twice fails with `RunDirectoryExists` naming /// it, and the first run's `run.json` stays byte for byte as written. #[test] fn an_existing_run_dir_is_never_overwritten() { @@ -160,7 +168,7 @@ fn an_existing_run_dir_is_never_overwritten() { let error = create(&root.0).unwrap_err(); assert!( - matches!(&error, RunDirError::RunDirExists(path) if *path == first.path()), + matches!(&error, RunDirectoryError::RunDirectoryExists(path) if *path == first.path()), "{error:?}" ); assert_eq!(std::fs::read(&run_json).unwrap(), before); @@ -201,7 +209,7 @@ fn arm_results_are_filed_per_engine_workload_and_arm() { let error = run.write_arm(&arm_result("a__b")).unwrap_err(); assert!( - matches!(&error, RunDirError::AmbiguousName { name, .. } if name == "a__b"), + matches!(&error, RunDirectoryError::AmbiguousName { name, .. } if name == "a__b"), "{error:?}" ); assert!(!run.path().join("results/fake/a__b__planned.json").exists()); @@ -277,7 +285,7 @@ fn a_result_file_is_never_overwritten() { let first = std::fs::read_to_string(&path).unwrap(); let error = run.write_arm(&arm_result("w")).unwrap_err(); assert!( - matches!(&error, RunDirError::Io { path: p, source } if *p == path + matches!(&error, RunDirectoryError::Io { path: p, source } if *p == path && source.kind() == std::io::ErrorKind::AlreadyExists), "{error:?}" ); @@ -347,7 +355,31 @@ fn a_data_record_is_filed_under_data_by_metric() { }; let error = run.write_data(&escaping).unwrap_err(); assert!( - matches!(&error, RunDirError::BadName { name, .. } if name == "../m"), + matches!(&error, RunDirectoryError::BadName { name, .. } if name == "../m"), "{error:?}" ); } + +/// `create_at` makes the given directory with the four subdirectories and +/// refuses an existing one; `open` accepts it and refuses a directory +/// missing `plans/`. +#[test] +fn create_at_and_open_a_run_directory_shared_by_engine_runs() { + let temp = TempDir::new("create-at"); + let path = temp.0.join("goal").join("run-1"); + let run = RunDirectory::create_at(&path).unwrap(); + assert_eq!(run.path(), path.as_path()); + for sub in ["workloads", "data", "plans", "results"] { + assert!(path.join(sub).is_dir(), "{sub}"); + } + assert!(matches!( + RunDirectory::create_at(&path), + Err(RunDirectoryError::RunDirectoryExists(existing)) if existing == path + )); + assert_eq!(RunDirectory::open(&path).unwrap().path(), path.as_path()); + std::fs::remove_dir(path.join("plans")).unwrap(); + match RunDirectory::open(&path) { + Err(RunDirectoryError::NotARunDirectory { missing, .. }) => assert_eq!(missing, "plans"), + other => panic!("expected NotARunDirectory, got {other:?}"), + } +}