diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index c8d92af0..9a6e81d0 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -11,7 +11,7 @@ implemented, what is next, and what is intentionally deferred. cardinality per label set. The arrival rate is derived from them, and `validate_facts` reports bad facts up front. - Eligibility enforces capability, metric, spatial filter, grouping, alignment, and the RQE's - measured `accuracy_metric` constraint. + measured accuracy, by each family's own metric, against the RAQE's SLA. - Candidate generation uses legal windows and subset gcds of query intervals, keeping only multiples of the scrape interval. A deployment may serve multiple compatible RQEs. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 87322771..f3d3cfad 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -47,9 +47,7 @@ Let `R = {r_1, ..., r_n}` be the RAQE workload. Each RAQE `r_i` provides: | `T_i` | Query slide: how often the RAQE runs. This is the current `interval` field. | | `metric_i` | Metric the RAQE reads. | | `G_i` | Group-by label set (`grouping_labels`). | -| `accuracy_metric_i` | Accuracy measurement to check. | -| `tol_i` | Accuracy threshold. | -| `direction_i` | Whether lower or higher values are better. | +| `tol_i` | Accuracy threshold, checked against each candidate family's own metric. | For each metric, the caller provides `MetricFacts`: @@ -203,8 +201,8 @@ An RAQE `r_i` is eligible for a candidate `D` when: 1. `cap_i = D.capability`, `metric_i = D.metric` and `G_i = D.G`. 2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. -3. The accuracy of `D` for `r_i` in `accuracy_metric_i` clears `tol_i` in - `direction_i`. +3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family + (`family_properties`, which also gives the direction), clears `tol_i`. Exact accumulators take that accuracy from the cost table, at both measured merge counts bracketing the query's `S_i / D.x` windows (count 1 is the @@ -221,7 +219,8 @@ lookback: series per group times scrapes per lookback. accuracy. - Between checkpoints, the worse neighbour. Below the first checkpoint, no accuracy. Past the last, the plateau if the point saturated, else none. -- The curve's `error_metric` must be `accuracy_metric_i`. +- The curve's `error_metric` must be the family's metric; `SaturationCurves::load` + refuses a curve for another metric as a stale study. - The window size doesn't matter: a merged answer reads the curve at the lookback's item count, like a single sketch. KLL and top-k merge lossily; their merge penalty is #158. diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index a7d27c7b..e08050b8 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -46,25 +46,10 @@ use rqe_optimizer::milp::{minimize, Objective}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; use rqe_optimizer::saturation::{DataShape, SaturationCurves}; use rqe_optimizer::{ - validate_facts, AccuracyDirection, AtomicCostTable, Capability, Deployment, LabelSet, - MetricFacts, Raqe, WorkloadFacts, + validate_facts, AtomicCostTable, Capability, Deployment, LabelSet, MetricFacts, Raqe, + WorkloadFacts, }; -/// Accuracy metric keys the real comparators actually report (checked -/// against `aqpbm-core/src/accuracy/{aggregate,quantile,cardinality}.rs`). -/// These three are lower-is-better errors; each RAQE below pairs its metric with the matching -/// [`AccuracyDirection`] so the comparison can't be applied the wrong way -/// round. -/// -/// Request rate is served by an exact counter accumulator, so its error -/// should be zero; the bound is there to reject anything that isn't. -const RATE_ERR: &str = "relative_error"; -const RANK_ERR: &str = "mean_rank_err"; -const CARDINALITY_ERR: &str = "relative_error"; -/// Top-k's metric is the odd one out: a *score*, not an error, so its -/// tolerance below is a floor and its direction is `HigherIsBetter`. -const TOPK_PRECISION: &str = "precision_at_k"; - const COST_TABLE_FILE: &str = "rqe_atomic_costs.json"; const REQUESTS: &str = "http_requests_total"; @@ -150,6 +135,13 @@ fn data_shape(distinct_keys: f64) -> DataShape { } } +/// Each RAQE's `accuracy_sla` is checked against the metric its candidate +/// family reports (`rqe_optimizer::family_properties`): rank error for KLL, +/// relative value error for DDSketch, relative error for the exact counter +/// and HLL, precision@k for top-k. +/// +/// Request rate is served by an exact counter accumulator, so its error +/// should be zero; the bound is there to reject anything that isn't. fn raqes() -> Vec { let se = label_set(&["service", "endpoint"]); let s = label_set(&["service"]); @@ -164,9 +156,7 @@ fn raqes() -> Vec { metric: requests(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RATE_ERR.to_string(), accuracy_sla: 0.1, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -177,9 +167,7 @@ fn raqes() -> Vec { metric: requests(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RATE_ERR.to_string(), accuracy_sla: 0.1, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -190,9 +178,7 @@ fn raqes() -> Vec { metric: requests(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RATE_ERR.to_string(), accuracy_sla: 0.1, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -203,9 +189,7 @@ fn raqes() -> Vec { metric: duration(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RANK_ERR.to_string(), accuracy_sla: 0.05, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -216,9 +200,7 @@ fn raqes() -> Vec { metric: duration(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RANK_ERR.to_string(), accuracy_sla: 0.05, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -229,9 +211,7 @@ fn raqes() -> Vec { metric: duration(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: RANK_ERR.to_string(), accuracy_sla: 0.05, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, Raqe { @@ -242,13 +222,11 @@ fn raqes() -> Vec { metric: requests(), spatial_filter: String::new(), grouping_labels: s.clone(), - accuracy_metric: CARDINALITY_ERR.to_string(), accuracy_sla: 0.1, - accuracy_direction: AccuracyDirection::LowerIsBetter, latency_sla_ms: None, }, - // The higher-is-better case: 0.9 is a *floor* on precision@k, not a - // ceiling on error. Served by cms-heap, whose measured precision is + // The higher-is-better case: top-k's metric is precision@k, so 0.9 is + // a *floor*, not a ceiling on error. Served by cms-heap, whose measured precision is // 1.0 at both configs under the zipf workload (it was 0.0 at both // under uniform -- top-k is meaningless without real skew). Raqe { @@ -259,9 +237,7 @@ fn raqes() -> Vec { metric: requests(), spatial_filter: String::new(), grouping_labels: se.clone(), - accuracy_metric: TOPK_PRECISION.to_string(), accuracy_sla: 0.9, - accuracy_direction: AccuracyDirection::HigherIsBetter, latency_sla_ms: None, }, ] diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index 756ef304..d819e0ff 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -45,9 +45,9 @@ pub fn window_adapter(raqe: &Raqe) -> (Millis, Millis) { (raqe.lookback_ms, gcd(raqe.lookback_ms, raqe.interval_ms)) } -/// Search every RAQE independently. `accuracy` is the benchmark oracle: the -/// measured metric named by `raqe.accuracy_metric` for a configuration, or -/// `None` when it was not measured. Returns the IDs of unservable RAQEs. +/// Search every RAQE independently. `accuracy` is the benchmark oracle: a +/// configuration's accuracy in its family's metric ([`crate::accuracy_key`]), +/// or `None` when it was not measured. Returns the IDs of unservable RAQEs. /// `allow_undeployable_families` as in /// [`crate::Capability::candidate_families`]. pub fn plan( @@ -149,7 +149,7 @@ pub fn search( continue; } probes.push(index); - let feasible = raqe.meets_sla(accuracy(raqe, &costs[index])); + let feasible = raqe.meets_sla(&costs[index].sketch, accuracy(raqe, &costs[index])); evaluated.insert(index, feasible); if feasible && best.is_none_or(|b| cheaper(index, b)) { best = Some(index); @@ -340,11 +340,9 @@ mod tests { use crate::analytical_cost_model::{score, PhaseCost}; use crate::candidates::is_eligible; use crate::test_support::{facts, METRIC}; - use crate::{table_accuracy_at, AccuracyDirection, Capability, LabelSet}; + use crate::{table_accuracy_at, Capability, LabelSet}; use std::collections::BTreeSet; - const ERR: &str = "err"; - fn cms(rows: u64, cols: u64) -> AtomicCostEntry { AtomicCostEntry { sketch: "cms-heap-topk-fastpath-vector2d".into(), @@ -356,8 +354,11 @@ mod tests { insert_cpu_secs: 1e-8 * rows as f64, merge_cpu_secs: 1e-6, query_cpu_secs: 1e-6, - // Error falls with width and depth, so feasibility is monotone. - query_accuracy: BTreeMap::from([(ERR.into(), 1.0 / (rows * cols) as f64)]), + // Precision rises with width and depth, so feasibility is monotone. + query_accuracy: BTreeMap::from([( + "precision_at_k".into(), + 1.0 - 1.0 / (rows * cols) as f64, + )]), merge_accuracy: BTreeMap::new(), measured_at: None, } @@ -369,7 +370,8 @@ mod tests { .collect() } - fn raqe(id: &str, lookback: Millis, interval: Millis, tolerance: f64) -> Raqe { + /// A top-k RAQE whose precision floor is `1 - error_budget`. + fn raqe(id: &str, lookback: Millis, interval: Millis, error_budget: f64) -> Raqe { Raqe { id: id.into(), capability: Capability::TopKByValue, @@ -378,20 +380,18 @@ mod tests { metric: METRIC.into(), spatial_filter: String::new(), grouping_labels: LabelSet::new(), - accuracy_metric: ERR.into(), - accuracy_sla: tolerance, - accuracy_direction: AccuracyDirection::LowerIsBetter, + accuracy_sla: 1.0 - error_budget, latency_sla_ms: None, } } - fn table_accuracy(raqe: &Raqe, config: &AtomicCostEntry) -> Option { - config.query_accuracy.get(&raqe.accuracy_metric).copied() + fn table_accuracy(_: &Raqe, config: &AtomicCostEntry) -> Option { + Some(table_accuracy_at(config, 1)) } fn cheapest_feasible(raqe: &Raqe, costs: &[AtomicCostEntry]) -> usize { (0..costs.len()) - .filter(|&i| raqe.meets_sla(table_accuracy_at(raqe, &costs[i], 1))) + .filter(|&i| raqe.meets_sla(&costs[i].sketch, table_accuracy(raqe, &costs[i]))) .min_by(|&a, &b| compare_resources(&costs[a], &costs[b])) .unwrap() } @@ -497,16 +497,17 @@ mod tests { insert_cpu_secs: 1e-8, merge_cpu_secs: 1e-6, query_cpu_secs: 1e-6, - query_accuracy: BTreeMap::from([(ERR.into(), 1.0 / k as f64)]), + query_accuracy: BTreeMap::from([("mean_rank_err".into(), 1.0 / k as f64)]), merge_accuracy: BTreeMap::new(), measured_at: None, } } - fn quantile_raqe(tolerance: f64) -> Raqe { + fn quantile_raqe(max_rank_err: f64) -> Raqe { Raqe { capability: Capability::Quantile, - ..raqe("q", 3_600_000, 60_000, tolerance) + accuracy_sla: max_rank_err, + ..raqe("q", 3_600_000, 60_000, 0.0) } } @@ -549,14 +550,15 @@ mod tests { // Precision rises with k; the target is a floor of 0.95. let costs: Vec<_> = (1..=10) .map(|k| { - let mut c = kll(k); - c.query_accuracy = BTreeMap::from([(ERR.into(), 0.9 + 0.01 * k as f64)]); + let mut c = cms(1, k); + c.query_accuracy = + BTreeMap::from([("precision_at_k".into(), 0.9 + 0.01 * k as f64)]); c }) .collect(); let r = Raqe { - accuracy_direction: AccuracyDirection::HigherIsBetter, - ..quantile_raqe(0.95) + accuracy_sla: 0.95, + ..raqe("r", 3_600_000, 60_000, 0.0) }; let found = search(&r, &costs, 11, false, table_accuracy); assert_eq!(found.selected, Some(4)); // k = 5: 0.95 diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 6aa9a2b9..8dd3503f 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -365,14 +365,14 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A && properties.needs_delta_set_key_tracker == d.key_tracker.is_some() && (!properties.one_fixed_size_sketch_for_all_groups || measured_at_group_count(&d.config, facts[&d.metric].cardinality[&d.grouping_labels])) - && r.meets_sla(accuracy(r, d)) + && r.meets_sla(&d.config.sketch, accuracy(r, d)) } #[cfg(test)] mod tests { use super::*; - use crate::test_support::{facts, METRIC}; - use crate::{table_accuracy, AccuracyDirection, LabelSet}; + use crate::test_support::{facts, perfect_accuracy, METRIC}; + use crate::{table_accuracy, LabelSet}; use std::collections::BTreeMap; fn raqe(id: &str, lookback: Millis, interval: Millis) -> Raqe { Raqe { @@ -383,9 +383,7 @@ mod tests { metric: METRIC.into(), spatial_filter: String::new(), grouping_labels: LabelSet::new(), - accuracy_metric: "err".into(), - accuracy_sla: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, + accuracy_sla: 0.5, latency_sla_ms: None, } } @@ -397,7 +395,7 @@ mod tests { insert_cpu_secs: 1.0, merge_cpu_secs: 1.0, query_cpu_secs: 1.0, - query_accuracy: BTreeMap::from([("err".into(), 0.1)]), + query_accuracy: perfect_accuracy(), merge_accuracy: BTreeMap::new(), measured_at: None, } @@ -405,9 +403,13 @@ mod tests { #[test] fn eligibility_checks_accuracy_at_the_queries_merge_count() { let mut config = cost(); - let err = |v: f64| BTreeMap::from([("err".into(), v)]); - // Error is not monotone in the count: 16 is worse than 4 and 64. - config.merge_accuracy = BTreeMap::from([(4, err(0.2)), (16, err(2.0)), (64, err(0.3))]); + let precision = |v: f64| BTreeMap::from([("precision_at_k".into(), v)]); + // Precision is not monotone in the count: 16 is worse than 4 and 64. + config.merge_accuracy = BTreeMap::from([ + (4, precision(0.8)), + (16, precision(0.1)), + (64, precision(0.7)), + ]); let at_window = |window_ms| Deployment { capability: Capability::TopKByValue, metric: METRIC.into(), @@ -540,15 +542,15 @@ mod tests { #[test] fn undeployable_families_are_candidates_only_when_allowed() { - let r = Raqe { - capability: Capability::Quantile, - ..raqe("r", 60_000, 60_000) - }; + let r = raqe("r", 60_000, 60_000); let named = |sketch: &str| AtomicCostEntry { sketch: sketch.into(), ..cost() }; - let costs = [named("kll-percall"), named("dd")]; + let costs = [ + named("cms-heap-topk-fastpath-vector2d"), + named("countsketch-heap-topk-fastpath-vector2d"), + ]; let candidates = build_all_candidates( std::slice::from_ref(&r), &costs, @@ -557,9 +559,13 @@ mod tests { &table_accuracy, ); assert!(!candidates.is_empty()); - assert!(candidates.iter().all(|d| d.config.sketch == "kll-percall")); + assert!(candidates + .iter() + .all(|d| d.config.sketch == "cms-heap-topk-fastpath-vector2d")); let all = build_all_candidates_unpruned(&[r], &costs, &facts(1, 1), true); - assert!(all.iter().any(|d| d.config.sketch == "dd")); + assert!(all + .iter() + .any(|d| d.config.sketch == "countsketch-heap-topk-fastpath-vector2d")); } #[test] @@ -742,7 +748,7 @@ mod tests { sketch: "hydra-kll".into(), mem_bytes_per_instance: 1000.0, query_accuracy: BTreeMap::from([ - ("err".into(), 0.1), + ("mean_rank_err".into(), 0.1), ("subpopulations".into(), subpopulations), ]), ..cost() diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 20c2ed53..d7873381 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -127,13 +127,11 @@ pub fn for_each_mapping_while( mod tests { use super::*; use crate::candidates; - use crate::test_support::{facts, METRIC}; + use crate::test_support::{facts, perfect_accuracy, METRIC}; use crate::{table_accuracy, AtomicCostEntry, Capability, Deployment, LabelSet}; use std::collections::BTreeMap; fn cost(sketch: &str) -> AtomicCostEntry { - let mut query_accuracy = BTreeMap::new(); - query_accuracy.insert("err".to_string(), 0.01); AtomicCostEntry { sketch: sketch.to_string(), sketch_config: serde_json::json!(null), @@ -141,7 +139,7 @@ mod tests { insert_cpu_secs: 1.0, merge_cpu_secs: 1.0, query_cpu_secs: 1.0, - query_accuracy, + query_accuracy: perfect_accuracy(), merge_accuracy: BTreeMap::new(), measured_at: None, } @@ -160,9 +158,7 @@ mod tests { metric: METRIC.into(), spatial_filter: String::new(), grouping_labels: LabelSet::new(), - accuracy_metric: "err".to_string(), - accuracy_sla: 1.0, - accuracy_direction: crate::AccuracyDirection::LowerIsBetter, + accuracy_sla: 0.5, latency_sla_ms: None, } } diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index ecfa12cb..31e68f67 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -117,6 +117,7 @@ pub const DEPLOYABLE_FAMILIES: &[&str] = &[ "exact-max", // MultipleMinMax, sub_type "max" "exact-increase", // MultipleIncrease "kll-percall", // DatasketchesKLL + "dd", // DDSketch "hll", // HLL "cms-heap-topk-fastpath-vector2d", // CountMinSketchWithHeap ]; @@ -141,35 +142,46 @@ pub struct FamilyProperties { /// Answers without error, so its accuracy comes from the cost table /// rather than a saturation curve. pub exact: bool, + /// The accuracy key this variant's comparator reports, and which way it + /// runs. `None` only for [`KEY_TRACKER_FAMILY`], which is never checked. + pub accuracy: Option<(&'static str, AccuracyDirection)>, } /// Panics on a variant with no entry: guessing would misprice it. +/// Accuracy keys mirror the comparator `export_rqe_optimizer_costs.sh` runs +/// per variant. pub fn family_properties(variant: &str) -> FamilyProperties { - let one_sketch_per_group = FamilyProperties { + use AccuracyDirection::{HigherIsBetter, LowerIsBetter}; + let one_sketch_per_group = |metric, direction| FamilyProperties { mergeable_across_windows: true, one_fixed_size_sketch_for_all_groups: false, needs_delta_set_key_tracker: false, exact: false, + accuracy: Some((metric, direction)), + }; + // `relative_error` is the worst group's, not `relative_error_mean`. + let exact = FamilyProperties { + exact: true, + ..one_sketch_per_group("relative_error", LowerIsBetter) }; match variant { - "exact-sum" | "exact-min" | "exact-max" | "exact-increase" | KEY_TRACKER_FAMILY => { - FamilyProperties { - exact: true, - ..one_sketch_per_group - } - } - "kll-percall" - | "dd" - | "hll" - | "univmon-cardinality" - | "cms-heap-topk-fastpath-vector2d" + "exact-sum" | "exact-min" | "exact-max" | "exact-increase" => exact, + KEY_TRACKER_FAMILY => FamilyProperties { + accuracy: None, + ..exact + }, + "hll" | "univmon-cardinality" => one_sketch_per_group("relative_error", LowerIsBetter), + "kll-percall" => one_sketch_per_group("mean_rank_err", LowerIsBetter), + "dd" => one_sketch_per_group("mean_relative_value_error", LowerIsBetter), + "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" - | "univmon-topk" => one_sketch_per_group, + | "univmon-topk" => one_sketch_per_group("precision_at_k", HigherIsBetter), "hydra-kll" => FamilyProperties { mergeable_across_windows: true, one_fixed_size_sketch_for_all_groups: true, needs_delta_set_key_tracker: true, exact: false, + accuracy: Some(("mean_rank_err", LowerIsBetter)), }, _ => panic!("{variant} has no FamilyProperties; add it to family_properties"), } @@ -216,6 +228,23 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec= 0, and every + // higher-is-better one is a fraction (precision), so its floor is <= 1. + let sla = raqe.accuracy_sla; + let floors_a_fraction = raqe.capability.families().iter().any(|family| { + family_properties(family) + .accuracy + .is_some_and(|(_, direction)| direction == AccuracyDirection::HigherIsBetter) + }); + let max = if floors_a_fraction { + 1.0 + } else { + f64::INFINITY + }; + if !(sla.is_finite() && (0.0..=max).contains(&sla)) { + problems.insert(format!("{id}: accuracy SLA {sla} is outside [0, {max}]")); + } if let Some(limit) = raqe.latency_sla_ms { if !(limit.is_finite() && limit > 0.0) { problems.insert(format!("{id}: latency SLA {limit} ms is not positive")); @@ -279,9 +308,9 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec, } impl Raqe { - /// The one place comparison direction is decided -- both the - /// candidate prefilter and eligibility route here so they can't drift. - pub fn accuracy_ok(&self, value: f64) -> bool { - match self.accuracy_direction { - AccuracyDirection::LowerIsBetter => value <= self.accuracy_sla, - AccuracyDirection::HigherIsBetter => value >= self.accuracy_sla, - } + /// Whether `accuracy`, in `sketch`'s [`accuracy_key`], clears the SLA. + /// Unknown or non-finite never passes. The MILP's eligibility and the + /// AutoSketch baseline both decide here. + pub fn meets_sla(&self, sketch: &str, accuracy: Option) -> bool { + let (_, direction) = accuracy_key(sketch); + accuracy.is_some_and(|value| { + value.is_finite() + && match direction { + AccuracyDirection::LowerIsBetter => value <= self.accuracy_sla, + AccuracyDirection::HigherIsBetter => value >= self.accuracy_sla, + } + }) } +} - /// Whether `accuracy` clears the SLA. Unknown or non-finite never passes. - /// The MILP's eligibility and the AutoSketch baseline both decide here. - pub fn meets_sla(&self, accuracy: Option) -> bool { - accuracy.is_some_and(|value| value.is_finite() && self.accuracy_ok(value)) - } +/// `sketch`'s [accuracy metric](FamilyProperties::accuracy) and direction. +/// Panics for [`KEY_TRACKER_FAMILY`], which is never a candidate. +pub fn accuracy_key(sketch: &str) -> (&'static str, AccuracyDirection) { + family_properties(sketch) + .accuracy + .unwrap_or_else(|| panic!("{sketch} has no accuracy metric, so it can't be a candidate")) } /// The accuracy `raqe` gets from a deployment, or `None` when unknown -- @@ -348,23 +380,31 @@ pub type Accuracy<'a> = dyn Fn(&Raqe, &Deployment) -> Option + 'a; /// The cost table's measured value after the query's `L / x` merges, which is /// the exact accumulators' accuracy. pub fn table_accuracy(raqe: &Raqe, deployment: &Deployment) -> Option { - table_accuracy_at( - raqe, + Some(table_accuracy_at( &deployment.config, raqe.lookback_ms / deployment.window_ms, - ) + )) } /// The worse of `config`'s scores at the two measured counts bracketing -/// `merges` (error is not monotone in the count). Missing at either is `None`. -pub fn table_accuracy_at(raqe: &Raqe, config: &AtomicCostEntry, merges: u64) -> Option { - let [below, above] = - accuracy_at(config, merges).map(|scores| scores.get(&raqe.accuracy_metric).copied()); - let (below, above) = (below?, above?); - Some(match raqe.accuracy_direction { +/// `merges` (error is not monotone in the count), in its family's +/// [`accuracy_key`]. Panics when either lacks it: the family table names +/// the metric, so its absence means the cost export is broken. +pub fn table_accuracy_at(config: &AtomicCostEntry, merges: u64) -> f64 { + let (metric, direction) = accuracy_key(&config.sketch); + let [below, above] = accuracy_at(config, merges).map(|scores| { + *scores.get(metric).unwrap_or_else(|| { + panic!( + "{} {} has no {metric}; the cost export is broken \ + (dd omits it when every true quantile is 0 or unanswered)", + config.sketch, config.sketch_config + ) + }) + }); + match direction { AccuracyDirection::LowerIsBetter => below.max(above), AccuracyDirection::HigherIsBetter => below.min(above), - }) + } } /// `config`'s scores at the two measured merge counts bracketing `merges`: @@ -455,6 +495,20 @@ pub(crate) mod test_support { pub const METRIC: &str = "m"; + /// Clears an SLA of 0.5 on every family's metric: errors 0, precision 1, + /// so a row renamed to any family stays feasible. + pub fn perfect_accuracy() -> BTreeMap { + [ + "relative_error", + "mean_rank_err", + "mean_relative_value_error", + ] + .map(|metric| (metric.to_string(), 0.0)) + .into_iter() + .chain([("precision_at_k".to_string(), 1.0)]) + .collect() + } + /// `groups` groups and `series` raw series scraped every second, so /// `λ = series`. Not validated: unit tests set `groups` freely. pub fn facts(groups: u64, series: u64) -> WorkloadFacts { @@ -480,9 +534,7 @@ pub(crate) mod test_support { metric: METRIC.into(), spatial_filter: String::new(), grouping_labels: LabelSet::new(), - accuracy_metric: "err".into(), - accuracy_sla: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, + accuracy_sla: 0.5, latency_sla_ms: None, } } @@ -508,7 +560,7 @@ pub(crate) mod test_support { insert_cpu_secs: insert, merge_cpu_secs: merge, query_cpu_secs: query, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), + query_accuracy: perfect_accuracy(), merge_accuracy: BTreeMap::new(), measured_at: None, }, @@ -533,6 +585,7 @@ mod tests { let mut config = deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config; let scores = |v: f64| BTreeMap::from([("err".to_string(), v)]); let at = |c: &AtomicCostEntry, merges| accuracy_at(c, merges).map(|s| s["err"]); + config.query_accuracy = scores(0.0); // No merge measurements: every count reads the single instance. assert_eq!(at(&config, 60), [0.0, 0.0]); config.merge_accuracy = @@ -552,7 +605,7 @@ mod tests { #[test] fn both_brackets_must_clear_a_higher_is_better_metric() { let mut config = deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config; - let precision = |v: f64| BTreeMap::from([("p".to_string(), v)]); + let precision = |v: f64| BTreeMap::from([("precision_at_k".to_string(), v)]); config.query_accuracy = precision(1.0); config.merge_accuracy = BTreeMap::from([ (4, precision(0.97)), @@ -560,12 +613,10 @@ mod tests { (64, precision(1.0)), ]); let r = Raqe { - accuracy_metric: "p".into(), accuracy_sla: 0.9, - accuracy_direction: AccuracyDirection::HigherIsBetter, ..raqe(60_000, 60_000) }; - let ok = |merges| table_accuracy_at(&r, &config, merges).is_some_and(|v| r.accuracy_ok(v)); + let ok = |merges| r.meets_sla(&config.sketch, Some(table_accuracy_at(&config, merges))); assert!(ok(1)); assert!(ok(4)); assert!(!ok(8)); // [4, 16]: 16 fails @@ -575,6 +626,40 @@ mod tests { assert!(ok(5_000)); // beyond: [64, 64] } + /// One quantile SLA: KLL is checked by rank error, DD by relative value + /// error, each against the same number. + #[test] + fn one_quantile_raqe_checks_each_family_by_its_own_metric() { + let r = Raqe { + capability: Capability::Quantile, + accuracy_sla: 0.05, + ..raqe(60_000, 60_000) + }; + let row = |sketch: &str, metric: &str, value: f64| AtomicCostEntry { + sketch: sketch.into(), + query_accuracy: BTreeMap::from([(metric.to_string(), value)]), + ..deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config + }; + let ok = |c: AtomicCostEntry| r.meets_sla(&c.sketch, Some(table_accuracy_at(&c, 1))); + assert!(ok(row("kll-percall", "mean_rank_err", 0.01))); + assert!(!ok(row("kll-percall", "mean_rank_err", 0.1))); + assert!(ok(row("dd", "mean_relative_value_error", 0.01))); + assert!(!ok(row("dd", "mean_relative_value_error", 0.1))); + } + + /// DD omits its metric when every true quantile is 0; a row without it + /// must not pass, nor be skipped silently. + #[test] + #[should_panic(expected = "dd null has no mean_relative_value_error")] + fn a_row_missing_its_familys_metric_panics() { + let config = AtomicCostEntry { + sketch: "dd".into(), + query_accuracy: BTreeMap::from([("mean_rank_err".to_string(), 0.0)]), + ..deployment(0.0, 0.0, 0.0, 0.0, 60_000, 60_000).config + }; + table_accuracy_at(&config, 1); + } + #[test] fn every_deployable_family_serves_a_capability() { for family in DEPLOYABLE_FAMILIES { @@ -699,6 +784,34 @@ mod tests { assert!(problems[1].starts_with("zero: lookback and interval must be nonzero")); } + /// No metric can meet a negative SLA, nor a precision floor above 1; an + /// error ceiling above 1 is merely loose. + #[test] + fn rejects_an_accuracy_sla_no_metric_can_meet() { + let sla = |id: &str, capability, accuracy_sla| Raqe { + id: id.into(), + capability, + accuracy_sla, + ..raqe(60_000, 60_000) + }; + let raqes = [ + sla("negative", Capability::Quantile, -0.1), + sla("nan", Capability::Quantile, f64::NAN), + sla("precision_above_1", Capability::TopKByValue, 1.5), + sla("loose_error", Capability::Cardinality, 1.5), + sla("exact_precision", Capability::TopKByValue, 1.0), + ]; + let problems = validate_facts(&raqes, &test_support::facts(1, 1)).unwrap_err(); + assert_eq!( + problems, + [ + "nan: accuracy SLA NaN is outside [0, inf]", + "negative: accuracy SLA -0.1 is outside [0, inf]", + "precision_above_1: accuracy SLA 1.5 is outside [0, 1]", + ] + ); + } + #[test] fn rejects_more_groups_than_series() { let facts = WorkloadFacts::from([( diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index e254ad1e..beda553b 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -18,8 +18,8 @@ use std::path::Path; use crate::autosketch::window_adapter; use crate::{ - family_properties, table_accuracy, AccuracyDirection, AtomicCostEntry, Deployment, LabelSet, - MetricFacts, Raqe, WorkloadFacts, + accuracy_key, family_properties, table_accuracy, AccuracyDirection, AtomicCostEntry, + Capability, Deployment, LabelSet, MetricFacts, Raqe, WorkloadFacts, }; use aqpbm_core::MeasuredShape; @@ -152,7 +152,8 @@ pub struct SaturationCurves { impl SaturationCurves { /// Reads `saturation.csv` (for the saturation point) and `saturation_curve.csv` from - /// each of [`RUN_DIRS`] under `dir`. + /// each of [`RUN_DIRS`] under `dir`. Fails on a candidate family's curve + /// for a metric other than its [`accuracy_key`]: that study is stale. pub fn load(dir: &Path) -> io::Result { type PointKey = (String, String, String, String, String); let key = |row: &CsvRow| -> PointKey { @@ -180,6 +181,18 @@ impl SaturationCurves { }, curve: Vec::new(), }; + let sketch = row["sketch"].as_str(); + let is_candidate = Capability::ALL + .iter() + .any(|capability| capability.families().contains(&sketch)); + if is_candidate && point.error_metric != accuracy_key(sketch).0 { + return Err(invalid(format!( + "{run}: {sketch} curve measured {}, but the optimizer reads {}; \ + rerun the study", + point.error_metric, + accuracy_key(sketch).0 + ))); + } run_points.insert(key(&row), (row["sketch"].clone(), point)); } for row in read_csv(&run_dir.join("saturation_curve.csv"))? { @@ -205,8 +218,9 @@ impl SaturationCurves { } /// The accuracy `raqe` gets from `deployment`, or `None` when it can't be - /// read: no fitted [`DataShape`], a config or shape outside the grid, the - /// wrong metric, or too few items. + /// read: no fitted [`DataShape`], a config or shape outside the grid, or + /// too few items. [`SaturationCurves::load`] guarantees the curve's metric + /// is the family's. /// Exact accumulators keep the cost table's value. `facts` must pass /// [`crate::validate_facts`]. pub fn accuracy( @@ -223,13 +237,11 @@ impl SaturationCurves { let shape = metric_facts.data_shape.get(grouping)?; let points = self.bracketing_points(&deployment.config, shape)?; let covered = items_per_group(metric_facts, grouping, raqe.lookback_ms); + let (_, direction) = accuracy_key(&deployment.config.sketch); let mut worst = None; for point in points { - if point.error_metric != raqe.accuracy_metric { - return None; - } - let error = point.error_at(covered, raqe.accuracy_direction)?; - worst = Some(worst.map_or(error, |w| worse(w, error, raqe.accuracy_direction))); + let error = point.error_at(covered, direction)?; + worst = Some(worst.map_or(error, |w| worse(w, error, direction))); } worst } @@ -490,8 +502,6 @@ mod tests { fn topk_raqe(lookback_ms: u64) -> Raqe { Raqe { capability: Capability::TopKByValue, - accuracy_metric: "precision_at_k".into(), - accuracy_direction: AccuracyDirection::HigherIsBetter, ..raqe(lookback_ms, lookback_ms) } } @@ -559,19 +569,6 @@ mod tests { assert_eq!(curves().accuracy(&r, &d, &facts(1, 10)), None); } - #[test] - fn a_metric_the_curve_did_not_measure_has_no_accuracy() { - let facts = workload(10, shape(1.2, 1e3)); - let r = Raqe { - accuracy_metric: "recall_at_k".into(), - ..topk_raqe(1_000_000) - }; - assert_eq!( - curves().accuracy(&r, &deployment(TOPK, 1_000_000), &facts), - None - ); - } - #[test] fn merged_answers_read_the_curve_at_the_lookback_count_whatever_the_window() { // 10 items/s: a 100 s window holds 1e3 items, below the 1e4 @@ -590,8 +587,10 @@ mod tests { #[test] fn exact_accumulators_keep_the_cost_table_value() { let r = topk_raqe(1_000_000); - let value = curves().accuracy(&r, &deployment("exact-sum", 1_000_000), &facts(1, 10)); - assert_eq!(value, Some(1.0)); + let mut d = deployment("exact-sum", 1_000_000); + d.config.query_accuracy = BTreeMap::from([("relative_error".into(), 0.0)]); + let value = curves().accuracy(&r, &d, &facts(1, 10)); + assert_eq!(value, Some(0.0)); } /// A top-k row measured at θ = 1.2, K = 1e3 and `items`, scoring @@ -686,4 +685,35 @@ mod tests { assert_eq!(points[0].shape, MeasuredShape::Pareto { tail_index: 2.0 }); assert_eq!(points[0].params, BTreeMap::from([("k".to_string(), 200.0)])); } + + /// A curve for another metric than the family's, such as DD's max error + /// before #175, is a stale study: refused at load, whatever the lookback. + #[test] + fn load_refuses_a_curve_for_another_metric() { + let dir = std::env::temp_dir().join(format!("rqe-stale-{}", std::process::id())); + let header = "family,sketch,config,dist,param,cardinality"; + let point = "quantile,dd,alpha=0.01,pareto,2.0,"; + for run in RUN_DIRS { + std::fs::create_dir_all(dir.join(run)).unwrap(); + std::fs::write( + dir.join(run).join("saturation.csv"), + format!( + "{header},n_sat,final_error,error_metric\n{point},1e8,0.01,max_relative_value_error\n" + ), + ) + .unwrap(); + std::fs::write( + dir.join(run).join("saturation_curve.csv"), + format!("{header},n,seed_mean_error,seed_se\n"), + ) + .unwrap(); + } + let loaded = SaturationCurves::load(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + let error = loaded.unwrap_err().to_string(); + assert!( + error.contains("dd curve measured max_relative_value_error"), + "{error}" + ); + } }