diff --git a/Cargo.lock b/Cargo.lock index 8c52dbca..2945fd27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2303,6 +2303,7 @@ name = "rqe-optimizer" version = "0.1.0" dependencies = [ "aqpbm-core", + "csv", "good_lp", "serde_json", ] diff --git a/aqpbm-core/src/atomic_costs.rs b/aqpbm-core/src/atomic_costs.rs index 11ce9cdf..24c8414a 100644 --- a/aqpbm-core/src/atomic_costs.rs +++ b/aqpbm-core/src/atomic_costs.rs @@ -765,5 +765,15 @@ mod tests { json, r#"{"sketch":"cms","sketch_config":{"algorithm":"cms","params":{"cols":1024,"rows":3}},"mem_bytes_per_instance":12288.0,"insert_cpu_secs":5e-7,"merge_cpu_secs":0.01,"query_cpu_secs":4e-6,"query_accuracy":{"relative_error_mean":0.01},"accuracy_metric":"relative_error_mean","measured_at":{"items_per_instance":1000000,"keys_per_instance":10000,"value_range":null,"merge_operand_items":null,"distribution":null}}"# ); + // A Hydra row also names its dataset and schema width; other rows + // leave both out, and rows written before them still load. + let hydra = MeasuredAt { + dataset: Some("hydra_http".into()), + schema_width: Some(4), + ..entry.measured_at.clone() + }; + let json = serde_json::to_string(&hydra).unwrap(); + assert!(json.ends_with(r#""distribution":null,"dataset":"hydra_http","schema_width":4}"#)); + assert_eq!(serde_json::from_str::(&json).unwrap(), hydra); } } diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index df192695..463f627e 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -222,10 +222,18 @@ univmon-cardinality, KLL and DDSketch. These don't, and serve only only bare `rate`/`increase`, which keep every label.) - **Top-k** (CMS-heap, CountSketch-heap, univmon-topk). A coarse group's top `k` can hold keys that are in none of its fine groups' heaps. -- **Hydra**. It inserts every label subset of its schema, so a coarse - grouping inside the schema is answered directly from the grid, never by - merging fine groups; it is not a candidate today - ([Hydra](rqe_optimizer_hydra.md)). +- **Hydra** (hydra-hll, hydra-univmon-cardinality, hydra-kll; planned only + with undeployable families allowed). It inserts every label subset of its + schema `Λ`, so any non-empty `G_r ⊆ Λ` is answered directly from the grid, + never by merging fine groups. A metric with a Hydra dataset + (`MetricFacts::hydra_dataset`) gets one grid per (capability, filter, + window, slide, config), over its full schema only (every schema label, + not the per-series ones), because that is the width the study measures + cost and accuracy at; its cost rows must name that dataset + (`measured_at.dataset`). Its accuracy is held to the worst case: the max + error over the covered groups, worst over the measured N and seeds + (`hydra_saturation.csv`), while per-group sketches read seed-mean curves. + The design is in [Hydra](rqe_optimizer_hydra.md). - **Cost**: ingest, compaction and storage stay at `G_d`; the query job merges `I_d · n − I_r` times and answers `card(G_r)` groups diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index f2f13972..da7916c4 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -18,8 +18,9 @@ is in [Hydra](rqe_optimizer_hydra.md). query memory is summed as if concurrent, there is no worker fan-out or compaction, and latency is serial query work. It is not the evaluation's billing model. -- **Hydra** is future work, not a candidate today; see - [Hydra](rqe_optimizer_hydra.md). +- **Hydra** is a Shared + Fixed sketch (below), a candidate only with + undeployable families allowed, built over a metric's full schema + ([Candidates](rqe_optimizer_candidates.md), roll-ups section). The two implemented objectives share the same resource primitives and §3's table; they differ in how they account for them over time, and in latency @@ -375,14 +376,13 @@ The model uses `I_d × m`, where `I_d` is instances per window: (`groups_per_instance`), making `m` a per-group cost. Their query cost is already per group. - Shared + Fixed: `I_d = 1`. In code this is the family property - `one_fixed_size_sketch_for_all_groups`, true only for HydraKLL. It applies + `one_fixed_size_sketch_for_all_groups`, true only for the Hydra families. It applies to memory and merge; query stays `card(G_r) × c_qry`, one probe per answered group. - Today's code also requires `card(G_d)` to be at most the `subpopulations` - its row was measured at. That is necessary, not sufficient: a Hydra - group's error depends on the grid's fanned-out mass against the group's - own size, not on the group count alone, so admission needs the measured - predicate of [Hydra](rqe_optimizer_hydra.md) §2.4. HydraKLL is never a - candidate today, so the check decides nothing. + A fixed-size sketch degrades as groups grow, so Hydra is built only at the + full schema its rows and accuracy were measured at (`measured_at.dataset`, + `hydra_saturation.csv`), and its accuracy is the worst case: max over the + covered groups, worst over N and seeds (per-group sketches read seed-mean + curves). PerGroup + PerKey is deferred until a family needs it: it needs the key labels `K`, the metric's labels minus `G`. So for every family in use, nothing scales @@ -404,8 +404,9 @@ follows from it): A Hydra grid is the Shared + Fixed case, `I_d = I_r = 1`; its row, probes and key tracker are in [Hydra](rqe_optimizer_hydra.md) §3. -HydraKLL has `FamilyProperties` but is in no capability's family list, so it -is never a candidate; see [Hydra](rqe_optimizer_hydra.md). +The Hydra families are in their capabilities' family lists but not in +`DEPLOYABLE_FAMILIES`, so they are candidates only when undeployable families +are allowed (the §6.3 eval runner); AutoSketch skips them (#159). ### Family properties and key tracker diff --git a/docs/rqe_optimizer_hydra.md b/docs/rqe_optimizer_hydra.md index dc3b7945..9a6cc227 100644 --- a/docs/rqe_optimizer_hydra.md +++ b/docs/rqe_optimizer_hydra.md @@ -1,8 +1,10 @@ # RQE optimizer: admitting Hydra -Status: design, not implemented. Hydra is never a candidate today: -`hydra-kll` has `FamilyProperties` (`rqe-optimizer/src/lib.rs`) but is in no -capability's family list, and the other four Hydra variants have none. This +Status: hydra-hll, hydra-univmon-cardinality and hydra-kll are candidates +when undeployable families are allowed (the §6.3 eval runner), built over a +metric's full schema with accuracy from `hydra_saturation.csv` +([Candidates](rqe_optimizer_candidates.md), roll-ups section). They are not +in `DEPLOYABLE_FAMILIES`, so ASAPQuery's planner never sees them. This document says, for each Hydra combination sketch-bench benchmarks, what accuracy guarantee it has, how it is costed, how it would enter the candidates and the MILP, and what sketch-bench must measure first. Symbols diff --git a/rqe-optimizer/Cargo.toml b/rqe-optimizer/Cargo.toml index db343da3..c32dafa5 100644 --- a/rqe-optimizer/Cargo.toml +++ b/rqe-optimizer/Cargo.toml @@ -10,3 +10,4 @@ description = "v1 brute-force solver for the RQE -> sketch-deployment mapping pr aqpbm-core = { workspace = true, default-features = false } serde_json.workspace = true good_lp.workspace = true +csv.workspace = true diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index 11b619d4..b7491266 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -21,10 +21,10 @@ //! versions, in one output file: //! //! - **Version 1, no latency constraint** (`results`): each method's cheapest -//! plan, its latency reported, and ASAP's and PerQuery's cost–latency -//! frontiers (`bound_ms`). +//! plan, its latency reported, and ASAP's (with and without roll-ups) and +//! PerQuery's cost–latency frontiers (`bound_ms`). //! - **Version 2, a batch latency SLA** (`sla_results`): at each SLA of the -//! grid, ASAP's and PerQuery's cheapest plan whose batch latency is at most +//! grid, ASAP's (both) and PerQuery's cheapest plan whose batch latency is at most //! the SLA (`milp::minimize_usage_cost` with `latency_bound_ms`, exact). //! An SLA below a method's tightest feasible bound has no plan //! (`infeasible`). AutoSketch ignores the SLA; its plan is recorded at @@ -38,6 +38,10 @@ //! weights and is priced under each. //! - **PerQuery-CostAware:** `milp::minimize_usage_cost` over each RQE's own //! candidates (separate copies, so no sharing). +//! - **ASAP (no roll-ups)** (`asap-norollup`), an ablation: ASAP's MILP and +//! candidates, with each RQE allowed only deployments at its own grouping +//! or Hydra grids (not a roll-up). Every result counts `rolled_up_rqes`, +//! the RQEs served from a strictly finer non-Hydra deployment. //! //! `traces` reads `data/autosketch-eval/table.json` (alibaba_v2022 and //! google_2011 are evaluated; boom is left out for now); `synthetic` reads one @@ -62,6 +66,16 @@ //! lookback's items; KLL and top-k merged from `L/x` shards read the merge //! curve, #158); AutoSketch reads `autosketch_accuracy` (one unmerged sketch //! per query window, no saturation requirement). +//! +//! Hydra: ASAP and PerQuery plan with undeployable families allowed, so a +//! Hydra grid over a schema metric's full schema competes with per-group +//! sketches (sketch-bench `docs/rqe_optimizer_hydra.md`). Its cost rows and +//! accuracy (`hydra_saturation.csv` under the saturation dir) are measured +//! on the dataset shaped like the stream's metric ([`hydra_dataset`]), at +//! that full schema; without them no Hydra deployment is eligible. Hydra is +//! held to the worst case (max over covered groups, worst over N and seeds), +//! per-group sketches to seed-mean curves. AutoSketch allows undeployable +//! families too but skips Hydra itself (#159). use std::collections::{BTreeMap, BTreeSet}; use std::time::Instant; @@ -293,6 +307,20 @@ fn groups_of(r: &Value, capability: Capability) -> u64 { } } +/// The `hydra_saturation.csv` dataset measured with a schema metric's +/// labels, shares and values (`configs/datagen/hydra_*.yaml`): `http`'s +/// latency for quantiles, its user ids otherwise, and `flows`' sources. +/// `None` for any other metric, which no Hydra deployment serves. +fn hydra_dataset(metric: &str, capability: Capability) -> Option { + let dataset = match (metric.rsplit('/').next()?, capability) { + ("http", Capability::Quantile) => "hydra_http_latency", + ("http", _) => "hydra_http", + ("flows", _) => "hydra_flows", + _ => return None, + }; + Some(dataset.to_string()) +} + fn label_set(names: &[&str]) -> LabelSet { names.iter().map(|s| s.to_string()).collect() } @@ -377,14 +405,25 @@ fn from_table( let series = (rate * SCRAPE_MS as f64 / 1000.0).round() as u64; let most = stream_series.entry(stream.clone()).or_default(); *most = (*most).max(series); + let most = *most; + // A schema metric's full schema (its labels without `x`) and its + // groups: the product of every label's fan-out, as the generator's + // grouping_cardinality (the full set holds every child's parent). + let full_schema: Option<(LabelSet, u64)> = schema["labels"].as_array().map(|labels| { + let names = labels + .iter() + .map(|l| l["name"].as_str().unwrap().to_string()) + .collect(); + let groups = labels + .iter() + .map(|l| l["cardinality"].as_u64().unwrap()) + .product(); + (names, groups) + }); let metric = facts.entry(stream.clone()).or_insert_with(|| { - let mut labels: LabelSet = match schema["labels"].as_array() { - Some(labels) => labels - .iter() - .map(|l| l["name"].as_str().unwrap().to_string()) - .collect(), - None => label_set(&["g"]), - }; + let mut labels = full_schema + .as_ref() + .map_or_else(|| label_set(&["g"]), |(names, _)| names.clone()); labels.insert("x".to_string()); MetricFacts { cardinality: [(labels.clone(), 0), (LabelSet::new(), 1)].into(), @@ -392,6 +431,10 @@ fn from_table( scrape_interval_ms: SCRAPE_MS, value_range: None, data_shape: BTreeMap::new(), + // A stream is one value of its metric, so one capability. + hydra_dataset: full_schema.as_ref().and_then(|(names, _)| { + Some((hydra_dataset(metric, capability)?, names.clone())) + }), } }); // A stream's RQEs may see different group counts (keys per window @@ -400,6 +443,12 @@ fn from_table( *card = (*card).max(groups); let total = metric.cardinality.get_mut(&metric.labels).unwrap(); *total = (*total).max(series).max(groups); + // The full schema (a Hydra grid's, and its tracker's keys), capped at + // the stream's series so it doesn't make the stream high-cardinality. + if let Some((names, groups)) = full_schema { + let card = metric.cardinality.entry(names).or_default(); + *card = (*card).max(groups.min(most)); + } // Queries one evaluation issues per instance (the table's q_r); tables // written before it existed charge one query phase per evaluation. let queries = r["queries_per_instance"].as_f64().unwrap_or(1.0); @@ -448,6 +497,7 @@ fn from_table( accuracy_sla: rqe_target.unwrap_or(0.0), latency_sla_ms: None, topk_k: topk_k_of(r, capability), + accuracy_covers_share: r.get("covers_share").and_then(Value::as_f64), }); } // Every stream may use every row; one evaluation runs q_r queries per @@ -566,15 +616,14 @@ fn group_by_stream(raqes: &[Raqe]) -> BTreeMap<&str, Vec> { out } -/// ASAP candidates, built per stream from that stream's entries. +/// ASAP candidates, built per stream from that stream's entries, with +/// undeployable families (Hydra) allowed. fn candidates(w: &Workload, raqes: &[Raqe]) -> Vec { group_by_stream(raqes) .into_iter() .flat_map(|(stream, group)| { let costs = w.costs.get(stream).map_or(&[][..], Vec::as_slice); - build_all_candidates(&group, costs, &w.facts, false, &|r, d| { - w.asap_accuracy(r, d) - }) + build_all_candidates(&group, costs, &w.facts, true, &|r, d| w.asap_accuracy(r, d)) }) .collect() } @@ -591,7 +640,9 @@ fn autosketch_plan( for (stream, group) in group_by_stream(raqes) { let costs = w.costs.get(stream).map_or(&[][..], Vec::as_slice); let oracle = |r: &Raqe, c: &AtomicCostEntry| w.autosketch_accuracy(r, c); - match autosketch::plan(&group, costs, SEED, false, oracle) { + // Undeployable families allowed, as for ASAP: AutoSketch skips + // Hydra itself (#159), so every method sees the same other families. + match autosketch::plan(&group, costs, SEED, true, oracle) { Ok(plan) => { deployments.extend(plan.deployments); searches.extend(plan.searches); @@ -617,6 +668,13 @@ fn autosketch_plan( }) } +/// Whether `d` serves `r` as a roll-up: a non-Hydra deployment at another +/// grouping (one that serves `r` is strictly finer). A Hydra grid answers any +/// subgrouping directly. +fn is_rollup(r: &Raqe, d: &Deployment) -> bool { + !d.properties().answers_any_subgrouping && d.grouping_labels != r.grouping_labels +} + /// A plan priced by use (`usage::usage_cost`): its cost, CPU and memory by /// part, its latency (the longest chain) and each RQE's choice. fn summarize( @@ -656,6 +714,15 @@ fn summarize( .sum(); let latencies: Vec = load.queries.iter().map(|q| q.chain_ms).collect(); let active: BTreeSet = mapping.iter().copied().collect(); + let hydra_rqes = mapping + .iter() + .filter(|&&d| deployments[d].properties().answers_any_subgrouping) + .count(); + let rolled_up_rqes = raqes + .iter() + .zip(mapping) + .filter(|(r, &d)| is_rollup(r, &deployments[d])) + .count(); let chosen: Vec = raqes .iter() .zip(mapping) @@ -677,7 +744,8 @@ fn summarize( .accuracy_with_source(r, d) .map(|(_, source)| format!("{source:?}")), }); - // A roll-up: the deployment is grouped finer than the RQE. + // A roll-up or a Hydra grid: the deployment is grouped finer than + // the RQE. if d.grouping_labels != r.grouping_labels { choice["deployment_grouping"] = json!(d.grouping_labels); } @@ -687,7 +755,7 @@ fn summarize( choice }) .collect(); - json!({ + let mut v = json!({ "objective": cost.value, "cpu": cost.cpu, "gib": gib(cost.bytes), @@ -701,8 +769,14 @@ fn summarize( "latency_ms": cost.latency_ms, "median_latency_ms": (!latencies.is_empty()).then(|| median(latencies.clone())), "active_deployments": active.len(), + "rolled_up_rqes": rolled_up_rqes, "chosen": chosen, - }) + }); + // Only workloads Hydra may serve report it, so others read as before. + if w.facts.values().any(|m| m.hydra_dataset.is_some()) { + v["hydra_rqes"] = json!(hydra_rqes); + } + v } /// `--slas-ms`: comma-separated SLAs in ms, each positive and finite. @@ -880,6 +954,16 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 perquery_candidates.extend(own); } let perquery_build_secs = started.elapsed().as_secs_f64(); + // ASAP without roll-ups: ASAP's candidates, each RQE kept off any finer + // non-Hydra deployment. + let norollup_allowed: Vec> = raqes + .iter() + .map(|r| { + (0..asap_candidates.len()) + .filter(|&d| !is_rollup(r, &asap_candidates[d])) + .collect() + }) + .collect(); // AutoSketch's plan ignores the weights and latency: one point. let auto_latency_ms = usage_cost( @@ -890,6 +974,7 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 .latency_ms; let asap_tightest = tightest_bound_ms(w, &raqes, &asap_candidates, None); let perquery_tightest = tightest_bound_ms(w, &raqes, &perquery_candidates, Some(&allowed)); + let norollup_tightest = tightest_bound_ms(w, &raqes, &asap_candidates, Some(&norollup_allowed)); let mut results = Vec::new(); let mut sla_results = Vec::new(); @@ -929,6 +1014,17 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 } Err(e) => json!({"error": e.to_string()}), }; + let (norollup, norollup_solve_secs) = + solve(&asap_candidates, Some(&norollup_allowed), None); + let norollup = match norollup { + Ok(s) => { + let mut v = summarize(w, &raqes, &asap_candidates, &s.mapping, w_cpu, w_mem); + v["planning_secs"] = json!(median(build_secs.clone()) + norollup_solve_secs); + v["candidates"] = json!(asap_candidates.len()); + v + } + Err(e) => json!({"error": e.to_string()}), + }; let (perquery, perquery_solve_secs) = solve(&perquery_candidates, Some(&allowed), None); let mut perq = match perquery { Ok(s) => summarize(w, &raqes, &perquery_candidates, &s.mapping, w_cpu, w_mem), @@ -940,13 +1036,32 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 auto["probes"] = json!(probes); auto["benchmark_secs_paper_rate"] = json!(paper_secs); - // ASAP costs no more than PerQuery, nor than AutoSketch when every - // AutoSketch choice is one ASAP could make. + // ASAP costs no more than without roll-ups, which costs no more than + // PerQuery (whose own candidates are at each RQE's grouping or + // Hydra), nor than AutoSketch when every AutoSketch choice is one ASAP + // could make. let cost = |v: &Value| v["objective"].as_f64(); - if let (Some(a), Some(b)) = (cost(&asap), cost(&perq)) { - if a > b * (1.0 + 1e-6) { - sanity.push(json!({"check": "asap <= perquery", "weights": weight_name, "asap": a, "perquery": b})); + // `sanity` gets a violation of `cheaper <= dearer`, both solved. + let ordered = |sanity: &mut Vec, + at: Value, + cheaper: (&str, &Value), + dearer: (&str, &Value)| { + if let (Some(a), Some(b)) = (cost(cheaper.1), cost(dearer.1)) { + if a > b * (1.0 + 1e-6) { + let mut v = json!({"check": format!("{} <= {}", cheaper.0, dearer.0), "weights": weight_name, (cheaper.0): a, (dearer.0): b}); + v.as_object_mut() + .unwrap() + .extend(at.as_object().unwrap().clone()); + sanity.push(v); + } } + }; + for (cheaper, dearer) in [ + (("asap", &asap), ("asap-norollup", &norollup)), + (("asap-norollup", &norollup), ("perquery", &perq)), + (("asap", &asap), ("perquery", &perq)), + ] { + ordered(&mut sanity, json!({}), cheaper, dearer); } if let (Some(a), Some(b)) = (cost(&asap), cost(&auto)) { let not_eligible: Vec<&str> = raqes @@ -959,8 +1074,11 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 sanity.push(json!({"check": "asap <= autosketch", "weights": weight_name, "asap": a, "autosketch": b})); } } - if asap.get("error").is_some() || perq.get("error").is_some() { - sanity.push(json!({"check": "every method solves", "weights": weight_name, "asap": asap.get("error"), "perquery": perq.get("error")})); + if [&asap, &norollup, &perq] + .iter() + .any(|v| v.get("error").is_some()) + { + sanity.push(json!({"check": "every method solves", "weights": weight_name, "asap": asap.get("error"), "asap-norollup": norollup.get("error"), "perquery": perq.get("error")})); } // The frontiers: the cheapest plan at most `L` slow, for a sweep of @@ -968,6 +1086,13 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 // at AutoSketch's latency. for (method, candidates, allowed, tightest, unbounded) in [ ("asap", &asap_candidates, None, asap_tightest, &asap), + ( + "asap-norollup", + &asap_candidates, + Some(&norollup_allowed[..]), + norollup_tightest, + &norollup, + ), ( "perquery", &perquery_candidates, @@ -1007,6 +1132,12 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 let mut at_sla = Vec::new(); for (method, candidates, allowed, tightest) in [ ("asap", &asap_candidates, None, asap_tightest), + ( + "asap-norollup", + &asap_candidates, + Some(&norollup_allowed[..]), + norollup_tightest, + ), ( "perquery", &perquery_candidates, @@ -1034,10 +1165,13 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 v["method"] = json!(method); at_sla.push(v); } - if let (Some(a), Some(b)) = (cost(&at_sla[0]), cost(&at_sla[1])) { - if a > b * (1.0 + 1e-6) { - sanity.push(json!({"check": "asap <= perquery at the SLA", "weights": weight_name, "sla_ms": sla, "asap": a, "perquery": b})); - } + for (i, j) in [(0, 1), (1, 2), (0, 2)] { + ordered( + &mut sanity, + json!({"sla_ms": sla}), + (at_sla[i]["method"].as_str().unwrap(), &at_sla[i]), + (at_sla[j]["method"].as_str().unwrap(), &at_sla[j]), + ); } let mut v = auto.clone(); v["meets_sla"] = json!(meets_sla(auto_latency_ms, sla)); @@ -1051,7 +1185,12 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 } } - for (method, value) in [("asap", asap), ("autosketch", auto), ("perquery", perq)] { + for (method, value) in [ + ("asap", asap), + ("asap-norollup", norollup), + ("autosketch", auto), + ("perquery", perq), + ] { let mut v = value; v["method"] = json!(method); v["weights"] = json!(weight_name); @@ -1076,6 +1215,7 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 "points": FRONTIER_POINTS, "asap_tightest_bound_ms": asap_tightest, "perquery_tightest_bound_ms": perquery_tightest, + "asap_norollup_tightest_bound_ms": norollup_tightest, "autosketch_latency_ms": auto_latency_ms, }, "autosketch": { @@ -1168,40 +1308,59 @@ mod tests { dir } - #[test] - fn a_schema_stream_carries_every_grouping_and_rolls_up() { - let rqe = |grouping: &[&str], groups: u64, covers: Option, smallest: f64| { - json!({ - "id": format!("t/{}", grouping.join(",")), "query_id": "q", "kind": "keys", - "capability": "cardinality", "metric": "http", "stream": "http/user_id", - "grouping": grouping, "covers_share": covers, "min_covered_share": smallest, - "max_covered_share": 0.5, - "lookback_secs": 300, "interval_secs": 60, "queries_per_instance": 1, - "label_set": {"groups": groups, "arrival_rate_per_sec": 2e6}, - "families": [{"family": "hll", "sketch": "hll", "target": 0.02, - "grid_param": 0.0, "grid_K": 1e6}], - }) - }; - let names = ["region", "service", "endpoint", "status"]; + /// An HLL RQE on `http`'s user ids, grouped by `grouping`. + fn http_rqe(grouping: &[&str], groups: u64, covers: Option, smallest: f64) -> Value { + json!({ + "id": format!("t/{}", grouping.join(",")), "query_id": "q", "kind": "keys", + "capability": "cardinality", "metric": "http", "stream": "http/user_id", + "grouping": grouping, "covers_share": covers, "min_covered_share": smallest, + "max_covered_share": 0.5, + "lookback_secs": 300, "interval_secs": 60, "queries_per_instance": 1, + "label_set": {"groups": groups, "arrival_rate_per_sec": 2e6}, + "families": [{"family": "hll", "sketch": "hll", "target": 0.02, + "grid_param": 0.0, "grid_K": 1e6}], + }) + } + + /// A workload of `rqes` on the `http` schema, on [`hll_saturation_dir`]. + fn http_workload(tag: &str, rqes: Vec) -> Workload { let table = json!({"workloads": [{ "dataset": "synthetic/test", - "schemas": {"http": {"labels": names.map(|n| json!({"name": n}))}}, - "rqes": [ - rqe(&["region"], 4, Some(0.05), 0.05), - rqe(&["region", "service"], 100, None, 0.001), - ], + "schemas": {"http": http_schema()}, + "rqes": rqes, }]}); - let path = std::env::temp_dir().join(format!("schema-table-{}.json", std::process::id())); + let inputs = hll_saturation_dir(tag); + let path = inputs.join("table.json"); std::fs::write(&path, table.to_string()).unwrap(); - let inputs = hll_saturation_dir("schema"); let w = from_table( path.to_str().unwrap(), None, Some("p95".into()), inputs.to_str().unwrap(), ); - std::fs::remove_file(&path).unwrap(); std::fs::remove_dir_all(&inputs).unwrap(); + w + } + + /// The unbounded plan of `method` at the first weight setting. + fn unbounded<'a>(result: &'a Value, method: &str) -> &'a Value { + result["results"] + .as_array() + .unwrap() + .iter() + .find(|r| r["method"] == method && r["bound_ms"].is_null()) + .unwrap() + } + + #[test] + fn a_schema_stream_carries_every_grouping_and_rolls_up() { + let w = http_workload( + "schema", + vec![ + http_rqe(&["region"], 4, Some(0.05), 0.05), + http_rqe(&["region", "service"], 100, None, 0.001), + ], + ); let facts = &w.facts["synthetic/test/http/user_id"]; assert_eq!( facts.labels, @@ -1210,6 +1369,17 @@ mod tests { assert_eq!(facts.cardinality[&label_set(&["region"])], 4); assert_eq!(facts.cardinality[&label_set(&["region", "service"])], 100); assert_eq!(facts.cardinality[&facts.labels], 2_000_000); + // Hydra reads `http`'s user ids over its full schema, at each RQE's + // coverage. + let (dataset, schema) = facts.hydra_dataset.as_ref().unwrap(); + assert_eq!(dataset, "hydra_http"); + assert_eq!( + schema, + &label_set(&["region", "service", "endpoint", "status"]) + ); + assert_eq!(facts.cardinality[schema], 4 * 25 * 25 * 4); + let covers: Vec<_> = w.raqes.iter().map(|r| r.accuracy_covers_share).collect(); + assert_eq!(covers, [Some(0.05), None]); // Accuracy is read at the smallest covered group's items: 5% of the // stream's, so 4 · 5% of the series for {region}'s mean group. let covered = &w.covered_facts["t/region"]["synthetic/test/http/user_id"]; @@ -1219,17 +1389,190 @@ mod tests { assert_eq!(every.cardinality[&every.labels], 200_000); // One {region, service} deployment serves both RQEs. let result = evaluate(&w, 1, &WEIGHTS[..1], &[1e4]); - let asap = result["results"] - .as_array() - .unwrap() - .iter() - .find(|r| r["method"] == "asap" && r["bound_ms"].is_null()) - .unwrap(); + let asap = unbounded(&result, "asap"); assert_eq!(asap["active_deployments"], 1); let coarse = &asap["chosen"][0]; assert_eq!(coarse["rqe"], "t/region"); assert_eq!(coarse["deployment_grouping"], json!(["region", "service"])); assert_eq!(coarse["covers_share"], 0.05); + // No hydra_saturation.csv: Hydra serves nothing, and says so. + assert_eq!(asap["hydra_rqes"], 0); + } + + /// Without roll-ups, the coarse RQE needs its own deployment, which costs + /// more than reading the fine one; every method counts its roll-ups. + #[test] + fn forbidding_roll_ups_costs_more_only_where_one_applies() { + let cost = |v: &Value| v["objective"].as_f64().unwrap(); + let w = http_workload( + "rollup", + vec![ + http_rqe(&["region"], 4, Some(0.05), 0.05), + http_rqe(&["region", "service"], 100, None, 0.001), + ], + ); + let result = evaluate(&w, 1, &WEIGHTS[..1], &[1e4]); + assert_eq!(result["sanity_violations"], json!([])); + let [asap, norollup, perquery] = + ["asap", "asap-norollup", "perquery"].map(|m| unbounded(&result, m)); + assert_eq!(asap["rolled_up_rqes"], 1); + assert_eq!(norollup["rolled_up_rqes"], 0); + assert_eq!(perquery["rolled_up_rqes"], 0); + assert_eq!(norollup["active_deployments"], 2); + assert!(cost(asap) < cost(norollup), "{asap} vs {norollup}"); + assert!(cost(norollup) <= cost(perquery) * (1.0 + 1e-6)); + // The ablation has a frontier and a plan at each SLA, like ASAP. + let norollup_rows = |key: &str| { + result[key] + .as_array() + .unwrap() + .iter() + .filter(|r| r["method"] == "asap-norollup") + .count() + }; + assert!(norollup_rows("results") > 1); + assert_eq!(norollup_rows("sla_results"), 1); + + // {region} and {service}: neither serves the other, so the two agree. + let w = http_workload( + "no-rollup", + vec![ + http_rqe(&["region"], 4, Some(0.05), 0.05), + http_rqe(&["service"], 25, Some(0.05), 0.01), + ], + ); + let result = evaluate(&w, 1, &WEIGHTS[..1], &[1e4]); + assert_eq!(result["sanity_violations"], json!([])); + let [asap, norollup] = ["asap", "asap-norollup"].map(|m| unbounded(&result, m)); + assert_eq!(asap["rolled_up_rqes"], 0); + assert_eq!(cost(asap), cost(norollup)); + } + + /// The generator's `http` schema: endpoint fans out under service. + fn http_schema() -> Value { + json!({"labels": [ + {"name": "region", "cardinality": 4}, + {"name": "service", "cardinality": 25}, + {"name": "endpoint", "cardinality": 25, "child_of": "service"}, + {"name": "status", "cardinality": 4}, + ]}) + } + + /// `flows`' distinct sources and `http`'s p99 latency each get a Hydra + /// grid over their full schema, from the cost rows measured on their own + /// dataset. `flows`' 3e6 schema groups exceed its 1e6 series, so its + /// cardinality is capped there and the stream kept. + #[test] + fn flows_and_http_latency_get_a_full_schema_hydra_grid() { + use rqe_optimizer::candidates::build_all_candidates_unpruned; + let rqe = |id: &str, + metric: &str, + value: &str, + capability: &str, + grouping: &[&str], + groups: u64, + rate: f64| { + let (sketch, target) = if capability == "quantile" { + ("kll-percall", 0.05) + } else { + ("hll", 0.02) + }; + json!({ + "id": id, "query_id": "q", "kind": "keys", "capability": capability, + "metric": metric, "stream": format!("{metric}/{value}"), "grouping": grouping, + "covers_share": null, "min_covered_share": 0.01, "max_covered_share": 0.5, + "lookback_secs": 300, "interval_secs": 60, "queries_per_instance": 1, + "label_set": {"groups": groups, "arrival_rate_per_sec": rate}, + "families": [{"sketch": sketch, "target": target}], + }) + }; + let flows = json!({"labels": [ + {"name": "dst_subnet", "cardinality": 1000}, + {"name": "dst_port", "cardinality": 1000}, + {"name": "proto", "cardinality": 3}, + ]}); + let table = json!({"workloads": [{ + "dataset": "synthetic/test", + "schemas": {"flows": flows, "http": http_schema()}, + "rqes": [ + rqe("t11", "flows", "src_ip", "cardinality", &["dst_subnet"], 1000, 1e6), + rqe("t16", "http", "latency", "quantile", &["service"], 25, 2e6), + ], + }]}); + let path = std::env::temp_dir().join(format!("hydra-table-{}.json", std::process::id())); + std::fs::write(&path, table.to_string()).unwrap(); + // The committed cost table plus a Hydra row per (variant, dataset), + // one measured on `http`'s user ids, which `flows` must not use. + let inputs = hll_saturation_dir("hydra"); + let mut costs: AtomicCostTable = + serde_json::from_str(&std::fs::read_to_string(inputs.join(COST_TABLE)).unwrap()) + .unwrap(); + let hydra = |from: &str, sketch: &str, dataset: &str| { + let mut row = costs.iter().find(|c| c.sketch == from).unwrap().clone(); + row.sketch = sketch.into(); + row.measured_at.dataset = Some(dataset.into()); + row + }; + let rows = [ + hydra("hll", "hydra-hll", "hydra_flows"), + hydra("hll", "hydra-univmon-cardinality", "hydra_http"), + hydra("kll-percall", "hydra-kll", "hydra_http_latency"), + ]; + costs.extend(rows); + std::fs::write( + inputs.join(COST_TABLE), + serde_json::to_string(&costs).unwrap(), + ) + .unwrap(); + let w = from_table(path.to_str().unwrap(), None, None, inputs.to_str().unwrap()); + std::fs::remove_file(&path).unwrap(); + std::fs::remove_dir_all(&inputs).unwrap(); + assert!(w.excluded_high_cardinality.is_empty()); + let flows_facts = &w.facts["synthetic/test/flows/src_ip"]; + let full = label_set(&["dst_subnet", "dst_port", "proto"]); + assert_eq!(flows_facts.cardinality[&full], 1_000_000); + let hydra: Vec = group_by_stream(&w.raqes) + .into_iter() + .flat_map(|(stream, group)| { + build_all_candidates_unpruned(&group, &w.costs[stream], &w.facts, true) + }) + .filter(|d| d.properties().answers_any_subgrouping) + .collect(); + // A grid finer than its RQE is not a roll-up; a per-group sketch there + // would be. + let t11 = &w.raqes[0]; + let grid = hydra.iter().find(|d| d.metric == t11.metric).unwrap(); + assert!(!is_rollup(t11, grid)); + let mut per_group = grid.clone(); + per_group.config.sketch = "hll".into(); + assert!(is_rollup(t11, &per_group)); + let grids: BTreeSet<(String, LabelSet)> = hydra + .into_iter() + .map(|d| (d.config.sketch, d.grouping_labels)) + .collect(); + assert_eq!( + grids, + BTreeSet::from([ + ("hydra-hll".to_string(), full), + ( + "hydra-kll".to_string(), + label_set(&["region", "service", "endpoint", "status"]) + ), + ]) + ); + } + + #[test] + fn hydra_reads_the_dataset_shaped_like_the_metric() { + let at = |metric| hydra_dataset(metric, Capability::Cardinality); + assert_eq!(at("http").as_deref(), Some("hydra_http")); + assert_eq!(at("data_1/http").as_deref(), Some("hydra_http")); + assert_eq!(at("flows").as_deref(), Some("hydra_flows")); + assert_eq!( + hydra_dataset("http", Capability::Quantile).as_deref(), + Some("hydra_http_latency") + ); + assert_eq!(at("data"), None); } /// `r`'s HLL accuracy (ASAP's, AutoSketch's) and the reads at its @@ -1267,7 +1610,7 @@ mod tests { }; let table = json!({"workloads": [{ "dataset": "synthetic/test", - "schemas": {"http": {"labels": [{"name": "region"}]}}, + "schemas": {"http": {"labels": [{"name": "region", "cardinality": 4}]}}, "rqes": [ rqe("covered", "http/user_id", json!({ "metric": "http", "grouping": ["region"], "covers_share": 0.01, diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 20cd2fea..dc2032e1 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -116,6 +116,7 @@ fn facts() -> WorkloadFacts { (label_set(&["service", "endpoint"]), data_shape(1_000.0)), ] .into(), + hydra_dataset: None, }; [ (REQUESTS.to_string(), http_metric_facts(None)), @@ -156,6 +157,7 @@ fn raqes() -> Vec { accuracy_sla: 0.1, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "req_rate_1d".to_string(), @@ -168,6 +170,7 @@ fn raqes() -> Vec { accuracy_sla: 0.1, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "req_rate_5m_tick".to_string(), @@ -180,6 +183,7 @@ fn raqes() -> Vec { accuracy_sla: 0.1, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "latency_p99_1h".to_string(), @@ -192,6 +196,7 @@ fn raqes() -> Vec { accuracy_sla: 0.05, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "latency_p99_6h_tick".to_string(), @@ -204,6 +209,7 @@ fn raqes() -> Vec { accuracy_sla: 0.05, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, // Shares KLL with the per-endpoint p99s by rolling up. Raqe { @@ -217,6 +223,7 @@ fn raqes() -> Vec { accuracy_sla: 0.05, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "latency_p99_1d".to_string(), @@ -229,6 +236,7 @@ fn raqes() -> Vec { accuracy_sla: 0.05, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, Raqe { id: "distinct_services_1h".to_string(), @@ -241,6 +249,7 @@ fn raqes() -> Vec { accuracy_sla: 0.1, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, // 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 @@ -257,6 +266,7 @@ fn raqes() -> Vec { accuracy_sla: 0.9, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, }, ] } diff --git a/rqe-optimizer/examples/workload_scenarios.rs b/rqe-optimizer/examples/workload_scenarios.rs index 09e0bcc4..45261445 100644 --- a/rqe-optimizer/examples/workload_scenarios.rs +++ b/rqe-optimizer/examples/workload_scenarios.rs @@ -77,6 +77,7 @@ fn query( accuracy_sla, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } @@ -306,6 +307,7 @@ fn facts() -> WorkloadFacts { (by_service_endpoint(), data_shape(1_000.0)), ] .into(), + hydra_dataset: None, }; let duration_range = Some((0.001, 60.0)); let per_service_metrics = (0..PER_SERVICE_METRIC_COUNT).map(|service_index| { diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 9e8cd16e..42729b39 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -18,6 +18,10 @@ //! divides their memory and merge cost by the group count, so `card(G) ×` //! prices them correctly too. A [key tracker](crate::Deployment::key_tracker) //! is priced like an exact accumulator on the same windows, in every phase. +//! A Hydra grid over a schema `Λ` (the deployment's grouping) is one such +//! fixed-size sketch, `I_d = I_r = 1`: its measured insert is per record with +//! the subset fan-out included, a query probes it once per `G_r` group, and +//! its tracker keeps `card(Λ)` keys per window. use crate::{ secs, AtomicCostEntry, Capability, Deployment, LabelSet, Mapping, Millis, Raqe, WorkloadFacts, diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index 0f01f131..b82dd56e 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -482,6 +482,7 @@ mod tests { accuracy_sla: 1.0 - error_budget, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 8973ef21..ee8623d8 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -44,30 +44,16 @@ fn subset_gcds(values: impl IntoIterator) -> BTreeSet { gcds } -/// Whether a fixed-size sketch shared by all groups (HydraKLL) was measured -/// holding at least `groups` subpopulations. A necessary check, not Hydra's -/// admission rule: a group's error depends on the grid's fanned-out mass -/// against the group's own size, not on the group count alone, so admission -/// needs the measured predicate of `docs/rqe_optimizer_hydra.md` §2.4. -/// HydraKLL is in no capability's family list, so this decides nothing today. -fn measured_at_group_count(config: &AtomicCostEntry, groups: u64) -> bool { - config - .query_accuracy - .get("subpopulations") - .is_some_and(|&measured| groups as f64 <= measured) -} - /// Windows and slides are multiples of the metric's scrape interval: anything /// finer only splits one scrape's samples. /// -/// Deployments are grouped by `grouping` and built from the families whose -/// [`mergeable_across_groups`](crate::FamilyProperties::mergeable_across_groups) -/// equals `mergeable_across_groups`. Their windows, slides and heaps come from +/// Deployments are grouped by `grouping` and built from the cost rows that +/// pass `row`. Their windows, slides and heaps come from /// `group`, the RAQEs they may serve. fn candidate_deployments( group: &[&Raqe], grouping: &LabelSet, - mergeable_across_groups: bool, + row: impl Fn(&AtomicCostEntry) -> bool, costs: &[AtomicCostEntry], metric_facts: &MetricFacts, allow_undeployable_families: bool, @@ -95,8 +81,7 @@ fn candidate_deployments( capability .candidate_families(allow_undeployable_families) .any(|family| family == c.sketch) - && crate::family_properties(&c.sketch).mergeable_across_groups - == mergeable_across_groups + && row(c) }) .collect(); let heap_rows = heap_rows_by_shape(&family_rows); @@ -325,38 +310,83 @@ pub fn build_all_candidates_unpruned( .or_default() .push(raqe); } - groups - .iter() - .flat_map(|(&(capability, metric, filter, grouping), exact_group)| { - // A family that rolls up may also serve RAQEs grouped by a subset, - // so its windows must suit theirs too. - let subset_group: Vec<&Raqe> = raqes + // RAQEs of `(capability, metric, filter)` grouped by a subset of + // `grouping`, non-empty ones only for Hydra. + let subset_group = + |(capability, metric, filter, grouping): (Capability, &str, &str, &LabelSet), + non_empty: bool| { + raqes .iter() .filter(|r| { r.capability == capability && r.metric == metric && r.spatial_filter == filter && r.grouping_labels.is_subset(grouping) + && !(non_empty && r.grouping_labels.is_empty()) }) - .collect(); + .collect::>() + }; + let mut candidates: Vec = groups + .iter() + .flat_map(|(&key, exact_group)| { + let (_, metric, _, grouping) = key; + // A family that rolls up may also serve RAQEs grouped by a subset, + // so its windows must suit theirs too. + let subset_group = subset_group(key, false); + let properties = |c: &AtomicCostEntry| crate::family_properties(&c.sketch); [ - (exact_group.as_slice(), false), - (subset_group.as_slice(), true), - ] - .into_iter() - .flat_map(|(group, mergeable_across_groups)| { candidate_deployments( - group, + exact_group, grouping, - mergeable_across_groups, + |c| { + !properties(c).answers_any_subgrouping + && !properties(c).mergeable_across_groups + }, costs, &facts[metric], allow_undeployable_families, - ) - }) - .collect::>() + ), + candidate_deployments( + &subset_group, + grouping, + |c| { + !properties(c).answers_any_subgrouping + && properties(c).mergeable_across_groups + }, + costs, + &facts[metric], + allow_undeployable_families, + ), + ] + .concat() }) - .collect() + .collect(); + // Hydra, on a metric with a measured dataset: one grid over its full + // schema `Λ`, the width the study measures cost and accuracy at, from + // the rows measured on that dataset. `Λ` is a label set, not an ordered + // list: the library encodes subkeys in schema order, and every metric + // keeps one order (the eval datasets fix it), so the set names the grid. + let streams: BTreeSet<(Capability, &str, &str)> = groups + .keys() + .map(|&(capability, metric, filter, _)| (capability, metric, filter)) + .collect(); + for (capability, metric, filter) in streams { + let Some((dataset, schema)) = &facts[metric].hydra_dataset else { + continue; + }; + candidates.extend(candidate_deployments( + &subset_group((capability, metric, filter, schema), true), + schema, + |c| { + crate::family_properties(&c.sketch).answers_any_subgrouping + && c.measured_at.dataset.as_ref() == Some(dataset) + }, + costs, + &facts[metric], + allow_undeployable_families, + )); + } + candidates } /// Remove a candidate only when another candidate can replace it in every @@ -545,14 +575,19 @@ pub fn eligible_deployments_for( /// Whether `d` can serve `r`. Every rule lives here, so the MILP, enumeration /// and candidate pruning agree on what is valid. -pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &Accuracy) -> bool { +pub fn is_eligible(r: &Raqe, d: &Deployment, _facts: &WorkloadFacts, accuracy: &Accuracy) -> bool { let properties = d.properties(); r.capability == d.capability && r.metric == d.metric && r.spatial_filter == d.spatial_filter - && (r.grouping_labels == d.grouping_labels - || (properties.mergeable_across_groups - && r.grouping_labels.is_subset(&d.grouping_labels))) + && (if properties.answers_any_subgrouping { + // Hydra: any non-empty subset of its schema, read directly. + !r.grouping_labels.is_empty() && r.grouping_labels.is_subset(&d.grouping_labels) + } else { + r.grouping_labels == d.grouping_labels + || (properties.mergeable_across_groups + && r.grouping_labels.is_subset(&d.grouping_labels)) + }) && d.window_ms != 0 && d.slide_ms != 0 && d.window_ms.is_multiple_of(d.slide_ms) @@ -560,8 +595,6 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A && r.interval_ms.is_multiple_of(d.slide_ms) && (properties.mergeable_across_windows || r.lookback_ms == d.window_ms) && 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])) && heap_capacity(&d.config).is_none_or(|heap| { d.heap_needed(r.lookback_ms, r.topk_k()) .is_some_and(|need| heap >= need) @@ -588,6 +621,7 @@ mod tests { accuracy_sla: 0.5, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } fn cost() -> AtomicCostEntry { @@ -1088,17 +1122,19 @@ mod tests { assert_eq!(retained, vec![direct, halves]); } - /// A whole-sketch hydra-kll row measured at `subpopulations` groups, and - /// a per-key DeltaSet row. - fn hydra_and_tracker(subpopulations: f64) -> [AtomicCostEntry; 2] { + /// A whole-grid hydra-kll row measured on `hydra_test`, and a per-key + /// DeltaSet row. + fn hydra_and_tracker() -> [AtomicCostEntry; 2] { [ AtomicCostEntry { sketch: "hydra-kll".into(), mem_bytes_per_instance: 1000.0, - query_accuracy: BTreeMap::from([ - ("mean_rank_err".into(), 0.1), - ("subpopulations".into(), subpopulations), - ]), + query_accuracy: BTreeMap::from([("mean_rank_err".into(), 0.1)]), + accuracy_metric: metric_of("hydra-kll"), + measured_at: aqpbm_core::MeasuredAt { + dataset: Some("hydra_test".into()), + ..crate::test_support::measured_at() + }, ..cost() }, AtomicCostEntry { @@ -1118,7 +1154,7 @@ mod tests { #[test] #[should_panic(expected = "exact-delta-set rows in the cost table")] fn two_tracker_rows_are_refused() { - let [hydra, tracker] = hydra_and_tracker(100.0); + let [hydra, tracker] = hydra_and_tracker(); build_all_candidates( &[quantile_raqe()], &[hydra, tracker.clone(), tracker], @@ -1231,4 +1267,117 @@ mod tests { assert!(topk_windows.contains(&HOUR)); assert!(!topk_windows.contains(&NINETY_MINUTES)); } + + /// Schema region (2) × service (5) × endpoint (10 per service), measured + /// as the Hydra dataset `hydra_test`, plus a per-series label `x`; every + /// RAQE grouping on it has a cardinality. + fn region_service_endpoint_facts() -> WorkloadFacts { + use crate::test_support::label_set; + let schema = label_set(&["region", "service", "endpoint"]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: label_set(&["region", "service", "endpoint", "x"]), + scrape_interval_ms: 1_000, + cardinality: BTreeMap::from([ + (label_set(&["region"]), 2), + (label_set(&["service"]), 5), + (label_set(&["region", "service"]), 10), + (label_set(&["service", "endpoint"]), 50), + (schema.clone(), 100), + (label_set(&["region", "service", "endpoint", "x"]), 1_000), + ]), + value_range: None, + data_shape: BTreeMap::new(), + hydra_dataset: Some(("hydra_test".into(), schema)), + }, + )]) + } + + fn quantile_by(grouping: &[&str]) -> Raqe { + crate::test_support::quantile_by(grouping, 60_000, 60_000) + } + + /// A Hydra grid over its schema answers every non-empty subset of it, + /// coarse or not a prefix, directly; nothing outside it, nor the + /// ungrouped query. A per-group sketch serves only subsets of its own + /// grouping that roll up. + #[test] + fn hydra_serves_any_non_empty_subset_of_its_schema() { + use crate::test_support::{kll_by, label_set}; + let facts = region_service_endpoint_facts(); + let [hydra, tracker] = hydra_and_tracker(); + let grid = Deployment { + grouping_labels: label_set(&["region", "service"]), + config: hydra, + key_tracker: Some(tracker), + ..kll_by(&[], 60_000) + }; + let serves = |grouping: &[&str]| { + is_eligible(&quantile_by(grouping), &grid, &facts, &|_, _| Some(0.0)) + }; + assert!(serves(&["region", "service"])); + assert!(serves(&["service"])); + assert!(serves(&["region"])); + assert!(!serves(&[])); + assert!(!serves(&["service", "endpoint"])); + assert!(!serves(&["region", "service", "endpoint"])); + // Its own measured accuracy still decides. + let r = quantile_by(&["service"]); + assert!(!is_eligible(&r, &grid, &facts, &|_, _| Some(0.9))); + } + + /// One Hydra grid per stream, over its full schema (without `x`), from + /// the rows measured on its dataset only, with the windows of the RAQEs + /// it can serve; none on a metric without a dataset. + #[test] + fn hydra_grids_are_built_at_the_full_schema_from_its_dataset_rows() { + use crate::test_support::label_set; + let mut facts = region_service_endpoint_facts(); + // Minute scrapes: windows of whole minutes only. + facts.get_mut(METRIC).unwrap().scrape_interval_ms = 60_000; + let raqes = [ + quantile_by(&["region"]), + crate::test_support::quantile_by(&["service", "endpoint"], 120_000, 120_000), + ]; + let [hydra, tracker] = hydra_and_tracker(); + let elsewhere = |dataset: Option<&str>| AtomicCostEntry { + mem_bytes_per_instance: 2000.0, + measured_at: aqpbm_core::MeasuredAt { + dataset: dataset.map(str::to_string), + ..crate::test_support::measured_at() + }, + ..hydra.clone() + }; + let costs = [ + hydra.clone(), + elsewhere(Some("hydra_other")), + elsewhere(None), + tracker, + ]; + let grids = |facts: &WorkloadFacts| { + build_all_candidates_unpruned(&raqes, &costs, facts, true) + .into_iter() + .filter(|d| d.config.sketch == "hydra-kll") + .map(|d| { + ( + d.grouping_labels, + d.window_ms, + d.config.mem_bytes_per_instance as u64, + ) + }) + .collect::>() + }; + let schema = label_set(&["region", "service", "endpoint"]); + assert_eq!( + grids(&facts), + BTreeSet::from([ + (schema.clone(), 60_000, 1000), + (schema.clone(), 120_000, 1000), + ]) + ); + // No Hydra dataset: no grid at all, and not as a plain candidate. + facts.get_mut(METRIC).unwrap().hydra_dataset = None; + assert!(grids(&facts).is_empty()); + } } diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 8fe68f70..83cd3d64 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -161,6 +161,7 @@ mod tests { accuracy_sla: 0.5, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index a3b59131..3c6a70e1 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -84,13 +84,20 @@ impl Capability { Capability::Min => &["exact-min"], Capability::Max => &["exact-max"], Capability::RateOrIncrease => &["exact-increase"], - Capability::Quantile => &["kll-percall", "dd"], + // Hydra (one grid for every subgrouping of a schema) is planned only + // with undeployable families allowed: ASAPQuery doesn't run it yet. + Capability::Quantile => &["kll-percall", "dd", "hydra-kll"], // univmon-cardinality is registered under KeyedCardinality in // sketch-bench, but its ground truth (`KeyedCardinalityGT`) is // "count of keys with a nonzero total" -- plain distinct-key // count, same target as HLL. Second candidate, not a second // capability. - Capability::Cardinality => &["hll", "univmon-cardinality"], + Capability::Cardinality => &[ + "hll", + "univmon-cardinality", + "hydra-hll", + "hydra-univmon-cardinality", + ], // The sketch is the same; ASAPQuery deploys the two kinds with // different `count_events`, so they never share one. Capability::TopKByValue | Capability::TopKByCount => &[ @@ -224,6 +231,12 @@ pub struct FamilyProperties { /// The sketch can't list its groups, so a DeltaSet records which keys /// each window saw, for the query to probe. pub needs_delta_set_key_tracker: bool, + /// Hydra: one grid over a label schema `Λ` (the deployment's + /// `grouping_labels`) answers any non-empty subgrouping of it directly, + /// from the subkeys every insert fans out to. Not a roll-up: nothing is + /// merged across groups. Its accuracy is measured per grouping + /// (`hydra_saturation.csv`). + pub answers_any_subgrouping: bool, /// Answers without error, so its accuracy comes from the cost table /// rather than a saturation curve. pub exact: bool, @@ -242,9 +255,20 @@ pub fn family_properties(variant: &str) -> FamilyProperties { mergeable_across_groups: true, one_fixed_size_sketch_for_all_groups: false, needs_delta_set_key_tracker: false, + answers_any_subgrouping: false, exact: false, accuracy: Some((metric, direction)), }; + // One grid holds every group; a DeltaSet lists the keys to probe. + let hydra = |metric| FamilyProperties { + mergeable_across_windows: true, + mergeable_across_groups: false, + one_fixed_size_sketch_for_all_groups: true, + needs_delta_set_key_tracker: true, + answers_any_subgrouping: true, + exact: false, + accuracy: Some((metric, LowerIsBetter)), + }; // `relative_error` is the worst group's, not `relative_error_mean`. let exact = FamilyProperties { exact: true, @@ -273,14 +297,8 @@ pub fn family_properties(variant: &str) -> FamilyProperties { mergeable_across_groups: false, ..one_sketch_per_group("precision_at_k", HigherIsBetter) }, - "hydra-kll" => FamilyProperties { - mergeable_across_windows: true, - mergeable_across_groups: false, - one_fixed_size_sketch_for_all_groups: true, - needs_delta_set_key_tracker: true, - exact: false, - accuracy: Some(("mean_rank_err", LowerIsBetter)), - }, + "hydra-hll" | "hydra-univmon-cardinality" => hydra("relative_error"), + "hydra-kll" => hydra("mean_rank_err"), _ => panic!("{variant} has no FamilyProperties; add it to family_properties"), } } @@ -303,6 +321,12 @@ pub struct MetricFacts { /// Fitted data parameters per grouping `G`, for reading sketch accuracy /// off the saturation curves. Without one, no sketch serves `G`. pub data_shape: BTreeMap, + /// The `hydra_saturation.csv` dataset whose schema and shares match this + /// metric's, and that schema `Λ` (its labels; `cardinality` must hold + /// it). Hydra grids are built only over `Λ`, the width the study + /// measures, from cost rows measured on the dataset. Without one, no + /// Hydra candidate is built on the metric. + pub hydra_dataset: Option<(String, LabelSet)>, } impl MetricFacts { @@ -386,6 +410,18 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec false, }; } + if let Some((_, schema)) = &metric_facts.hydra_dataset { + if !schema.is_subset(all_labels) { + problems.insert(format!( + "{metric}: Hydra schema {schema:?} is not a subset of its labels {all_labels:?}" + )); + } + if cardinality.get(schema).is_none_or(|&groups| groups == 0) { + problems.insert(format!( + "{metric}: Hydra schema {schema:?} needs a nonzero cardinality" + )); + } + } } // Dropping labels never adds groups. A roll-up's merge count, // `card(G_d) · L/x − card(G_r)`, relies on it, so it is checked between @@ -468,6 +504,10 @@ pub struct Raqe { /// A top-k RAQE's `k`; `None` means [`TOPK_K`]. Ignored for other /// capabilities. pub topk_k: Option, + /// The groups the accuracy SLA covers: those holding at least this + /// share of the metric's records, plus always the largest; `None` for + /// every group. Read only by Hydra's accuracy, measured per coverage. + pub accuracy_covers_share: Option, } impl Raqe { @@ -645,6 +685,7 @@ pub(crate) mod test_support { cardinality: BTreeMap::from([(LabelSet::new(), groups), (labels, series)]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -661,6 +702,7 @@ pub(crate) mod test_support { accuracy_sla: 0.5, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } @@ -713,6 +755,7 @@ pub(crate) mod test_support { cardinality: BTreeMap::from([(service, 5), (service_endpoint, 50)]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -855,6 +898,7 @@ mod tests { ]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]); let r = Raqe { @@ -874,6 +918,7 @@ mod tests { cardinality: BTreeMap::from([(labels(&["service"]), 0)]), value_range: Some((0.0, 1.0)), data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]); let raqes = [ @@ -969,6 +1014,7 @@ mod tests { ]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -1022,4 +1068,34 @@ mod tests { }; assert_eq!(validate_facts(&[r], &inconsistent_facts()), Ok(())); } + + /// Hydra's schema must be the metric's labels with a known group count. + #[test] + fn rejects_a_hydra_schema_outside_the_labels_or_without_cardinality() { + let mut facts = test_support::facts(1, 1); + let metric_facts = facts.get_mut(METRIC).unwrap(); + let mut outside = metric_facts.labels.clone(); + outside.insert("pod".into()); + metric_facts.hydra_dataset = Some(("hydra_test".into(), outside.clone())); + let problems = validate_facts(&[raqe(60_000, 60_000)], &facts).unwrap_err(); + assert_eq!( + problems, + [ + format!( + "{METRIC}: Hydra schema {outside:?} is not a subset of its labels {:?}", + facts[METRIC].labels + ), + format!("{METRIC}: Hydra schema {outside:?} needs a nonzero cardinality"), + ] + ); + let metric_facts = facts.get_mut(METRIC).unwrap(); + let schema = metric_facts.labels.clone(); + metric_facts.cardinality.insert(schema.clone(), 0); + metric_facts.hydra_dataset = Some(("hydra_test".into(), schema)); + let problems = validate_facts(&[raqe(60_000, 60_000)], &facts).unwrap_err(); + assert!( + problems.iter().any(|p| p.contains("Hydra schema")), + "{problems:?}" + ); + } } diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index cea60c71..bacc7363 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -13,6 +13,10 @@ //! curve, at the row's `measured_at`, and [`SaturationCurves::check_cost_table`] //! checks that the two agree there (#171). Both come from one study run //! (`study_saturation.py --phase optimizer-cost`, #174). +//! +//! Hydra reads none of these curves: its accuracy is measured per dataset +//! and grouping (`hydra_saturation.csv`, `docs/rqe_optimizer_hydra.md` +//! §2.4), see [`SaturationCurves::accuracy`]. use std::collections::{BTreeMap, BTreeSet}; use std::io; @@ -49,6 +53,26 @@ const RUN_DIRS: [&str; 2] = ["out_grid_1e7_cost", "out_1e9"]; /// `study_saturation.py --phase optimizer-cost --out DIR/optimizer_cost`. pub const COST_TABLE: &str = "optimizer_cost/rqe_atomic_costs.json"; +/// Hydra's measurements under the same directory, written by +/// `study_saturation.py --phase hydra` on datasets shaped like the +/// workload's metrics. Optional: without it no Hydra deployment has an +/// accuracy. +pub const HYDRA_SATURATION: &str = "hydra_saturation.csv"; + +/// `hydra_saturation.csv`'s error columns, by the share of records a group +/// must hold to be covered (the largest group always is): every group, then +/// the two measured thresholds. +const HYDRA_COVERAGE: [(f64, &str); 3] = [ + (0.0, "err_max"), + (0.01, "err_max_cov_0.01"), + (0.05, "err_max_cov_0.05"), +]; + +/// Hydra measurements of one (variant, config, dataset, grouping), by merge +/// shards: each [`HYDRA_COVERAGE`] column's worst over the records and seeds +/// that filled it, `None` where every row left it empty. +type HydraErrors = BTreeMap; 3]>; + /// One (sketch, config, data shape) point of the study. #[derive(Debug, Clone, PartialEq)] struct GridPoint { @@ -217,12 +241,14 @@ fn curve_error_at( /// (#131): a merged answer reads their merge curve. UnivMon's counters add /// exactly, but each level's heavy-hitter heap is rebuilt from the union of /// the two heaps, so a key heavy only in the union is lost. The other -/// sketches merge exactly. +/// sketches merge exactly. Hydra's cells merge as their sketch does. fn merges_lossily(sketch: &str) -> bool { matches!( sketch, "kll-percall" | "univmon-cardinality" + | "hydra-kll" + | "hydra-univmon-cardinality" | "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" | "univmon-topk" @@ -266,6 +292,9 @@ pub struct CostTableCheck { #[derive(Debug, Clone, Default)] pub struct SaturationCurves { points_by_sketch: BTreeMap>, + /// [`HYDRA_SATURATION`], keyed by variant, config params (as + /// [`config_params`] prints them), dataset and grouping. + hydra: BTreeMap<(String, String, String, LabelSet), HydraErrors>, } impl SaturationCurves { @@ -289,9 +318,18 @@ impl SaturationCurves { for run in RUN_DIRS { let run_dir = dir.join(run); let mut run_points = BTreeMap::new(); - for row in read_csv(&run_dir.join("saturation.csv"))? { + let columns = [ + "sketch", + "config", + "dist", + "param", + "cardinality", + "n_sat", + "error_metric", + ]; + for row in read_csv(&run_dir.join("saturation.csv"), &columns)? { let point = GridPoint { - params: parse_config(&row["config"]), + params: parse_config(&row["config"])?, shape: parse_shape(&row)?, error_metric: row["error_metric"].clone(), n_sat: match row["n_sat"].as_str() { @@ -312,7 +350,17 @@ impl SaturationCurves { } run_points.insert(key(&row), (row["sketch"].clone(), point)); } - for row in read_csv(&run_dir.join("saturation_curve.csv"))? { + let columns = [ + "sketch", + "config", + "dist", + "param", + "cardinality", + "n", + "seed_mean_error", + "seed_se", + ]; + for row in read_csv(&run_dir.join("saturation_curve.csv"), &columns)? { let Some((_, point)) = run_points.get_mut(&key(&row)) else { return Err(invalid(format!( "{run}: curve row for a point not in saturation.csv: {row:?}" @@ -326,7 +374,18 @@ impl SaturationCurves { } let merge_path = run_dir.join("saturation_merge_curve.csv"); if merge_path.exists() { - for row in read_csv(&merge_path)? { + let columns = [ + "sketch", + "config", + "dist", + "param", + "cardinality", + "shards", + "n", + "seed_mean_error", + "seed_se", + ]; + for row in read_csv(&merge_path, &columns)? { let Some((_, point)) = run_points.get_mut(&key(&row)) else { return Err(invalid(format!( "{run}: merge curve row for a point not in saturation.csv: {row:?}" @@ -416,7 +475,58 @@ impl SaturationCurves { } } } - Ok(Self { points_by_sketch }) + let hydra_path = dir.join(HYDRA_SATURATION); + let hydra = if hydra_path.exists() { + load_hydra(&hydra_path)? + } else { + BTreeMap::new() + }; + Ok(Self { + points_by_sketch, + hydra, + }) + } + + /// Hydra's accuracy for `raqe` on `deployment`: the measurement at the + /// metric's [`MetricFacts::hydra_dataset`], the deployment's config and the + /// RAQE's grouping, in the column of the RAQE's + /// [`Raqe::accuracy_covers_share`] (a share between the measured ones + /// reads the next stricter column), worst over records and seeds. A + /// lossy merge of `L / x` windows reads the worse of the measured shard + /// counts either side; past the largest, or with no measurement, it is + /// unknown. + // Assumes error depends on group shares, not on N, at fixed shares; the + // study's N sweep backs it. + fn hydra_accuracy( + &self, + raqe: &Raqe, + deployment: &Deployment, + facts: &WorkloadFacts, + ) -> Option { + let sketch = &deployment.config.sketch; + let key = ( + sketch.clone(), + format!("{:?}", config_params(&deployment.config)?), + facts[&deployment.metric].hydra_dataset.as_ref()?.0.clone(), + raqe.grouping_labels.clone(), + ); + let by_shards = self.hydra.get(&key)?; + let merges = if merges_lossily(sketch) { + deployment.query_instance_count(raqe.lookback_ms)? + } else { + 1 + }; + let column = HYDRA_COVERAGE + .iter() + .rposition(|&(share, _)| raqe.accuracy_covers_share.is_some_and(|t| t >= share)) + .unwrap_or(0); + let (_, below) = by_shards.range(..=merges).next_back()?; + let (_, above) = by_shards.range(merges..).next()?; + Some(worse( + below[column]?, + above[column]?, + accuracy_key(sketch).1, + )) } /// The accuracy `raqe` gets from `deployment`, or `None` when it can't be @@ -447,9 +557,15 @@ impl SaturationCurves { deployment: &Deployment, facts: &WorkloadFacts, ) -> Option<(f64, AccuracySource)> { - if family_properties(&deployment.config.sketch).exact { + let properties = family_properties(&deployment.config.sketch); + if properties.exact { return table_accuracy(raqe, deployment).map(|v| (v, AccuracySource::Measured)); } + if properties.answers_any_subgrouping { + return self + .hydra_accuracy(raqe, deployment, facts) + .map(|v| (v, AccuracySource::Measured)); + } let metric_facts = &facts[&deployment.metric]; // The answered groups: the RAQE's, coarser than the deployment's on a // roll-up, whose answer is the merged coarse group's. @@ -771,13 +887,80 @@ fn config_params(config: &AtomicCostEntry) -> Option> { .collect() } +/// [`HYDRA_SATURATION`]'s rows of the Hydra variants some capability plans +/// (the rest, such as hydra-cms, are skipped), each column's worst over +/// records and seeds. +fn load_hydra( + path: &Path, +) -> io::Result> { + let mut out: BTreeMap<_, HydraErrors> = BTreeMap::new(); + let columns = [ + "variant", + "config", + "dataset", + "group_columns", + "merge_shards", + HYDRA_COVERAGE[0].1, + HYDRA_COVERAGE[1].1, + HYDRA_COVERAGE[2].1, + ]; + for row in read_csv(path, &columns)? { + let variant = row["variant"].as_str(); + if !is_candidate(variant) || !family_properties(variant).answers_any_subgrouping { + continue; + } + let shards: u64 = row["merge_shards"] + .parse() + .map_err(|_| invalid(format!("{HYDRA_SATURATION}: merge_shards: {row:?}")))?; + let mut errors = [None; 3]; + for (error, (_, column)) in errors.iter_mut().zip(HYDRA_COVERAGE) { + if !row[column].is_empty() { + *error = Some(parse_number(&row[column])?); + } + } + let key = ( + variant.to_string(), + format!("{:?}", parse_config(&row["config"])?), + row["dataset"].clone(), + row["group_columns"] + .split(',') + .map(str::to_string) + .collect(), + ); + let direction = accuracy_key(variant).1; + let by_shards = out.entry(key).or_default(); + match by_shards.get_mut(&shards) { + None => { + by_shards.insert(shards, errors); + } + Some(worst) => { + // An empty cell means no covered group was scored in that + // run (say, all had zero truth): it bounds nothing. + for (worst, error) in worst.iter_mut().zip(errors) { + *worst = match (*worst, error) { + (Some(a), Some(b)) => Some(worse(a, b, direction)), + (a, b) => a.or(b), + }; + } + } + } + } + Ok(out) +} + /// `"rows=3 cols=1024"` → `{rows: 3, cols: 1024}`; the grid's config strings. -fn parse_config(config: &str) -> BTreeMap { +/// Fails on a pair that isn't `name=number`. +fn parse_config(config: &str) -> io::Result> { config .split_whitespace() - .filter_map(|pair| { - let (name, value) = pair.split_once('=')?; - Some((name.to_string(), value.parse().ok()?)) + .map(|pair| { + let (name, value) = pair + .split_once('=') + .ok_or_else(|| invalid(format!("config {config:?}: {pair:?} is not name=value")))?; + let value = value + .parse() + .map_err(|_| invalid(format!("config {config:?}: {name} is not a number")))?; + Ok((name.to_string(), value)) }) .collect() } @@ -806,23 +989,47 @@ fn invalid(message: String) -> io::Error { type CsvRow = BTreeMap; -// ponytail: plain comma split; the study's CSVs quote nothing (configs hold -// spaces, never commas). Use the csv crate if that changes. -fn read_csv(path: &Path) -> io::Result> { +/// Fields may be quoted: `hydra_saturation.csv`'s groupings hold commas. +/// Fails unless the header has every `required` column and every row +/// exactly one field per header column. +fn read_csv(path: &Path, required: &[&str]) -> io::Result> { + let failed = |e: csv::Error| invalid(format!("{}: {e}", path.display())); let text = std::fs::read_to_string(path) .map_err(|e| io::Error::new(e.kind(), format!("{}: {e}", path.display())))?; - let mut lines = text.lines(); - let header: Vec<&str> = lines.next().unwrap_or_default().split(',').collect(); - Ok(lines - .filter(|line| !line.is_empty()) - .map(|line| { - header + let mut reader = csv::ReaderBuilder::new() + .flexible(true) + .from_reader(text.as_bytes()); + let header = reader.headers().map_err(failed)?.clone(); + let missing: Vec<_> = required + .iter() + .filter(|&&column| !header.iter().any(|name| name == column)) + .collect(); + if !missing.is_empty() { + return Err(invalid(format!( + "{}: missing columns {missing:?}", + path.display() + ))); + } + reader + .records() + .map(|record| { + let record = record.map_err(failed)?; + if record.len() != header.len() { + return Err(invalid(format!( + "{}: line {}: {} fields, the header has {}", + path.display(), + record.position().map_or(0, |p| p.line()), + record.len(), + header.len() + ))); + } + Ok(header .iter() - .zip(line.split(',')) + .zip(record.iter()) .map(|(name, value)| (name.to_string(), value.to_string())) - .collect() + .collect()) }) - .collect()) + .collect() } #[cfg(test)] @@ -855,7 +1062,7 @@ mod tests { ] }; let point = |theta: f64, keys: f64, offset: f64, n_sat: Option| GridPoint { - params: parse_config("rows=3 cols=1024"), + params: parse_config("rows=3 cols=1024").unwrap(), shape: MeasuredShape::Zipf { skew: theta, keys }, error_metric: "precision_at_k".into(), n_sat, @@ -872,6 +1079,7 @@ mod tests { point(1.2, 1e5, 0.08, None), ], )]), + ..SaturationCurves::default() } } @@ -1013,7 +1221,7 @@ mod tests { use crate::test_support::{kll_by, label_set, quantile_by, service_endpoint_facts}; let curve = |error: f64| vec![(1e3, error, 0.0), (1e4, error + 0.01, 0.0)]; let kll = GridPoint { - params: parse_config("k=200"), + params: parse_config("k=200").unwrap(), shape: MeasuredShape::Pareto { tail_index: 2.0 }, error_metric: "mean_rank_err".into(), n_sat: None, @@ -1022,6 +1230,7 @@ mod tests { }; let curves = SaturationCurves { points_by_sketch: BTreeMap::from([("kll-percall".to_string(), vec![kll])]), + ..SaturationCurves::default() }; let mut facts = service_endpoint_facts(); let metric = facts.get_mut(METRIC).unwrap(); @@ -1585,4 +1794,309 @@ mod tests { "{error}" ); } + + const HYDRA_HEADER: &str = "variant,config,R,W,dataset,group_columns,schema_width,\ + records,fanned_mass,merge_shards,seed,err_mean,err_p50,err_p90,err_max,groups_scored,\ + err_max_cov_0.01,err_max_cov_0.05"; + + /// A `hydra_saturation.csv` row on `hydra_http` at rows=3 cols=1024: + /// `variant`, `grouping` (label names), records, merge shards, seed, then + /// err_max, err_max_cov_0.01 and err_max_cov_0.05 as written. + fn hydra_row( + variant: &str, + grouping: &str, + records: f64, + shards: u64, + seed: u64, + errors: [&str; 3], + ) -> String { + let [all, cov_1, cov_5] = errors; + format!( + "{variant},rows=3 cols=1024,3,1024,hydra_http,\"{grouping}\",2,{records},0,{shards},\ + {seed},0,0,0,{all},10,{cov_1},{cov_5}" + ) + } + + /// A saturation dir with empty curves and, when `rows` is `Some`, a + /// `hydra_saturation.csv` of them, loaded. `tag` keeps parallel tests' + /// dirs apart. + fn hydra_curves(tag: &str, rows: Option<&[String]>) -> SaturationCurves { + let csv = rows.map(|rows| format!("{HYDRA_HEADER}\n{}\n", rows.join("\n"))); + load_hydra_csv(tag, csv).unwrap() + } + + /// [`hydra_curves`] with `csv`, when `Some`, as `hydra_saturation.csv`. + fn load_hydra_csv(tag: &str, csv: Option) -> io::Result { + let dir = std::env::temp_dir().join(format!("rqe-hydra-{tag}-{}", std::process::id())); + for run in RUN_DIRS { + std::fs::create_dir_all(dir.join(run)).unwrap(); + let header = "family,sketch,config,dist,param,cardinality"; + std::fs::write( + dir.join(run).join("saturation.csv"), + format!("{header},n_sat,final_error,error_metric\n"), + ) + .unwrap(); + std::fs::write( + dir.join(run).join("saturation_curve.csv"), + format!("{header},n,seed_mean_error,seed_se\n"), + ) + .unwrap(); + } + if let Some(csv) = csv { + std::fs::write(dir.join(HYDRA_SATURATION), csv).unwrap(); + } + let loaded = SaturationCurves::load(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + loaded + } + + /// A malformed `hydra_saturation.csv` fails the load, naming the + /// problem, rather than leaving Hydra silently without accuracy. + #[test] + fn a_malformed_hydra_csv_is_an_error() { + let row = hydra_row("hydra-hll", "service", 1e5, 1, 0, ["0.1"; 3]); + let error = + |tag: &str, csv: String| load_hydra_csv(tag, Some(csv)).unwrap_err().to_string(); + let no_cov = HYDRA_HEADER.trim_end_matches(",err_max_cov_0.05"); + let missing = error("missing", format!("{no_cov}\n{row}\n")); + assert!( + missing.contains("missing columns [\"err_max_cov_0.05\"]"), + "{missing}" + ); + let (short_row, _) = row.rsplit_once(',').unwrap(); + let short = error("short", format!("{HYDRA_HEADER}\n{short_row}\n")); + assert!( + short.contains("line 2: 17 fields, the header has 18"), + "{short}" + ); + let long = error("long", format!("{HYDRA_HEADER}\n{row},extra\n")); + assert!( + long.contains("line 2: 19 fields, the header has 18"), + "{long}" + ); + let wide = row.replace("cols=1024", "cols=wide"); + let config = error("config", format!("{HYDRA_HEADER}\n{wide}\n")); + assert!(config.contains("cols is not a number"), "{config}"); + } + + /// 5 services × 10 endpoints, measured as `hydra_http`. + fn hydra_facts() -> WorkloadFacts { + let mut facts = crate::test_support::service_endpoint_facts(); + let schema = crate::test_support::label_set(&["service", "endpoint"]); + facts.get_mut(METRIC).unwrap().hydra_dataset = Some(("hydra_http".into(), schema)); + facts + } + + fn tracker() -> AtomicCostEntry { + AtomicCostEntry { + sketch: crate::KEY_TRACKER_FAMILY.into(), + sketch_config: serde_json::json!({"params": {}}), + mem_bytes_per_instance: 10.0, + accuracy_metric: "relative_error".into(), + ..deployment(TOPK, 60_000).config + } + } + + /// A `sketch` grid at rows=3 cols=1024 over (service, endpoint), with + /// its key tracker. + fn hydra(sketch: &str, window_ms: u64) -> Deployment { + let base = deployment(sketch, window_ms); + Deployment { + capability: if sketch == "hydra-kll" { + Capability::Quantile + } else { + Capability::Cardinality + }, + grouping_labels: crate::test_support::label_set(&["service", "endpoint"]), + config: AtomicCostEntry { + mem_bytes_per_instance: 2_000.0, + ..base.config.clone() + }, + key_tracker: Some(tracker()), + ..base + } + } + + /// A distinct count by `grouping` over `lookback_ms` within 5%, covering + /// groups of share `covers` (`None`: every group). + fn distinct_by(grouping: &[&str], lookback_ms: u64, covers: Option) -> Raqe { + Raqe { + capability: Capability::Cardinality, + accuracy_sla: 0.05, + accuracy_covers_share: covers, + ..crate::test_support::quantile_by(grouping, lookback_ms, lookback_ms) + } + } + + #[test] + fn hydra_reads_the_column_its_coverage_selects() { + let rows = [hydra_row( + "hydra-hll", + "service", + 1e5, + 1, + 0, + ["0.3", "0.2", "0.1"], + )]; + let curves = hydra_curves("coverage", Some(&rows)); + let at = |covers| { + curves.accuracy( + &distinct_by(&["service"], 60_000, covers), + &hydra("hydra-hll", 60_000), + &hydra_facts(), + ) + }; + assert_eq!(at(None), Some(0.3)); + assert_eq!(at(Some(0.01)), Some(0.2)); + assert_eq!(at(Some(0.05)), Some(0.1)); + assert_eq!(at(Some(0.5)), Some(0.1)); + // Between the measured shares, the next stricter column; below the + // smallest, every group's. + assert_eq!(at(Some(0.03)), Some(0.2)); + assert_eq!(at(Some(0.001)), Some(0.3)); + } + + /// Error is taken to depend on shares, not N: the worst over the + /// measured records and seeds. An empty cell (no covered group scored) + /// is skipped; a column every row left empty is unknown. + #[test] + fn hydra_takes_the_worst_over_records_and_seeds() { + let rows = [ + hydra_row("hydra-hll", "service", 1e5, 1, 0, ["0.1", "", "0.1"]), + hydra_row("hydra-hll", "service", 1e6, 1, 0, ["0.15", "0.1", ""]), + hydra_row("hydra-hll", "service", 1e6, 1, 1, ["0.12", "", ""]), + ]; + let curves = hydra_curves("worst", Some(&rows)); + let at = |covers| { + curves.accuracy( + &distinct_by(&["service"], 60_000, covers), + &hydra("hydra-hll", 60_000), + &hydra_facts(), + ) + }; + assert_eq!(at(None), Some(0.15)); + assert_eq!(at(Some(0.01)), Some(0.1)); + assert_eq!(at(Some(0.05)), Some(0.1)); + let rows = [hydra_row( + "hydra-hll", + "service", + 1e5, + 1, + 0, + ["0.1", "0.1", ""], + )]; + let curves = hydra_curves("all_empty", Some(&rows)); + let at_5pct = curves.accuracy( + &distinct_by(&["service"], 60_000, Some(0.05)), + &hydra("hydra-hll", 60_000), + &hydra_facts(), + ); + assert_eq!(at_5pct, None); + } + + /// hydra-kll merges lossily: `L / x` windows read the worse of the + /// measured shard counts either side, and past the largest nothing. + /// hydra-hll merges exactly and reads one shard at any merge count. + #[test] + fn a_lossy_hydra_merge_reads_the_worse_bracketing_shard_count() { + let rows: Vec = ["hydra-kll", "hydra-hll"] + .iter() + .flat_map(|variant| { + [(1, "0.01"), (4, "0.02"), (16, "0.05")] + .map(|(shards, err)| hydra_row(variant, "service", 1e5, shards, 0, [err; 3])) + }) + .collect(); + let curves = hydra_curves("merges", Some(&rows)); + let at = |sketch: &str, merges: u64| { + let mut r = distinct_by(&["service"], 60_000 * merges, None); + if sketch == "hydra-kll" { + r.capability = Capability::Quantile; + } + curves.accuracy(&r, &hydra(sketch, 60_000), &hydra_facts()) + }; + assert_eq!(at("hydra-kll", 1), Some(0.01)); + assert_eq!(at("hydra-kll", 2), Some(0.02)); + assert_eq!(at("hydra-kll", 4), Some(0.02)); + assert_eq!(at("hydra-kll", 8), Some(0.05)); + assert_eq!(at("hydra-kll", 16), Some(0.05)); + assert_eq!(at("hydra-kll", 32), None); + assert_eq!(at("hydra-hll", 32), Some(0.01)); + } + + /// Hydra's accuracy is its own measurement or nothing: no file, no + /// dataset for the metric, or an unmeasured grouping leaves it unknown. + #[test] + fn without_a_hydra_measurement_no_hydra_deployment_has_accuracy() { + let r = distinct_by(&["service"], 60_000, None); + let d = hydra("hydra-hll", 60_000); + let rows = [hydra_row("hydra-hll", "service", 1e5, 1, 0, ["0.01"; 3])]; + let measured = hydra_curves("measured", Some(&rows)); + assert_eq!(measured.accuracy(&r, &d, &hydra_facts()), Some(0.01)); + let absent = hydra_curves("absent", None); + assert_eq!(absent.accuracy(&r, &d, &hydra_facts()), None); + let no_dataset = crate::test_support::service_endpoint_facts(); + assert_eq!(measured.accuracy(&r, &d, &no_dataset), None); + let by_endpoint = distinct_by(&["service", "endpoint"], 60_000, None); + assert_eq!(measured.accuracy(&by_endpoint, &d, &hydra_facts()), None); + } + + /// Distinct counts by (service) and (service, endpoint). Per-group HLL + /// at (service, endpoint) serves both, a roll-up for (service), at + /// 50 · 1000 B per window; one Hydra grid over the same schema holds + /// them in 2000 B plus a 10 B tracker key per group. Memory-priced, the + /// grid wins while its measured error clears the SLA, and loses + /// otherwise. + #[test] + fn a_hydra_grid_beats_per_group_hll_on_memory_only_when_accurate() { + use crate::candidates::build_all_candidates; + use crate::milp::minimize_usage_cost; + let facts = hydra_facts(); + let raqes = [ + distinct_by(&["service"], 60_000, None), + distinct_by(&["service", "endpoint"], 60_000, None), + ]; + let named = |sketch: &str, memory: f64| AtomicCostEntry { + mem_bytes_per_instance: memory, + accuracy_metric: "relative_error".into(), + measured_at: aqpbm_core::MeasuredAt { + dataset: Some("hydra_http".into()), + ..crate::test_support::measured_at() + }, + ..deployment(sketch, 60_000).config + }; + let costs = [ + named("hll", 1_000.0), + named("hydra-hll", 2_000.0), + tracker(), + ]; + let plan = |error: &str| { + let rows = ["service", "service,endpoint"] + .map(|grouping| hydra_row("hydra-hll", grouping, 1e5, 1, 0, [error; 3])); + let curves = hydra_curves(&format!("milp-{error}"), Some(&rows)); + // HLL passes everywhere; Hydra reads its measurement. + let accuracy = |r: &Raqe, d: &Deployment| { + if d.properties().answers_any_subgrouping { + curves.accuracy(r, d, &facts) + } else { + Some(0.0) + } + }; + let without = build_all_candidates(&raqes, &costs, &facts, false, &accuracy); + assert!(without.iter().all(|d| d.config.sketch == "hll")); + let candidates = build_all_candidates(&raqes, &costs, &facts, true, &accuracy); + let solved = + minimize_usage_cost(&raqes, &candidates, &facts, 0.0, 1.0, &accuracy, None, None) + .unwrap(); + solved + .mapping + .iter() + .map(|&d| candidates[d].clone()) + .collect::>() + }; + let accurate = plan("0.01"); + assert!(accurate.iter().all(|d| d.config.sketch == "hydra-hll")); + assert_eq!(accurate[0], accurate[1], "one grid serves both"); + let inaccurate = plan("0.2"); + assert!(inaccurate.iter().all(|d| d.config.sketch == "hll")); + } } diff --git a/rqe-optimizer/tests/mixed_grouping.rs b/rqe-optimizer/tests/mixed_grouping.rs index 59c5f3d5..0850ac2c 100644 --- a/rqe-optimizer/tests/mixed_grouping.rs +++ b/rqe-optimizer/tests/mixed_grouping.rs @@ -35,6 +35,7 @@ fn facts() -> WorkloadFacts { ]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -51,6 +52,7 @@ fn raqe(id: &str, capability: Capability, grouping: &[&str], accuracy_sla: f64) accuracy_sla, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } diff --git a/scripts/plot_autosketch_vs_asap_sla.py b/scripts/plot_autosketch_vs_asap_sla.py index 0de7682a..308d4998 100644 --- a/scripts/plot_autosketch_vs_asap_sla.py +++ b/scripts/plot_autosketch_vs_asap_sla.py @@ -7,13 +7,16 @@ Writes, into OUT: fig_cost_vs_sla.png one panel per workload (columns) and weight setting (rows): cost by use (absolute, labeled) at each SLA, - ASAP and PerQuery as lines over the SLAs they can meet, + ASAP, ASAP (no roll-ups, dashed) and PerQuery as + lines over the SLAs they can meet, AutoSketch as a horizontal reference at its one plan's cost, a filled marker where its latency meets the SLA and a cross where it misses summary_sla.md per workload, weights and SLA: each method's cost, latency, CPU and GiB; AutoSketch's planning time as - search + measured benchmark + search + measured benchmark; the roll-up ablation + (RQEs rolled up, deployments and cost with and + without roll-ups, saving %) Usage: scripts/plot_autosketch_vs_asap_sla.py OUT RESULT.json... """ @@ -28,9 +31,13 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 -METHODS = ["asap", "perquery", "autosketch"] -LABELS = {"asap": "ASAP", "perquery": "PerQuery-CostAware", "autosketch": "AutoSketch-Adapted"} -COLORS = {"asap": "#1f77b4", "perquery": "#ff7f0e", "autosketch": "#2ca02c"} +METHODS = ["asap", "asap-norollup", "perquery", "autosketch"] +LABELS = {"asap": "ASAP", "asap-norollup": "ASAP (no roll-ups)", + "perquery": "PerQuery-CostAware", "autosketch": "AutoSketch-Adapted"} +COLORS = {"asap": "#1f77b4", "asap-norollup": "#4a3aa7", "perquery": "#ff7f0e", + "autosketch": "#2ca02c"} +MARKERS = {"asap": "o", "asap-norollup": "^", "perquery": "o"} +LINESTYLES = {"asap-norollup": "--"} UNITS = {"cpu": "vCPU", "fargate": "$/hour"} @@ -71,13 +78,13 @@ def figure(runs, out): for col, data in enumerate(runs): for row, w in enumerate(weights): ax = axes[row][col] - for m in ("asap", "perquery"): + for m in ("asap", "asap-norollup", "perquery"): pts = [(r["sla_ms"], r["objective"]) for r in rows(data, m, w) if not r.get("infeasible") and "objective" in r] if not pts: continue - ax.plot(*zip(*pts), marker="o", markersize=4, linewidth=2, color=COLORS[m], - label=LABELS[m]) + ax.plot(*zip(*pts), marker=MARKERS[m], markersize=4, linewidth=2, + linestyle=LINESTYLES.get(m, "-"), color=COLORS[m], label=LABELS[m]) for x, y in pts: ax.annotate(fmt(y), (x, y), textcoords="offset points", xytext=(3, 3), fontsize=6, color="#333333") @@ -104,7 +111,7 @@ def figure(runs, out): if col == 0: ax.set_ylabel(f"cost by use ({UNITS.get(w, w)})", fontsize=8) handles, labels = axes[0][0].get_legend_handles_labels() - fig.legend(handles, labels, loc="upper center", ncol=3, fontsize=8, + fig.legend(handles, labels, loc="upper center", ncol=4, fontsize=8, title="AutoSketch: ● meets the SLA, × misses it", title_fontsize=7) fig.tight_layout(rect=(0, 0, 1, 0.9)) fig.savefig(out / "fig_cost_vs_sla.png", dpi=150) @@ -142,9 +149,34 @@ def summary(runs, out): f"{fmt(r['latency_ms'])} | {fmt(r['cpu'])} | {fmt(r['gib'])} | " f"{meets} |") lines.append("") + lines.extend(rollup_section(data)) (out / "summary_sla.md").write_text("\n".join(lines)) +def rollup_section(data): + """The roll-up ablation at each weight setting and SLA where both ASAP and + ASAP (no roll-ups) have a plan; none without the ablation.""" + out = [] + for w in [x["name"] for x in data["weights"]]: + for sla in data["sla_grid_ms"]: + with_, without = (next((r for r in rows(data, m, w) if r["sla_ms"] == sla + and "objective" in r), None) + for m in ("asap", "asap-norollup")) + if with_ is None or without is None: + continue + saving = 100 * (without["objective"] - with_["objective"]) / without["objective"] + out.append(f"| {w} | {fmt(sla)} | {with_.get('rolled_up_rqes', '—')} | " + f"{with_['active_deployments']} | {without['active_deployments']} | " + f"{fmt(with_['objective'])} | {fmt(without['objective'])} | " + f"{saving:.1f}% |") + if not out: + return [] + return ["Roll-up ablation (ASAP vs. ASAP without roll-ups):\n", + "| weights | SLA (ms) | RQEs rolled up | deployments with | deployments without | " + "cost with | cost without | saving |", + "|---|---|---|---|---|---|---|---|", *out, ""] + + def main(): out = pathlib.Path(sys.argv[1]) runs = [json.loads(pathlib.Path(p).read_text()) for p in sys.argv[2:]] diff --git a/scripts/plot_autosketch_vs_asap_synthetic.py b/scripts/plot_autosketch_vs_asap_synthetic.py index 153f2be9..e75bf47b 100644 --- a/scripts/plot_autosketch_vs_asap_synthetic.py +++ b/scripts/plot_autosketch_vs_asap_synthetic.py @@ -10,15 +10,20 @@ Writes, next to the inputs: fig_frontier.png cost vs. query latency, one column per workload, one - row per weight setting; ASAP and PerQuery frontiers - as lines, AutoSketch as a point; every point labeled - with its cost + row per weight setting; ASAP, ASAP (no roll-ups) + and PerQuery frontiers as lines, AutoSketch as a + point; every point labeled with its cost + fig_rollup_ablation.png the roll-up ablation: per workload, ASAP's and ASAP + (no roll-ups)'s unbounded cost as grouped bars, one + panel per weight setting, absolute values labeled fig_planning_time.png planning time vs. RQEs over the metrics dimension; AutoSketch's is its search plus its measured benchmark (60 s per probe only as a labeled reference) summary_synthetic.md every workload and weight setting: each method's unbounded plan, its cost at AutoSketch's latency, and - the frontier points + the frontier points; the roll-up ablation (RQEs + rolled up, deployments and cost with and without + roll-ups, saving %) Usage: scripts/plot_autosketch_vs_asap_synthetic.py DIR """ @@ -33,12 +38,15 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt # noqa: E402 -METHODS = ["asap", "perquery", "autosketch"] -LABELS = {"asap": "ASAP", "perquery": "PerQuery-CostAware", "autosketch": "AutoSketch-Adapted"} -# Categorical slots 1-3 of the dataviz reference palette, with marker shapes as -# a second encoding. -COLORS = {"asap": "#2a78d6", "perquery": "#eb6834", "autosketch": "#1baf7a"} -MARKERS = {"asap": "o", "perquery": "s", "autosketch": "D"} +METHODS = ["asap", "asap-norollup", "perquery", "autosketch"] +LABELS = {"asap": "ASAP", "asap-norollup": "ASAP (no roll-ups)", + "perquery": "PerQuery-CostAware", "autosketch": "AutoSketch-Adapted"} +# Categorical slots 1-3 and 7 of the dataviz reference palette, with marker +# shapes (and the ablation's dashes) as a second encoding. +COLORS = {"asap": "#2a78d6", "asap-norollup": "#4a3aa7", "perquery": "#eb6834", + "autosketch": "#1baf7a"} +MARKERS = {"asap": "o", "asap-norollup": "^", "perquery": "s", "autosketch": "D"} +LINESTYLES = {"asap-norollup": "--"} UNITS = {"cpu": "vCPU", "fargate": "$/hour"} WEIGHT_TITLES = {"cpu": "CPU only", "fargate": "Fargate prices"} @@ -77,7 +85,8 @@ def records(data, method, weights): def unbounded(data, method, weights): - return next(r for r in records(data, method, weights) if r["bound_ms"] is None) + """The method's unbounded plan; None for results without the method.""" + return next((r for r in records(data, method, weights) if r["bound_ms"] is None), None) def at_autosketch_latency(data, method, weights): @@ -105,12 +114,14 @@ def fig_frontier(runs, out): ax = axes[row][col] for m in METHODS: pts = frontier(data, m, w) + if not pts: + continue style = dict(color=COLORS[m], marker=MARKERS[m], markersize=4, linewidth=1.5, label=LABELS[m]) if m == "autosketch": ax.plot(*zip(*pts), linestyle="none", **style) else: - ax.plot(*zip(*pts), **style) + ax.plot(*zip(*pts), linestyle=LINESTYLES.get(m, "-"), **style) for x, y in pts: ax.annotate(fmt(y), (x, y), textcoords="offset points", xytext=(3, 3), fontsize=5, color="#52514e") @@ -126,12 +137,54 @@ def fig_frontier(runs, out): ax.set_ylabel(f"{WEIGHT_TITLES.get(w, w)}: cost by use ({UNITS.get(w, w)})", fontsize=7) handles, labels = axes[0][0].get_legend_handles_labels() - fig.legend(handles, labels, loc="upper center", ncol=3, fontsize=8) + fig.legend(handles, labels, loc="upper center", ncol=4, fontsize=8) fig.tight_layout(rect=(0, 0, 1, 0.93)) fig.savefig(out / "fig_frontier.png", dpi=150) plt.close(fig) +def fig_rollup_ablation(runs, out): + """Per workload with the ablation: ASAP's and ASAP (no roll-ups)'s unbounded + cost, grouped bars, one panel per weight setting.""" + runs = {k: d for k, d in runs.items() + if any(unbounded(d, "asap-norollup", w["name"]) for w in d["weights"])} + if not runs: + return + weights = [w["name"] for w in next(iter(runs.values()))["weights"]] + fig, axes = plt.subplots(1, len(weights), squeeze=False, + figsize=((1.2 * len(runs) + 1.0) * len(weights), 3.6)) + width = 0.38 + for col, w in enumerate(weights): + ax = axes[0][col] + for i, m in enumerate(("asap", "asap-norollup")): + xs, ys = [], [] + for x, data in enumerate(runs.values()): + r = unbounded(data, m, w) + if r is not None: + xs.append(x + (i - 0.5) * width) + ys.append(r["objective"]) + bars = ax.bar(xs, ys, width=width * 0.95, color=COLORS[m], label=LABELS[m], + hatch="//" if m == "asap-norollup" else None, edgecolor="white", + linewidth=0.5) + ax.bar_label(bars, labels=[fmt(y) for y in ys], fontsize=6, color="#52514e", + padding=2) + ax.set_xticks(range(len(runs))) + ax.set_xticklabels([f"{title(k).replace(', ', chr(10))}\n({d['rqes']} RQEs)" + for k, d in runs.items()], + fontsize=6) + ax.set_ylabel(f"cost by use, unbounded ({UNITS.get(w, w)})", fontsize=7) + ax.set_title(WEIGHT_TITLES.get(w, w), fontsize=8) + ax.tick_params(axis="y", labelsize=6) + ax.grid(True, axis="y", color="#e5e4e0", linewidth=0.5) + ax.set_axisbelow(True) + ax.margins(y=0.12) + handles, labels = axes[0][0].get_legend_handles_labels() + fig.legend(handles, labels, loc="upper center", ncol=2, fontsize=8) + fig.tight_layout(rect=(0, 0, 1, 0.9)) + fig.savefig(out / "fig_rollup_ablation.png", dpi=150) + plt.close(fig) + + def fig_planning_time(runs, out): """Over the metrics dimension (shared = 1) of the `all` set, CPU-only weights.""" @@ -204,6 +257,8 @@ def summary(runs, out): for w in [x["name"] for x in data["weights"]]: for m in METHODS: r = unbounded(data, m, w) + if r is None: + continue planning = r.get("planning_secs") if m == "autosketch" and "benchmark_secs_measured" in a: planning = planning + a["benchmark_secs_measured"] @@ -216,17 +271,40 @@ def summary(runs, out): lines.append("") lines.append("Frontier points (latency ms, cost), by weights:\n") for w in [x["name"] for x in data["weights"]]: - for m in ("asap", "perquery"): + for m in ("asap", "asap-norollup", "perquery"): pts = ", ".join(f"({fmt(x)}, {fmt(y)})" for x, y in frontier(data, m, w)) - lines.append(f"- {w}, {LABELS[m]}: {pts}") + if pts: + lines.append(f"- {w}, {LABELS[m]}: {pts}") lines.append("") + lines.extend(rollup_section(data, unbounded)) (out / "summary_synthetic.md").write_text("\n".join(lines)) +def rollup_section(data, plan): + """The roll-up ablation's markdown lines: per weight setting, `plan(data, + method, weights)` with and without roll-ups; none without the ablation.""" + rows = [] + for w in [x["name"] for x in data["weights"]]: + with_, without = plan(data, "asap", w), plan(data, "asap-norollup", w) + if with_ is None or without is None: + continue + saving = 100 * (without["objective"] - with_["objective"]) / without["objective"] + rows.append(f"| {w} | {with_.get('rolled_up_rqes', '—')} | " + f"{with_['active_deployments']} | {without['active_deployments']} | " + f"{fmt(with_['objective'])} | {fmt(without['objective'])} | {saving:.1f}% |") + if not rows: + return [] + return ["Roll-up ablation (ASAP vs. ASAP without roll-ups):\n", + "| weights | RQEs rolled up | deployments with | deployments without | " + "cost with | cost without | saving |", + "|---|---|---|---|---|---|---|", *rows, ""] + + def main(): out = pathlib.Path(sys.argv[1]) runs = load(out) fig_frontier(runs, out) + fig_rollup_ablation(runs, out) fig_planning_time(runs, out) summary(runs, out) diff --git a/scripts/run_autosketch_vs_asap_synthetic.sh b/scripts/run_autosketch_vs_asap_synthetic.sh index 34b5a1fe..eddc687a 100755 --- a/scripts/run_autosketch_vs_asap_synthetic.sh +++ b/scripts/run_autosketch_vs_asap_synthetic.sh @@ -36,7 +36,7 @@ run) done < "$TABLES/plan.tsv" | xargs -P "$JOBS" -L 1 sh -c \ 'timeout "$JOB_TIMEOUT" "$0" synthetic --table "$1" --target "$2" --runs "$RUNS" \ - --saturation-dir "$SATURATION_DIR" --out "$3" 2>> "$3.log" \ + --saturation-dir "$SATURATION_DIR" --no-chosen --out "$3" 2>> "$3.log" \ || echo "$3" >> "$OUT/failed.txt"' \ "$BIN" ;;