From 8f22bc024a039b2b3e9ff3409aa5d7294688680d Mon Sep 17 00:00:00 2001 From: zz_y Date: Mon, 16 Nov 2026 21:01:36 +0000 Subject: [PATCH 01/28] harness: aqpbm-harness crate skeleton and the thread CPU clock stub The engine traits, records and every module of the harness core, with todo!() bodies; ThreadCpuTime in aqpbm-core with its unit test. The implementation follows once the tests are approved. --- Cargo.lock | 15 ++ Cargo.toml | 5 + aqpbm-core/src/metrics/mod.rs | 2 +- aqpbm-core/src/metrics/time.rs | 30 ++++ aqpbm-harness/Cargo.toml | 22 +++ aqpbm-harness/src/accuracy.rs | 54 ++++++ aqpbm-harness/src/arm_run.rs | 47 +++++ aqpbm-harness/src/conformance.rs | 78 +++++++++ aqpbm-harness/src/data.rs | 84 +++++++++ aqpbm-harness/src/data_stats.rs | 56 ++++++ aqpbm-harness/src/engine.rs | 286 +++++++++++++++++++++++++++++++ aqpbm-harness/src/fake.rs | 146 ++++++++++++++++ aqpbm-harness/src/fit.rs | 123 +++++++++++++ aqpbm-harness/src/gate.rs | 96 +++++++++++ aqpbm-harness/src/lib.rs | 28 +++ aqpbm-harness/src/machine.rs | 91 ++++++++++ aqpbm-harness/src/protocol.rs | 207 ++++++++++++++++++++++ aqpbm-harness/src/records.rs | 76 ++++++++ aqpbm-harness/src/rundir.rs | 85 +++++++++ aqpbm-harness/src/sweep.rs | 25 +++ 20 files changed, 1555 insertions(+), 1 deletion(-) create mode 100644 aqpbm-harness/Cargo.toml create mode 100644 aqpbm-harness/src/accuracy.rs create mode 100644 aqpbm-harness/src/arm_run.rs create mode 100644 aqpbm-harness/src/conformance.rs create mode 100644 aqpbm-harness/src/data.rs create mode 100644 aqpbm-harness/src/data_stats.rs create mode 100644 aqpbm-harness/src/engine.rs create mode 100644 aqpbm-harness/src/fake.rs create mode 100644 aqpbm-harness/src/fit.rs create mode 100644 aqpbm-harness/src/gate.rs create mode 100644 aqpbm-harness/src/lib.rs create mode 100644 aqpbm-harness/src/machine.rs create mode 100644 aqpbm-harness/src/protocol.rs create mode 100644 aqpbm-harness/src/records.rs create mode 100644 aqpbm-harness/src/rundir.rs create mode 100644 aqpbm-harness/src/sweep.rs diff --git a/Cargo.lock b/Cargo.lock index 784459bd..7d39955d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -154,6 +154,21 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "aqpbm-harness" +version = "0.1.0" +dependencies = [ + "aqpbm-core", + "aqpbm-datagen", + "chrono", + "libc", + "rand 0.9.4", + "rand_xoshiro", + "serde", + "serde_json", + "thiserror 2.0.18", +] + [[package]] name = "aqpbm-planeval" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0da29f3a..f00d6739 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "aqpbm-usecase", "aqpbm-planeval", "aqpbm-systemeval", + "aqpbm-harness", ] exclude = ["sketch-runtime"] @@ -48,6 +49,9 @@ clap = { version = "4", features = ["derive", "wrap_help", "env"] } thiserror = "2" anyhow = "1" +# OS calls: CPU clocks, thread pinning (aqpbm-core, aqpbm-harness). +libc = "0.2" + # Bitflags for MetricsMask. bitflags = "2" @@ -62,6 +66,7 @@ aqpbm-datagen = { path = "aqpbm-datagen" } aqpbm-core = { path = "aqpbm-core", default-features = false } sketch-bench = { path = "sketch-bench" } aqpbm-usecase = { path = "aqpbm-usecase" } +aqpbm-harness = { path = "aqpbm-harness" } # sketch-runtime = { path = "sketch-runtime" } # parked; [profile.release] diff --git a/aqpbm-core/src/metrics/mod.rs b/aqpbm-core/src/metrics/mod.rs index c57512e7..25b3a256 100644 --- a/aqpbm-core/src/metrics/mod.rs +++ b/aqpbm-core/src/metrics/mod.rs @@ -16,4 +16,4 @@ pub use mask::{is_measurable, Metric, MetricsMask, Operation, OperationMask}; pub use memory::{JemallocAllocated, Rss}; pub use run::RunMetrics; pub use throughput::ItemsPerSec; -pub use time::{CpuTimeSample, CpuTimeSampler, WallClock}; +pub use time::{CpuTimeSample, CpuTimeSampler, ThreadCpuTime, WallClock}; diff --git a/aqpbm-core/src/metrics/time.rs b/aqpbm-core/src/metrics/time.rs index 36668a1a..ca33e8de 100644 --- a/aqpbm-core/src/metrics/time.rs +++ b/aqpbm-core/src/metrics/time.rs @@ -47,6 +47,20 @@ impl CpuTimeSampler { } } +/// CPU time of the calling thread (user + system), from +/// `CLOCK_THREAD_CPUTIME_ID`; 0 off unix. Unlike [`CpuTimeSampler`], work on +/// other threads of the process does not count: a thread that sleeps 100 ms +/// while another thread spins reads about 0 ns. +#[derive(Debug, Clone, Copy)] +pub struct ThreadCpuTime; + +impl ThreadCpuTime { + /// The calling thread's CPU time so far, in ns. + pub fn now_ns() -> u64 { + todo!("implemented after test approval") + } +} + #[derive(Debug, Clone, Copy, Default)] pub struct CpuTimeSample { pub user_ns: u64, @@ -119,4 +133,20 @@ mod tests { sample.sys_ns ); } + + #[cfg(unix)] + #[test] + fn thread_cpu_time_advances_with_work_on_this_thread() { + let before = ThreadCpuTime::now_ns(); + let mut acc: u64 = 0; + for i in 0..10_000_000u64 { + acc = acc.wrapping_add(i); + } + std::hint::black_box(acc); + let after = ThreadCpuTime::now_ns(); + assert!( + after > before, + "thread CPU did not advance: {before} -> {after}" + ); + } } diff --git a/aqpbm-harness/Cargo.toml b/aqpbm-harness/Cargo.toml new file mode 100644 index 00000000..19bb93b0 --- /dev/null +++ b/aqpbm-harness/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "aqpbm-harness" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +description = "Engine-neutral measurement harness: the traits an engine under test implements, the measurement protocol (pinning, idle check, warm-up, median of N), the machine key, model fitting with leave-one-setting-out, accuracy curves, data statistics, run records, gate and sweep arithmetic, a fake-clock engine and the conformance kit every engine adapter runs. Depends on no sketch library, no polars, no CLI crate and no planner." + +[dependencies] +aqpbm-core.workspace = true +aqpbm-datagen.workspace = true +chrono.workspace = true +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[target.'cfg(unix)'.dependencies] +libc.workspace = true + +[dev-dependencies] +rand.workspace = true +rand_xoshiro.workspace = true diff --git a/aqpbm-harness/src/accuracy.rs b/aqpbm-harness/src/accuracy.rs new file mode 100644 index 00000000..7b02f768 --- /dev/null +++ b/aqpbm-harness/src/accuracy.rs @@ -0,0 +1,54 @@ +//! Accuracy curves: the nearest-rank `(1 - δ)` quantile of per-value errors, +//! and per key the worst of it over merge counts. +//! +//! Example: 1,000 trials of a KLL sketch with errors 0.0015, 0.0018 and +//! 0.0017 at δ = 0.01 after 1, 6 and 360 merges record 0.0018 at δ = 0.01. + +use serde::{Deserialize, Serialize}; + +/// The nearest-rank `(1 - failure_probability)` quantile of `errors`: the +/// `ceil((1 - δ) n)`-th smallest, with the rank computed exactly. +pub fn error_quantile(errors: &[f64], failure_probability: f64) -> Result { + let _ = (errors, failure_probability); + todo!("implemented after test approval") +} + +/// The error quantiles of one key after `merge_count` merges. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MergeCountErrors { + /// Opaque to the harness, such as `{"sketch": "kll", "k": 547, "metric": "rank"}`. + pub key: serde_json::Value, + pub merge_count: u32, + pub trials: u32, + /// `(δ, error quantile)` pairs. + pub error_at: Vec<(f64, f64)>, +} + +/// Per key, the worst error over merge counts at each δ. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AccuracyCurve { + pub key: serde_json::Value, + pub trials: u32, + /// `(δ, error)` pairs, δ ascending. + pub error_at: Vec<(f64, f64)>, +} + +/// Per key, the worst error over merge counts at each δ >= 3 / trials; a +/// smaller δ has too few failures to measure and is dropped. +pub fn worst_over_merge_counts(results: &[MergeCountErrors]) -> Vec { + let _ = results; + todo!("implemented after test approval") +} + +/// Errors that cannot give a quantile. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum AccuracyError { + #[error("no errors to take a quantile of")] + NoErrors, + #[error("error {index} is NaN")] + NotANumber { index: usize }, + #[error("failure probability must be in (0, 1)")] + FailureProbabilityOutOfRange, +} diff --git a/aqpbm-harness/src/arm_run.rs b/aqpbm-harness/src/arm_run.rs new file mode 100644 index 00000000..76b9de94 --- /dev/null +++ b/aqpbm-harness/src/arm_run.rs @@ -0,0 +1,47 @@ +//! One arm of one workload, run under the protocol: install, ingest every +//! refresh chunk, evaluate at every time, and record the costs the harness +//! measured. + +use crate::data::DataError; +use crate::engine::{ArmSpec, EngineError, EngineUnderTest, WorkloadSpec}; +use crate::protocol::{CpuClock, LoadProbe, Protocol, ProtocolError}; +use crate::records::ArmResult; + +/// When to ingest and when to evaluate. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArmSchedule { + /// Ingest in chunks `(end - refresh_ms, end]`. + pub refresh_ms: u64, + /// Evaluate at these times, ascending; each after the chunk that ends there. + pub evaluate_at_ms: Vec, +} + +/// 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. +#[allow(clippy::too_many_arguments)] +pub fn run_arm( + engine: &dyn EngineUnderTest, + workload: &WorkloadSpec, + arm: &ArmSpec, + schedule: &ArmSchedule, + protocol: &Protocol, + core: usize, + probe: &mut dyn LoadProbe, + clock: &dyn CpuClock, +) -> Result { + let _ = ( + engine, workload, arm, schedule, protocol, core, probe, clock, + ); + todo!("implemented after test approval") +} + +#[derive(Debug, Clone, PartialEq, thiserror::Error)] +pub enum ArmRunError { + #[error(transparent)] + Engine(#[from] EngineError), + #[error(transparent)] + Protocol(#[from] ProtocolError), + #[error(transparent)] + Data(#[from] DataError), +} diff --git a/aqpbm-harness/src/conformance.rs b/aqpbm-harness/src/conformance.rs new file mode 100644 index 00000000..ad824984 --- /dev/null +++ b/aqpbm-harness/src/conformance.rs @@ -0,0 +1,78 @@ +//! The conformance kit every engine adapter runs: answers are deterministic +//! under one seed, windows are left-open, calibration closures process the +//! units the engine's cost model charges, and a `CallingThread` engine does +//! its work on the calling thread. + +use crate::engine::{EngineUnderTest, WorkloadSpec}; +use crate::protocol::CpuClock; + +/// One check of the kit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConformanceCheck { + DeterministicAnswers, + LeftOpenWindow, + CalibrationUnits, + WorkOnCallingThread, +} + +/// The checks an engine passed, in check order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConformanceReport { + pub passed: Vec, +} + +/// A failed check, with what was seen. +#[derive(Debug, Clone, PartialEq, thiserror::Error)] +pub enum ConformanceFailure { + /// Two installs with one seed answered differently. + #[error("NondeterministicAnswers: answers differ between two installs with seed {seed} at t={at_ms} ms: {series} {first} vs {second}")] + NondeterministicAnswers { + seed: u64, + at_ms: i64, + series: String, + first: f64, + second: f64, + }, + /// A sample on the window start was counted. + #[error("WindowNotLeftOpen: {query} at t={at_ms} ms returned {returned}, expected {expected}: the window is ({window_start_ms}, {at_ms}]")] + WindowNotLeftOpen { + query: String, + at_ms: i64, + returned: f64, + expected: f64, + window_start_ms: i64, + }, + /// The calibration closure processed other units than the cost model charges. + #[error("UnitsMismatch: target {target} at size {size}: the calibration closure processed {closure_units} units but the cost model charges {charged_units}")] + UnitsMismatch { + target: String, + size: u64, + closure_units: u64, + charged_units: f64, + }, + /// A `CallingThread` engine used CPU off the calling thread. + #[error("WorkOffCallingThread: {step} used {:.1} ms of process CPU but {:.1} ms on the calling thread: report CpuAccounting::Processes or do the work on the calling thread", *process_cpu_ns as f64 / 1e6, *thread_cpu_ns as f64 / 1e6)] + WorkOffCallingThread { + step: String, + process_cpu_ns: u64, + thread_cpu_ns: u64, + }, +} + +/// Runs the probe workloads twice with one seed, checks the window boundary, +/// the calibration units and (for `CallingThread` engines) that no step's +/// work ran on another thread. Every failure is listed, in check order. +pub fn check( + engine: &mut dyn EngineUnderTest, + clock: &dyn CpuClock, +) -> Result> { + let _ = (engine, clock); + todo!("implemented after test approval") +} + +/// The probe workloads, each with PromQL and SQL texts: `probe` sampled every +/// 10 s from 0 (first sample at 10,000 ms), with `sum_over_time(probe[10s])` +/// and `count_over_time(probe[10s])` evaluated every 10 s; seed 7. +pub fn probe_workloads() -> Vec { + todo!("implemented after test approval") +} diff --git a/aqpbm-harness/src/data.rs b/aqpbm-harness/src/data.rs new file mode 100644 index 00000000..a274f187 --- /dev/null +++ b/aqpbm-harness/src/data.rs @@ -0,0 +1,84 @@ +//! Data: samples, their JSONL form, the `data/.datagen.json` record +//! a run keeps instead of the samples, and the refresh chunks an engine +//! ingests. +//! +//! Every engine reads the same samples: `aqpbm-datagen`'s +//! `TimeSeriesDescription` on the left-open grid `(start, start + duration]`. + +use std::collections::BTreeMap; + +use aqpbm_datagen::TimeSeriesDescription; +use serde::{Deserialize, Serialize}; + +/// A series' labels, `__name__` included, such as +/// `{__name__: "m", job: "job_0"}`. +pub type SeriesLabels = BTreeMap; + +/// One sample. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Sample { + pub labels: SeriesLabels, + pub ts_ms: i64, + pub value: f64, +} + +/// Reads one sample per line, `{"labels": {...}, "ts_ms": 1, "value": 2.0}`; +/// blank lines are skipped. A bad line is an error naming its 0-based index. +pub fn read_samples_jsonl(text: &str) -> Result, SampleReadError> { + let _ = text; + todo!("implemented after test approval") +} + +/// A JSONL line that is not a sample. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("samples line {line}: {message}")] +pub struct SampleReadError { + /// 0-based line index. + pub line: usize, + pub message: String, +} + +/// `data/.datagen.json`: the generator description and seed of one +/// metric, never the samples. Regenerating from it gives bit-identical samples. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DataRecord { + /// Written as the `__name__` label of every series. + pub metric: String, + pub description: TimeSeriesDescription, +} + +/// The samples of one refresh: every sample in `(end_ms - refresh, end_ms]`, +/// time-major. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SampleChunk { + pub end_ms: i64, + pub samples: Vec, +} + +/// The record's samples cut into refresh chunks `(end - refresh_ms, end]`, +/// with ends `start + refresh_ms`, `start + 2 refresh_ms`, ... A sample on a +/// chunk end belongs to the chunk it ends. A generator error ends the chunks +/// with that error. +pub fn refresh_chunks( + record: &DataRecord, + refresh_ms: u64, +) -> Result>, DataError> { + let _ = (record, refresh_ms); + todo!("implemented after test approval"); + #[allow(unreachable_code)] + Ok(std::iter::empty()) +} + +/// Data that cannot be generated or cut. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DataError { + /// The description is invalid, or a counter passed 2^53 while generating. + #[error("data of metric {metric}: {message}")] + Generator { metric: String, message: String }, + /// A refresh interval of 0. + #[error("refresh_ms must be > 0")] + ZeroRefresh, +} diff --git a/aqpbm-harness/src/data_stats.rs b/aqpbm-harness/src/data_stats.rs new file mode 100644 index 00000000..03709b6e --- /dev/null +++ b/aqpbm-harness/src/data_stats.rs @@ -0,0 +1,56 @@ +//! Per-source statistics over samples, like a database's `ANALYZE`: series +//! count, sample interval, distinct label values, value magnitude and sign. +//! Statistics that depend on a query's window or grouping stay with the +//! engine that plans the query. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::data::Sample; + +/// The smallest and largest non-zero absolute value seen. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ObservedMagnitude { + pub min_abs: f64, + pub max_abs: f64, +} + +/// The sign of every value seen, read from the sign bit: `-0.0` is negative. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ObservedSign { + NonNegative, + Negative, + Mixed, +} + +/// Statistics of one metric. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DataStatistics { + /// Distinct label sets. + pub series_count: u64, + /// The median over series of each series' median gap between samples; + /// `None` when no series has two samples. + pub sample_interval_ms: Option, + /// Per label name (not `__name__`), the distinct values; a series without + /// the label counts as one more value. + pub distinct_values_per_label: BTreeMap, + /// Per label set asked for (names sorted), the distinct observed + /// combinations; only sets whose labels all occur in the metric. + pub distinct_values_per_label_set: Vec<(Vec, u64)>, + /// `None` when every value is zero. + pub value_magnitude: Option, + pub value_sign: ObservedSign, +} + +/// Statistics per metric (`__name__`) over `samples`. `label_sets` are the +/// groupings whose distinct combinations to count, such as `[["job", "instance"]]`. +pub fn data_statistics( + samples: &[Sample], + label_sets: &[Vec], +) -> BTreeMap { + let _ = (samples, label_sets); + todo!("implemented after test approval") +} diff --git a/aqpbm-harness/src/engine.rs b/aqpbm-harness/src/engine.rs new file mode 100644 index 00000000..fcc6a4d1 --- /dev/null +++ b/aqpbm-harness/src/engine.rs @@ -0,0 +1,286 @@ +//! The engine under test: the traits every engine implements, and the +//! records it exchanges with the harness. +//! +//! An engine never times itself. [`InstalledArm::ingest`] and +//! [`InstalledArm::evaluate`] return a [`StepReport`] with the counters the +//! engine keeps (scanned bytes, a per-query CPU counter of its own), and the +//! harness builds the [`StepCost`] of the step from its own clock. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +pub use crate::data::{DataRecord, SampleChunk, SeriesLabels}; + +/// An engine the harness can measure: the Planner's executor, a fake, or an +/// external server such as ClickHouse. +pub trait EngineUnderTest { + /// Id, version and build profile, recorded in every run. + fn description(&self) -> EngineDescription; + /// Where the harness reads this engine's CPU time. + fn cpu_accounting(&self) -> CpuAccounting; + /// Plan (if the engine plans) and install one arm of one workload. + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError>; + /// The engine's cost calibration, when it has a cost model to calibrate. + fn calibration(&mut self) -> Option<&mut dyn Calibratable> { + None + } +} + +/// Which engine and which build a measurement ran on. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EngineDescription { + /// Short id, such as `fake`, `asap` or `clickhouse`. + pub id: String, + /// A commit for an in-tree engine; a server version for an external one. + pub version: String, + /// The working tree had uncommitted changes when the engine was built. + pub version_dirty: bool, + /// Cargo profile or server build, such as `release`. + pub build_profile: String, +} + +/// Where an engine's CPU time is read. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum CpuAccounting { + /// In-process: the work of a step runs on the thread that calls it, and + /// the harness reads that thread's CPU clock. + CallingThread, + /// External servers: the harness sums `/proc//stat` CPU of these + /// processes around each step. + Processes(Vec), +} + +/// One arm of a workload: how the engine is asked to run it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArmSpec { + /// `exact`, `planned`, `noraw`, `stored`, ... + pub name: String, + /// Whether the engine keeps raw samples it could answer exactly from. + pub raw_data_retained: bool, + /// Opaque to the harness; read only by the engine adapter. + pub engine_options: serde_json::Value, +} + +/// The queries of a workload in every language it is written in, and the +/// data they run over; an engine picks the language it reads. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkloadSpec { + pub name: String, + pub queries: Vec, + pub data: Vec, +} + +/// One recurring query: evaluated every `evaluation_interval_ms` over the +/// left-open window `(t - window_ms, t]`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkloadQuery { + pub id: String, + pub texts: Vec, + pub window_ms: u64, + pub evaluation_interval_ms: u64, +} + +/// A query text in one language. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct QueryText { + pub language: QueryLanguage, + pub text: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum QueryLanguage { + PromQl, + Sql, +} + +/// One installed arm. The harness calls `ingest` per refresh chunk and +/// `evaluate` per evaluation time, and times each call itself. +pub trait InstalledArm { + /// What the engine installed: plan text, node kinds, stored outputs. + fn plan_summary(&self) -> PlanSummary; + /// The engine's own predicted cost; `None` for an engine that does not plan. + fn predicted(&self) -> Option { + None + } + /// One refresh chunk; the harness times the call. + fn ingest(&mut self, chunk: &SampleChunk) -> Result; + /// Answers of every query at `at_ms`; the harness times the call. + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>; + /// Bytes held after the run. + fn footprint(&self) -> Result; + /// Per-operator timing hook: per node, per batch, the CPU the node itself + /// used during the evaluations since the last call. + fn node_profiles(&mut self) -> Option> { + None + } + /// Per node: the units the engine's own cost model charges per constant. + fn node_terms(&self) -> Option> { + None + } + /// Measured usage priced at the engine's own prices (the Planner: cost + /// model 1). `None` for an engine without a cost model. + fn price(&self, usage: &MeasuredUsage) -> Option { + let _ = usage; + None + } +} + +/// What an engine reports about one step besides time. It never reports its +/// own CPU time, only counters it keeps itself, such as ClickHouse's +/// per-query CPU counter. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StepReport { + /// Bytes the step scanned, when the engine counts them. + pub scanned_bytes: Option, + /// The engine's own CPU counter for the step, in ns, when it keeps one. + pub engine_reported_cpu_ns: Option, +} + +/// What the harness measured for one step. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StepCost { + /// CPU of the calling thread, in ns; `None` for a `Processes` engine. + pub thread_cpu_ns: Option, + /// CPU of the measured processes (this process for `CallingThread`), in ns. + pub process_cpu_ns: u64, + /// Wall time of the call, in ns. + pub wall_ns: u64, + /// The engine's own counters for the step. + pub report: StepReport, +} + +/// The answers of one evaluation: one value per output series. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Answers(pub BTreeMap); + +/// Serialized as a list of `[labels, value]` pairs: JSON object keys must be +/// strings, and a series is a label map. +impl Serialize for Answers { + fn serialize(&self, serializer: S) -> Result { + let _ = serializer; + todo!("implemented after test approval") + } +} + +impl<'de> Deserialize<'de> for Answers { + fn deserialize>(deserializer: D) -> Result { + let _ = deserializer; + todo!("implemented after test approval") + } +} + +/// What an engine installed for one arm. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PlanSummary { + /// The engine's own plan text. + pub text: String, + /// The kind of each node, such as `scan` or `sum`. + pub node_kinds: Vec, + /// Outputs the arm stores between evaluations (views, sketches). + pub stored_outputs: Vec, +} + +/// The engine's own predicted cost of an arm. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PredictedCost { + /// In the engine's cost units per second of data (the Planner: cost model 1). + pub engine_cost_per_second: f64, +} + +/// Bytes an arm holds. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Footprint { + /// Bytes of stored outputs (views, sketches). + pub view_bytes: u64, + /// Bytes of raw samples kept. + pub raw_retained_bytes: u64, + /// Peak bytes during the run, when the engine can tell. + pub peak_bytes: Option, +} + +/// What the harness measured over a run, per second of data, for +/// [`InstalledArm::price`]. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MeasuredUsage { + pub ingest_cpu_ns_per_second: f64, + pub query_cpu_ns_per_second: f64, + pub memory_bytes: u64, +} + +/// One node's own CPU per batch, from the per-operator timing hook. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NodeProfile { + pub node: String, + pub method: ProfilingMethod, + /// The node's own CPU in each batch, in ns. A node shared by two + /// consumers is timed once per batch. + pub cpu_ns_per_batch: Vec, +} + +/// How node CPU was measured; recorded so the method can be replaced later. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum ProfilingMethod { + /// The executor times each operator per batch. + OperatorTimingHook, +} + +/// The units a node is charged per cost constant by the engine's cost model, +/// for fitting the constants from measured node CPU. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NodeTerms { + pub node: String, + pub units_per_constant: Vec<(String, f64)>, +} + +/// An engine whose cost constants the harness can calibrate. +pub trait Calibratable { + /// What to measure: one target per constant and operator family. + fn cost_targets(&self) -> Vec; + /// The harness pins, warms up and times each call; the closure returns the + /// units it processed. + #[allow(clippy::type_complexity)] + fn prepare_cost_target( + &mut self, + target: &CostTarget, + size: u64, + ) -> Result Result>, EngineError>; + /// The units the engine's own cost model charges `target.constant` at `size`. + fn charged_units(&self, target: &CostTarget, size: u64) -> f64; +} + +/// One calibration target. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CostTarget { + /// Opaque to the harness; the engine maps it back to its operator. + pub key: serde_json::Value, + /// The constant measured, such as `ns_per_unit`. + pub constant: String, + /// What one unit is, such as `samples`. + pub unit: String, + /// The sizes to run, in units. + pub sizes: Vec, +} + +/// An engine failure, with the engine's own message. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct EngineError(pub String); diff --git a/aqpbm-harness/src/fake.rs b/aqpbm-harness/src/fake.rs new file mode 100644 index 00000000..79e04b2f --- /dev/null +++ b/aqpbm-harness/src/fake.rs @@ -0,0 +1,146 @@ +//! A deterministic in-process engine on a shared fake clock, for the +//! harness's own tests. +//! +//! It answers `sum_over_time([])` and `count_over_time([])` +//! per series over `(t - w, t]`. Ingesting a chunk charges `ns_per_call + +//! ns_per_sample` per sample to the clock; evaluating charges `ns_per_call + +//! ns_per_series` per answered series. Example: with the defaults (50, 150 +//! and 10,000 ns), ingesting 1,000 samples costs 60,000 ns and evaluating +//! 4 series 10,600 ns. +//! +//! Its plan has one `scan` node per metric, shared by every query over that +//! metric, and one node per query, named after the query id; the operator +//! timing hook times each node once per evaluation. + +use std::cell::Cell; +use std::rc::Rc; + +use crate::engine::{ + ArmSpec, Calibratable, CostTarget, CpuAccounting, EngineDescription, EngineError, + EngineUnderTest, InstalledArm, WorkloadSpec, +}; +use crate::protocol::CpuClock; + +/// The ticks of a [`FakeClock`], in ns. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FakeTicks { + pub thread_ns: u64, + pub process_ns: u64, + pub wall_ns: u64, +} + +/// A clock only the fake engine (or a test) advances. Clones share the ticks. +#[derive(Debug, Clone, Default)] +pub struct FakeClock(pub Rc>); + +impl FakeClock { + /// Work on the calling thread: advances thread, process and wall time by `ns`. + pub fn charge_thread(&self, ns: u64) { + let _ = ns; + todo!("implemented after test approval") + } + + /// Work on another thread of this process: advances process and wall + /// time by `ns`, thread time not at all. + pub fn charge_other_thread(&self, ns: u64) { + let _ = ns; + todo!("implemented after test approval") + } + + pub fn ticks(&self) -> FakeTicks { + self.0.get() + } +} + +impl CpuClock for FakeClock { + fn thread_cpu_ns(&self) -> u64 { + self.0.get().thread_ns + } + fn process_cpu_ns(&self) -> u64 { + self.0.get().process_ns + } + fn wall_ns(&self) -> u64 { + self.0.get().wall_ns + } +} + +/// A broken behavior the conformance kit must catch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FakeFault { + /// Adds 0.5 to every answer from the second install on. + NondeterministicAnswers, + /// Counts a sample at the window start, `[t - w, t]`. + CountsWindowStart, + /// `charged_units` reports twice the units the calibration closure returns. + CalibrationUnitsDouble, + /// Charges 1 ms of thread CPU and 9 ms more on another thread per ingest. + WorksOnAnotherThread, +} + +/// The fake engine. +#[derive(Debug, Clone)] +pub struct FakeEngine { + pub clock: FakeClock, + pub ns_per_sample: u64, + pub ns_per_series: u64, + pub ns_per_call: u64, + /// Reported in every `StepReport`, like an external engine's own counter. + pub engine_reported_cpu_ns: Option, + pub cpu_accounting: CpuAccounting, + pub faults: Vec, +} + +impl Default for FakeEngine { + /// 50 ns per sample, 150 ns per series, 10 µs per call, on a new clock, + /// `CallingThread`, no faults. + fn default() -> Self { + FakeEngine { + clock: FakeClock::default(), + ns_per_sample: 50, + ns_per_series: 150, + ns_per_call: 10_000, + engine_reported_cpu_ns: None, + cpu_accounting: CpuAccounting::CallingThread, + faults: Vec::new(), + } + } +} + +impl EngineUnderTest for FakeEngine { + fn description(&self) -> EngineDescription { + todo!("implemented after test approval") + } + fn cpu_accounting(&self) -> CpuAccounting { + todo!("implemented after test approval") + } + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + let _ = (workload, arm); + todo!("implemented after test approval") + } + fn calibration(&mut self) -> Option<&mut dyn Calibratable> { + todo!("implemented after test approval") + } +} + +/// One calibration target, `fake/ingest`: `ns_per_sample` over `samples`. +impl Calibratable for FakeEngine { + fn cost_targets(&self) -> Vec { + todo!("implemented after test approval") + } + fn prepare_cost_target( + &mut self, + target: &CostTarget, + size: u64, + ) -> Result Result>, EngineError> { + let _ = (target, size); + todo!("implemented after test approval") + } + fn charged_units(&self, target: &CostTarget, size: u64) -> f64 { + let _ = (target, size); + todo!("implemented after test approval") + } +} diff --git a/aqpbm-harness/src/fit.rs b/aqpbm-harness/src/fit.rs new file mode 100644 index 00000000..6561e71f --- /dev/null +++ b/aqpbm-harness/src/fit.rs @@ -0,0 +1,123 @@ +//! Model fitting: relative-weighted least squares over named constants, and +//! leave-one-setting-out validation on top of it. +//! +//! Example: an operator's cost `cpu_ns = units * ns_per_unit + +//! ns_per_invocation` is the two-constant case, with terms `[units, 1]` per +//! point; the points (1e3, 60,000), (1e4, 510,000), (1e5, 5,010,000) fit +//! 50 ns per unit and 10,000 ns per invocation. + +use serde::{Deserialize, Serialize}; + +use crate::protocol::{CpuClock, Protocol}; + +/// One measurement: the units charged per constant (`terms`, in the order of +/// the constant names) and the measured value. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct FitPoint { + /// The setting the point was measured in; leave-one-setting-out holds out + /// every point of one setting together. + pub setting: String, + pub terms: Vec, + pub measured: f64, +} + +/// Fitted constants, by name, and what the fit flagged. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ConstantsFit { + pub constants: Vec<(String, f64)>, + pub flags: Vec, +} + +/// Something about a fit a reader must know. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum FitFlag { + /// The unconstrained fit gave this constant a negative value; it is set + /// to 0 and the others refitted without it. + NegativeConstantClamped { constant: String, raw_value: f64 }, + /// A point misses the fit by more than 10% of its measured value. + ResidualAboveTolerance { + setting: String, + relative_residual: f64, + }, + /// No point has a non-zero term for this constant, so it is not fitted. + ConstantNotIdentified { constant: String }, +} + +/// Relative-weighted least squares (weights `1 / measured^2`) of `measured` +/// on `terms`, one constant per name. A negative constant is set to 0 and the +/// rest refitted without it. +pub fn fit_constants(names: &[&str], points: &[FitPoint]) -> Result { + let _ = (names, points); + todo!("implemented after test approval") +} + +/// One fold: the fit without one setting, and its relative error on that +/// setting's points. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HeldOutSetting { + pub setting: String, + pub fit: ConstantsFit, + /// `(predicted - measured) / measured` summed over the held-out points; + /// `None` when a constant the setting needs is not identified without it. + pub relative_error: Option, +} + +/// Leave-one-setting-out over every setting. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LeaveOneSettingOut { + /// One fold per setting, in first-appearance order. + pub held_out: Vec, + /// `sqrt(mean(ln(predicted / measured)^2))` over the scored folds. + pub rms_log_error: f64, + /// Folds with a `relative_error`. + pub settings_scored: usize, +} + +/// Fits without each setting in turn and scores the fit on it. +pub fn leave_one_setting_out( + names: &[&str], + points: &[FitPoint], +) -> Result { + let _ = (names, points); + todo!("implemented after test approval") +} + +/// Times `run(size)` at each size on `clock` under `protocol` (warm-up, then +/// the median of `measured_runs` thread-CPU times). `run` returns the units +/// it processed. One point per size: setting = the size, terms = +/// `[units, 1]`. +pub fn measure_sizes( + protocol: &Protocol, + clock: &dyn CpuClock, + sizes: &[u64], + run: &mut dyn FnMut(u64) -> u64, +) -> Vec { + let _ = (protocol, clock, sizes, run); + todo!("implemented after test approval") +} + +/// A fit that cannot be computed. +#[derive(Debug, Clone, PartialEq, thiserror::Error)] +pub enum FitError { + /// No points. + #[error("no points to fit")] + NoPoints, + /// A point's term count differs from the constant count. + #[error("setting {setting}: {got} terms for {expected} constants")] + TermCountMismatch { + setting: String, + expected: usize, + got: usize, + }, + /// A measured value of 0, a negative value or NaN: the weight `1 / y^2` + /// is undefined. + #[error("setting {setting}: measured {measured} cannot be weighted by 1 / measured^2")] + BadMeasurement { setting: String, measured: f64 }, + /// Leave-one-setting-out needs two settings. + #[error("leave-one-setting-out needs at least 2 settings, got {settings}")] + TooFewSettings { settings: usize }, +} diff --git a/aqpbm-harness/src/gate.rs b/aqpbm-harness/src/gate.rs new file mode 100644 index 00000000..88bf3550 --- /dev/null +++ b/aqpbm-harness/src/gate.rs @@ -0,0 +1,96 @@ +//! The gate: per (workload, setting) row, the selected arm passes when its +//! engine cost is at most 1.05 times the exact arm's and its measured error is +//! at most the target. Raw CPU is reported beside the engine cost and never +//! decides. + +use serde::{Deserialize, Serialize}; + +/// The selected arm may cost at most this many times the exact arm. +pub const GATE_MAX_COST_RATIO: f64 = 1.05; + +/// One row of the gate. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GateRow { + pub workload: String, + pub setting: String, + /// The exact arm's engine cost per second; `None` when the exact arm is missing. + pub exact_engine_cost_per_second: Option, + /// `Err` with the reason when the selected arm failed; `Ok(None)` when the + /// engine has no cost model. + pub selected_engine_cost_per_second: Result, String>, + /// Reported, never deciding. + pub exact_query_cpu_ns: Option, + /// Reported, never deciding. + pub selected_query_cpu_ns: Option, + pub measured_error: f64, + pub target_error: f64, +} + +impl GateRow { + /// Selected over exact query CPU, for the summary; `None` when either is missing. + pub fn raw_cpu_ratio(&self) -> Option { + todo!("implemented after test approval") + } +} + +/// Why a row fails. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum GateFailure { + CostAboveExact { + workload: String, + setting: String, + selected: f64, + exact: f64, + }, + ErrorAboveTarget { + workload: String, + setting: String, + measured_error: f64, + target_error: f64, + }, + ExactArmMissing { + workload: String, + setting: String, + }, + SelectedArmFailed { + workload: String, + setting: String, + reason: String, + }, + EngineCostMissing { + workload: String, + setting: String, + }, + ErrorNotANumber { + workload: String, + setting: String, + }, + /// An expected (workload, setting) has no row. + MissingRow { + workload: String, + setting: String, + }, + /// A row nobody expected. + ExtraRow { + workload: String, + setting: String, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum GateVerdict { + Pass, + Fail(Vec), +} + +/// The verdict over `rows` against the `(workload, setting)` pairs expected. +/// With `cost_gate` false only errors and row presence decide. +pub fn gate_verdict( + expected: &[(String, String)], + rows: &[GateRow], + cost_gate: bool, +) -> GateVerdict { + let _ = (expected, rows, cost_gate); + todo!("implemented after test approval") +} diff --git a/aqpbm-harness/src/lib.rs b/aqpbm-harness/src/lib.rs new file mode 100644 index 00000000..e93545e7 --- /dev/null +++ b/aqpbm-harness/src/lib.rs @@ -0,0 +1,28 @@ +//! Engine-neutral measurement harness. +//! +//! An engine under test (an in-process planner and executor, or an external +//! server) implements [`engine::EngineUnderTest`]. The harness installs one +//! arm of a workload on it, feeds it the samples of `aqpbm-datagen` in +//! refresh chunks, asks it for answers at evaluation times, and times every +//! step itself under one measurement protocol: the engine never reports its +//! own time. +//! +//! Example: the fake engine of [`fake`] answers `sum_over_time(probe[10s])` +//! over the left-open window `(t - 10 s, t]`; [`conformance::check`] runs it +//! twice under one seed and checks the answers match, the window boundary, +//! the calibration units and that the work ran on the calling thread. + +pub mod accuracy; +pub mod arm_run; +pub mod conformance; +pub mod data; +pub mod data_stats; +pub mod engine; +pub mod fake; +pub mod fit; +pub mod gate; +pub mod machine; +pub mod protocol; +pub mod records; +pub mod rundir; +pub mod sweep; diff --git a/aqpbm-harness/src/machine.rs b/aqpbm-harness/src/machine.rs new file mode 100644 index 00000000..a887309e --- /dev/null +++ b/aqpbm-harness/src/machine.rs @@ -0,0 +1,91 @@ +//! The machine a measurement ran on, and the key calibrations and runs are +//! stored under: CPU architecture, CPU model, logical cores and memory type. +//! Never the hostname and never the memory size. +//! +//! Example: an "Intel(R) Xeon(R) CPU E5-2683 v3 @ 2.00GHz" on x86_64 with 56 +//! logical cores and registered DDR4 DIMMs is +//! `x86_64-intel-xeon-e5-2683-v3-56c-registered-ddr4`. + +use serde::{Deserialize, Serialize}; + +/// The memory type of a machine whose DIMM types cannot be read (no EDAC, as +/// in a VM) and that has no override. +pub const UNKNOWN_MEMORY_TYPE: &str = "unknown-memory"; + +/// The environment variable that overrides the memory type, like `--memory-type`. +pub const MEMORY_TYPE_ENV: &str = "AQPBM_MEMORY_TYPE"; + +/// What `machine.json` and `run.json` record. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MachineDescription { + /// `std::env::consts::ARCH`, for example `x86_64`. + pub cpu_architecture: String, + /// The `model name` of `/proc/cpuinfo`. + pub cpu_model: String, + /// `processor` lines of `/proc/cpuinfo`: the machine's cores, not this + /// process's affinity mask. + pub logical_cores: u32, + /// The DIMM type, for example `Registered-DDR4`; differing DIMM types are + /// the sorted unique values joined by `-`; [`UNKNOWN_MEMORY_TYPE`] when + /// unreadable and not overridden. + pub memory_type: String, + /// `MemTotal`, in KiB. Recorded for information; not part of the key. + pub memory_kib: u64, + pub os: String, +} + +impl MachineDescription { + /// The machine `/proc/cpuinfo`, `/proc/meminfo` and the EDAC DIMM types + /// (`/sys/devices/system/edac/mc/mc*/dimm*/dimm_mem_type`, one string per + /// DIMM, empty without EDAC) describe. `memory_type_override` + /// (`--memory-type` / [`MEMORY_TYPE_ENV`]) replaces the EDAC types. + pub fn from_proc( + cpu_architecture: &str, + cpuinfo: &str, + meminfo: &str, + dimm_memory_types: &[&str], + memory_type_override: Option<&str>, + os: &str, + ) -> Result { + let _ = ( + cpu_architecture, + cpuinfo, + meminfo, + dimm_memory_types, + memory_type_override, + os, + ); + todo!("implemented after test approval") + } + + /// This machine, read from `/proc` and `/sys`. + pub fn detect(memory_type_override: Option<&str>) -> Result { + let _ = memory_type_override; + todo!("implemented after test approval") + } + + /// The directory name calibrations and runs are stored under: `[a-z0-9-]+` + /// from architecture, model, cores and memory type, e.g. + /// `x86_64-intel-xeon-e5-2683-v3-56c-registered-ddr4`. + pub fn machine_key(&self) -> String { + todo!("implemented after test approval") + } + + /// A warning when the memory type is [`UNKNOWN_MEMORY_TYPE`], naming it and + /// the `--memory-type` / [`MEMORY_TYPE_ENV`] override. + pub fn warning(&self) -> Option { + todo!("implemented after test approval") + } +} + +/// A machine description that cannot be read. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum MachineError { + /// `/proc/cpuinfo` or `/proc/meminfo` lacks a field, such as `model name`. + #[error("{file} has no '{field}' field")] + MissingField { file: String, field: String }, + /// A file could not be read. + #[error("cannot read {path}: {message}")] + Read { path: String, message: String }, +} diff --git a/aqpbm-harness/src/protocol.rs b/aqpbm-harness/src/protocol.rs new file mode 100644 index 00000000..7102e5b8 --- /dev/null +++ b/aqpbm-harness/src/protocol.rs @@ -0,0 +1,207 @@ +//! The measurement protocol: pin the job to one core, check the core is idle +//! before and after, discard warm-up runs, take the median of an odd number +//! of measured runs, and call differences inside the noise band ties. +//! +//! Example: with warm-up 1 and 5 runs, a job whose calls cost 100, 50, 70, +//! 60, 90 and 80 ns records the samples 50, 70, 60, 90, 80 and the median 70. + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::engine::{EngineError, StepCost, StepReport}; + +/// The clocks the harness reads around a step. +pub trait CpuClock { + /// CPU of the calling thread, in ns. + fn thread_cpu_ns(&self) -> u64; + /// CPU of the measured processes, in ns. + fn process_cpu_ns(&self) -> u64; + /// Wall time, in ns from an arbitrary origin. On the clock so a fake clock + /// makes whole runs deterministic. + fn wall_ns(&self) -> u64; +} + +/// The OS clocks: `aqpbm_core::metrics::time::ThreadCpuTime` for the thread, +/// `CpuTimeSampler` (`getrusage`) for the process, `Instant` for wall time. +#[derive(Debug, Clone, Copy, Default)] +pub struct OsCpuClock; + +impl CpuClock for OsCpuClock { + fn thread_cpu_ns(&self) -> u64 { + todo!("implemented after test approval") + } + fn process_cpu_ns(&self) -> u64 { + todo!("implemented after test approval") + } + fn wall_ns(&self) -> u64 { + todo!("implemented after test approval") + } +} + +/// Pins the calling thread to `core` with `sched_setaffinity`. A core outside +/// the allowed set is refused, naming the set (for example `0-55`). +pub fn pin_current_thread(core: usize) -> Result<(), ProtocolError> { + let _ = core; + todo!("implemented after test approval") +} + +/// Busy fraction of `core` between two `/proc/stat` texts: +/// `1 - (Δidle + Δiowait) / Δtotal` over the `cpu` line. +pub fn core_busy_fraction(core: usize, before: &str, after: &str) -> Result { + let _ = (core, before, after); + todo!("implemented after test approval") +} + +/// `utime + stime` (fields 14 and 15) of one `/proc//stat` line, in ns +/// at `ticks_per_second`. The command name in parentheses may hold spaces and +/// parentheses. +pub fn process_cpu_ns_from_stat(stat: &str, ticks_per_second: u64) -> Result { + let _ = (stat, ticks_per_second); + todo!("implemented after test approval") +} + +/// The summed CPU of `pids`, read from `//stat`. A missing +/// pid is an error naming it. +pub fn processes_cpu_ns( + proc_root: &Path, + pids: &[u32], + ticks_per_second: u64, +) -> Result { + let _ = (proc_root, pids, ticks_per_second); + todo!("implemented after test approval") +} + +/// How busy the machine is; the OS form reads `/proc/stat` and `/proc/loadavg`. +pub trait LoadProbe { + /// The busy fraction of `core` over a short sampling interval. + fn core_busy_fraction(&mut self, core: usize) -> Result; + /// The 1-minute load average. + fn loadavg(&mut self) -> f64; +} + +/// The protocol of a run, recorded in `run.json`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Protocol { + /// Runs discarded before measuring. + pub warmup_runs: u32, + /// Runs measured; odd, so the median is one measured value. Default 5. + pub measured_runs: u32, + /// A core busier than this before the job refuses it; after the job it + /// marks the job. Default 0.10. + pub max_core_busy_fraction: f64, +} + +impl Default for Protocol { + fn default() -> Self { + Protocol { + warmup_runs: 1, + measured_runs: 5, + max_core_busy_fraction: 0.10, + } + } +} + +/// One measured job: where it ran, the load around it, and its samples. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct JobRecord { + pub core: usize, + pub busy_before: f64, + pub busy_after: f64, + /// The load average before and after. + pub loadavg: [f64; 2], + pub marks: Vec, + /// One cost per measured run, warm-up excluded. + pub samples: Vec, + /// The sample with the median thread CPU (process CPU for a `Processes` + /// engine). + pub median: StepCost, +} + +/// Something that happened around a job that a reader must know. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum JobMark { + /// The core was busier than the limit after the job. + BusyAfter { busy_fraction: f64 }, +} + +impl Protocol { + /// Pin, check idle, warm up, run `measured_runs` times, check idle again. + pub fn run_job( + &self, + core: usize, + probe: &mut dyn LoadProbe, + clock: &dyn CpuClock, + job: &mut dyn FnMut() -> Result, + ) -> Result { + let _ = (core, probe, clock, job); + todo!("implemented after test approval") + } +} + +/// The median of an odd number of values: the middle one, never a mean. +pub fn median(values: &[f64]) -> Result { + let _ = values; + todo!("implemented after test approval") +} + +/// `|m_a - m_b| / min(m_a, m_b)` of the medians of two arms that ran the same +/// plan. +pub fn noise_band(arm_a: &[f64], arm_b: &[f64]) -> Result { + let _ = (arm_a, arm_b); + todo!("implemented after test approval") +} + +/// How a candidate's cost compares with a reference's. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Comparison { + Cheaper, + Tie, + Costlier, +} + +/// `candidate` against `reference`: a tie when the larger is at most +/// `(1 + band)` times the smaller. +pub fn compare(candidate: f64, reference: f64, band: f64) -> Comparison { + let _ = (candidate, reference, band); + todo!("implemented after test approval") +} + +/// A protocol step that refused or failed. +#[derive(Debug, Clone, PartialEq, thiserror::Error)] +pub enum ProtocolError { + /// The core is outside this process's allowed set. + #[error("core {core} is outside the allowed cores {allowed}")] + CoreNotAllowed { core: usize, allowed: String }, + /// The core was busy before the job; the job did not run. + #[error("core {core} is {:.0}% busy (load average {loadavg}), above the {:.0}% limit: pick an idle core (taskset) or wait", busy_fraction * 100.0, limit * 100.0)] + CoreBusy { + core: usize, + busy_fraction: f64, + loadavg: f64, + limit: f64, + }, + /// Two `/proc/stat` samples with no ticks between them. + #[error("core {core}: /proc/stat did not advance between the two samples, so idleness is unmeasured")] + IdleUnmeasurable { core: usize }, + /// An even or zero run count. + #[error("measured_runs must be odd so the median is one measured value, got {0}")] + RunCountNotOdd(u32), + /// A median of zero or less, which cannot scale a noise band. + #[error("a noise band needs positive medians, got {median}")] + NonPositiveMedian { median: f64 }, + /// `/proc/stat` or `/proc//stat` text that does not parse. + #[error("cannot parse {what}: {message}")] + Parse { what: String, message: String }, + /// A process whose stat file is missing. + #[error("process {pid} has no {path}")] + MissingProcess { pid: u32, path: String }, + /// Pinning failed in the OS. + #[error("pinning to core {core} failed: {message}")] + Pin { core: usize, message: String }, + /// The job's engine call failed. + #[error("the job failed: {0}")] + Job(#[from] EngineError), +} diff --git a/aqpbm-harness/src/records.rs b/aqpbm-harness/src/records.rs new file mode 100644 index 00000000..3f88a3ea --- /dev/null +++ b/aqpbm-harness/src/records.rs @@ -0,0 +1,76 @@ +//! The JSON records of a run: `run.json`, one `results//__.json` +//! per arm, and `calibrate-run.json`. + +use serde::{Deserialize, Serialize}; + +use crate::engine::{ + Answers, EngineDescription, Footprint, NodeProfile, PlanSummary, PredictedCost, +}; +use crate::fit::{ConstantsFit, FitPoint}; +use crate::machine::MachineDescription; +use crate::protocol::{JobRecord, Protocol}; + +/// `run.json`: how the run was started and under which protocol. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RunRecord { + /// The command line. + pub args: Vec, + /// `CARGO_PKG_VERSION`, plus the build-time git commit when known. + pub harness_version: String, + pub machine: MachineDescription, + pub engines: Vec, + pub protocol: Protocol, +} + +/// One arm's results. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ArmResult { + pub engine: String, + pub workload: String, + pub arm: String, + pub plan: PlanSummary, + pub predicted: Option, + /// One job per refresh chunk. + pub ingest: Vec, + /// One job per evaluation time. + pub evaluate: Vec, + /// The answers at each evaluation time. + pub answers: Vec<(i64, Answers)>, + pub footprint: Footprint, + /// Measured usage at the engine's own prices; `None` for an engine + /// without a cost model. + pub engine_cost_per_second: Option, + pub node_profiles: Option>, +} + +/// `calibrate-run.json`: the raw points and fits of one calibration. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CalibrationRun { + pub engine: EngineDescription, + pub machine: MachineDescription, + pub protocol: Protocol, + pub targets: Vec, +} + +/// One calibration target's points and fit. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CalibratedTarget { + /// The engine's opaque target key. + pub key: serde_json::Value, + pub points: Vec, + pub fit: ConstantsFit, +} + +/// A warning when `current` differs from the engine a calibration was +/// measured on, or is dirty, naming both versions and `calibrate`. +pub fn calibration_staleness( + recorded: &EngineDescription, + current: &EngineDescription, +) -> Option { + let _ = (recorded, current); + todo!("implemented after test approval") +} diff --git a/aqpbm-harness/src/rundir.rs b/aqpbm-harness/src/rundir.rs new file mode 100644 index 00000000..70b270fb --- /dev/null +++ b/aqpbm-harness/src/rundir.rs @@ -0,0 +1,85 @@ +//! The run directory: +//! `/runs//--