diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs index 0c24d104..ac17385d 100644 --- a/aqpbm-cli/src/benchmark_external_cmd.rs +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -6,8 +6,10 @@ use std::path::PathBuf; -use anyhow::{bail, Context, Result}; -use aqpbm_core::harness::benchmark_external::{report, run_engine, write_report, EngineRunSetup}; +use anyhow::{bail, Result}; +use aqpbm_core::harness::benchmark_external::{ + report, run_engine, write_report, EngineRunSetup, ReportTruth, +}; use aqpbm_core::harness::cgroup::CgroupSource; use aqpbm_core::harness::engine::EngineUnderTest; use aqpbm_core::harness::fake::FakeEngine; @@ -98,7 +100,9 @@ pub struct RunArgs { pub struct ReportArgs { #[arg(long)] pub run_directory: PathBuf, - /// The cells answers are compared with: `/`. + /// What answers are compared with: `declared` (each query's declared + /// statistic, computed from the workload's data) or the cells of + /// `/`. #[arg(long)] pub truth: String, } @@ -207,12 +211,9 @@ fn server_cgroup(args: &RunArgs) -> Option { } fn report_cmd(args: ReportArgs) -> Result<()> { - let (engine, variant) = args - .truth - .split_once('/') - .context("--truth must be /")?; + let truth = ReportTruth::parse(&args.truth).map_err(anyhow::Error::msg)?; let run_directory = RunDirectory::open(&args.run_directory)?; - let report = report(&run_directory, engine, variant)?; + let report = report(&run_directory, &truth)?; write_report(&run_directory, &report)?; print!("{}", report.summary_markdown()); Ok(()) diff --git a/aqpbm-cli/tests/benchmark_external_cli.rs b/aqpbm-cli/tests/benchmark_external_cli.rs index 5f88c3b6..e2010a80 100644 --- a/aqpbm-cli/tests/benchmark_external_cli.rs +++ b/aqpbm-cli/tests/benchmark_external_cli.rs @@ -19,6 +19,7 @@ fn workload(name: &str) -> WorkloadSpec { }], window_ms: 10_000, evaluation_interval_ms: 10_000, + truth: None, }], data: vec![DataRecord { metric: "m".into(), diff --git a/aqpbm-core/src/accuracy/declared_truth.rs b/aqpbm-core/src/accuracy/declared_truth.rs new file mode 100644 index 00000000..820c781b --- /dev/null +++ b/aqpbm-core/src/accuracy/declared_truth.rs @@ -0,0 +1,286 @@ +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use anyhow::Result; +use aqpbm_datagen::{ColumnData, GeneratedTable}; +use serde::{Deserialize, Serialize}; + +use crate::accuracy::cardinality::CardinalityGT; +use crate::accuracy::keyed::KeyedEntropyGT; +use crate::accuracy::quantile::{RankErrorGT, ReferenceRankErrorGT}; +use crate::accuracy::topk::TopkGT; +use crate::accuracy::windowed::{WindowScore, Windowed}; +use crate::accuracy::GroundTruth; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Truth { + pub statistic: Statistic, + pub metric: String, + #[serde(default)] + pub matchers: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "snake_case")] +pub enum Statistic { + Quantile(f64), + Entropy, + Distinct, + TopK { k: usize, by: String }, +} + +pub struct Series { + pub labels: BTreeMap, + pub points: Vec<(i64, f64)>, +} + +impl Series { + pub fn between(&self, start_exclusive: i64, end_inclusive: i64) -> &[(i64, f64)] { + let from = self.points.partition_point(|&(t, _)| t <= start_exclusive); + let to = self.points.partition_point(|&(t, _)| t <= end_inclusive); + &self.points[from..to.max(from)] + } + + pub fn up_to(&self, end_inclusive: i64) -> &[(i64, f64)] { + &self.points[..self.points.partition_point(|&(t, _)| t <= end_inclusive)] + } +} + +pub type Labels = BTreeMap; + +pub type Scores = BTreeMap; + +pub type Cell = (i64, Labels, Option); + +pub type AnswerAt = (i64, Labels, f64); + +const TIME_COLUMN: usize = 0; + +pub struct QueryTruth { + statistic: Statistic, + metric: String, + matchers: Vec<(String, String)>, + width_ms: i64, +} + +struct Samples { + table: GeneratedTable, + label_names: Vec, +} + +impl Samples { + fn value_column(&self) -> usize { + self.label_names.len() + 1 + } + + fn weight_column(&self) -> usize { + self.label_names.len() + 2 + } + + fn label_columns(&self) -> Vec { + (1..=self.label_names.len()).collect() + } + + fn labels_of(&self, group: &[String]) -> Labels { + self.label_names + .iter() + .zip(group) + .filter(|(_, value)| !value.is_empty()) + .map(|(name, value)| (name.clone(), value.clone())) + .collect() + } +} + +pub fn without_name(labels: &Labels) -> Labels { + labels + .iter() + .filter(|(name, _)| name.as_str() != "__name__") + .map(|(name, value)| (name.clone(), value.clone())) + .collect() +} + +pub fn keyed(answers: &[AnswerAt]) -> HashMap<(i64, Labels), f64> { + answers + .iter() + .map(|(time, labels, value)| ((*time, without_name(labels)), *value)) + .collect() +} + +impl QueryTruth { + pub fn new(truth: &Truth, width_ms: i64) -> QueryTruth { + QueryTruth { + statistic: truth.statistic.clone(), + metric: truth.metric.clone(), + matchers: truth + .matchers + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect(), + width_ms, + } + } + + fn selects(&self, labels: &Labels) -> bool { + labels.get("__name__") == Some(&self.metric) + && self + .matchers + .iter() + .all(|(name, value)| labels.get(name).map_or("", String::as_str) == value) + } + + fn samples(&self, series: &[Series]) -> Samples { + let chosen: Vec<&Series> = series.iter().filter(|s| self.selects(&s.labels)).collect(); + let label_names: Vec = chosen + .iter() + .flat_map(|s| s.labels.keys()) + .filter(|name| name.as_str() != "__name__") + .cloned() + .collect::>() + .into_iter() + .collect(); + let rows: usize = chosen.iter().map(|s| s.points.len()).sum(); + let mut time = Vec::with_capacity(rows); + let mut value = Vec::with_capacity(rows); + let mut labels: Vec> = vec![Vec::with_capacity(rows); label_names.len()]; + for s in chosen { + for &(t, v) in &s.points { + time.push(t); + value.push(v); + for (column, name) in labels.iter_mut().zip(&label_names) { + column.push(s.labels.get(name).cloned().unwrap_or_default()); + } + } + } + let mut column_title = vec!["time".to_string()]; + column_title.extend(label_names.iter().cloned()); + column_title.extend(["value".to_string(), "weight".to_string()]); + let mut data = vec![ColumnData::Int64(time)]; + data.extend(labels.into_iter().map(ColumnData::String)); + data.push(ColumnData::Float64(value)); + data.push(ColumnData::Int64(vec![1; rows])); + Samples { + table: GeneratedTable::new(column_title, data) + .expect("every column holds one entry per sample"), + label_names, + } + } + + fn windowed(&self, ground_truth: G, group_columns: Vec, ends: &[i64]) -> Windowed { + Windowed { + ground_truth, + time_column: TIME_COLUMN, + group_columns, + width: self.width_ms, + ends: ends.to_vec(), + } + } + + fn per_series( + &self, + samples: &Samples, + ground_truth: G, + ends: &[i64], + mut answer: F, + ) -> Result> + where + G: GroundTruth, + F: FnMut(i64, &Labels) -> Option, + G::Answer: Clone, + { + let cells = self + .windowed(ground_truth, samples.label_columns(), ends) + .score(&samples.table, |end, group, probes| { + answer(end, &samples.labels_of(group)).map(|a| vec![a; probes.len()]) + })?; + Ok(cells_of(samples, cells)) + } + + pub fn score( + &self, + series: &[Series], + ends: &[i64], + answers: &[AnswerAt], + ) -> Result> { + let samples = self.samples(series); + let value = samples.value_column(); + let by_key = keyed(answers); + let lookup = |end: i64, labels: &Labels| by_key.get(&(end, labels.clone())).copied(); + match &self.statistic { + Statistic::Quantile(q) => self.per_series( + &samples, + RankErrorGT { + column: value, + fractions: vec![*q], + }, + ends, + lookup, + ), + Statistic::Entropy => self.per_series( + &samples, + KeyedEntropyGT::::over_columns(value, samples.weight_column()), + ends, + lookup, + ), + Statistic::Distinct => { + self.per_series(&samples, CardinalityGT { column: value }, ends, lookup) + } + Statistic::TopK { k, by } => { + let Some(column) = samples.label_names.iter().position(|name| name == by) else { + return Ok(Vec::new()); + }; + let mut lists: BTreeMap> = BTreeMap::new(); + for (time, labels, count) in answers { + if let Some(key) = labels.get(by) { + lists + .entry(*time) + .or_default() + .push((key.clone(), count.round() as u64)); + } + } + let cells = self + .windowed( + TopkGT::::over_column(*k, column + 1), + Vec::new(), + ends, + ) + .score(&samples.table, |end, _, probes| { + let list = lists.get(&end).cloned().unwrap_or_default(); + Some(vec![list; probes.len()]) + })?; + Ok(cells_of(&samples, cells)) + } + } + } + + pub fn reference_rank_errors( + &self, + series: &[Series], + ends: &[i64], + answers: &[AnswerAt], + reference: &HashMap<(i64, Labels), f64>, + ) -> Result> { + if !matches!(self.statistic, Statistic::Quantile(_)) { + return Ok(Vec::new()); + } + let samples = self.samples(series); + let by_key = keyed(answers); + self.per_series( + &samples, + ReferenceRankErrorGT { + column: samples.value_column(), + }, + ends, + |end, labels| { + let key = (end, labels.clone()); + Some((*reference.get(&key)?, *by_key.get(&key)?)) + }, + ) + } +} + +fn cells_of(samples: &Samples, cells: Vec) -> Vec { + cells + .into_iter() + .map(|cell| (cell.end, samples.labels_of(&cell.group), cell.scores)) + .collect() +} diff --git a/aqpbm-core/src/accuracy/mod.rs b/aqpbm-core/src/accuracy/mod.rs index 83eb9ef3..d814b552 100644 --- a/aqpbm-core/src/accuracy/mod.rs +++ b/aqpbm-core/src/accuracy/mod.rs @@ -14,6 +14,7 @@ use crate::error::RunError; pub mod aggregate; pub mod cardinality; pub(crate) mod curve; +pub mod declared_truth; pub mod frequency; pub mod heavy_hitter; pub mod keyed; diff --git a/aqpbm-core/src/harness/benchmark_external.rs b/aqpbm-core/src/harness/benchmark_external.rs index aaebb4ae..a4cbc3b5 100644 --- a/aqpbm-core/src/harness/benchmark_external.rs +++ b/aqpbm-core/src/harness/benchmark_external.rs @@ -5,7 +5,8 @@ //! //! ```text //! workloads/.json harness WorkloadSpec -//! plans//variant.json {"substitutions_allowed": false} +//! plans//variant.json {"substitutions_allowed": false}, optionally +//! "plans": false, "run_by_default": false //! plans//.plan.json a plan file, opaque to the harness //! plans//.no-plan.json {"reason": "ExcludedByDeployment"} //! ``` @@ -14,8 +15,9 @@ //! `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`. +//! against a truth (one engine run's cells, or each query's declared +//! statistic), and [`write_report`] writes `summary.csv`, `summary.md`, +//! `accuracy.csv` and `scores.csv`. //! //! Example: engine `clickhouse` over variants `clickhouse.equivalent-only` and //! `clickhouse.with-substitutes`, engine `asap` over both, report with truth @@ -27,7 +29,9 @@ use std::path::{Path, PathBuf}; use chrono::Utc; use serde::{Deserialize, Serialize}; +use crate::accuracy::declared_truth::{without_name, AnswerAt, QueryTruth, Series, Statistic}; use crate::harness::arm_run::{run_arm, ArmSchedule}; +use crate::harness::data::{workload_chunks, SeriesLabels}; use crate::harness::engine::{ ArmSpec, CpuAccounting, EngineDescription, EngineUnderTest, WorkloadSpec, }; @@ -45,6 +49,18 @@ pub struct VariantRecord { /// 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, + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub plans: bool, + #[serde(default = "yes", skip_serializing_if = "is_yes")] + pub run_by_default: bool, +} + +fn yes() -> bool { + true +} + +fn is_yes(value: &bool) -> bool { + *value } /// `plans//.no-plan.json`: why the planner wrote no plan. @@ -59,6 +75,7 @@ pub struct NoPlanRecord { pub enum PlanEntry { PlanFile(PathBuf), NoPlan { reason: String }, + QueryTextOnly, } /// One variant of the run directory. @@ -173,6 +190,17 @@ pub fn read_variants( let record = record.ok_or_else(|| { BenchmarkExternalError::Layout(format!("variant {name} has no variant.json")) })?; + if !record.plans { + if let Some(workload) = entries.keys().next() { + return Err(BenchmarkExternalError::Layout(format!( + "variant {name} has plans: false but holds an entry for {workload}" + ))); + } + entries = workloads + .keys() + .map(|workload| (workload.clone(), PlanEntry::QueryTextOnly)) + .collect(); + } 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" @@ -219,6 +247,14 @@ pub fn run_engine( ))); } variants.retain(|variant| only.contains(&variant.name)); + } else { + let any = !variants.is_empty(); + variants.retain(|variant| variant.record.run_by_default); + if any && variants.is_empty() { + return Err(BenchmarkExternalError::Layout( + "no variant under plans/ runs by default; name one with --variant".into(), + )); + } } let engine_id = engine.description().id; let engine_directory = run_directory.path().join("results").join(&engine_id); @@ -252,19 +288,28 @@ pub fn run_engine( 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 }, - } - } + PlanEntry::PlanFile(plan_file) => match run_cell( + run_directory, + engine, + workload, + variant, + serde_json::json!({ "plan_file": plan_file }), + &mut setup, + ) { + Ok(()) => CellOutcome::Ran, + Err(error) => CellOutcome::NotRun { error }, + }, + PlanEntry::QueryTextOnly => match run_cell( + run_directory, + engine, + workload, + variant, + serde_json::json!({}), + &mut setup, + ) { + Ok(()) => CellOutcome::Ran, + Err(error) => CellOutcome::NotRun { error }, + }, }; let cell = EngineRunCell { engine: engine_id.clone(), @@ -288,14 +333,14 @@ fn run_cell( engine: &dyn EngineUnderTest, workload: &WorkloadSpec, variant: &Variant, - plan_file: &Path, + engine_options: serde_json::Value, 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 }), + engine_options, }; let result = run_arm( engine, @@ -382,11 +427,47 @@ pub struct QueryAccuracy { pub variant: String, pub query: String, pub errors: PointErrors, + pub scores: BTreeMap, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ScoreSummary { + pub max: f64, + pub median: f64, + pub points: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReportTruth { + Declared, + Cells { engine: String, variant: String }, +} + +impl ReportTruth { + pub fn parse(text: &str) -> Result { + if text == "declared" { + return Ok(ReportTruth::Declared); + } + let (engine, variant) = text + .split_once('/') + .ok_or_else(|| format!("--truth must be declared or /, not {text}"))?; + Ok(ReportTruth::Cells { + engine: engine.to_string(), + variant: variant.to_string(), + }) + } + + pub fn name(&self) -> String { + match self { + ReportTruth::Declared => "declared".to_string(), + ReportTruth::Cells { engine, variant } => format!("{engine}/{variant}"), + } + } } #[derive(Debug, Clone, PartialEq)] pub struct Report { - /// `engine/variant` of the truth. + /// `engine/variant` of the truth, or `declared`. pub truth: String, pub rows: Vec, pub accuracy: Vec, @@ -484,14 +565,16 @@ fn errors_against( 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). +/// Joins every engine run's cells into the report, with accuracy against +/// `truth`: the cells of one engine run, or each query's declared statistic +/// computed from the workload's data. Refuses a truth with no cell, a +/// workload whose ran cells ingested different numbers of samples (the +/// engine runs did not read the same data), and, against declared +/// statistics, a workload that no longer generates the samples its cells +/// ingested. pub fn report( run_directory: &RunDirectory, - truth_engine: &str, - truth_variant: &str, + truth: &ReportTruth, ) -> Result { let results = run_directory.path().join("results"); let mut cells: Vec<(EngineRunCell, Option)> = Vec::new(); @@ -510,14 +593,24 @@ pub fn report( cells.push((cell, result)); } } - if !cells - .iter() - .any(|(cell, _)| cell.engine == truth_engine && cell.variant == truth_variant) + let (truth_engine, truth_variant) = match truth { + ReportTruth::Cells { engine, variant } => (engine.as_str(), variant.as_str()), + ReportTruth::Declared => ("", ""), + }; + if matches!(truth, ReportTruth::Cells { .. }) + && !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 workloads = match truth { + ReportTruth::Declared => read_workloads(run_directory)?, + ReportTruth::Cells { .. } => BTreeMap::new(), + }; + let mut series_of: BTreeMap, u64)> = BTreeMap::new(); let mut samples_per_workload: BTreeMap<&str, (u64, String)> = BTreeMap::new(); for (cell, result) in &cells { let Some(result) = result else { continue }; @@ -571,7 +664,47 @@ pub fn report( }; if let Some(result) = result { fill_measurements(&mut row, result); - if let Some(truth) = truth_of(&cell.workload) { + if matches!(truth, ReportTruth::Declared) { + let workload = workloads.get(&cell.workload).ok_or_else(|| { + BenchmarkExternalError::Report(format!( + "workload {} is not in workloads/", + cell.workload + )) + })?; + if !series_of.contains_key(&cell.workload) { + series_of.insert(cell.workload.clone(), series_of_workload(workload)?); + } + let (series, generated) = &series_of[&cell.workload]; + if *generated != result.ingested_samples { + return Err(BenchmarkExternalError::Report(format!( + "workload {}: workloads/{}.json generates {generated} samples but {}/{} ingested {}", + cell.workload, cell.workload, cell.engine, cell.variant, result.ingested_samples + ))); + } + let per_query = declared_scores(workload, series, result) + .map_err(BenchmarkExternalError::Report)?; + if per_query.is_empty() { + row.no_truth = true; + } else { + let mut all = DeclaredQuery::default(); + for (query, declared) in per_query { + all.relative_errors + .extend_from_slice(&declared.relative_errors); + all.points += declared.points; + all.missing_points += declared.missing_points; + all.extra_points += declared.extra_points; + accuracy.push(QueryAccuracy { + workload: cell.workload.clone(), + engine: cell.engine.clone(), + variant: cell.variant.clone(), + query, + errors: declared.point_errors(), + scores: declared.scores, + }); + } + row.accuracy = Some(all.point_errors()); + } + } else 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); @@ -589,6 +722,7 @@ pub fn report( errors.missing_points, errors.extra_points, ), + scores: BTreeMap::new(), }); } row.accuracy = Some(point_errors(&all, missing, extra)); @@ -599,12 +733,153 @@ pub fn report( rows.push(row); } Ok(Report { - truth: format!("{truth_engine}/{truth_variant}"), + truth: truth.name(), rows, accuracy, }) } +fn series_of_workload( + workload: &WorkloadSpec, +) -> Result<(Vec, u64), BenchmarkExternalError> { + let refresh_ms = ArmSchedule::for_workload(workload) + .map_err(|e| BenchmarkExternalError::Report(format!("workload {}: {e}", workload.name)))? + .refresh_ms; + let mut points: BTreeMap> = BTreeMap::new(); + let mut generated = 0u64; + let chunks = workload_chunks(&workload.data, refresh_ms) + .map_err(|e| BenchmarkExternalError::Report(format!("workload {}: {e}", workload.name)))?; + for chunk in chunks { + let chunk = chunk.map_err(|e| { + BenchmarkExternalError::Report(format!("workload {}: {e}", workload.name)) + })?; + generated += chunk.samples.len() as u64; + for sample in chunk.samples { + points + .entry((*sample.labels).clone()) + .or_default() + .push((sample.ts_ms, sample.value)); + } + } + let series = points + .into_iter() + .map(|(labels, mut points)| { + points.sort_by_key(|(t, _)| *t); + Series { labels, points } + }) + .collect(); + Ok((series, generated)) +} + +const NOT_SCORES: [&str; 7] = [ + "truth", + "estimate", + "items", + "grid_points", + "probes", + "stream_items", + "stream_distinct", +]; + +#[derive(Debug, Default)] +struct DeclaredQuery { + relative_errors: Vec, + points: u64, + missing_points: u64, + extra_points: u64, + scores: BTreeMap, +} + +impl DeclaredQuery { + fn point_errors(&self) -> PointErrors { + PointErrors { + max_relative_error: self.relative_errors.iter().copied().max_by(f64::total_cmp), + median_relative_error: median_of(&self.relative_errors), + points: self.points, + missing_points: self.missing_points, + extra_points: self.extra_points, + } + } +} + +fn declared_scores( + workload: &WorkloadSpec, + series: &[Series], + result: &ArmResult, +) -> Result, String> { + let ends: Vec = result.answers.iter().map(|(t, _)| *t).collect(); + let mut per_query = BTreeMap::new(); + for query in &workload.queries { + let Some(declared) = &query.truth else { + continue; + }; + let answered: Vec = result + .answers + .iter() + .flat_map(|(t, answers)| { + answers + .0 + .get(&query.id) + .into_iter() + .flatten() + .map(|(labels, value)| (*t, labels.clone(), *value)) + }) + .collect(); + let cells = QueryTruth::new(declared, query.window_ms as i64) + .score(series, &ends, &answered) + .map_err(|e| format!("workload {}, query {}: {e}", workload.name, query.id))?; + let mut summary = DeclaredQuery::default(); + let mut values: BTreeMap> = BTreeMap::new(); + let mut truth_keys = std::collections::HashSet::new(); + for (end, labels, scores) in &cells { + truth_keys.insert((*end, labels.clone())); + match scores { + None => summary.missing_points += 1, + Some(scores) => { + summary.points += 1; + if let (Some(truth), Some(estimate)) = + (scores.get("truth"), scores.get("estimate")) + { + summary + .relative_errors + .push(relative_error(*estimate, *truth)); + } + for (name, value) in scores { + if !NOT_SCORES.contains(&name.as_str()) { + values.entry(name.clone()).or_default().push(*value); + } + } + } + } + } + if !matches!(declared.statistic, Statistic::TopK { .. }) { + summary.extra_points = answered + .iter() + .filter(|(t, labels, _)| !truth_keys.contains(&(*t, without_name(labels)))) + .count() as u64; + } + summary.scores = values + .into_iter() + .map(|(name, values)| { + ( + name, + ScoreSummary { + max: values + .iter() + .copied() + .max_by(f64::total_cmp) + .unwrap_or(f64::NAN), + median: median_of(&values).unwrap_or(f64::NAN), + points: values.len() as u64, + }, + ) + }) + .collect(); + per_query.insert(query.id.clone(), summary); + } + Ok(per_query) +} + 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); @@ -655,6 +930,8 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { /// 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"; +pub const SCORES_CSV_HEADER: &str = "workload,engine,variant,query,score,max,median,points"; + /// 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"; @@ -731,6 +1008,26 @@ impl Report { text } + pub fn scores_csv(&self) -> String { + let mut text = format!("{SCORES_CSV_HEADER}\n"); + for row in &self.accuracy { + for (name, summary) in &row.scores { + text.push_str(&format!( + "{},{},{},{},{},{},{},{}\n", + csv_text(&row.workload), + csv_text(&row.engine), + csv_text(&row.variant), + csv_text(&row.query), + csv_text(name), + summary.max, + summary.median, + summary.points, + )); + } + } + 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 { @@ -802,6 +1099,7 @@ pub fn write_report( ("summary.csv", report.summary_csv()), ("summary.md", report.summary_markdown()), ("accuracy.csv", report.accuracy_csv()), + ("scores.csv", report.scores_csv()), ] { let path = run_directory.path().join(name); std::fs::write(&path, text).map_err(|e| io(&path, e))?; diff --git a/aqpbm-core/src/harness/conformance.rs b/aqpbm-core/src/harness/conformance.rs index bdf38797..5bf282c4 100644 --- a/aqpbm-core/src/harness/conformance.rs +++ b/aqpbm-core/src/harness/conformance.rs @@ -453,6 +453,7 @@ pub fn probe_workloads() -> Vec { ], window_ms: PROBE_STEP_MS, evaluation_interval_ms: PROBE_STEP_MS, + truth: None, }], data: vec![data.clone()], }) diff --git a/aqpbm-core/src/harness/engine.rs b/aqpbm-core/src/harness/engine.rs index 381f36ad..5d2315bc 100644 --- a/aqpbm-core/src/harness/engine.rs +++ b/aqpbm-core/src/harness/engine.rs @@ -92,6 +92,8 @@ pub struct WorkloadQuery { pub texts: Vec, pub window_ms: u64, pub evaluation_interval_ms: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub truth: Option, } /// A query text in one language. diff --git a/aqpbm-core/tests/harness_arm_schedule.rs b/aqpbm-core/tests/harness_arm_schedule.rs index cdc3b7b5..7c3b8faa 100644 --- a/aqpbm-core/tests/harness_arm_schedule.rs +++ b/aqpbm-core/tests/harness_arm_schedule.rs @@ -14,6 +14,7 @@ fn query(id: &str, window_ms: u64, evaluation_interval_ms: u64) -> WorkloadQuery }], window_ms, evaluation_interval_ms, + truth: None, } } diff --git a/aqpbm-core/tests/harness_benchmark_external.rs b/aqpbm-core/tests/harness_benchmark_external.rs index be02f848..745e4b9d 100644 --- a/aqpbm-core/tests/harness_benchmark_external.rs +++ b/aqpbm-core/tests/harness_benchmark_external.rs @@ -3,9 +3,10 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; +use aqpbm_core::accuracy::declared_truth::{Statistic, Truth}; use aqpbm_core::harness::benchmark_external::{ read_variants, read_workloads, report, run_engine, write_report, CellOutcome, EngineRunCell, - EngineRunSetup, SUMMARY_CSV_HEADER, + EngineRunSetup, PlanEntry, ReportTruth, SUMMARY_CSV_HEADER, }; use aqpbm_core::harness::cgroup::CgroupMemory; use aqpbm_core::harness::data::{DataRecord, SeriesLabels}; @@ -65,6 +66,7 @@ fn workload(name: &str) -> WorkloadSpec { }], window_ms: 10_000, evaluation_interval_ms: 10_000, + truth: None, }], data: vec![DataRecord { metric: "m".into(), @@ -505,7 +507,14 @@ fn report_fixture(temp: &TempDir) -> RunDirectory { 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 report = report( + &run, + &ReportTruth::Cells { + engine: "a".into(), + variant: "v1".into(), + }, + ) + .unwrap(); let csv = report.summary_csv(); let lines: Vec<&str> = csv.lines().collect(); assert_eq!(lines[0], SUMMARY_CSV_HEADER); @@ -554,7 +563,15 @@ fn the_summary_has_absolute_numbers_and_errors_against_the_truth() { } fn report_error(run: &RunDirectory, engine: &str, variant: &str) -> String { - report(run, engine, variant).unwrap_err().to_string() + report( + run, + &ReportTruth::Cells { + engine: engine.into(), + variant: variant.into(), + }, + ) + .unwrap_err() + .to_string() } /// P2: the relative-error rules. @@ -646,3 +663,206 @@ fn result_file_names_are_checked_before_any_cell_runs() { assert!(error.contains("w__3") && error.contains("__"), "{error}"); assert!(!run.path().join("results/fake").exists()); } + +#[test] +fn variants_without_plans_and_variants_run_only_when_named() { + let temp = TempDir::new("plan-free"); + let run = fixture(&temp, "{}", "{}"); + let plans = run.path().join("plans"); + write( + &plans.join("normal/variant.json"), + r#"{"substitutions_allowed": true, "plans": false}"#, + ); + write( + &plans.join("named/variant.json"), + r#"{"substitutions_allowed": true, "plans": false, "run_by_default": false}"#, + ); + let workloads = read_workloads(&run).unwrap(); + let variants = read_variants(&run, &workloads).unwrap(); + let normal = variants.iter().find(|v| v.name == "normal").unwrap(); + assert!(normal + .entries + .values() + .all(|e| *e == PlanEntry::QueryTextOnly)); + assert_eq!(normal.entries.len(), 2); + + let cells = run_fake(&run, None).unwrap(); + let ran: std::collections::BTreeSet<(String, String)> = cells + .iter() + .map(|c| (c.workload.clone(), c.variant.clone())) + .collect(); + assert!(ran.contains(&("w1".into(), "normal".into()))); + assert!(ran.contains(&("w2".into(), "normal".into()))); + assert!(!ran.iter().any(|(_, v)| v == "named")); + + let named = run_fake(&run, Some(&["named".to_string()])).unwrap(); + let only_named = TempDir::new("only-named"); + let lone = fixture(&only_named, "{}", "{}"); + for variant in ["v1", "v2"] { + let path = lone.path().join(format!("plans/{variant}/variant.json")); + let text = std::fs::read_to_string(&path).unwrap(); + write(&path, &text.replace('}', r#", "run_by_default": false}"#)); + } + let error = run_fake(&lone, None).unwrap_err(); + assert!(error.contains("--variant"), "{error}"); + assert_eq!(named.len(), 2); + assert!(named.iter().all(|c| c.variant == "named")); + + write(&plans.join("normal/w1.plan.json"), "{}"); + let error = read_variants(&run, &workloads).unwrap_err().to_string(); + assert!(error.contains("plans: false"), "{error}"); +} + +#[test] +fn answers_are_scored_against_each_queries_declared_statistic() { + let temp = TempDir::new("declared"); + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + let mut spec = workload("w1"); + spec.queries[0].id = "distinct".into(); + spec.queries[0].truth = Some(Truth { + statistic: Statistic::Distinct, + metric: "m".into(), + matchers: BTreeMap::new(), + }); + let mut undeclared = spec.queries[0].clone(); + undeclared.id = "undeclared".into(); + undeclared.truth = None; + spec.queries.push(undeclared); + let mut quantile = spec.queries[0].clone(); + quantile.id = "median".into(); + quantile.truth = Some(Truth { + statistic: Statistic::Quantile(0.5), + metric: "m".into(), + matchers: BTreeMap::new(), + }); + spec.queries.push(quantile); + write( + &run.path().join("workloads/w1.json"), + &serde_json::to_string(&spec).unwrap(), + ); + let mut plain = workload("w2"); + plain.queries[0].truth = None; + write( + &run.path().join("workloads/w2.json"), + &serde_json::to_string(&plain).unwrap(), + ); + let mut labels: Vec = Vec::new(); + let mut generated = 0u64; + for chunk in aqpbm_core::harness::data::workload_chunks(&spec.data, 10_000).unwrap() { + let chunk = chunk.unwrap(); + generated += chunk.samples.len() as u64; + for sample in chunk.samples { + let mut l = (*sample.labels).clone(); + l.remove("__name__"); + if !labels.contains(&l) { + labels.push(l); + } + } + } + labels.sort(); + assert_eq!(labels.len(), 2); + let at = |values: Vec<(SeriesLabels, f64)>| { + Answers( + [ + ("distinct".to_string(), values.clone().into_iter().collect()), + ("undeclared".to_string(), BTreeMap::new()), + ("median".to_string(), values.into_iter().collect()), + ] + .into_iter() + .collect(), + ) + }; + let mut extra = labels[0].clone(); + extra.insert("s".into(), "nowhere".into()); + let answers = vec![ + ( + 10_000, + at(vec![(labels[0].clone(), 10.0), (labels[1].clone(), 10.0)]), + ), + (20_000, at(vec![(labels[0].clone(), 12.0)])), + ( + 30_000, + at(vec![ + (labels[0].clone(), 10.0), + (labels[1].clone(), 10.0), + (extra, 3.0), + ]), + ), + ]; + let mut w1 = result("e", "w1", "v", answers); + w1.ingested_samples = generated; + put(&run, "e", "w1", "v", CellOutcome::Ran, Some(w1.clone())); + let mut w2 = result("e", "w2", "v", vec![(10_000, answers_of_sum())]); + w2.ingested_samples = generated; + put(&run, "e", "w2", "v", CellOutcome::Ran, Some(w2)); + let report = report(&run, &ReportTruth::Declared).unwrap(); + assert_eq!(report.truth, "declared"); + let distinct: Vec<_> = report + .accuracy + .iter() + .filter(|a| a.workload == "w1" && a.query == "distinct") + .collect(); + assert_eq!(distinct.len(), 1, "{:?}", report.accuracy); + assert!(!report.accuracy.iter().any(|a| a.query == "undeclared")); + let median = report + .accuracy + .iter() + .find(|a| a.query == "median") + .unwrap(); + assert_eq!(median.errors.points, 5); + assert_eq!(median.errors.missing_points, 1); + assert_eq!(median.errors.max_relative_error, None); + assert!( + median.scores.keys().any(|name| name.contains("rank")), + "{:?}", + median.scores + ); + let errors = &distinct[0].errors; + assert_eq!(errors.points, 5); + assert_eq!(errors.missing_points, 1); + assert_eq!(errors.extra_points, 1); + assert!((errors.max_relative_error.unwrap() - 0.2).abs() < 1e-12); + assert_eq!(errors.median_relative_error, Some(0.0)); + assert!(distinct[0].scores.contains_key("relative_error")); + assert!(!distinct[0].scores.contains_key("truth")); + assert!(!distinct[0].scores.contains_key("estimate")); + let w2 = report.rows.iter().find(|r| r.workload == "w2").unwrap(); + assert!(w2.no_truth); + write_report(&run, &report).unwrap(); + let scores = std::fs::read_to_string(run.path().join("scores.csv")).unwrap(); + let mut edited = spec.clone(); + edited.data[0].description.duration_ms = 30_000; + write( + &run.path().join("workloads/w1.json"), + &serde_json::to_string(&edited).unwrap(), + ); + let error = aqpbm_core::harness::benchmark_external::report(&run, &ReportTruth::Declared) + .unwrap_err() + .to_string(); + assert!(error.contains("generates"), "{error}"); + assert!(scores.starts_with("workload,engine,variant,query,score,max,median,points\n")); + assert!( + scores.contains("w1,e,v,distinct,relative_error,0.2,0,5"), + "{scores}" + ); +} + +fn answers_of_sum() -> Answers { + Answers([("sum".to_string(), BTreeMap::new())].into_iter().collect()) +} + +#[test] +fn the_truth_is_declared_or_one_engines_cells() { + assert_eq!( + ReportTruth::parse("declared").unwrap(), + ReportTruth::Declared + ); + assert_eq!( + ReportTruth::parse("fake/v1").unwrap(), + ReportTruth::Cells { + engine: "fake".into(), + variant: "v1".into() + } + ); + assert!(ReportTruth::parse("fake").is_err()); +} diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs index ed12957e..c2fcb6f4 100644 --- a/aqpbm-core/tests/harness_cgroup.rs +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -256,6 +256,7 @@ fn two_series_workload() -> WorkloadSpec { }], window_ms: 10_000, evaluation_interval_ms: 10_000, + truth: None, }], data: vec![DataRecord { metric: "m".into(), diff --git a/aqpbm-core/tests/harness_fake.rs b/aqpbm-core/tests/harness_fake.rs index 2ec71d7a..9fa9f324 100644 --- a/aqpbm-core/tests/harness_fake.rs +++ b/aqpbm-core/tests/harness_fake.rs @@ -72,6 +72,7 @@ fn sum_query(id: &str, metric: &str, window_s: u64) -> WorkloadQuery { }], window_ms: window_s * 1_000, evaluation_interval_ms: 10_000, + truth: None, } } diff --git a/aqpbm-usecase/src/accuracy.rs b/aqpbm-usecase/src/accuracy.rs index cb68ab4a..a5001afe 100644 --- a/aqpbm-usecase/src/accuracy.rs +++ b/aqpbm-usecase/src/accuracy.rs @@ -1,253 +1,3 @@ -use std::collections::{BTreeMap, BTreeSet, HashMap}; - -use anyhow::Result; -use aqpbm_core::accuracy::cardinality::CardinalityGT; -use aqpbm_core::accuracy::keyed::KeyedEntropyGT; -use aqpbm_core::accuracy::quantile::{RankErrorGT, ReferenceRankErrorGT}; -use aqpbm_core::accuracy::topk::TopkGT; -use aqpbm_core::accuracy::windowed::{WindowScore, Windowed}; -use aqpbm_core::accuracy::GroundTruth; -use aqpbm_datagen::{ColumnData, GeneratedTable}; - -use crate::data::Series; -use crate::spec::{QuerySpec, Statistic}; - -pub type Labels = BTreeMap; - -pub type Scores = BTreeMap; - -pub type Cell = (i64, Labels, Option); - -pub type AnswerAt = (i64, Labels, f64); - -const TIME_COLUMN: usize = 0; - -pub struct QueryTruth { - statistic: Statistic, - metric: String, - matchers: Vec<(String, String)>, - width_ms: i64, -} - -struct Samples { - table: GeneratedTable, - label_names: Vec, -} - -impl Samples { - fn value_column(&self) -> usize { - self.label_names.len() + 1 - } - - fn weight_column(&self) -> usize { - self.label_names.len() + 2 - } - - fn label_columns(&self) -> Vec { - (1..=self.label_names.len()).collect() - } - - fn labels_of(&self, group: &[String]) -> Labels { - self.label_names - .iter() - .zip(group) - .filter(|(_, value)| !value.is_empty()) - .map(|(name, value)| (name.clone(), value.clone())) - .collect() - } -} - -pub fn without_name(labels: &Labels) -> Labels { - labels - .iter() - .filter(|(name, _)| name.as_str() != "__name__") - .map(|(name, value)| (name.clone(), value.clone())) - .collect() -} - -pub fn keyed(answers: &[AnswerAt]) -> HashMap<(i64, Labels), f64> { - answers - .iter() - .map(|(time, labels, value)| ((*time, without_name(labels)), *value)) - .collect() -} - -impl QueryTruth { - pub fn of(query: &QuerySpec) -> Option { - let truth = query.truth.as_ref()?; - Some(QueryTruth { - statistic: truth.statistic.clone(), - metric: truth.metric.clone(), - matchers: truth - .matchers - .iter() - .map(|(name, value)| (name.clone(), value.clone())) - .collect(), - width_ms: query.window_ms, - }) - } - - fn selects(&self, labels: &Labels) -> bool { - labels.get("__name__") == Some(&self.metric) - && self - .matchers - .iter() - .all(|(name, value)| labels.get(name).map_or("", String::as_str) == value) - } - - fn samples(&self, series: &[Series]) -> Samples { - let chosen: Vec<&Series> = series.iter().filter(|s| self.selects(&s.labels)).collect(); - let label_names: Vec = chosen - .iter() - .flat_map(|s| s.labels.keys()) - .filter(|name| name.as_str() != "__name__") - .cloned() - .collect::>() - .into_iter() - .collect(); - let rows: usize = chosen.iter().map(|s| s.points.len()).sum(); - let mut time = Vec::with_capacity(rows); - let mut value = Vec::with_capacity(rows); - let mut labels: Vec> = vec![Vec::with_capacity(rows); label_names.len()]; - for s in chosen { - for &(t, v) in &s.points { - time.push(t); - value.push(v); - for (column, name) in labels.iter_mut().zip(&label_names) { - column.push(s.labels.get(name).cloned().unwrap_or_default()); - } - } - } - let mut column_title = vec!["time".to_string()]; - column_title.extend(label_names.iter().cloned()); - column_title.extend(["value".to_string(), "weight".to_string()]); - let mut data = vec![ColumnData::Int64(time)]; - data.extend(labels.into_iter().map(ColumnData::String)); - data.push(ColumnData::Float64(value)); - data.push(ColumnData::Int64(vec![1; rows])); - Samples { - table: GeneratedTable::new(column_title, data) - .expect("every column holds one entry per sample"), - label_names, - } - } - - fn windowed(&self, ground_truth: G, group_columns: Vec, ends: &[i64]) -> Windowed { - Windowed { - ground_truth, - time_column: TIME_COLUMN, - group_columns, - width: self.width_ms, - ends: ends.to_vec(), - } - } - - fn per_series( - &self, - samples: &Samples, - ground_truth: G, - ends: &[i64], - mut answer: F, - ) -> Result> - where - G: GroundTruth, - F: FnMut(i64, &Labels) -> Option, - G::Answer: Clone, - { - let cells = self - .windowed(ground_truth, samples.label_columns(), ends) - .score(&samples.table, |end, group, probes| { - answer(end, &samples.labels_of(group)).map(|a| vec![a; probes.len()]) - })?; - Ok(cells_of(samples, cells)) - } - - pub fn score( - &self, - series: &[Series], - ends: &[i64], - answers: &[AnswerAt], - ) -> Result> { - let samples = self.samples(series); - let value = samples.value_column(); - let by_key = keyed(answers); - let lookup = |end: i64, labels: &Labels| by_key.get(&(end, labels.clone())).copied(); - match &self.statistic { - Statistic::Quantile(q) => self.per_series( - &samples, - RankErrorGT { - column: value, - fractions: vec![*q], - }, - ends, - lookup, - ), - Statistic::Entropy => self.per_series( - &samples, - KeyedEntropyGT::::over_columns(value, samples.weight_column()), - ends, - lookup, - ), - Statistic::Distinct => { - self.per_series(&samples, CardinalityGT { column: value }, ends, lookup) - } - Statistic::TopK { k, by } => { - let Some(column) = samples.label_names.iter().position(|name| name == by) else { - return Ok(Vec::new()); - }; - let mut lists: BTreeMap> = BTreeMap::new(); - for (time, labels, count) in answers { - if let Some(key) = labels.get(by) { - lists - .entry(*time) - .or_default() - .push((key.clone(), count.round() as u64)); - } - } - let cells = self - .windowed( - TopkGT::::over_column(*k, column + 1), - Vec::new(), - ends, - ) - .score(&samples.table, |end, _, probes| { - let list = lists.get(&end).cloned().unwrap_or_default(); - Some(vec![list; probes.len()]) - })?; - Ok(cells_of(&samples, cells)) - } - } - } - - pub fn reference_rank_errors( - &self, - series: &[Series], - ends: &[i64], - answers: &[AnswerAt], - reference: &HashMap<(i64, Labels), f64>, - ) -> Result> { - if !matches!(self.statistic, Statistic::Quantile(_)) { - return Ok(Vec::new()); - } - let samples = self.samples(series); - let by_key = keyed(answers); - self.per_series( - &samples, - ReferenceRankErrorGT { - column: samples.value_column(), - }, - ends, - |end, labels| { - let key = (end, labels.clone()); - Some((*reference.get(&key)?, *by_key.get(&key)?)) - }, - ) - } -} - -fn cells_of(samples: &Samples, cells: Vec) -> Vec { - cells - .into_iter() - .map(|cell| (cell.end, samples.labels_of(&cell.group), cell.scores)) - .collect() -} +pub use aqpbm_core::accuracy::declared_truth::{ + keyed, without_name, AnswerAt, Cell, Labels, QueryTruth, Scores, +}; diff --git a/aqpbm-usecase/src/data.rs b/aqpbm-usecase/src/data.rs index cb313a13..8908c8ad 100644 --- a/aqpbm-usecase/src/data.rs +++ b/aqpbm-usecase/src/data.rs @@ -12,25 +12,10 @@ use aqpbm_datagen::ColumnData; use crate::spec::{Change, Import, MetricSpec, Phase, SeriesGroup, Spec}; -pub struct Series { - pub labels: BTreeMap, - pub points: Vec<(i64, f64)>, -} +pub use aqpbm_core::accuracy::declared_truth::Series; pub type Slice<'a> = (&'a Series, &'a [(i64, f64)]); -impl Series { - pub fn between(&self, start_exclusive: i64, end_inclusive: i64) -> &[(i64, f64)] { - let from = self.points.partition_point(|&(t, _)| t <= start_exclusive); - let to = self.points.partition_point(|&(t, _)| t <= end_inclusive); - &self.points[from..to.max(from)] - } - - pub fn up_to(&self, end_inclusive: i64) -> &[(i64, f64)] { - &self.points[..self.points.partition_point(|&(t, _)| t <= end_inclusive)] - } -} - pub fn between(series: &[Series], start_exclusive: i64, end_inclusive: i64) -> Vec> { series .iter() diff --git a/aqpbm-usecase/src/score.rs b/aqpbm-usecase/src/score.rs index 00bf12b7..d1e83dcf 100644 --- a/aqpbm-usecase/src/score.rs +++ b/aqpbm-usecase/src/score.rs @@ -5,7 +5,7 @@ use anyhow::{Context, Result}; use aqpbm_core::accuracy::scalar_error; use serde_json::Value; -use crate::accuracy::{keyed, without_name, AnswerAt, Labels, QueryTruth, Scores}; +use crate::accuracy::{keyed, without_name, AnswerAt, Labels, Scores}; use crate::data::Series; use crate::output::{Answer, TruthCell}; use crate::spec::QuerySpec; @@ -49,7 +49,7 @@ pub fn score( answered: &[AnswerAt], exact: Option<&BTreeMap>>, ) -> Result { - let truth = QueryTruth::of(query); + let truth = query.declared_truth(); let computed_truth = truth .as_ref() .map(|truth| truth.score(series, times, answered)) diff --git a/aqpbm-usecase/src/spec.rs b/aqpbm-usecase/src/spec.rs index d9035552..f1c4db8a 100644 --- a/aqpbm-usecase/src/spec.rs +++ b/aqpbm-usecase/src/spec.rs @@ -5,6 +5,9 @@ use anyhow::{bail, Context, Result}; use aqpbm_datagen::DataDistribution; use serde::Deserialize; +use aqpbm_core::accuracy::declared_truth::QueryTruth; +pub use aqpbm_core::accuracy::declared_truth::{Statistic, Truth}; + #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct Spec { @@ -111,22 +114,10 @@ pub struct QuerySpec { pub truth: Option, } -#[derive(Debug, Clone, PartialEq, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Truth { - pub statistic: Statistic, - pub metric: String, - #[serde(default)] - pub matchers: BTreeMap, -} - -#[derive(Debug, Clone, PartialEq, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "snake_case")] -pub enum Statistic { - Quantile(f64), - Entropy, - Distinct, - TopK { k: usize, by: String }, +impl QuerySpec { + pub fn declared_truth(&self) -> Option { + Some(QueryTruth::new(self.truth.as_ref()?, self.window_ms)) + } } impl MetricSpec { diff --git a/aqpbm-usecase/tests/uc1.rs b/aqpbm-usecase/tests/uc1.rs index e6968bc7..fbf1b0e3 100644 --- a/aqpbm-usecase/tests/uc1.rs +++ b/aqpbm-usecase/tests/uc1.rs @@ -1,6 +1,6 @@ use std::path::Path; -use aqpbm_usecase::accuracy::{Labels, QueryTruth}; +use aqpbm_usecase::accuracy::Labels; use aqpbm_usecase::data::{generate, Series}; use aqpbm_usecase::spec::{Spec, Statistic, Truth}; @@ -87,7 +87,9 @@ fn a_quantile_answer_is_scored_by_rank_within_its_window_and_series() { metric: "m".into(), matchers: Default::default(), }); - let truth = QueryTruth::of(&spec.queries[0]).expect("the query declares its truth"); + let truth = spec.queries[0] + .declared_truth() + .expect("the query declares its truth"); let cells = truth .score(&series, &[5], &[(5, labels("a"), 1.0)]) .unwrap(); diff --git a/system-bench/tests/clickhouse_conformance.rs b/system-bench/tests/clickhouse_conformance.rs index 5d0703f0..1b659635 100644 --- a/system-bench/tests/clickhouse_conformance.rs +++ b/system-bench/tests/clickhouse_conformance.rs @@ -98,6 +98,7 @@ fn workload(plan: &Value, interval_ms: Option) -> WorkloadSpec { }], window_ms: 60_000, evaluation_interval_ms: interval_ms, + truth: None, }) .collect(), data: vec![], @@ -734,7 +735,9 @@ fn suite_sized_workload() { #[test] #[ignore = "needs a ClickHouse server"] fn the_clickhouse_engine_matches_the_fake_engine() { - use aqpbm_core::harness::benchmark_external::{report, run_engine, EngineRunSetup}; + use aqpbm_core::harness::benchmark_external::{ + report, run_engine, EngineRunSetup, ReportTruth, + }; use aqpbm_core::harness::fake::FakeEngine; use aqpbm_core::harness::protocol::{ load_probe_for, MeasurementClocks, OsCpuClock, ProcessCpuFiles, Protocol, @@ -798,7 +801,14 @@ fn the_clickhouse_engine_matches_the_fake_engine() { .unwrap(); println!("{} cells: {cells:?}", engine.description().id); } - let report = report(&run_directory, "fake", "equivalent-only").unwrap(); + let report = report( + &run_directory, + &ReportTruth::Cells { + engine: "fake".into(), + variant: "equivalent-only".into(), + }, + ) + .unwrap(); println!("{}", report.summary_markdown()); let csv = report.summary_csv(); let clickhouse_rows: Vec<&str> = csv.lines().filter(|l| l.contains(",clickhouse,")).collect(); diff --git a/system-bench/tests/clickhouse_server.rs b/system-bench/tests/clickhouse_server.rs index e8619e24..3c908226 100644 --- a/system-bench/tests/clickhouse_server.rs +++ b/system-bench/tests/clickhouse_server.rs @@ -186,6 +186,7 @@ fn workload_of(plan: &str, interval_ms: u64, start_ms: i64) -> WorkloadSpec { }], window_ms: 60_000, evaluation_interval_ms: interval_ms, + truth: None, }) .collect(), data: vec![data_record(start_ms)], @@ -736,6 +737,7 @@ fn only_a_bare_selector_keeps_the_metric_name() { }], window_ms: 60_000, evaluation_interval_ms: 60_000, + truth: None, }], data: vec![data_record(0)], }; diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs index 567a83e1..7a07524f 100644 --- a/system-bench/tests/victoriametrics_conformance.rs +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -91,6 +91,7 @@ fn workload(plan: &Value, interval_ms: u64) -> WorkloadSpec { }], window_ms: 60_000, evaluation_interval_ms: interval_ms, + truth: None, }) .collect(), data: vec![], diff --git a/system-bench/tests/victoriametrics_server.rs b/system-bench/tests/victoriametrics_server.rs index 72b26515..e3e5e5b3 100644 --- a/system-bench/tests/victoriametrics_server.rs +++ b/system-bench/tests/victoriametrics_server.rs @@ -288,6 +288,7 @@ fn workload(texts: &[&str], interval_ms: u64) -> WorkloadSpec { }], window_ms: 60_000, evaluation_interval_ms: interval_ms, + truth: None, }) .collect(), data: vec![],