From f6dd276ff59215e059ff40b53406dda119804ace Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:02:29 +0000 Subject: [PATCH 01/10] eval: multi-grouping anomaly-detection templates (http, flows) The generator gets a metric-level ordered label schema (labels with cardinality, child_of fan-out and skew; per-value data shape) and per-RQE `grouping` and `covers_share`. The 10 templates are now the "classic" set, byte-for-byte the committed tables; "all" adds templates 11, 12, 14, 15, 16, 17 on `http` and `flows`, whose streams each carry several groupings so roll-ups (and later Hydra) can share. The plan runs both sets over the grid. The runner builds each schema stream's MetricFacts from the schema (labels = schema + x; cardinality per used grouping and the full set), takes Raqe.grouping_labels from the RQE's grouping, maps the `cardinality` capability to HLL, and reports covers_share and roll-up deployment groupings in each choice. Classic output is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 136 +++++++++++--- .../autosketch-vs-asap-synthetic/README.md | 46 +++++ scripts/export_autosketch_eval_table.py | 173 ++++++++++++++++-- scripts/test_export_autosketch_eval_table.py | 120 +++++++++++- 4 files changed, 425 insertions(+), 50 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index 027947b3..d0d41550 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -45,7 +45,10 @@ //! 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). //! //! Costs and accuracy come from `--saturation-dir`, the same inputs the //! planner reads (#174): the cost table `optimizer_cost/rqe_atomic_costs.json` @@ -101,6 +104,9 @@ 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). Reported only: the planner reads every group's accuracy. + covers_share: BTreeMap>, curves: SaturationCurves, notes: Vec, } @@ -199,6 +205,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 +286,7 @@ 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(); 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 +303,50 @@ 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` + if let Some(share) = r.get("covers_share") { + covers_share.insert(id.clone(), share.as_f64()); + } + // 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 +419,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 @@ -419,6 +445,7 @@ fn from_table( costs, metric_of, excluded_high_cardinality, + covers_share, curves, notes: vec![ format!("{skipped_families} families skipped: they serve another capability"), @@ -564,7 +591,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"], @@ -579,7 +606,15 @@ fn summarize( .curves .accuracy_with_source(r, d, &w.facts) .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!({ @@ -1022,6 +1057,57 @@ mod tests { assert!(!meets_sla(100.1, 100.0)); } + /// Runs on the committed eval inputs, whose curves are #194's. + #[test] + fn a_schema_stream_carries_every_grouping_and_rolls_up() { + let rqe = |grouping: &[&str], groups: u64| { + json!({ + "id": format!("t/{}", grouping.join(",")), "query_id": "q", "kind": "keys", + "capability": "cardinality", "metric": "http", "stream": "http/user_id", + "grouping": grouping, "covers_share": 0.05, + "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.8, "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), rqe(&["region", "service"], 100)], + }]}); + let path = std::env::temp_dir().join(format!("schema-table-{}.json", std::process::id())); + std::fs::write(&path, table.to_string()).unwrap(); + let inputs = concat!( + env!("CARGO_MANIFEST_DIR"), + "/results/autosketch-vs-asap-inputs/saturation" + ); + let w = from_table(path.to_str().unwrap(), None, Some("p95".into()), inputs); + std::fs::remove_file(&path).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); + // 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); + } + #[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..69a4c684 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -66,6 +66,52 @@ 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 only groups holding at least that share of the items; +`null`: every group); the table's `schemas` gives each metric's labels. + +| Metric | Labels (values, Zipf skew) | Rate | Values | +|---|---|---|---| +| `http` | region 4, service 25, endpoint 25 per service (625), status 4; uniform; 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: one subnet 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). + +| # | Query | Groupings | Covers | Groups (items per group in 5m) | +|---|---|---|---|---| +| 11 | distinct src_ip | {dst_subnet} | share ≥ 5% | 1e3 (1.2e6) | +| 12 | distinct src_ip | {dst_port}, {dst_subnet, dst_port}, {dst_port, proto} | share ≥ 5% | 1e3, 1e6, 3e3 (1.2e6, 1.2e3, 4e5) | +| 14 | distinct user_id | {region}, {service}, {region, service}, {service, endpoint} | share ≥ 1% | 4, 25, 100, 625 (1.5e8 to 9.6e5) | +| 15 | distinct user_id | all 15 non-empty subsets of http's labels | share ≥ 5% | 4 to 1e4 (1.5e8 to 6e4) | +| 16 | p99 latency | {service}, {region, service}, {service, status} | all groups | 25, 100, 100 (2.4e7, 6e6, 6e6) | +| 17 | distinct user_id | {region, service, endpoint, status} (negative control) | all groups | 1e4 (6e4) | + +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. The planner reads every group's accuracy for now; +`covers_share` is carried through to each choice in the runner's output. + +On the committed inputs (`all`, r = 1, CPU weights, `--runs 1`), no RQE is +dropped and no sanity check fails; ASAP serves 38 of the 54 new RQEs from a +finer deployment: every RQE of templates 14 and 15 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 {service, status}. 15 active deployments in +all, 5.06 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..4665de6a 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,99 @@ 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`). A value names its families' +# data shape: Zipf θ over `keys` distinct values (distinct counts), or the +# Pareto tail index (quantiles). 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.0}, + {"name": "service", "cardinality": 25, "skew": 0.0}, + {"name": "endpoint", "cardinality": 25, "child_of": "service", "skew": 0.0}, + {"name": "status", "cardinality": 4, "skew": 0.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: one subnet gets + # 5% of the traffic from 1e4 distinct sources. + "src_ip": {"zipf": 0.0, "keys": 1_000_000, + "burst": {"label": "dst_subnet", "share": 0.05, "keys": 10_000}}, + }, + }, +} +SCHEMA_WINDOWS = "5m,15m" + + +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", "dst_port"], ["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: the full label set, every group. + (17, "distinct_users", "http", "user_id", "cardinality", + [all_subsets("http")[-1]], None), +] + + +def grouping_cardinality(metric, grouping): + """Groups of `grouping` on `metric`: the product of its labels' fan-outs, + with every child's ancestors included (a child value names its parent).""" + 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 math.prod(labels[name]["cardinality"] for name in closed) 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 +362,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 +412,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 +430,49 @@ 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 + 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, + "assumptions": [], + **DEFAULT_TARGETS, + }) return out @@ -372,21 +507,22 @@ 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` and `covers_share`.""" 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, @@ -399,6 +535,9 @@ def synthetic_entry(q): "assumptions": q["assumptions"], "families": families, } + if "grouping" in q: + entry.update(grouping=q["grouping"], covers_share=q["covers_share"]) + return entry def queries_per_instance(q): @@ -432,13 +571,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/test_export_autosketch_eval_table.py b/scripts/test_export_autosketch_eval_table.py index e45bf28c..1d823daa 100644 --- a/scripts/test_export_autosketch_eval_table.py +++ b/scripts/test_export_autosketch_eval_table.py @@ -15,9 +15,9 @@ 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, grouping_cardinality, 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 +149,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 +161,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 +173,114 @@ 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], [["region", "service", "endpoint", "status"]]) + + 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_region,service,endpoint,status/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) + + 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 +307,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)) From 747adfd6d158fb78feae9df83f86ba310889116b Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:20:45 +0000 Subject: [PATCH 02/10] eval: skewed http labels, per-RQE group coverage, fresh-checkout test Review of #196. http's labels are now Zipf-skewed (region 0.5, service 1.1, endpoint 1.1 within its service, status 2.0) and the flows DDoS burst targets a tail subnet, so covers_share selects a few groups. The generator computes each group's share (product of its labels' shares) and, per RQE, the covered groups (share >= tau, plus always the largest) and the smallest covered group's share and items per window. The runner reads a covered RQE's accuracy (ASAP and AutoSketch) at that group's items instead of the mean group's; covers_share = null is unchanged. The schema test reads an inline HLL curve fixture instead of the gitignored study curves. The synthetic plot keys runs by template set too, and both plot scripts title classic "mixed" and all "mixed + multi-grouping". README: the coverage rule, the N the runner uses, and which schema fields are descriptive. label_set.keys_per_window is commented as the universe K. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 91 +++++++++++++++--- .../autosketch-vs-asap-synthetic/README.md | 52 ++++++---- scripts/export_autosketch_eval_table.py | 95 +++++++++++++++---- scripts/plot_autosketch_vs_asap_sla.py | 4 +- scripts/plot_autosketch_vs_asap_synthetic.py | 30 +++--- scripts/test_export_autosketch_eval_table.py | 40 +++++++- 6 files changed, 253 insertions(+), 59 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index d0d41550..7724dd49 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -49,6 +49,9 @@ //! 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`, at its smallest covered group's (`min_covered_share` of +//! the stream's): the hardest group its target covers. //! //! Costs and accuracy come from `--saturation-dir`, the same inputs the //! planner reads (#174): the cost table `optimizer_cost/rqe_atomic_costs.json` @@ -105,21 +108,31 @@ struct Workload { /// 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). Reported only: the planner reads every group's accuracy. + /// 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`: its stream's, with the series + /// scaled so the mean group gets that group's items. + covered_facts: BTreeMap, curves: SaturationCurves, notes: Vec, } impl Workload { + /// 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) + } + /// ASAP's accuracy: the planner's own lookup. fn asap_accuracy(&self, r: &Raqe, d: &Deployment) -> Option { - self.curves.accuracy(r, d, &self.facts) + self.curves.accuracy(r, d, self.accuracy_facts(r)) } /// 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.curves + .autosketch_accuracy(r, c, self.accuracy_facts(r)) } } @@ -287,6 +300,7 @@ fn from_table( 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(); 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); @@ -316,6 +330,9 @@ fn from_table( }; if let Some(share) = r.get("covers_share") { covers_share.insert(id.clone(), share.as_f64()); + if !share.is_null() { + min_covered_share.insert(id.clone(), r["min_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 @@ -433,6 +450,19 @@ 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 covered group's items. + let covered_facts = raqes + .iter() + .filter_map(|r| { + let share = min_covered_share.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 name = if dataset.starts_with("synthetic") { format!("{dataset}/t{}", target.as_deref().unwrap_or("p95")) } else { @@ -446,6 +476,7 @@ fn from_table( metric_of, excluded_high_cardinality, covers_share, + covered_facts, curves, notes: vec![ format!("{skipped_families} families skipped: they serve another capability"), @@ -604,7 +635,7 @@ fn summarize( "asap_accuracy": w.asap_accuracy(r, d), "accuracy_source": w .curves - .accuracy_with_source(r, d, &w.facts) + .accuracy_with_source(r, d, w.accuracy_facts(r)) .map(|(_, source)| format!("{source:?}")), }); // A roll-up: the deployment is grouped finer than the RQE. @@ -1057,18 +1088,49 @@ mod tests { assert!(!meets_sla(100.1, 100.0)); } - /// Runs on the committed eval inputs, whose curves are #194's. + /// 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. + fn hll_saturation_dir() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("hll-saturation-{}", 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| { json!({ "id": format!("t/{}", grouping.join(",")), "query_id": "q", "kind": "keys", "capability": "cardinality", "metric": "http", "stream": "http/user_id", - "grouping": grouping, "covers_share": 0.05, + "grouping": grouping, "covers_share": 0.05, "min_covered_share": 0.05, "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.8, "grid_K": 1e6}], + "grid_param": 0.0, "grid_K": 1e6}], }) }; let names = ["region", "service", "endpoint", "status"]; @@ -1079,12 +1141,15 @@ mod tests { }]}); let path = std::env::temp_dir().join(format!("schema-table-{}.json", std::process::id())); std::fs::write(&path, table.to_string()).unwrap(); - let inputs = concat!( - env!("CARGO_MANIFEST_DIR"), - "/results/autosketch-vs-asap-inputs/saturation" + let inputs = hll_saturation_dir(); + let w = from_table( + path.to_str().unwrap(), + None, + Some("p95".into()), + inputs.to_str().unwrap(), ); - let w = from_table(path.to_str().unwrap(), None, Some("p95".into()), inputs); 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, @@ -1093,6 +1158,10 @@ 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); + // 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); // One {region, service} deployment serves both RQEs. let result = evaluate(&w, 1, &WEIGHTS[..1], &[1e4]); let asap = result["results"] diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index 69a4c684..3000de13 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -75,37 +75,55 @@ 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 only groups holding at least that share of the items; -`null`: every group); the table's `schemas` gives each metric's labels. +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); the table's `schemas` gives each metric's labels. | Metric | Labels (values, Zipf skew) | Rate | Values | |---|---|---|---| -| `http` | region 4, service 25, endpoint 25 per service (625), status 4; uniform; 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: one subnet gets 5% of the traffic from 1e4 sources | +| `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). +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: the +mean group's (`max_N`) for `covers_share` = `null`, else the smallest +covered group's (`covered_min_N`), the hardest group the target covers. The +skew of the counted value is the same in every group; label skew changes only +the group sizes. + +| # | 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, dst_port}, {dst_port, proto} | share ≥ 5% | 1e3, 1e6, 3e3 (1.2e6, 1.2e3, 4e5) | 3, 1, 3 (7.4e7, 4.7e7, 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 | +| 17 | distinct user_id | {region, service, endpoint, status} (negative control) | all groups | 1e4 (6e4) | all | -| # | Query | Groupings | Covers | Groups (items per group in 5m) | -|---|---|---|---|---| -| 11 | distinct src_ip | {dst_subnet} | share ≥ 5% | 1e3 (1.2e6) | -| 12 | distinct src_ip | {dst_port}, {dst_subnet, dst_port}, {dst_port, proto} | share ≥ 5% | 1e3, 1e6, 3e3 (1.2e6, 1.2e3, 4e5) | -| 14 | distinct user_id | {region}, {service}, {region, service}, {service, endpoint} | share ≥ 1% | 4, 25, 100, 625 (1.5e8 to 9.6e5) | -| 15 | distinct user_id | all 15 non-empty subsets of http's labels | share ≥ 5% | 4 to 1e4 (1.5e8 to 6e4) | -| 16 | p99 latency | {service}, {region, service}, {service, status} | all groups | 25, 100, 100 (2.4e7, 6e6, 6e6) | -| 17 | distinct user_id | {region, service, endpoint, status} (negative control) | all groups | 1e4 (6e4) | +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. The planner reads every group's accuracy for now; -`covers_share` is carried through to each choice in the runner's output. +at the p95 level. `covers_share` is carried through to each choice in the +runner's output. On the committed inputs (`all`, r = 1, CPU weights, `--runs 1`), no RQE is -dropped and no sanity check fails; ASAP serves 38 of the 54 new RQEs from a +dropped and no sanity check fails (the same numbers as with uniform labels); ASAP serves 38 of the 54 new RQEs from a finer deployment: every RQE of templates 14 and 15 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 diff --git a/scripts/export_autosketch_eval_table.py b/scripts/export_autosketch_eval_table.py index 4665de6a..be3658e3 100644 --- a/scripts/export_autosketch_eval_table.py +++ b/scripts/export_autosketch_eval_table.py @@ -249,18 +249,21 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): # 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`). A value names its families' -# data shape: Zipf θ over `keys` distinct values (distinct counts), or the -# Pareto tail index (quantiles). Rates are the classic set's 2e6 samples/s, +# 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.0}, - {"name": "service", "cardinality": 25, "skew": 0.0}, - {"name": "endpoint", "cardinality": 25, "child_of": "service", "skew": 0.0}, - {"name": "status", "cardinality": 4, "skew": 0.0}, + {"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": { @@ -279,10 +282,12 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): ], "rate": 2 * SYNTHETIC_SERIES * SYNTHETIC_SAMPLES_PER_SEC, "values": { - # Uniform background sources, plus a DDoS burst: one subnet gets - # 5% of the traffic from 1e4 distinct sources. + # 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", "share": 0.05, "keys": 10_000}}, + "burst": {"label": "dst_subnet", "value": 999, "share": 0.05, + "keys": 10_000}}, }, }, } @@ -313,9 +318,9 @@ def all_subsets(metric): ] -def grouping_cardinality(metric, grouping): - """Groups of `grouping` on `metric`: the product of its labels' fan-outs, - with every child's ancestors included (a child value names its parent).""" +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: @@ -323,7 +328,56 @@ def grouping_cardinality(metric, grouping): if name not in closed: closed.add(name) todo += [labels[name]["child_of"]] if "child_of" in labels[name] else [] - return math.prod(labels[name]["cardinality"] for name in closed) + 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 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) + # 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] + assert covered, (metric, grouping) + return len(covered), min(covered) def synthetic_plan(): @@ -458,6 +512,7 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): continue seen.add((query_id, rng)) n_items = schema["rate"] * s / groups + covered, min_share = group_coverage(name, grouping, covers) out.append({ "dataset": dataset, "query_id": query_id, "kind": "values" if capability == "quantile" else "keys", @@ -470,6 +525,8 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): "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": schema["rate"] * s * min_share, "assumptions": [], **DEFAULT_TARGETS, }) @@ -508,7 +565,8 @@ 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. A - schema_queries() RQE also names its `grouping` and `covers_share`.""" + 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: @@ -530,13 +588,18 @@ 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: - entry.update(grouping=q["grouping"], covers_share=q["covers_share"]) + # max_N is the mean group's items per window; covered_min_N the + # smallest covered group's (min_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"]}) return entry 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 1d823daa..613462a9 100644 --- a/scripts/test_export_autosketch_eval_table.py +++ b/scripts/test_export_autosketch_eval_table.py @@ -16,7 +16,7 @@ from study_saturation import COST_KEYS, COST_PARETO_ALPHA, COST_THETA # noqa: E402 from export_autosketch_eval_table import ( # noqa: E402 SCHEMA_TEMPLATES, SCHEMAS, SYNTHETIC_DEFAULT, SYNTHETIC_GRID, SYNTHETIC_TEMPLATE_SETS, - all_subsets, boom_query, grouping_cardinality, main, metric_queries, queries_per_instance, + 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 @@ -261,6 +261,44 @@ def test_rqe_entries_name_grouping_coverage_and_shape(self): 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["covered_min_N"]), + group_coverage("http", ["region", "service"], 0.01) + + (2e6 * 300 * r["min_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))) + # No group holds 50%: the largest alone is covered. + self.assertEqual(group_coverage("http", ["region", "status"], 0.5), (1, max(shares))) + self.assertEqual(group_coverage("http", ["region", "status"], None), + (16, min(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 q.get("covers_share") is not None: + 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) def test_metric_copies_name_their_schema_metrics(self): qs = metric_queries({**SYNTHETIC_DEFAULT, "metrics": 2}) From 561ee86289c45a888055f3f4cdfcd445888d8cb1 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:33:34 +0000 Subject: [PATCH 03/10] eval: read null-coverage RQEs at their smallest group; template 17 at {service, endpoint} - covers_share = null covers every group, so the runner reads its accuracy at the smallest group (min_covered_share), like a tau RQE's smallest covered group. Classic RQEs (no covers_share) are unchanged. - Template 17 (negative control) groups by {service, endpoint}: its smallest group holds 4.5e4 items in 5m, on the curves. - The generator asserts every schema RQE's covered_min_N >= 1e3 (drops the vacuous `assert covered`); a test checks the old full-label-set template fails it. - Covered facts go through validate_facts. - README: null semantics, template 17, and the numbers' provenance (fresh `all` table, committed saturation inputs). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 33 +++++++++++++------ .../autosketch-vs-asap-synthetic/README.md | 30 +++++++++-------- scripts/export_autosketch_eval_table.py | 13 +++++--- scripts/test_export_autosketch_eval_table.py | 15 +++++++-- 4 files changed, 60 insertions(+), 31 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index 7724dd49..e3a57247 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -50,8 +50,8 @@ //! 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`, at its smallest covered group's (`min_covered_share` of -//! the stream's): the hardest group its target covers. +//! a `covers_share` (`null`: every group), at its smallest covered group's +//! (`min_covered_share` of the stream's): the hardest group its target covers. //! //! Costs and accuracy come from `--saturation-dir`, the same inputs the //! planner reads (#174): the cost table `optimizer_cost/rqe_atomic_costs.json` @@ -111,8 +111,8 @@ struct Workload { /// 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`: its stream's, with the series - /// scaled so the mean group gets that group's items. + /// 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, curves: SaturationCurves, notes: Vec, @@ -328,11 +328,10 @@ fn from_table( None if groups > 1 => label_set(&["g"]), None => LabelSet::new(), }; + // `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()); - if !share.is_null() { - min_covered_share.insert(id.clone(), r["min_covered_share"].as_f64().unwrap()); - } + min_covered_share.insert(id.clone(), r["min_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 @@ -772,6 +771,14 @@ 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() + .filter_map(|r| Some((r, w.covered_facts.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(); @@ -1122,11 +1129,11 @@ mod tests { #[test] fn a_schema_stream_carries_every_grouping_and_rolls_up() { - let rqe = |grouping: &[&str], groups: u64| { + 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": 0.05, "min_covered_share": 0.05, + "grouping": grouping, "covers_share": covers, "min_covered_share": smallest, "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, @@ -1137,7 +1144,10 @@ mod tests { let table = json!({"workloads": [{ "dataset": "synthetic/test", "schemas": {"http": {"labels": names.map(|n| json!({"name": n}))}}, - "rqes": [rqe(&["region"], 4), rqe(&["region", "service"], 100)], + "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(); @@ -1162,6 +1172,9 @@ mod tests { // 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"] diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index 3000de13..c5aece39 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -97,10 +97,12 @@ 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: the -mean group's (`max_N`) for `covers_share` = `null`, else the smallest -covered group's (`covered_min_N`), the hardest group the target covers. The -skew of the counted value is the same in every group; label skew changes only -the group sizes. +smallest covered group's (`covered_min_N`), the hardest group the target +covers; for `covers_share` = `null` that is the smallest group of all. 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) | |---|---|---|---|---|---| @@ -108,8 +110,8 @@ the group sizes. | 12 | distinct src_ip | {dst_port}, {dst_subnet, dst_port}, {dst_port, proto} | share ≥ 5% | 1e3, 1e6, 3e3 (1.2e6, 1.2e3, 4e5) | 3, 1, 3 (7.4e7, 4.7e7, 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 | -| 17 | distinct user_id | {region, service, endpoint, status} (negative control) | all groups | 1e4 (6e4) | all | +| 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 @@ -122,13 +124,15 @@ 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 the committed inputs (`all`, r = 1, CPU weights, `--runs 1`), no RQE is -dropped and no sanity check fails (the same numbers as with uniform labels); ASAP serves 38 of the 54 new RQEs from a -finer deployment: every RQE of templates 14 and 15 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 {service, status}. 15 active deployments in -all, 5.06 vCPU; PerQuery-CostAware 11.8 vCPU; AutoSketch 3.42e+03 vCPU. +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 diff --git a/scripts/export_autosketch_eval_table.py b/scripts/export_autosketch_eval_table.py index be3658e3..37b54f59 100644 --- a/scripts/export_autosketch_eval_table.py +++ b/scripts/export_autosketch_eval_table.py @@ -292,6 +292,7 @@ def rqe_entry(q, curves, curves_big, sat, sat_big, merge): }, } SCHEMA_WINDOWS = "5m,15m" +SCHEMA_MIN_COVERED_N = 1e3 def all_subsets(metric): @@ -312,9 +313,8 @@ def all_subsets(metric): (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: the full label set, every group. - (17, "distinct_users", "http", "user_id", "cardinality", - [all_subsets("http")[-1]], None), + # Negative control: every group, the smallest included. + (17, "distinct_users", "http", "user_id", "cardinality", [["service", "endpoint"]], None), ] @@ -376,7 +376,6 @@ def walk(i, share): walk(0, 1.0) covered = covered or [largest] - assert covered, (metric, grouping) return len(covered), min(covered) @@ -513,6 +512,10 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): seen.add((query_id, rng)) n_items = schema["rate"] * s / groups covered, min_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", @@ -526,7 +529,7 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): "arrival_rate": schema["rate"], "grouping": grouping, "covers_share": covers, "schema": schema, "covered_groups": covered, "min_covered_share": min_share, - "covered_min_N": schema["rate"] * s * min_share, + "covered_min_N": covered_min_n, "assumptions": [], **DEFAULT_TARGETS, }) diff --git a/scripts/test_export_autosketch_eval_table.py b/scripts/test_export_autosketch_eval_table.py index 613462a9..1681983e 100644 --- a/scripts/test_export_autosketch_eval_table.py +++ b/scripts/test_export_autosketch_eval_table.py @@ -10,6 +10,7 @@ import sys import tempfile import unittest +from unittest import mock sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -241,7 +242,7 @@ def test_template_groupings_are_ordered_subsets_of_the_schema(self): 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], [["region", "service", "endpoint", "status"]]) + self.assertEqual(groupings[17], [["service", "endpoint"]]) def test_rqe_entries_name_grouping_coverage_and_shape(self): with tempfile.TemporaryDirectory() as out: @@ -256,7 +257,7 @@ def test_rqe_entries_name_grouping_coverage_and_shape(self): 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_region,service,endpoint,status/15m"] + 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)) @@ -294,12 +295,20 @@ def test_coverage_is_the_groups_over_the_share_plus_the_largest(self): def test_every_covered_rqe_names_its_covered_groups_and_their_items(self): for q in synthetic_queries(templates="all"): - if q.get("covers_share") is not None: + 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) + 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] From e7d8a036409e164814cd345c07a60f12fee313bc Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 11:32:31 +0000 Subject: [PATCH 04/10] eval: hold covered RQEs to the worse of their smallest and largest group Per sketch-bench#189, KLL/DD/HLL error does not fall as N grows, so the largest covered group can be harder than the smallest. The generator also emits max_covered_share / covered_max_N (the largest group, always covered); the runner reads each covered RQE's accuracy at both the smallest and the largest covered group and keeps the worse (direction-aware), unknown if either read is. Classic RQEs and Hydra's lookup are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 207 +++++++++++++++--- .../autosketch-vs-asap-synthetic/README.md | 11 +- scripts/export_autosketch_eval_table.py | 24 +- scripts/test_export_autosketch_eval_table.py | 17 +- 4 files changed, 208 insertions(+), 51 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index e3a57247..11b619d4 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -50,8 +50,10 @@ //! 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 covered group's -//! (`min_covered_share` of the stream's): the hardest group its target covers. +//! 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` @@ -68,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}; @@ -114,6 +116,8 @@ struct Workload { /// 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, } @@ -124,15 +128,45 @@ impl Workload { self.covered_facts.get(&r.id).unwrap_or(&self.facts) } - /// ASAP's accuracy: the planner's own lookup. + /// `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.accuracy_facts(r)) + 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.accuracy_facts(r)) + self.worse_read(r, &c.sketch, |facts| { + Some((self.curves.autosketch_accuracy(r, c, facts)?, ())) + }) + .map(|(value, _)| value) } } @@ -301,6 +335,7 @@ fn from_table( 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); @@ -332,6 +367,7 @@ fn from_table( 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 @@ -450,18 +486,22 @@ fn from_table( 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 covered group's items. - let covered_facts = raqes - .iter() - .filter_map(|r| { - let share = min_covered_share.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(); + // 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 { @@ -476,6 +516,7 @@ fn from_table( excluded_high_cardinality, covers_share, covered_facts, + largest_facts, curves, notes: vec![ format!("{skipped_families} families skipped: they serve another capability"), @@ -633,8 +674,7 @@ fn summarize( "deployment": di, "asap_accuracy": w.asap_accuracy(r, d), "accuracy_source": w - .curves - .accuracy_with_source(r, d, w.accuracy_facts(r)) + .accuracy_with_source(r, d) .map(|(_, source)| format!("{source:?}")), }); // A roll-up: the deployment is grouped finer than the RQE. @@ -771,10 +811,11 @@ 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() - .filter_map(|r| Some((r, w.covered_facts.get(&r.id)?))) - { + 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:?}"); } @@ -1097,9 +1138,9 @@ mod tests { /// 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. - fn hll_saturation_dir() -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("hll-saturation-{}", std::process::id())); + /// 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" @@ -1134,6 +1175,7 @@ mod tests { "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, @@ -1151,7 +1193,7 @@ mod tests { }]}); 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(); + let inputs = hll_saturation_dir("schema"); let w = from_table( path.to_str().unwrap(), None, @@ -1190,6 +1232,109 @@ mod tests { 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 c5aece39..e6239848 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -81,7 +81,7 @@ 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); the table's `schemas` gives each metric's labels. +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 | |---|---|---|---| @@ -96,9 +96,12 @@ 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: the -smallest covered group's (`covered_min_N`), the hardest group the target -covers; for `covers_share` = `null` that is the smallest group of all. The +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 diff --git a/scripts/export_autosketch_eval_table.py b/scripts/export_autosketch_eval_table.py index 37b54f59..80f41986 100644 --- a/scripts/export_autosketch_eval_table.py +++ b/scripts/export_autosketch_eval_table.py @@ -351,15 +351,16 @@ def label_shares(metric, label): def group_coverage(metric, grouping, covers_share): - """(covered groups, smallest 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 + """(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) + 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)] @@ -376,7 +377,7 @@ def walk(i, share): walk(0, 1.0) covered = covered or [largest] - return len(covered), min(covered) + return len(covered), min(covered), largest def synthetic_plan(): @@ -511,7 +512,7 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): continue seen.add((query_id, rng)) n_items = schema["rate"] * s / groups - covered, min_share = group_coverage(name, grouping, covers) + 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). @@ -529,7 +530,8 @@ def schema_queries(interval, dataset, range_with_interval, seen, metric=None): "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, + "covered_min_N": covered_min_n, "max_covered_share": max_share, + "covered_max_N": schema["rate"] * s * max_share, "assumptions": [], **DEFAULT_TARGETS, }) @@ -599,10 +601,12 @@ def synthetic_entry(q): "families": families, } if "grouping" in q: - # max_N is the mean group's items per window; covered_min_N the - # smallest covered group's (min_covered_share of the stream's). + # 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"]}) + "min_covered_share", "covered_min_N", + "max_covered_share", "covered_max_N"]}) return entry diff --git a/scripts/test_export_autosketch_eval_table.py b/scripts/test_export_autosketch_eval_table.py index 1681983e..ac3a7ee3 100644 --- a/scripts/test_export_autosketch_eval_table.py +++ b/scripts/test_export_autosketch_eval_table.py @@ -262,9 +262,11 @@ def test_rqe_entries_name_grouping_coverage_and_shape(self): 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["covered_min_N"]), + 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["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(): @@ -283,13 +285,13 @@ def test_coverage_is_the_groups_over_the_share_plus_the_largest(self): 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))) + (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))) + 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))) + (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) + n, smallest, _ = group_coverage("flows", ["dst_subnet"], 0.05) self.assertGreater(n, 1) self.assertAlmostEqual(smallest, label_shares("flows", SCHEMAS["flows"]["labels"][0])[999]) @@ -300,6 +302,9 @@ def test_every_covered_rqe_names_its_covered_groups_and_their_items(self): 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. From 390bfb324d987655e73ad4260066571afdf4eac7 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 12:25:22 +0000 Subject: [PATCH 05/10] eval: template 12 groups by (dst_subnet, proto), not (dst_subnet, dst_port) (dst_subnet, dst_port) has 1e6 groups; answering each every minute takes about 49 s on one core, which set every plan's batch latency above the largest SLA (10 s) and collapsed the multi-grouping frontier. (dst_subnet, proto) has 3e3 groups and keeps three groupings over one stream. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md | 2 +- scripts/export_autosketch_eval_table.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index e6239848..40b42e79 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -110,7 +110,7 @@ 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, dst_port}, {dst_port, proto} | share ≥ 5% | 1e3, 1e6, 3e3 (1.2e6, 1.2e3, 4e5) | 3, 1, 3 (7.4e7, 4.7e7, 9.2e7) | +| 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) | diff --git a/scripts/export_autosketch_eval_table.py b/scripts/export_autosketch_eval_table.py index 80f41986..fa4e963a 100644 --- a/scripts/export_autosketch_eval_table.py +++ b/scripts/export_autosketch_eval_table.py @@ -307,7 +307,7 @@ def all_subsets(metric): SCHEMA_TEMPLATES = [ (11, "distinct_src", "flows", "src_ip", "cardinality", [["dst_subnet"]], 0.05), (12, "distinct_src", "flows", "src_ip", "cardinality", - [["dst_port"], ["dst_subnet", "dst_port"], ["dst_port", "proto"]], 0.05), + [["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), From b4f67bb3a2570a4caccb211868b676ed439b333c Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 05:03:02 +0000 Subject: [PATCH 06/10] rqe-optimizer: admit Hydra (HLL, UnivMon cardinality, KLL) as candidates, with measured accuracy by coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - FamilyProperties for hydra-hll, hydra-univmon-cardinality and hydra-kll: one fixed-size grid, DeltaSet key tracker, no roll-up, and the new answers_any_subgrouping. Added to Capability::families, not to DEPLOYABLE_FAMILIES. - Candidates: on a metric with a hydra_dataset, one grid per schema Λ (each RAQE grouping and the union, where card(Λ) is known); eligible for any RAQE with ∅ ≠ G_r ⊆ Λ. The subpopulations ceiling is gone. - Accuracy: hydra_saturation.csv under the saturation dir (optional), keyed by variant, config, dataset and grouping; the column the RAQE's accuracy_covers_share selects; worst over records and seeds; lossy merges bracketed by merge_shards, unknown past the largest. - Runner: ASAP and PerQuery plan with undeployable families; RQEs carry covers_share; http/flows streams name their Hydra dataset; results report hydra_rqes for workloads Hydra may serve. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- Cargo.lock | 1 + rqe-optimizer/Cargo.toml | 1 + rqe-optimizer/examples/autosketch_vs_asap.rs | 69 +++- rqe-optimizer/examples/small_problem.rs | 10 + rqe-optimizer/examples/workload_scenarios.rs | 2 + rqe-optimizer/src/analytical_cost_model.rs | 4 + rqe-optimizer/src/autosketch.rs | 1 + rqe-optimizer/src/candidates.rs | 230 ++++++++--- rqe-optimizer/src/enumerate.rs | 1 + rqe-optimizer/src/lib.rs | 52 ++- rqe-optimizer/src/saturation.rs | 413 ++++++++++++++++++- rqe-optimizer/tests/mixed_grouping.rs | 2 + 12 files changed, 703 insertions(+), 83 deletions(-) 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/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..27ce5f19 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -62,6 +62,13 @@ //! 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 groupings competes with per-group +//! sketches (sketch-bench `docs/rqe_optimizer_hydra.md`). Its accuracy is +//! `hydra_saturation.csv` under the saturation dir, measured on the +//! dataset shaped like the stream's metric ([`hydra_dataset`]); without the +//! file no Hydra deployment is eligible. AutoSketch skips Hydra (#159). use std::collections::{BTreeMap, BTreeSet}; use std::time::Instant; @@ -293,6 +300,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() } @@ -392,6 +413,11 @@ 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: schema + .is_object() + .then(|| hydra_dataset(metric, capability)) + .flatten(), } }); // A stream's RQEs may see different group counts (keys per window @@ -448,6 +474,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 +593,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() } @@ -656,6 +682,10 @@ 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 chosen: Vec = raqes .iter() .zip(mapping) @@ -677,7 +707,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 +718,7 @@ fn summarize( choice }) .collect(); - json!({ + let mut v = json!({ "objective": cost.value, "cpu": cost.cpu, "gib": gib(cost.bytes), @@ -702,7 +733,12 @@ fn summarize( "median_latency_ms": (!latencies.is_empty()).then(|| median(latencies.clone())), "active_deployments": active.len(), "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. @@ -1210,6 +1246,10 @@ 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, at each RQE's coverage. + assert_eq!(facts.hydra_dataset.as_deref(), Some("hydra_http")); + 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"]; @@ -1230,6 +1270,21 @@ mod tests { 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); + } + + #[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 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 09afe4fa..0c1ecfeb 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -3,7 +3,8 @@ use crate::analytical_cost_model; use crate::{ config_topk_k, has_heap, heap_capacity, heap_needed, Accuracy, AtomicCostEntry, Capability, - Deployment, LabelSet, MetricFacts, Millis, Raqe, WorkloadFacts, KEY_TRACKER_FAMILY, + Deployment, FamilyProperties, LabelSet, MetricFacts, Millis, Raqe, WorkloadFacts, + KEY_TRACKER_FAMILY, }; use std::collections::{BTreeMap, BTreeSet}; @@ -44,31 +45,16 @@ fn subset_gcds(values: impl IntoIterator) -> BTreeSet { gcds } -/// Whether a fixed-size sketch shared by all groups was measured holding at -/// least `groups` of them. Its accuracy degrades as groups grow, and the row -/// holds one measured point (`subpopulations`). Models a sketch keyed by the -/// joined `G` value alone, so it holds exactly `card(G)` subpopulations; the -/// current rows fan out to every label subset (sketch-bench#165). -// ponytail: one point, so larger groupings are never planned. Rows at more -// group counts (sketch-bench#143 S5) loosen this with no code change. -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 +/// properties pass `family`. Their windows, slides and heaps come from /// `group`, the RAQEs they may serve. fn candidate_deployments( group: &[&Raqe], grouping: &LabelSet, - mergeable_across_groups: bool, + family: impl Fn(FamilyProperties) -> bool, costs: &[AtomicCostEntry], metric_facts: &MetricFacts, allow_undeployable_families: bool, @@ -96,8 +82,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 + && family(crate::family_properties(&c.sketch)) }) .collect(); let heap_rows = heap_rows_by_shape(&family_rows); @@ -326,38 +311,82 @@ 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 plain = |p: FamilyProperties| !p.answers_any_subgrouping; [ - (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, + |p| plain(p) && !p.mergeable_across_groups, costs, &facts[metric], allow_undeployable_families, - ) - }) - .collect::>() + ), + candidate_deployments( + &subset_group, + grouping, + |p| plain(p) && p.mergeable_across_groups, + costs, + &facts[metric], + allow_undeployable_families, + ), + ] + .concat() }) - .collect() + .collect(); + // Hydra, on a metric with a measured dataset: one grid per schema `Λ`, + // each RAQE grouping and the union of a (capability, metric, filter)'s + // groupings, where the metric knows `card(Λ)` (its key tracker's + // groups). `Λ` 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 mut schemas: BTreeMap<(Capability, &str, &str), BTreeSet<&LabelSet>> = BTreeMap::new(); + for &(capability, metric, filter, grouping) in groups.keys() { + if facts[metric].hydra_dataset.is_some() && !grouping.is_empty() { + schemas + .entry((capability, metric, filter)) + .or_default() + .insert(grouping); + } + } + for ((capability, metric, filter), groupings) in schemas { + let union: LabelSet = groupings.iter().copied().flatten().cloned().collect(); + let cardinality = &facts[metric].cardinality; + let unions = cardinality.get_key_value(&union).map(|(union, _)| union); + for schema in groupings.into_iter().chain(unions).collect::>() { + candidates.extend(candidate_deployments( + &subset_group((capability, metric, filter, schema), true), + schema, + |p| p.answers_any_subgrouping, + costs, + &facts[metric], + allow_undeployable_families, + )); + } + } + candidates } /// Remove a candidate only when another candidate can replace it in every @@ -546,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) @@ -561,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) @@ -589,6 +621,7 @@ mod tests { accuracy_sla: 0.5, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } fn cost() -> AtomicCostEntry { @@ -1089,17 +1122,14 @@ 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 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"), ..cost() }, AtomicCostEntry { @@ -1119,7 +1149,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], @@ -1232,4 +1262,100 @@ mod tests { assert!(topk_windows.contains(&HOUR)); assert!(!topk_windows.contains(&NINETY_MINUTES)); } + + /// region (2) × service (5) × endpoint (10 per service), measured as a + /// Hydra dataset; every RAQE grouping on it has a cardinality. + fn region_service_endpoint_facts() -> WorkloadFacts { + use crate::test_support::label_set; + let labels = label_set(&["region", "service", "endpoint"]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels.clone(), + 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), + (labels, 100), + ]), + value_range: None, + data_shape: BTreeMap::new(), + hydra_dataset: Some("hydra_test".into()), + }, + )]) + } + + 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))); + } + + /// Hydra schemas are each RAQE grouping and their union, here the full + /// label set, on a metric with a Hydra dataset only; each takes the + /// windows of the RAQEs it can serve. + #[test] + fn hydra_schemas_are_each_grouping_and_their_union() { + 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 schemas = |facts: &WorkloadFacts| { + build_all_candidates_unpruned(&raqes, &hydra_and_tracker(), facts, true) + .into_iter() + .filter(|d| d.config.sketch == "hydra-kll") + .map(|d| (d.grouping_labels, d.window_ms)) + .collect::>() + }; + let all = label_set(&["region", "service", "endpoint"]); + assert_eq!( + schemas(&facts), + BTreeSet::from([ + (label_set(&["region"]), 60_000), + (label_set(&["service", "endpoint"]), 60_000), + (label_set(&["service", "endpoint"]), 120_000), + (all.clone(), 60_000), + (all.clone(), 120_000), + ]) + ); + // No cardinality for the union: no grid over it. + facts.get_mut(METRIC).unwrap().cardinality.remove(&all); + assert!(schemas(&facts).iter().all(|(schema, _)| schema != &all)); + // No Hydra dataset: no grid at all, and not as a plain candidate. + facts.get_mut(METRIC).unwrap().hydra_dataset = None; + assert!(schemas(&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 e7868d5d..dad3ffc5 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,10 @@ 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, for reading Hydra's accuracy. Without one, no Hydra + /// candidate is built on it. + pub hydra_dataset: Option, } impl MetricFacts { @@ -468,6 +490,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 { @@ -643,6 +669,7 @@ pub(crate) mod test_support { cardinality: BTreeMap::from([(LabelSet::new(), groups), (labels, series)]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -659,6 +686,7 @@ pub(crate) mod test_support { accuracy_sla: 0.5, latency_sla_ms: None, topk_k: None, + accuracy_covers_share: None, } } @@ -711,6 +739,7 @@ pub(crate) mod test_support { cardinality: BTreeMap::from([(service, 5), (service_endpoint, 50)]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } @@ -853,6 +882,7 @@ mod tests { ]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]); let r = Raqe { @@ -872,6 +902,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 = [ @@ -967,6 +998,7 @@ mod tests { ]), value_range: None, data_shape: BTreeMap::new(), + hydra_dataset: None, }, )]) } diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index bbf623ee..cb3e138e 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 records and seeds, +/// `None` where a 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 { @@ -416,7 +445,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.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 +527,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,6 +857,52 @@ 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(); + for row in read_csv(path)? { + 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) => { + for (worst, error) in worst.iter_mut().zip(errors) { + *worst = worst.zip(error).map(|(a, b)| worse(a, b, direction)); + } + } + } + } + Ok(out) +} + /// `"rows=3 cols=1024"` → `{rows: 3, cols: 1024}`; the grid's config strings. fn parse_config(config: &str) -> BTreeMap { config @@ -806,23 +938,25 @@ 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. +/// Fields may be quoted: `hydra_saturation.csv`'s groupings hold commas. fn read_csv(path: &Path) -> 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(); + reader + .records() + .map(|record| { + Ok(header .iter() - .zip(line.split(',')) + .zip(record.map_err(failed)?.iter()) .map(|(name, value)| (name.to_string(), value.to_string())) - .collect() + .collect()) }) - .collect()) + .collect() } #[cfg(test)] @@ -872,6 +1006,7 @@ mod tests { point(1.2, 1e5, 0.08, None), ], )]), + ..SaturationCurves::default() } } @@ -1022,6 +1157,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(); @@ -1583,4 +1719,253 @@ 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 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(rows) = rows { + let csv = format!("{HYDRA_HEADER}\n{}\n", rows.join("\n")); + std::fs::write(dir.join(HYDRA_SATURATION), csv).unwrap(); + } + let loaded = SaturationCurves::load(&dir); + std::fs::remove_dir_all(&dir).unwrap(); + loaded.unwrap() + } + + /// 5 services × 10 endpoints, measured as `hydra_http`. + fn hydra_facts() -> WorkloadFacts { + let mut facts = crate::test_support::service_endpoint_facts(); + facts.get_mut(METRIC).unwrap().hydra_dataset = Some("hydra_http".into()); + 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 leaves its column 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", "0.1"]), + hydra_row("hydra-hll", "service", 1e6, 1, 1, ["0.12", "0.1", "0.1"]), + ]; + 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.05)), 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(), + ..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 b33c564d..45048db6 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, } } From 600bf6600b50ad56db56191dc77b01ad0f9652c5 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 05:35:14 +0000 Subject: [PATCH 07/10] rqe-optimizer: Hydra grids at the full schema from their dataset's rows Round-1 review of #201: - One Hydra grid per (stream, variant, config, window, slide), over the metric's full schema only (MetricFacts::hydra_dataset now carries the dataset and the schema), the width the study measures. - MeasuredAt gains optional `dataset` and `schema_width`; a Hydra row is a candidate on a metric only if measured on its dataset. - Runner: card(full schema) = product of label fan-outs, capped at the stream's series; AutoSketch also allows undeployable families (it skips Hydra itself, #159). - read_csv checks required columns and short rows; config params must be numbers. - Docs: Hydra held to the worst case, built only at the full schema. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- aqpbm-core/src/atomic_costs.rs | 22 +++ docs/rqe_optimizer_candidates.md | 14 +- docs/rqe_optimizer_cost_model.md | 21 ++- rqe-optimizer/examples/autosketch_vs_asap.rs | 172 ++++++++++++++++--- rqe-optimizer/src/candidates.rs | 148 +++++++++------- rqe-optimizer/src/lib.rs | 10 +- rqe-optimizer/src/saturation.rs | 142 +++++++++++++-- rqe-optimizer/tests/mixed_grouping.rs | 2 + 8 files changed, 413 insertions(+), 118 deletions(-) diff --git a/aqpbm-core/src/atomic_costs.rs b/aqpbm-core/src/atomic_costs.rs index fa5c8ee7..b89ff062 100644 --- a/aqpbm-core/src/atomic_costs.rs +++ b/aqpbm-core/src/atomic_costs.rs @@ -74,6 +74,14 @@ pub struct MeasuredAt { pub merge_operand_items: Option, /// The value column's distribution as generated, e.g. Zipf with its skew. pub distribution: Option, + /// The datagen config (yaml stem, e.g. `hydra_http`) a Hydra row was + /// measured on; `None` on other rows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dataset: Option, + /// The label schema width a Hydra row's grid fanned out over; `None` on + /// other rows. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub schema_width: Option, } impl MeasuredAt { @@ -320,6 +328,8 @@ fn measured_at(record: &MergedRecord, groups_measured: Option) -> MeasuredA .filter(|&m| m > 0) .map(|m| items / m as u64), distribution: value.map(|c| c.distribution.clone()), + dataset: None, + schema_width: None, } } @@ -719,6 +729,8 @@ mod tests { value_range: None, merge_operand_items: None, distribution: None, + dataset: None, + schema_width: None, }, }; let json = serde_json::to_string(&entry).unwrap(); @@ -726,5 +738,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 fd0d9cee..eca058f2 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -221,9 +221,17 @@ 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** (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. - **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 02b4f162..c0e8990a 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -17,7 +17,9 @@ snapshot-AUC objective. Candidates and eligibility are in 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. +- **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 @@ -373,13 +375,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. - A fixed-size sketch degrades as groups grow, so it is eligible only when - `card(G_d)` is at most the `subpopulations` its row was measured at. This - models a sketch keyed by the joined `G` value alone; the current rows fan - out to every label subset (sketch-bench#165), and merging several windows - is not yet measured (sketch-bench#166). + 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 @@ -398,8 +400,9 @@ follows from it): | key tracker part | none | none | DeltaSet, `I_d = card(G_d)` | | rolls up (`G_r ⊂ G_d`) | yes | yes | no | -HydraKLL has `FamilyProperties` but is in no capability's family list, so it -is never a candidate. +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/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index 27ce5f19..b1a1e4a6 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -64,11 +64,14 @@ //! per query window, no saturation requirement). //! //! Hydra: ASAP and PerQuery plan with undeployable families allowed, so a -//! Hydra grid over a schema metric's groupings competes with per-group -//! sketches (sketch-bench `docs/rqe_optimizer_hydra.md`). Its accuracy is -//! `hydra_saturation.csv` under the saturation dir, measured on the -//! dataset shaped like the stream's metric ([`hydra_dataset`]); without the -//! file no Hydra deployment is eligible. AutoSketch skips Hydra (#159). +//! 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; @@ -398,14 +401,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(), @@ -414,10 +428,9 @@ fn from_table( value_range: None, data_shape: BTreeMap::new(), // A stream is one value of its metric, so one capability. - hydra_dataset: schema - .is_object() - .then(|| hydra_dataset(metric, capability)) - .flatten(), + 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 @@ -426,6 +439,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); @@ -617,7 +636,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); @@ -1218,10 +1239,9 @@ mod tests { "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}))}}, + "schemas": {"http": http_schema()}, "rqes": [ rqe(&["region"], 4, Some(0.05), 0.05), rqe(&["region", "service"], 100, None, 0.001), @@ -1246,8 +1266,15 @@ 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, at each RQE's coverage. - assert_eq!(facts.hydra_dataset.as_deref(), Some("hydra_http")); + // 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 @@ -1274,6 +1301,109 @@ mod tests { assert_eq!(asap["hydra_rqes"], 0); } + /// 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, + "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 grids: BTreeSet<(String, LabelSet)> = 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) + .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); diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 0c1ecfeb..ee8623d8 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -3,8 +3,7 @@ use crate::analytical_cost_model; use crate::{ config_topk_k, has_heap, heap_capacity, heap_needed, Accuracy, AtomicCostEntry, Capability, - Deployment, FamilyProperties, LabelSet, MetricFacts, Millis, Raqe, WorkloadFacts, - KEY_TRACKER_FAMILY, + Deployment, LabelSet, MetricFacts, Millis, Raqe, WorkloadFacts, KEY_TRACKER_FAMILY, }; use std::collections::{BTreeMap, BTreeSet}; @@ -48,13 +47,13 @@ fn subset_gcds(values: impl IntoIterator) -> BTreeSet { /// 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 -/// properties pass `family`. 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, - family: impl Fn(FamilyProperties) -> bool, + row: impl Fn(&AtomicCostEntry) -> bool, costs: &[AtomicCostEntry], metric_facts: &MetricFacts, allow_undeployable_families: bool, @@ -82,7 +81,7 @@ fn candidate_deployments( capability .candidate_families(allow_undeployable_families) .any(|family| family == c.sketch) - && family(crate::family_properties(&c.sketch)) + && row(c) }) .collect(); let heap_rows = heap_rows_by_shape(&family_rows); @@ -334,12 +333,15 @@ pub fn build_all_candidates_unpruned( // 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 plain = |p: FamilyProperties| !p.answers_any_subgrouping; + let properties = |c: &AtomicCostEntry| crate::family_properties(&c.sketch); [ candidate_deployments( exact_group, grouping, - |p| plain(p) && !p.mergeable_across_groups, + |c| { + !properties(c).answers_any_subgrouping + && !properties(c).mergeable_across_groups + }, costs, &facts[metric], allow_undeployable_families, @@ -347,7 +349,10 @@ pub fn build_all_candidates_unpruned( candidate_deployments( &subset_group, grouping, - |p| plain(p) && p.mergeable_across_groups, + |c| { + !properties(c).answers_any_subgrouping + && properties(c).mergeable_across_groups + }, costs, &facts[metric], allow_undeployable_families, @@ -356,35 +361,30 @@ pub fn build_all_candidates_unpruned( .concat() }) .collect(); - // Hydra, on a metric with a measured dataset: one grid per schema `Λ`, - // each RAQE grouping and the union of a (capability, metric, filter)'s - // groupings, where the metric knows `card(Λ)` (its key tracker's - // groups). `Λ` 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 mut schemas: BTreeMap<(Capability, &str, &str), BTreeSet<&LabelSet>> = BTreeMap::new(); - for &(capability, metric, filter, grouping) in groups.keys() { - if facts[metric].hydra_dataset.is_some() && !grouping.is_empty() { - schemas - .entry((capability, metric, filter)) - .or_default() - .insert(grouping); - } - } - for ((capability, metric, filter), groupings) in schemas { - let union: LabelSet = groupings.iter().copied().flatten().cloned().collect(); - let cardinality = &facts[metric].cardinality; - let unions = cardinality.get_key_value(&union).map(|(union, _)| union); - for schema in groupings.into_iter().chain(unions).collect::>() { - candidates.extend(candidate_deployments( - &subset_group((capability, metric, filter, schema), true), - schema, - |p| p.answers_any_subgrouping, - costs, - &facts[metric], - allow_undeployable_families, - )); - } + // 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 } @@ -1122,7 +1122,8 @@ mod tests { assert_eq!(retained, vec![direct, halves]); } - /// A whole-grid hydra-kll row and a per-key DeltaSet row. + /// A whole-grid hydra-kll row measured on `hydra_test`, and a per-key + /// DeltaSet row. fn hydra_and_tracker() -> [AtomicCostEntry; 2] { [ AtomicCostEntry { @@ -1130,6 +1131,10 @@ mod tests { mem_bytes_per_instance: 1000.0, 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 { @@ -1263,26 +1268,28 @@ mod tests { assert!(!topk_windows.contains(&NINETY_MINUTES)); } - /// region (2) × service (5) × endpoint (10 per service), measured as a - /// Hydra dataset; every RAQE grouping on it has a cardinality. + /// 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 labels = label_set(&["region", "service", "endpoint"]); + let schema = label_set(&["region", "service", "endpoint"]); WorkloadFacts::from([( METRIC.to_string(), MetricFacts { - labels: labels.clone(), + 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), - (labels, 100), + (schema.clone(), 100), + (label_set(&["region", "service", "endpoint", "x"]), 1_000), ]), value_range: None, data_shape: BTreeMap::new(), - hydra_dataset: Some("hydra_test".into()), + hydra_dataset: Some(("hydra_test".into(), schema)), }, )]) } @@ -1320,11 +1327,11 @@ mod tests { assert!(!is_eligible(&r, &grid, &facts, &|_, _| Some(0.9))); } - /// Hydra schemas are each RAQE grouping and their union, here the full - /// label set, on a metric with a Hydra dataset only; each takes the - /// windows of the RAQEs it can serve. + /// 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_schemas_are_each_grouping_and_their_union() { + 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. @@ -1333,29 +1340,44 @@ mod tests { quantile_by(&["region"]), crate::test_support::quantile_by(&["service", "endpoint"], 120_000, 120_000), ]; - let schemas = |facts: &WorkloadFacts| { - build_all_candidates_unpruned(&raqes, &hydra_and_tracker(), facts, true) + 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)) + .map(|d| { + ( + d.grouping_labels, + d.window_ms, + d.config.mem_bytes_per_instance as u64, + ) + }) .collect::>() }; - let all = label_set(&["region", "service", "endpoint"]); + let schema = label_set(&["region", "service", "endpoint"]); assert_eq!( - schemas(&facts), + grids(&facts), BTreeSet::from([ - (label_set(&["region"]), 60_000), - (label_set(&["service", "endpoint"]), 60_000), - (label_set(&["service", "endpoint"]), 120_000), - (all.clone(), 60_000), - (all.clone(), 120_000), + (schema.clone(), 60_000, 1000), + (schema.clone(), 120_000, 1000), ]) ); - // No cardinality for the union: no grid over it. - facts.get_mut(METRIC).unwrap().cardinality.remove(&all); - assert!(schemas(&facts).iter().all(|(schema, _)| schema != &all)); // No Hydra dataset: no grid at all, and not as a plain candidate. facts.get_mut(METRIC).unwrap().hydra_dataset = None; - assert!(schemas(&facts).is_empty()); + assert!(grids(&facts).is_empty()); } } diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index dad3ffc5..94c8f9db 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -322,9 +322,11 @@ pub struct MetricFacts { /// 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, for reading Hydra's accuracy. Without one, no Hydra - /// candidate is built on it. - pub hydra_dataset: Option, + /// 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 { @@ -654,6 +656,8 @@ pub(crate) mod test_support { value_range: None, merge_operand_items: None, distribution: None, + dataset: None, + schema_width: None, } } diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index cb3e138e..fd82f19b 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -318,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() { @@ -341,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:?}" @@ -355,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:?}" @@ -477,7 +507,7 @@ impl SaturationCurves { let key = ( sketch.clone(), format!("{:?}", config_params(&deployment.config)?), - facts[&deployment.metric].hydra_dataset.clone()?, + facts[&deployment.metric].hydra_dataset.as_ref()?.0.clone(), raqe.grouping_labels.clone(), ); let by_shards = self.hydra.get(&key)?; @@ -864,7 +894,17 @@ fn load_hydra( path: &Path, ) -> io::Result> { let mut out: BTreeMap<_, HydraErrors> = BTreeMap::new(); - for row in read_csv(path)? { + 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; @@ -880,7 +920,7 @@ fn load_hydra( } let key = ( variant.to_string(), - format!("{:?}", parse_config(&row["config"])), + format!("{:?}", parse_config(&row["config"])?), row["dataset"].clone(), row["group_columns"] .split(',') @@ -904,12 +944,18 @@ fn load_hydra( } /// `"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() } @@ -939,7 +985,9 @@ fn invalid(message: String) -> io::Error { type CsvRow = BTreeMap; /// Fields may be quoted: `hydra_saturation.csv`'s groupings hold commas. -fn read_csv(path: &Path) -> io::Result> { +/// Fails unless the header has every `required` column and every row a +/// field for each 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())))?; @@ -947,12 +995,32 @@ fn read_csv(path: &Path) -> io::Result> { .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(record.map_err(failed)?.iter()) + .zip(record.iter()) .map(|(name, value)| (name.to_string(), value.to_string())) .collect()) }) @@ -989,7 +1057,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, @@ -1148,7 +1216,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, @@ -1456,6 +1524,8 @@ mod tests { population_size: 1_000, seed: 1, })), + dataset: None, + schema_width: None, }, ..deployment(TOPK, 1).config } @@ -1746,6 +1816,12 @@ mod tests { /// `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(); @@ -1761,19 +1837,43 @@ mod tests { ) .unwrap(); } - if let Some(rows) = rows { - let csv = format!("{HYDRA_HEADER}\n{}\n", rows.join("\n")); + 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.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 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(); - facts.get_mut(METRIC).unwrap().hydra_dataset = Some("hydra_http".into()); + let schema = crate::test_support::label_set(&["service", "endpoint"]); + facts.get_mut(METRIC).unwrap().hydra_dataset = Some(("hydra_http".into(), schema)); facts } @@ -1931,6 +2031,10 @@ mod tests { 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 = [ diff --git a/rqe-optimizer/tests/mixed_grouping.rs b/rqe-optimizer/tests/mixed_grouping.rs index 45048db6..0850ac2c 100644 --- a/rqe-optimizer/tests/mixed_grouping.rs +++ b/rqe-optimizer/tests/mixed_grouping.rs @@ -94,6 +94,8 @@ fn cost_row(sketch: &str, params: serde_json::Value) -> AtomicCostEntry { value_range: None, merge_operand_items: None, distribution: None, + dataset: None, + schema_width: None, }, } } From 812fa8bab66c43bc7b350874fdda0429087b9fa3 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 06:54:47 +0000 Subject: [PATCH 08/10] rqe-optimizer: validate the Hydra schema, skip empty Hydra cells, reject long CSV rows validate_facts reports a Hydra schema outside the metric's labels or without a nonzero cardinality, instead of a later panic. The Hydra accuracy fold skips empty cells (no covered group scored in that run) and is unknown only when every row left the column empty. read_csv rejects rows longer than the header too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/src/lib.rs | 42 ++++++++++++++++++++++++++++ rqe-optimizer/src/saturation.rs | 49 +++++++++++++++++++++++++-------- 2 files changed, 80 insertions(+), 11 deletions(-) diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 94c8f9db..3c6a70e1 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -410,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 @@ -1056,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 fd82f19b..bacc7363 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -69,8 +69,8 @@ const HYDRA_COVERAGE: [(f64, &str); 3] = [ ]; /// Hydra measurements of one (variant, config, dataset, grouping), by merge -/// shards: each [`HYDRA_COVERAGE`] column's worst over records and seeds, -/// `None` where a row left it empty. +/// 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. @@ -934,8 +934,13 @@ fn load_hydra( 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 = worst.zip(error).map(|(a, b)| worse(a, b, direction)); + *worst = match (*worst, error) { + (Some(a), Some(b)) => Some(worse(a, b, direction)), + (a, b) => a.or(b), + }; } } } @@ -985,8 +990,8 @@ fn invalid(message: String) -> io::Error { type CsvRow = BTreeMap; /// Fields may be quoted: `hydra_saturation.csv`'s groupings hold commas. -/// Fails unless the header has every `required` column and every row a -/// field for each header column. +/// 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) @@ -1009,7 +1014,7 @@ fn read_csv(path: &Path, required: &[&str]) -> io::Result> { .records() .map(|record| { let record = record.map_err(failed)?; - if record.len() < header.len() { + if record.len() != header.len() { return Err(invalid(format!( "{}: line {}: {} fields, the header has {}", path.display(), @@ -1864,6 +1869,11 @@ mod tests { 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}"); @@ -1947,13 +1957,14 @@ mod tests { } /// Error is taken to depend on shares, not N: the worst over the - /// measured records and seeds. An empty cell leaves its column unknown. + /// 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", "0.1"]), - hydra_row("hydra-hll", "service", 1e6, 1, 1, ["0.12", "0.1", "0.1"]), + 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| { @@ -1964,7 +1975,23 @@ mod tests { ) }; assert_eq!(at(None), Some(0.15)); - assert_eq!(at(Some(0.05)), None); + 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 From b03bd496a2496af83c0086f768c14855e1a64441 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 11:35:39 +0000 Subject: [PATCH 09/10] eval: test fixtures carry max_covered_share and label cardinalities After rebasing onto #196's two-ended coverage read: #201's runner test RQEs need max_covered_share, and #196's coverage test schema needs the label cardinality the full-schema Hydra grid reads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index b1a1e4a6..adea8701 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -1333,7 +1333,7 @@ mod tests { 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, + "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}], @@ -1452,7 +1452,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, From b0319d17abdeb13e4d1349d19542731418764ca2 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 13:57:16 +0000 Subject: [PATCH 10/10] eval: roll-up ablation, ASAP without roll-ups The runner adds the method `asap-norollup` ("ASAP (no roll-ups)"): ASAP's MILP, candidates, frontier sweep and SLA grid, with each RQE allowed only deployments at its own grouping or Hydra grids. Every result counts `rolled_up_rqes` (RQEs served by a finer non-Hydra deployment), and sanity checks asap <= asap-norollup <= perquery unbounded and at each SLA. The plot scripts draw it as a dashed violet line, add fig_rollup_ablation.png (unbounded cost with and without roll-ups, absolute, CPU and Fargate panels) and a roll-up section in both summaries; results without the method still plot. The run script passes --no-chosen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/autosketch_vs_asap.rs | 244 +++++++++++++++---- scripts/plot_autosketch_vs_asap_sla.py | 50 +++- scripts/plot_autosketch_vs_asap_synthetic.py | 108 ++++++-- scripts/run_autosketch_vs_asap_synthetic.sh | 2 +- 4 files changed, 336 insertions(+), 68 deletions(-) diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index adea8701..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 @@ -664,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( @@ -707,6 +718,11 @@ fn summarize( .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) @@ -753,6 +769,7 @@ 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. @@ -937,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( @@ -947,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(); @@ -986,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), @@ -997,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 @@ -1016,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 @@ -1025,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, @@ -1064,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, @@ -1091,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)); @@ -1108,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); @@ -1133,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": { @@ -1225,39 +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}], - }) - }; + /// 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": http_schema()}, - "rqes": [ - rqe(&["region"], 4, Some(0.05), 0.05), - rqe(&["region", "service"], 100, None, 0.001), - ], + "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, @@ -1286,12 +1389,7 @@ 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"); @@ -1301,6 +1399,55 @@ mod tests { 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": [ @@ -1384,12 +1531,23 @@ mod tests { 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 grids: BTreeSet<(String, LabelSet)> = group_by_stream(&w.raqes) + 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!( 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" ;;