diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index 027947b3..11b619d4 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -45,7 +45,15 @@ //! gives the workload: RQEs, and each stream's groups, rate and data shape //! (the family's `grid_param`/`grid_K`, the worst case rounded to the grid). //! Each stream (`traces`: dataset, query and kind; `synthetic`: the table's -//! `stream`) is one metric, which is where sharing comes from. +//! `stream`) is one metric, which is where sharing comes from. A stream of a +//! metric with a label schema (the table's `schemas`) has the schema's labels, +//! and its RQEs name their `grouping`, so one stream carries several +//! groupings and a fine deployment can serve a coarse RQE (a roll-up). +//! Accuracy is read at the mean group's items per window, or, for an RQE with +//! a `covers_share` (`null`: every group), at its smallest and its largest +//! covered group's (`min_covered_share` and `max_covered_share` of the +//! stream's), the worse of the two: a per-group sketch's error need not fall +//! as N grows (sketch-bench#189), so either may be the hardest group. //! //! Costs and accuracy come from `--saturation-dir`, the same inputs the //! planner reads (#174): the cost table `optimizer_cost/rqe_atomic_costs.json` @@ -62,11 +70,11 @@ use rqe_optimizer::analytical_cost_model::chain_ms; use rqe_optimizer::autosketch; use rqe_optimizer::candidates::{build_all_candidates, eligible_deployments_for, is_eligible}; use rqe_optimizer::milp::minimize_usage_cost; -use rqe_optimizer::saturation::{DataShape, SaturationCurves, COST_TABLE}; +use rqe_optimizer::saturation::{AccuracySource, DataShape, SaturationCurves, COST_TABLE}; use rqe_optimizer::usage::{usage_cost, PlanLoad}; use rqe_optimizer::{ - validate_facts, AtomicCostEntry, AtomicCostTable, Capability, Deployment, LabelSet, Mapping, - MetricFacts, Millis, Raqe, WorkloadFacts, + accuracy_key, validate_facts, AccuracyDirection, AtomicCostEntry, AtomicCostTable, Capability, + Deployment, LabelSet, Mapping, MetricFacts, Millis, Raqe, WorkloadFacts, }; use serde_json::{json, Value}; @@ -101,19 +109,64 @@ struct Workload { metric_of: BTreeMap, /// RQEs of streams with more keys than samples/s, left out. excluded_high_cardinality: Vec, + /// The table's `covers_share` by RQE id, for RQEs that name one (`None`: + /// every group). + covers_share: BTreeMap>, + /// Facts for reading an RQE's accuracy at its smallest covered group, by + /// RQE id, for RQEs with a `covers_share` (`null` too): its stream's, + /// with the series scaled so the mean group gets that group's items. + covered_facts: BTreeMap, + /// The same, at its largest covered group. + largest_facts: BTreeMap, curves: SaturationCurves, notes: Vec, } impl Workload { - /// ASAP's accuracy: the planner's own lookup. + /// The facts `r`'s accuracy is read with. + fn accuracy_facts(&self, r: &Raqe) -> &WorkloadFacts { + self.covered_facts.get(&r.id).unwrap_or(&self.facts) + } + + /// `read` at `r`'s accuracy facts, and for an RQE with a largest covered + /// group also at its, the worse in `sketch`'s direction; unknown if + /// either is. + fn worse_read( + &self, + r: &Raqe, + sketch: &str, + read: impl Fn(&WorkloadFacts) -> Option<(f64, T)>, + ) -> Option<(f64, T)> { + let smallest = read(self.accuracy_facts(r))?; + let Some(facts) = self.largest_facts.get(&r.id) else { + return Some(smallest); + }; + let largest = read(facts)?; + let largest_worse = match accuracy_key(sketch).1 { + AccuracyDirection::LowerIsBetter => largest.0 > smallest.0, + AccuracyDirection::HigherIsBetter => largest.0 < smallest.0, + }; + Some(if largest_worse { largest } else { smallest }) + } + + /// ASAP's accuracy: the planner's own lookup, and where it came from. + fn accuracy_with_source(&self, r: &Raqe, d: &Deployment) -> Option<(f64, AccuracySource)> { + self.worse_read(r, &d.config.sketch, |facts| { + self.curves.accuracy_with_source(r, d, facts) + }) + } + + /// ASAP's accuracy. fn asap_accuracy(&self, r: &Raqe, d: &Deployment) -> Option { - self.curves.accuracy(r, d, &self.facts) + self.accuracy_with_source(r, d).map(|(value, _)| value) } /// AutoSketch's: one unmerged sketch per query window. fn autosketch_accuracy(&self, r: &Raqe, c: &AtomicCostEntry) -> Option { - self.curves.autosketch_accuracy(r, c, &self.facts) + self.worse_read(r, &c.sketch, |facts| { + Some((self.curves.autosketch_accuracy(r, c, facts)?, ())) + }) + .map(|(value, _)| value) } } @@ -199,6 +252,7 @@ fn capability_of(r: &Value) -> Capability { // `topk(k, sum by (...) (...))`: ranked by summed value. (Some("topk"), _) => Capability::TopKByValue, (Some("quantile"), _) | (None, "values") => Capability::Quantile, + (Some("cardinality"), _) => Capability::Cardinality, other => panic!("unknown capability {other:?}"), } } @@ -279,6 +333,9 @@ fn from_table( let mut metric_of = BTreeMap::new(); let mut skipped_families = 0; let mut stream_series: BTreeMap = BTreeMap::new(); + let mut covers_share = BTreeMap::new(); + let mut min_covered_share = BTreeMap::new(); + let mut max_covered_share = BTreeMap::new(); for r in workload["rqes"].as_array().unwrap() { let id = r["id"].as_str().unwrap().to_string(); let metric = r["metric"].as_str().unwrap_or(dataset); @@ -295,36 +352,53 @@ fn from_table( let capability = capability_of(r); let rate = r["label_set"]["arrival_rate_per_sec"].as_f64().unwrap(); let groups = groups_of(r, capability); - let grouping = if groups > 1 { - label_set(&["g"]) - } else { - LabelSet::new() + // A schema metric's RQE names its grouping (its `groups` are that + // grouping's); otherwise the stream has one label `g`, the grouping. + let schema = &workload["schemas"][metric]; + let grouping: LabelSet = match r["grouping"].as_array() { + Some(labels) => labels + .iter() + .map(|l| l.as_str().unwrap().to_string()) + .collect(), + None if groups > 1 => label_set(&["g"]), + None => LabelSet::new(), }; - // One metric per stream, labels {g, x}: `g` is the grouping (card = - // groups), and with one scrape a second `{g, x}` has one series per - // sample/s. A stream's RQEs differ only in range, so take the - // largest per-RQE rate (conservative). Rates below `groups` + // `null` covers every group, so its smallest is read too. + if let Some(share) = r.get("covers_share") { + covers_share.insert(id.clone(), share.as_f64()); + min_covered_share.insert(id.clone(), r["min_covered_share"].as_f64().unwrap()); + max_covered_share.insert(id.clone(), r["max_covered_share"].as_f64().unwrap()); + } + // One metric per stream, labels {g, x} (or the schema's and x), and + // with one scrape a second the full label set has one series per + // sample/s. A stream's RQEs differ only in range and grouping, so + // take the largest per-RQE rate (conservative). Rates below `groups` // samples/s are rounded up so every group has a series. 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 metric = facts.entry(stream.clone()).or_insert_with(|| MetricFacts { - labels: label_set(&["g", "x"]), - scrape_interval_ms: SCRAPE_MS, - cardinality: [ - (label_set(&["g", "x"]), 0), - (label_set(&["g"]), groups), - (LabelSet::new(), 1), - ] - .into(), - value_range: None, - data_shape: BTreeMap::new(), + 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"]), + }; + labels.insert("x".to_string()); + MetricFacts { + cardinality: [(labels.clone(), 0), (LabelSet::new(), 1)].into(), + labels, + scrape_interval_ms: SCRAPE_MS, + value_range: None, + data_shape: BTreeMap::new(), + } }); // A stream's RQEs may see different group counts (keys per window // grow with the range): take the largest (conservative). - let card = metric.cardinality.get_mut(&label_set(&["g"])).unwrap(); + let card = metric.cardinality.entry(grouping.clone()).or_default(); *card = (*card).max(groups); - let total = metric.cardinality.get_mut(&label_set(&["g", "x"])).unwrap(); + let total = metric.cardinality.get_mut(&metric.labels).unwrap(); *total = (*total).max(series).max(groups); // Queries one evaluation issues per instance (the table's q_r); tables // written before it existed charge one query phase per evaluation. @@ -397,7 +471,11 @@ fn from_table( // Such streams are left out, and their RQEs listed. let high_cardinality: BTreeSet = facts .iter() - .filter(|(stream, m)| m.cardinality[&label_set(&["g"])] > stream_series[*stream]) + .filter(|(stream, m)| { + m.cardinality + .iter() + .any(|(labels, &card)| labels != &m.labels && card > stream_series[*stream]) + }) .map(|(stream, _)| stream.clone()) .collect(); let excluded_high_cardinality: Vec = raqes @@ -407,6 +485,23 @@ fn from_table( .collect(); raqes.retain(|r| !high_cardinality.contains(&r.metric)); facts.retain(|stream, _| !high_cardinality.contains(stream)); + // Only the items per group read the series count: scaled by share·groups, + // the mean group gets the smallest (largest) covered group's items. + let scaled = |shares: &BTreeMap| { + raqes + .iter() + .filter_map(|r| { + let share = shares.get(&r.id)?; + let mut m = facts[&r.metric].clone(); + let groups = m.cardinality[&r.grouping_labels] as f64; + let series = m.cardinality.get_mut(&m.labels).unwrap(); + *series = (*series as f64 * share * groups).round() as u64; + Some((r.id.clone(), [(r.metric.clone(), m)].into())) + }) + .collect() + }; + let covered_facts = scaled(&min_covered_share); + let largest_facts = scaled(&max_covered_share); let name = if dataset.starts_with("synthetic") { format!("{dataset}/t{}", target.as_deref().unwrap_or("p95")) } else { @@ -419,6 +514,9 @@ fn from_table( costs, metric_of, excluded_high_cardinality, + covers_share, + covered_facts, + largest_facts, curves, notes: vec![ format!("{skipped_families} families skipped: they serve another capability"), @@ -564,7 +662,7 @@ fn summarize( .zip(&latencies) .map(|((r, &di), &latency)| { let d = &deployments[di]; - json!({ + let mut choice = json!({ "rqe": r.id, "sketch": d.config.sketch, "params": d.config.sketch_config["params"], @@ -576,10 +674,17 @@ fn summarize( "deployment": di, "asap_accuracy": w.asap_accuracy(r, d), "accuracy_source": w - .curves - .accuracy_with_source(r, d, &w.facts) + .accuracy_with_source(r, d) .map(|(_, source)| format!("{source:?}")), - }) + }); + // A roll-up: the deployment is grouped finer than the RQE. + if d.grouping_labels != r.grouping_labels { + choice["deployment_grouping"] = json!(d.grouping_labels); + } + if let Some(share) = w.covers_share.get(&r.id) { + choice["covers_share"] = json!(share); + } + choice }) .collect(); json!({ @@ -706,6 +811,15 @@ fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64 if let Err(problems) = validate_facts(&raqes, &w.facts) { panic!("invalid facts: {problems:?}"); } + for (r, facts) in raqes.iter().flat_map(|r| { + [&w.covered_facts, &w.largest_facts] + .into_iter() + .filter_map(move |f| Some((r, f.get(&r.id)?))) + }) { + if let Err(problems) = validate_facts(std::slice::from_ref(r), facts) { + panic!("invalid covered facts: {problems:?}"); + } + } // AutoSketch: one plan, independent of the weights. let mut search_secs = Vec::new(); @@ -1022,6 +1136,205 @@ mod tests { assert!(!meets_sla(100.1, 100.0)); } + /// A saturation dir with the committed cost table and inline HLL curves + /// (each lg_k, uniform over 1e6 keys), so the test runs without the + /// study's (gitignored) curves. `tag` keeps parallel tests' dirs apart. + fn hll_saturation_dir(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("hll-saturation-{tag}-{}", std::process::id())); + let costs = concat!( + env!("CARGO_MANIFEST_DIR"), + "/results/autosketch-vs-asap-inputs/saturation/optimizer_cost/rqe_atomic_costs.json" + ); + std::fs::create_dir_all(dir.join("optimizer_cost")).unwrap(); + std::fs::copy(costs, dir.join(COST_TABLE)).unwrap(); + for run in ["out_grid_1e7_cost", "out_1e9"] { + let mut summary = "family,sketch,config,dist,param,cardinality,n_sat,final_error,\ + error_metric,insert_cpu_secs,merge_cpu_secs,query_cpu_secs,memory_bytes\n" + .to_string(); + let mut curve = + "family,sketch,config,dist,param,cardinality,n,seed_mean_error,seed_se\n" + .to_string(); + for lg_k in [12, 14, 16].iter().filter(|_| run == "out_grid_1e7_cost") { + let point = format!("cardinality,hll,lg_k={lg_k},zipf,0.0,1000000"); + summary += &format!("{point},1000,0.01,relative_error,,,,\n"); + for n in ["1000", "100000", "10000000"] { + curve += &format!("{point},{n},0.01,0.0\n"); + } + } + std::fs::create_dir_all(dir.join(run)).unwrap(); + std::fs::write(dir.join(run).join("saturation.csv"), summary).unwrap(); + std::fs::write(dir.join(run).join("saturation_curve.csv"), curve).unwrap(); + } + 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"]; + 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), + ], + }]}); + let path = std::env::temp_dir().join(format!("schema-table-{}.json", std::process::id())); + 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(); + let facts = &w.facts["synthetic/test/http/user_id"]; + assert_eq!( + facts.labels, + label_set(&["region", "service", "endpoint", "status", "x"]) + ); + 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); + // 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"]; + assert_eq!(covered.cardinality[&covered.labels], 400_000); + // `null` covers every group: 100 · 0.1% of the series. + let every = &w.covered_facts["t/region,service"]["synthetic/test/http/user_id"]; + 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(); + 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); + } + + /// `r`'s HLL accuracy (ASAP's, AutoSketch's) and the reads at its + /// smallest and largest covered groups, on curves with `errors` at N = + /// 1e3 .. 1e7; `r` covers groups of 1% and 50% of a 1000 samples/s + /// stream (3e3 and 1.5e5 items per 5m window, read at the worse of the + /// bracketing N). A classic RQE on another + /// stream reads the mean group alone. + fn covered_reads(errors: [f64; 5]) -> [Option; 4] { + let inputs = hll_saturation_dir(&format!("{errors:?}")); + let mut curve = + "family,sketch,config,dist,param,cardinality,n,seed_mean_error,seed_se\n".to_string(); + for lg_k in [12, 14, 16] { + for (n, error) in ["1e3", "1e4", "1e5", "1e6", "1e7"].iter().zip(errors) { + curve += &format!("cardinality,hll,lg_k={lg_k},zipf,0.0,1000000,{n},{error},0.0\n"); + } + } + let curves = inputs + .join("out_grid_1e7_cost") + .join("saturation_curve.csv"); + std::fs::write(curves, curve).unwrap(); + let rqe = |id: &str, stream: &str, extra: Value| { + let mut r = json!({ + "id": id, "query_id": "q", "kind": "keys", "capability": "cardinality", + "stream": stream, "lookback_secs": 300, "interval_secs": 60, + "queries_per_instance": 1, + "label_set": {"groups": 4, "arrival_rate_per_sec": 1000.0}, + "families": [{"family": "hll", "sketch": "hll", "target": 0.02, + "grid_param": 0.0, "grid_K": 1e6}], + }); + r.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + r + }; + let table = json!({"workloads": [{ + "dataset": "synthetic/test", + "schemas": {"http": {"labels": [{"name": "region"}]}}, + "rqes": [ + rqe("covered", "http/user_id", json!({ + "metric": "http", "grouping": ["region"], "covers_share": 0.01, + "min_covered_share": 0.01, "max_covered_share": 0.5})), + rqe("classic", "classic/user_id", json!({})), + ], + }]}); + let path = inputs.join("table.json"); + std::fs::write(&path, table.to_string()).unwrap(); + let w = from_table( + path.to_str().unwrap(), + None, + Some("p95".into()), + inputs.to_str().unwrap(), + ); + std::fs::remove_dir_all(&inputs).unwrap(); + let [covered, classic] = [&w.raqes[0], &w.raqes[1]]; + let hll = |r: &Raqe| { + let costs = &w.costs[&r.metric]; + rqe_optimizer::candidates::build_all_candidates_unpruned( + std::slice::from_ref(r), + costs, + &w.facts, + false, + ) + .into_iter() + .find(|d| d.config.sketch == "hll") + .unwrap() + }; + // A classic RQE: the mean group's read, as before. + let d = hll(classic); + assert!(!w.largest_facts.contains_key(&classic.id)); + assert_eq!( + w.asap_accuracy(classic, &d), + w.curves.accuracy(classic, &d, &w.facts) + ); + assert_eq!( + w.autosketch_accuracy(classic, &d.config), + w.curves.autosketch_accuracy(classic, &d.config, &w.facts) + ); + let d = hll(covered); + let autosketch = w.autosketch_accuracy(covered, &d.config); + assert_eq!(autosketch, w.asap_accuracy(covered, &d)); + [ + w.asap_accuracy(covered, &d), + autosketch, + w.curves.accuracy(covered, &d, &w.covered_facts["covered"]), + w.curves.accuracy(covered, &d, &w.largest_facts["covered"]), + ] + } + + #[test] + fn a_covered_rqe_is_held_to_the_worse_of_its_smallest_and_largest_group() { + // Relative error: a 3% target accepts at most 0.03. + let at = |target: f64, error: Option| error.unwrap() <= target; + // Error grows with N (#189): the largest group rejects what the + // smallest accepts. + let [asap, autosketch, smallest, largest] = covered_reads([0.01, 0.01, 0.05, 0.05, 0.05]); + assert!(at(0.03, smallest) && !at(0.03, largest)); + assert_eq!((asap, autosketch), (largest, largest)); + assert!(!at(0.03, asap)); + // Error falls with N: the smallest group rejects. + let [asap, autosketch, smallest, largest] = covered_reads([0.05, 0.05, 0.01, 0.01, 0.01]); + assert!(!at(0.03, smallest) && at(0.03, largest)); + assert_eq!((asap, autosketch), (smallest, smallest)); + } + #[test] fn one_95_percent_level_in_each_familys_metric() { assert_eq!(strictness_target("p95", Capability::Sum), 0.0); diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index 462edace..40b42e79 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -66,6 +66,77 @@ benchmark; the paper's 60 s per probe is a reference only): | 400 | 6.82 s | 5.55 s | 0.0153 s | 1.7e+03 s | 4.8e+03 s | | 800 | 14.7 s | 11.7 s | 0.031 s | 3.39e+03 s | 9.6e+03 s | +## Template sets + +The results above are the 10-template mixed set, now named `classic` +(`--synthetic` writes it as `synthetic-templatesclassic-*.json`; the +committed `templatesall` tables and results predate the rename and hold +exactly today's `classic` tables). `all` is `classic` plus six +multi-grouping templates on two metrics with an ordered label schema. Each +metric value is one stream read at several groupings, so a fine deployment +can serve a coarse RQE (a roll-up) and one Hydra grid can serve them all. +Every RQE of these templates names its `grouping` and `covers_share` τ: the +accuracy target covers the groups holding at least τ of the stream's records, +plus always the largest group (`null`: every group). The generator computes +each group's share as the product of its labels' shares (labels are drawn +independently given their parents) and writes each RQE's `covered_groups`, +`min_covered_share` and `covered_min_N` (the smallest covered group's items +per window), and `max_covered_share` and `covered_max_N` (the largest's); the table's `schemas` gives each metric's labels. + +| Metric | Labels (values, Zipf skew) | Rate | Values | +|---|---|---|---| +| `http` | region 4 (0.5), service 25 (1.1), endpoint 25 per service (1.1; 625 in all), status 4 (2.0); 1e4 label combinations | 2e6 samples/s (as `classic`) | `user_id`: Zipf 0.8 over 1e6; `latency`: Pareto a = 2, scaled per service, one endpoint 10x slower | +| `flows` | dst_subnet 1e3 (1.1), dst_port 1e3 (1.2), proto 3 (uniform) | 4e6 samples/s | `src_ip`: uniform over 1e6, plus a DDoS burst: the least popular subnet (999) gets 5% of the traffic from 1e4 sources | + +`flows` runs at twice the rate so its finest grouping, {dst_subnet, +dst_port} (1e6 groups), holds 1,200 items per group in 5m, above the +curves' first N (1e3). The burst targets a tail subnet so that it is +visible: its share rises to just over 5%, so template 11 covers it. + +The runner reads each value's data shape (Zipf θ and K, or the Pareto a), the +groups per grouping and the coverage; the other fields (label skew beyond the +shares, latency scaling, the anomaly, the burst's sources) describe the data +and are not modeled. Accuracy is read at N items per group per window at +both the smallest covered group (`covered_min_N`; for `covers_share` = +`null` the smallest group of all) and the largest (`covered_max_N`), and +the worse of the two reads holds (unknown if either is): KLL, DD and HLL +error does not fall as N grows, so the largest group can be the hardest +(sketch-bench#189). The +generator fails if any RQE's `covered_min_N` is below the curves' first N +(1e3). The skew of the counted value is the same in every group; label skew +changes only the group sizes. (RQEs without a `grouping`, `classic`'s, are +read at the mean group's items, `max_N`, as before.) + +| # | Query | Groupings | Covers | Groups (mean items per group in 5m) | Covered groups (smallest covered group's items in 5m) | +|---|---|---|---|---|---| +| 11 | distinct src_ip | {dst_subnet} | share ≥ 5% | 1e3 (1.2e6) | 4, the burst subnet among them (6e7) | +| 12 | distinct src_ip | {dst_port}, {dst_subnet, proto}, {dst_port, proto} | share ≥ 5% | 1e3, 3e3, 3e3 (1.2e6, 4e5, 4e5) | 3, 3, 3 (7.4e7, 6.8e7, 9.2e7) | +| 14 | distinct user_id | {region}, {service}, {region, service}, {service, endpoint} | share ≥ 1% | 4, 25, 100, 625 (1.5e8 to 9.6e5) | 4, 21, 23, 16 (1.1e8, 6.3e6, 6.3e6, 6.3e6) | +| 15 | distinct user_id | all 15 non-empty subsets of http's labels | share ≥ 5% | 4 to 1e4 (1.5e8 to 6e4) | 1 to 5 (1.3e7 to 1.1e8) | +| 16 | p99 latency | {service}, {region, service}, {service, status} | all groups | 25, 100, 100 (2.4e7, 6e6, 6e6) | all (5.2e6, 9.3e5, 2.3e5) | +| 17 | distinct user_id | {service, endpoint} (negative control) | all groups | 625 (9.6e5) | all (4.5e4) | + +The plot scripts title `classic` "mixed" and `all` "mixed + multi-grouping" +(so the committed `templatesall` results, which are `classic`'s, need +regenerating under their new name before they are re-plotted). + +Each repeats every minute over 5m and 15m windows: 54 RQEs, so `all` has +104 (shared replicas repeat them at their own interval; each of the `m` +metrics has its own `data_i/http` and `data_i/flows`). Distinct counts are +HLL (Zipf θ and K of the value), the p99 KLL and DDSketch (Pareto a = 2), +at the p95 level. `covers_share` is carried through to each choice in the +runner's output. + +On a freshly generated `all` table (`--synthetic`; r = 1, p95, CPU +weights, `--runs 1`) with the committed saturation inputs (the committed +`templatesall` tables are `classic`'s), no RQE is dropped and no sanity +check fails; ASAP serves 40 of the 54 new RQEs from a finer deployment: +every RQE of templates 14, 15 and 17 from an HLL at {region, service, +status} or at the full label set (bar the RQEs at those two groupings), +{dst_port} from {dst_port, proto}, and the p99 by {service} from DDSketch +at {region, service} or {service, status}. 15 active deployments in all, +5.05 vCPU; PerQuery-CostAware 11.8 vCPU; AutoSketch 3.42e+03 vCPU. + ## Inputs Costs and accuracy come from one saturation-study directory `DIR`, the same diff --git a/scripts/export_autosketch_eval_table.py b/scripts/export_autosketch_eval_table.py index b89e0338..fa4e963a 100644 --- a/scripts/export_autosketch_eval_table.py +++ b/scripts/export_autosketch_eval_table.py @@ -38,6 +38,7 @@ import argparse import csv import hashlib +import itertools import json import math import os @@ -216,7 +217,8 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): SYNTHETIC_INTERVAL = 60 SYNTHETIC_QUANTILES = ["0.5", "0.75", "0.9", "0.95", "0.99"] SYNTHETIC_FAMILIES = {"sum": ["exact-sum"], "rate": ["exact-increase"], "topk": ["topk"], - "quantile": ["kll", "dd"]} + "quantile": ["kll", "dd"], "cardinality": ["hll"]} +SYNTHETIC_SKETCHES = {**FAMILIES, "hll": ("hll", "target_hll_rel_err", False)} EXACT_SKETCH = {"exact-sum": "exact-sum", "exact-increase": "exact-increase"} WINDOW_SECS = {"1m": 60, "5m": 300, "10m": 600, "15m": 900, "1h": 3600, "6h": 21600, "24h": 86400} @@ -227,9 +229,11 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): SHARED_QUANTILES = 3 SHARED_INTERVALS = [10, 60, 300] SHARED_SEED = 7 -TEMPLATE_SETS = ["dashboard", "all"] -# Workload grid (#777 section 6): the mixed template set ("all"), then each -# scaling dimension alone. One accuracy level, 95% in each family's metric +# "classic" is the 10-template mixed set; "all" adds the multi-grouping +# templates below. +TEMPLATE_SETS = ["dashboard", "classic", "all"] +# Workload grid (#777 section 6): for each of SYNTHETIC_TEMPLATE_SETS, the +# default point, then each scaling dimension alone. One accuracy level, 95% in each family's metric # (the runner's p95). `shared` replicas read one metric (the sharing benefit); # `metrics` copies of the template set each read their own metric, so RQEs # grow as 50 · m (planning time vs. RQEs). @@ -238,13 +242,153 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): "shared": [1, 8], "metrics": [1, 8, 16], } +SYNTHETIC_TEMPLATE_SETS = ["all", "classic"] + +# Multi-grouping templates (sketch-bench docs/rqe_optimizer_hydra.md): two +# metrics with an ordered label schema, each value read at several groupings +# on one stream, so a fine deployment can serve a coarse RQE (a roll-up) and +# one Hydra grid can serve them all. A label has `cardinality` values, or, +# with `child_of`, that many under each parent value (aqpbm-datagen's fan-out: +# the value is "parent.i"), drawn Zipf(`skew`) independently of the other +# labels given its parent. A value names its families' data shape: Zipf θ over +# `keys` distinct values (distinct counts), or the Pareto tail index +# (quantiles). The runner reads the shape, the groups and their shares +# (group_coverage()); the rest (latency scaling, the anomaly, the burst's +# sources) describes the data and is not modeled. Rates are the classic set's 2e6 samples/s, +# doubled for flows so its finest grouping (1e6 groups) holds the curves' +# first N (1e3 items) in a 5m window. +SCHEMAS = { + "http": { + "labels": [ + {"name": "region", "cardinality": 4, "skew": 0.5}, + {"name": "service", "cardinality": 25, "skew": 1.1}, + {"name": "endpoint", "cardinality": 25, "child_of": "service", "skew": 1.1}, + {"name": "status", "cardinality": 4, "skew": 2.0}, + ], + "rate": SYNTHETIC_SERIES * SYNTHETIC_SAMPLES_PER_SEC, + "values": { + "user_id": {"zipf": 0.8, "keys": 1_000_000}, + # Each service's latencies scaled by its own factor; one endpoint + # is 10x slower (the anomaly). Scaling keeps the tail index. + "latency": {"pareto": SYNTHETIC_ALPHA, "scaled_by": "service", + "anomaly": {"label": "endpoint", "factor": 10}}, + }, + }, + "flows": { + "labels": [ + {"name": "dst_subnet", "cardinality": 1000, "skew": 1.1}, + {"name": "dst_port", "cardinality": 1000, "skew": 1.2}, + {"name": "proto", "cardinality": 3, "skew": 0.0}, + ], + "rate": 2 * SYNTHETIC_SERIES * SYNTHETIC_SAMPLES_PER_SEC, + "values": { + # Uniform background sources, plus a DDoS burst: a tail subnet + # (the least popular, value 999) gets 5% of the traffic from 1e4 + # distinct sources, which makes it a group of share >= 5%. + "src_ip": {"zipf": 0.0, "keys": 1_000_000, + "burst": {"label": "dst_subnet", "value": 999, "share": 0.05, + "keys": 10_000}}, + }, + }, +} +SCHEMA_WINDOWS = "5m,15m" +SCHEMA_MIN_COVERED_N = 1e3 + + +def all_subsets(metric): + """Every non-empty subset of `metric`'s labels, in schema order.""" + names = [label["name"] for label in SCHEMAS[metric]["labels"]] + return [list(c) for n in range(1, len(names) + 1) for c in itertools.combinations(names, n)] + + +# (template, query, metric, value, capability, groupings, covers_share): one +# RQE per grouping and window. `covers_share` is the accuracy target's scope: +# only groups holding at least that share of the items (None: every group). +SCHEMA_TEMPLATES = [ + (11, "distinct_src", "flows", "src_ip", "cardinality", [["dst_subnet"]], 0.05), + (12, "distinct_src", "flows", "src_ip", "cardinality", + [["dst_port"], ["dst_subnet", "proto"], ["dst_port", "proto"]], 0.05), + (14, "distinct_users", "http", "user_id", "cardinality", + [["region"], ["service"], ["region", "service"], ["service", "endpoint"]], 0.01), + (15, "distinct_users", "http", "user_id", "cardinality", all_subsets("http"), 0.05), + (16, "p99_latency", "http", "latency", "quantile", + [["service"], ["region", "service"], ["service", "status"]], None), + # Negative control: every group, the smallest included. + (17, "distinct_users", "http", "user_id", "cardinality", [["service", "endpoint"]], None), +] + + +def closed_labels(metric, grouping): + """`grouping`'s labels with every child's ancestors (a child value names + its parent), in schema order.""" + labels = {label["name"]: label for label in SCHEMAS[metric]["labels"]} + closed, todo = set(), list(grouping) + while todo: + name = todo.pop() + if name not in closed: + closed.add(name) + todo += [labels[name]["child_of"]] if "child_of" in labels[name] else [] + return [labels[name] for name in labels if name in closed] + + +def grouping_cardinality(metric, grouping): + """Groups of `grouping` on `metric`: the product of its labels' fan-outs, + with every child's ancestors included.""" + return math.prod(label["cardinality"] for label in closed_labels(metric, grouping)) + + +def label_shares(metric, label): + """Each value's share of `metric`'s records (a child's: given its parent): + Zipf(`skew`), mixed with a value's burst.""" + weights = [(i + 1) ** -label["skew"] for i in range(label["cardinality"])] + shares = [w / sum(weights) for w in weights] + for value in SCHEMAS[metric]["values"].values(): + burst = value.get("burst") + if burst and burst["label"] == label["name"]: + shares = [(1 - burst["share"]) * p for p in shares] + shares[burst["value"]] += burst["share"] + return shares + + +def group_coverage(metric, grouping, covers_share): + """(covered groups, smallest and largest covered group's share of the + records) of an RQE at `grouping` covering groups of share >= + `covers_share`, plus always the largest group (None: every group). A group's share is the product of + its labels' shares: labels are drawn independently given their parents.""" + marginals = [sorted(label_shares(metric, label), reverse=True) + for label in closed_labels(metric, grouping)] + largest = math.prod(m[0] for m in marginals) + if covers_share is None: + return (grouping_cardinality(metric, grouping), math.prod(m[-1] for m in marginals), + largest) + # Enumerate the groups of share >= covers_share, largest values first; + # a prefix whose best completion falls short ends its loop. + best_rest = [math.prod(m[0] for m in marginals[i:]) for i in range(len(marginals) + 1)] + covered = [] + + def walk(i, share): + if i == len(marginals): + covered.append(share) + return + for p in marginals[i]: + if share * p * best_rest[i + 1] < covers_share: + break + walk(i + 1, share * p) + + walk(0, 1.0) + covered = covered or [largest] + return len(covered), min(covered), largest def synthetic_plan(): - """The default point and every dimension varied alone, each a full dict.""" - points = [dict(SYNTHETIC_DEFAULT)] - for dim, values in SYNTHETIC_GRID.items(): - points += [{**SYNTHETIC_DEFAULT, dim: v} for v in values] + """Per template set, the default point and every dimension varied alone, + each a full dict.""" + points = [] + for templates in SYNTHETIC_TEMPLATE_SETS: + default = {**SYNTHETIC_DEFAULT, "templates": templates} + points.append(default) + for dim, values in SYNTHETIC_GRID.items(): + points += [{**default, dim: v} for v in values] unique = [] for p in points: if p not in unique: @@ -272,7 +416,8 @@ def synthetic_queries(windows=SYNTHETIC_WINDOWS, interval=SYNTHETIC_INTERVAL, (S = T = 1 s); temporal ones repeat every `interval` seconds over each lookback in `windows`. RQEs that repeat another's query and range (template 10, D5) are kept once. With `metric`, every stream and query id names it, - so the queries share nothing with another metric's. + so the queries share nothing with another metric's. `all` adds + schema_queries() to the `classic` set. """ rate = SYNTHETIC_SERIES * SYNTHETIC_SAMPLES_PER_SEC # samples/s over all series dataset = dataset or "synthetic/" + point_id({"templates": templates, "shared": 1}) @@ -321,6 +466,7 @@ def add(query_id, stream, capability, rng, s, t, groups, keys=None): add(f"quantile_over_time_p{q}", "series/dist", "quantile", label(rng), s, interval, C) return out + assert templates in ("classic", "all"), templates quantiles = quantiles or SYNTHETIC_QUANTILES add("sum_by_job", "job/value", "sum", "1s", 1, 1, J) for q in quantiles: @@ -338,6 +484,57 @@ def add(query_id, stream, capability, rng, s, t, groups, keys=None): add("topk32_sum_by_label0_rate", "label_0/increment", "topk", lbl, s, interval, 1, C) for q in ["0.9", "0.5"]: # template 10, the same RQEs as template 5's add(f"quantile_over_time_p{q}", "series/dist", "quantile", lbl, s, interval, C) + if templates == "all": + out += schema_queries(interval, dataset, range_with_interval, seen, metric) + return out + + +def schema_queries(interval, dataset, range_with_interval, seen, metric=None): + """SCHEMA_TEMPLATES as synthetic_queries' query-ranges, over + SCHEMA_WINDOWS, repeating every `interval` seconds. A metric's values are + its streams (`http/user_id`); each RQE names its `grouping` and + `covers_share`, and carries its metric's schema. With `metric`, the + schema metrics are named under it (`data_1/http`).""" + out = [] + for n, what, name, value, capability, groupings, covers in SCHEMA_TEMPLATES: + schema = SCHEMAS[name] + shape = schema["values"][value] + full = f"{metric}/{name}" if metric else name + for grouping in groupings: + groups = grouping_cardinality(name, grouping) + query_id = f"t{n}_{what}_by_{','.join(grouping)}" + if metric: + query_id = f"{query_id}_{metric}" + for w in SCHEMA_WINDOWS.split(","): + s = WINDOW_SECS[w] + rng = f"{w}@{interval}s" if range_with_interval else w + if (query_id, rng) in seen: + continue + seen.add((query_id, rng)) + n_items = schema["rate"] * s / groups + covered, min_share, max_share = group_coverage(name, grouping, covers) + covered_min_n = schema["rate"] * s * min_share + # Accuracy is read at the smallest covered group: keep it on + # the curves (their first N is 1e3). + assert covered_min_n >= SCHEMA_MIN_COVERED_N, (query_id, rng, covered_min_n) + out.append({ + "dataset": dataset, "query_id": query_id, + "kind": "values" if capability == "quantile" else "keys", + "range": rng, "range_s": s, "step_s": interval, + "theta": shape.get("zipf"), "K": shape.get("keys"), + "min_N": n_items, "max_N": n_items, + "alpha_rank": shape.get("pareto"), "alpha_memory": shape.get("pareto"), + "tail_class": "", + "families": SYNTHETIC_FAMILIES[capability], "capability": capability, + "stream": f"{full}/{value}", "metric": full, "groups": groups, + "arrival_rate": schema["rate"], + "grouping": grouping, "covers_share": covers, "schema": schema, + "covered_groups": covered, "min_covered_share": min_share, + "covered_min_N": covered_min_n, "max_covered_share": max_share, + "covered_max_N": schema["rate"] * s * max_share, + "assumptions": [], + **DEFAULT_TARGETS, + }) return out @@ -372,21 +569,23 @@ def metric_queries(point): def synthetic_entry(q): """The table entry for one `synthetic` query-range: the workload only. Each family names its sketch, target and data shape (θ and K, or the - Pareto a for quantiles); exact accumulators need no shape.""" + Pareto a for quantiles); exact accumulators need no shape. A + schema_queries() RQE also names its `grouping`, `covers_share` and its + coverage (group_coverage()).""" families = [] for family in q["families"]: if family in EXACT_SKETCH: families.append({"family": family, "sketch": EXACT_SKETCH[family], "target": 0.0, "grid_param": None, "grid_K": None}) continue - sketch, target_col, _ = FAMILIES[family] + sketch, target_col, _ = SYNTHETIC_SKETCHES[family] quantile = q["capability"] == "quantile" families.append({ "family": family, "sketch": sketch, "target": q[target_col], - "grid_param": SYNTHETIC_ALPHA if quantile else SYNTHETIC_THETA, + "grid_param": q["alpha_rank"] if quantile else q["theta"], "grid_K": None if quantile else q["K"], }) - return { + entry = { "id": f"{q['dataset']}/{q['query_id']}/{q['kind']}/{q['range']}", "dataset": q["dataset"], "query_id": q["query_id"], "kind": q["kind"], "range": q["range"], "instant": False, @@ -394,11 +593,21 @@ def synthetic_entry(q): "min_N": q["min_N"], "max_N": q["max_N"], "queries_per_instance": queries_per_instance(q), "stream": q["stream"], "metric": q["metric"], "capability": q["capability"], + # keys_per_window: the value's universe K (the families' grid_K), not + # the distinct keys one group sees in a window. "label_set": {"groups": q["groups"], "arrival_rate_per_sec": q["arrival_rate"], "keys_per_window": q["K"]}, "assumptions": q["assumptions"], "families": families, } + if "grouping" in q: + # max_N is the mean group's items per window; covered_min_N and + # covered_max_N the smallest and largest covered group's + # (min_covered_share and max_covered_share of the stream's). + entry.update({k: q[k] for k in ["grouping", "covers_share", "covered_groups", + "min_covered_share", "covered_min_N", + "max_covered_share", "covered_max_N"]}) + return entry def queries_per_instance(q): @@ -432,13 +641,17 @@ def build_synthetic(args): else: qs = synthetic_queries(templates=point["templates"], dataset="synthetic/" + point_id(point)) + workload = {"dataset": qs[0]["dataset"], "rqes": [synthetic_entry(q) for q in qs]} + # Each schema metric's label schema, for the runner's facts. + schemas = {q["metric"]: q["schema"] for q in qs if "schema" in q} + if schemas: + workload["schemas"] = schemas out[name] = { "schema_version": 1, "plan": "ProjectASAP/ASAPQuery#777", "inputs": {}, "sketch_bench_revision": args.revision, - "workloads": [{"dataset": qs[0]["dataset"], - "rqes": [synthetic_entry(q) for q in qs]}], + "workloads": [workload], } result = name[:-len(".json")] + f"-t{point['target']}.json" plan.append((name, point["target"], result)) diff --git a/scripts/plot_autosketch_vs_asap_sla.py b/scripts/plot_autosketch_vs_asap_sla.py index 103b1294..0de7682a 100644 --- a/scripts/plot_autosketch_vs_asap_sla.py +++ b/scripts/plot_autosketch_vs_asap_sla.py @@ -35,11 +35,11 @@ def title(data): - """`mixed, r = 8` from `synthetic/templates=all/shared=8/tp95`.""" + """`mixed, r = 8` from `synthetic/templates=classic/shared=8/tp95`.""" m = re.search(r"templates=(\w+)/shared=(\d+)(?:/metrics=(\d+))?", data["workload"]) if not m: return data["workload"] - name = "mixed" if m.group(1) == "all" else m.group(1) + name = {"classic": "mixed", "all": "mixed + multi-grouping"}.get(m.group(1), m.group(1)) if m.group(3): return f"{name}, m = {m.group(3)}" if m.group(2) != "1": diff --git a/scripts/plot_autosketch_vs_asap_synthetic.py b/scripts/plot_autosketch_vs_asap_synthetic.py index 72849e2c..153f2be9 100644 --- a/scripts/plot_autosketch_vs_asap_synthetic.py +++ b/scripts/plot_autosketch_vs_asap_synthetic.py @@ -43,19 +43,24 @@ WEIGHT_TITLES = {"cpu": "CPU only", "fargate": "Fargate prices"} +# Each template set's title (export_autosketch_eval_table.py's TEMPLATE_SETS). +TEMPLATE_TITLES = {"classic": "mixed", "all": "mixed + multi-grouping"} + + def point(data): - """(shared, metrics) of a result's workload name.""" - m = re.search(r"shared=(\d+)(?:/metrics=(\d+))?", data["workload"]) - return int(m.group(1)), int(m.group(2) or 1) + """(templates, shared, metrics) of a result's workload name.""" + m = re.search(r"templates=(\w+)/shared=(\d+)(?:/metrics=(\d+))?", data["workload"]) + return m.group(1), int(m.group(2)), int(m.group(3) or 1) def title(key): - shared, metrics = key + templates, shared, metrics = key + name = TEMPLATE_TITLES.get(templates, templates) if shared > 1: - return f"mixed, r = {shared}" + return f"{name}, r = {shared}" if metrics > 1: - return f"mixed, m = {metrics}" - return "mixed" + return f"{name}, m = {metrics}" + return name def load(directory): @@ -128,10 +133,11 @@ def fig_frontier(runs, out): def fig_planning_time(runs, out): - """Over the metrics dimension (shared = 1), CPU-only weights.""" + """Over the metrics dimension (shared = 1) of the `all` set, CPU-only + weights.""" series = {"asap": [], "perquery": [], "search": [], "measured": [], "paper": []} - for (shared, _), data in runs.items(): - if shared != 1: + for (templates, shared, _), data in runs.items(): + if templates != "all" or shared != 1: continue n = data["rqes"] a = data["autosketch"] @@ -165,7 +171,7 @@ def fig_planning_time(runs, out): ax.set_xscale("log") ax.set_yscale("log") ax.grid(True, which="major", color="#e5e4e0", linewidth=0.5) - ax.set_xlabel("RQEs (mixed set, m = 1, 8, 16 metrics)", fontsize=8) + ax.set_xlabel(f"RQEs ({TEMPLATE_TITLES['all']}, m = 1, 8, 16 metrics)", fontsize=8) ax.set_ylabel("planning time (s)", fontsize=8) ax.tick_params(labelsize=7) ax.legend(fontsize=6, loc="upper center", bbox_to_anchor=(0.5, -0.2), ncol=2) @@ -175,7 +181,7 @@ def fig_planning_time(runs, out): def summary(runs, out): - lines = ["# Synthetic mixed set: AutoSketch vs. ASAP, cost by use\n", + lines = ["# Synthetic workload: AutoSketch vs. ASAP, cost by use\n", "Cost by use: `w_cpu · AUC(CPU) + w_mem · AUC(memory)` (CPU only, in vCPU; " "Fargate prices, in $/hour). Latency: a plan's query latency (its longest " "chain, compaction then query, CPU elastic), and the median over its RQEs. " diff --git a/scripts/test_export_autosketch_eval_table.py b/scripts/test_export_autosketch_eval_table.py index e45bf28c..ac3a7ee3 100644 --- a/scripts/test_export_autosketch_eval_table.py +++ b/scripts/test_export_autosketch_eval_table.py @@ -10,14 +10,15 @@ import sys import tempfile import unittest +from unittest import mock sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from study_saturation import COST_KEYS, COST_PARETO_ALPHA, COST_THETA # noqa: E402 from export_autosketch_eval_table import ( # noqa: E402 - SYNTHETIC_DEFAULT, SYNTHETIC_GRID, boom_query, main, metric_queries, queries_per_instance, - shared_queries, - synthetic_plan, synthetic_queries) + SCHEMA_TEMPLATES, SCHEMAS, SYNTHETIC_DEFAULT, SYNTHETIC_GRID, SYNTHETIC_TEMPLATE_SETS, + all_subsets, boom_query, group_coverage, grouping_cardinality, label_shares, main, metric_queries, queries_per_instance, + shared_queries, synthetic_plan, synthetic_queries) from study_saturation import CURVE_COLUMNS, SUMMARY_COLUMNS # noqa: E402 SUMMARY_HEADER = [ @@ -149,7 +150,7 @@ def test_chunk_defines_n_and_window(self): class SyntheticQueriesTest(unittest.TestCase): def test_ten_templates_give_50_distinct_rqes(self): - qs = synthetic_queries(templates="all") + qs = synthetic_queries(templates="classic") # 1 + 5 spatial; per window 1 + 1 + 5 + 1 + 1 + 1 + 1 temporal, and # template 10's operands repeat template 5's. self.assertEqual(len(qs), 6 + 11 * 4) @@ -161,7 +162,7 @@ def test_ten_templates_give_50_distinct_rqes(self): ("label_0/value", "topk", 1), ("label_0/increment", "topk", 1)}) def test_items_per_instance_follow_the_data_model(self): - qs = {(q["query_id"], q["range"]): q for q in synthetic_queries(templates="all")} + qs = {(q["query_id"], q["range"]): q for q in synthetic_queries(templates="classic")} # 1e4 series x 200 samples/s = 2e6 samples/s. self.assertEqual(qs[("quantile_by_job_p0.5", "1s")]["max_N"], 2e5) self.assertEqual(qs[("quantile_over_time_p0.5", "15m")]["max_N"], 200 * 900) @@ -173,14 +174,165 @@ def test_every_template_issues_one_query_per_instance(self): {1}) +COMMITTED_TABLES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", + "rqe-optimizer", "results", "autosketch-vs-asap-inputs", + "tables") + + +class SchemaTemplatesTest(unittest.TestCase): + def test_classic_tables_are_main_s_all_tables_byte_for_byte(self): + # The committed tables are the 10-template set's, from before "all" + # grew: renamed, today's "classic" tables match them byte for byte. + with tempfile.TemporaryDirectory() as out: + main(["--synthetic", "--revision", "test", "--out", out]) + classic = [n for n in sorted(os.listdir(out)) if "templatesclassic" in n] + self.assertEqual(len(classic), 4) + for name in classic: + with open(os.path.join(out, name)) as f: + ours = json.loads(f.read().replace("templates=classic", "templates=all")) + with open(os.path.join(COMMITTED_TABLES, + name.replace("templatesclassic", "templatesall"))) as f: + committed = json.load(f) + del ours["sketch_bench_revision"], committed["sketch_bench_revision"] + self.assertEqual(json.dumps(ours, sort_keys=True), + json.dumps(committed, sort_keys=True), name) + + def test_all_is_classic_plus_the_schema_templates(self): + classic = synthetic_queries(templates="classic", dataset="d") + every = synthetic_queries(templates="all", dataset="d") + self.assertEqual(every[:len(classic)], classic) + new = every[len(classic):] + # Per window (5m, 15m): 1 + 3 + 4 + 15 + 3 + 1 groupings. + self.assertEqual(len(new), 2 * 27) + self.assertEqual({q["stream"] for q in new}, + {"flows/src_ip", "http/user_id", "http/latency"}) + self.assertEqual({q["range"] for q in new}, {"5m", "15m"}) + self.assertTrue(all("grouping" not in q for q in classic)) + + def test_schema_cardinalities_count_a_child_with_its_parent(self): + self.assertEqual(grouping_cardinality("http", ["region"]), 4) + # An endpoint value names its service: 25 per service, 625 in all. + self.assertEqual(grouping_cardinality("http", ["endpoint"]), 625) + self.assertEqual(grouping_cardinality("http", ["service", "endpoint"]), 625) + self.assertEqual(grouping_cardinality("http", all_subsets("http")[-1]), 10_000) + self.assertEqual(grouping_cardinality("flows", ["dst_subnet", "dst_port"]), 10**6) + + def test_dropping_labels_never_adds_groups_and_rates_cover_every_group(self): + for metric, schema in SCHEMAS.items(): + subsets = all_subsets(metric) + for fine in subsets: + for coarse in subsets: + if set(coarse) < set(fine): + self.assertLessEqual(grouping_cardinality(metric, coarse), + grouping_cardinality(metric, fine)) + # Every grouping a template reads has a series per group (the + # runner's full label set) and the curves' first N in a 5m window. + for q in synthetic_queries(templates="all"): + if "grouping" in q: + self.assertLessEqual(q["groups"], q["arrival_rate"]) + self.assertGreaterEqual(q["max_N"], 1000) + + def test_template_groupings_are_ordered_subsets_of_the_schema(self): + for n, _, metric, value, _, groupings, _ in SCHEMA_TEMPLATES: + names = [label["name"] for label in SCHEMAS[metric]["labels"]] + self.assertIn(value, SCHEMAS[metric]["values"]) + for g in groupings: + self.assertTrue(g, n) + self.assertEqual(g, [x for x in names if x in g], n) + self.assertEqual(len(groupings), len({tuple(g) for g in groupings}), n) + groupings = {n: g for n, *_, g, _ in SCHEMA_TEMPLATES} + self.assertEqual(len(groupings[15]), 15) + self.assertEqual(groupings[17], [["service", "endpoint"]]) + + def test_rqe_entries_name_grouping_coverage_and_shape(self): + with tempfile.TemporaryDirectory() as out: + main(["--synthetic", "--revision", "test", "--out", out]) + with open(os.path.join(out, "synthetic-templatesall-shared1.json")) as f: + workload = json.load(f)["workloads"][0] + self.assertEqual(set(workload["schemas"]), {"http", "flows"}) + rqes = {r["query_id"] + "/" + r["range"]: r for r in workload["rqes"]} + r = rqes["t14_distinct_users_by_region,service/5m"] + self.assertEqual((r["grouping"], r["covers_share"], r["label_set"]["groups"]), + (["region", "service"], 0.01, 100)) + self.assertEqual(r["families"][0]["sketch"], "hll") + self.assertEqual((r["families"][0]["grid_param"], r["families"][0]["grid_K"]), + (0.8, 1_000_000)) + self.assertIsNone(rqes["t17_distinct_users_by_service,endpoint/15m"] + ["covers_share"]) + kll, dd = rqes["t16_p99_latency_by_service,status/5m"]["families"] + self.assertEqual((kll["grid_param"], kll["grid_K"]), (COST_PARETO_ALPHA, None)) + self.assertEqual(rqes["t11_distinct_src_by_dst_subnet/5m"]["covers_share"], 0.05) + self.assertEqual((r["covered_groups"], r["min_covered_share"], r["max_covered_share"], + r["covered_min_N"], r["covered_max_N"]), + group_coverage("http", ["region", "service"], 0.01) + + (2e6 * 300 * r["min_covered_share"], + 2e6 * 300 * r["max_covered_share"])) + + def test_label_shares_are_skewed_and_the_burst_lifts_a_tail_subnet(self): + for metric, schema in SCHEMAS.items(): + for label in schema["labels"]: + self.assertAlmostEqual(sum(label_shares(metric, label)), 1.0) + service = label_shares("http", SCHEMAS["http"]["labels"][1]) + self.assertGreater(service[0], 5 * service[-1]) + subnets = label_shares("flows", SCHEMAS["flows"]["labels"][0]) + self.assertGreaterEqual(subnets[999], 0.05) + + def test_coverage_is_the_groups_over_the_share_plus_the_largest(self): + # Brute force over every group: shares are products of the labels'. + http = {label["name"]: label for label in SCHEMAS["http"]["labels"]} + region, status = (label_shares("http", http[n]) for n in ["region", "status"]) + shares = [r * s for r in region for s in status] + for tau in [0.01, 0.05, 0.2]: + covered = [x for x in shares if x >= tau] + self.assertEqual(group_coverage("http", ["region", "status"], tau), + (len(covered), min(covered), max(shares))) + # No group holds 50%: the largest alone is covered. + self.assertEqual(group_coverage("http", ["region", "status"], 0.5), (1, max(shares), max(shares))) + self.assertEqual(group_coverage("http", ["region", "status"], None), + (16, min(shares), max(shares))) + # The DDoS subnet is one of template 11's covered groups. + n, smallest, _ = group_coverage("flows", ["dst_subnet"], 0.05) + self.assertGreater(n, 1) + self.assertAlmostEqual(smallest, label_shares("flows", SCHEMAS["flows"]["labels"][0])[999]) + + def test_every_covered_rqe_names_its_covered_groups_and_their_items(self): + for q in synthetic_queries(templates="all"): + if "grouping" in q: + self.assertGreaterEqual(q["covered_groups"], 1) + self.assertEqual(q["covered_min_N"], + q["arrival_rate"] * q["range_s"] * q["min_covered_share"]) + self.assertGreaterEqual(q["covered_min_N"], 1000) + self.assertEqual(q["covered_max_N"], + q["arrival_rate"] * q["range_s"] * q["max_covered_share"]) + self.assertGreaterEqual(q["max_covered_share"], q["min_covered_share"]) + + def test_a_covered_group_below_the_curves_first_n_fails_loudly(self): + # Every group of the full label set: the smallest has ~350 items in 5m. + full = (17, "distinct_users", "http", "user_id", "cardinality", + [all_subsets("http")[-1]], None) + with mock.patch("export_autosketch_eval_table.SCHEMA_TEMPLATES", [full]): + with self.assertRaises(AssertionError): + synthetic_queries(templates="all") + + def test_metric_copies_name_their_schema_metrics(self): + qs = metric_queries({**SYNTHETIC_DEFAULT, "metrics": 2}) + ids = [(q["query_id"], q["range"]) for q in qs] + self.assertEqual(len(ids), len(set(ids))) + self.assertEqual({q["metric"] for q in qs if "grouping" in q}, + {"data_0/http", "data_0/flows", "data_1/http", "data_1/flows"}) + + class SyntheticPlanTest(unittest.TestCase): def test_plan_is_the_default_and_each_dimension_alone(self): plan = synthetic_plan() self.assertEqual(plan[0], SYNTHETIC_DEFAULT) - for dim, values in SYNTHETIC_GRID.items(): - for v in values: - self.assertIn({**SYNTHETIC_DEFAULT, dim: v}, plan) - self.assertEqual(len(plan), 1 + sum(len(v) - 1 for v in SYNTHETIC_GRID.values())) + for templates in SYNTHETIC_TEMPLATE_SETS: + default = {**SYNTHETIC_DEFAULT, "templates": templates} + for dim, values in SYNTHETIC_GRID.items(): + for v in values: + self.assertIn({**default, dim: v}, plan) + self.assertEqual(len(plan), len(SYNTHETIC_TEMPLATE_SETS) + * (1 + sum(len(v) - 1 for v in SYNTHETIC_GRID.values()))) class DashboardAndSharedTest(unittest.TestCase): @@ -207,7 +359,7 @@ def test_shared_replicas_read_one_stream_and_dedupe(self): self.assertLess(sizes[0], sizes[1]) def test_metric_copies_share_nothing_and_grow_linearly(self): - point = {**SYNTHETIC_DEFAULT, "metrics": 8} + point = {**SYNTHETIC_DEFAULT, "templates": "classic", "metrics": 8} qs = metric_queries(point) self.assertEqual(len(qs), 8 * 50) self.assertEqual(len({(q["query_id"], q["range"]) for q in qs}), len(qs))