From 79d3983724a3400ebeb0473a93e3b0fd796d6e73 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Fri, 9 Oct 2026 13:38:17 -0400 Subject: [PATCH 01/13] rqe-optimizer: let mergeable finer-group deployments serve coarser RAQEs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A deployment grouped by G_d now serves a RAQE grouped by any subset G_r when its family merges across groups (exact sum/min/max, HLL, UnivMon cardinality, KLL, DD). The read is priced at G_r: card(G_d)·L/x − card(G_r) merges, with card(G_r) accumulators, probes and output. Accuracy reads G_r's shape and items, and KLL's merge curve at the average fan-out times L/x. Fine candidates take windows from coarser RAQEs. validate_facts rejects a label set with more groups than a superset. Closes #187 Co-Authored-By: Claude Opus 5.5 --- rqe-optimizer/examples/small_problem.rs | 24 ++- rqe-optimizer/src/analytical_cost_model.rs | 165 +++++++++++++++----- rqe-optimizer/src/candidates.rs | 149 +++++++++++++++++- rqe-optimizer/src/enumerate.rs | 10 +- rqe-optimizer/src/lib.rs | 100 +++++++++++-- rqe-optimizer/src/saturation.rs | 50 ++++++- rqe-optimizer/tests/mixed_grouping.rs | 166 +++++++++++++++++++++ 7 files changed, 604 insertions(+), 60 deletions(-) create mode 100644 rqe-optimizer/tests/mixed_grouping.rs diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 2ea5f4fa..20cd2fea 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -205,6 +205,19 @@ fn raqes() -> Vec { latency_sla_ms: None, topk_k: None, }, + // Shares KLL with the per-endpoint p99s by rolling up. + Raqe { + id: "latency_p99_1h_by_service".to_string(), + capability: Capability::Quantile, + lookback_ms: 3_600_000, + interval_ms: 60_000, + metric: duration(), + spatial_filter: String::new(), + grouping_labels: s.clone(), + accuracy_sla: 0.05, + latency_sla_ms: None, + topk_k: None, + }, Raqe { id: "latency_p99_1d".to_string(), capability: Capability::Quantile, @@ -503,8 +516,17 @@ fn main() { .zip(&solution.raqes) .zip(&solution.plan_cost.query_latency_ms) { + let served_by = &solution.deployments[planned.deployment].deployment; + let roll_up = if served_by.grouping_labels == raqe.grouping_labels { + String::new() + } else { + format!( + " rolls up {:?} -> {:?}", + served_by.grouping_labels, raqe.grouping_labels + ) + }; println!( - " {} -> deployment {} merged_instances={} query_latency={latency:.3e} ms", + " {} -> deployment {} merged_instances={} query_latency={latency:.3e} ms{roll_up}", raqe.id, planned.deployment, planned.merged_instance_count, ); } diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 56a2b0d9..834099be 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -11,12 +11,17 @@ //! Measured costs are per instance. A deployment holds `card(G)` instances //! per window, or one if its family keeps [one fixed-size sketch for all //! groups](crate::FamilyProperties::one_fixed_size_sketch_for_all_groups). +//! A RAQE grouped by `G_r`, a subset of the deployment's `G_d`, is read by +//! merging each `G_r` group's instances into one (a roll-up), so merge and +//! query are priced at `G_r`, ingest and storage at `G_d`. //! Exact accumulators hold many groups in one instance, but the export //! 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. -use crate::{secs, AtomicCostEntry, Capability, Deployment, Mapping, Millis, Raqe, WorkloadFacts}; +use crate::{ + secs, AtomicCostEntry, Capability, Deployment, LabelSet, Mapping, Millis, Raqe, WorkloadFacts, +}; use std::collections::{BTreeMap, BTreeSet}; pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; @@ -73,9 +78,9 @@ impl PlanCost { } } -/// `card(G)`: cardinality of `G`, the number of groups. -fn group_count(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { - facts[&deployment.metric].cardinality[&deployment.grouping_labels] as f64 +/// `card(grouping)` on `deployment`'s metric: the number of groups. +fn group_count(deployment: &Deployment, grouping: &LabelSet, facts: &WorkloadFacts) -> f64 { + facts[&deployment.metric].cardinality[grouping] as f64 } /// The sketch and its key tracker, if any, each with its instances per @@ -98,7 +103,7 @@ fn priced_parts<'a>( "{}: key tracker present iff the family needs one, or the plan is mispriced", deployment.config.sketch ); - let groups = group_count(deployment, facts); + let groups = group_count(deployment, &deployment.grouping_labels, facts); let sketch_instances = if properties.one_fixed_size_sketch_for_all_groups { 1.0 } else { @@ -113,8 +118,8 @@ fn priced_parts<'a>( } /// `m`: memory of one `config` instance (`deployment`'s sketch or its key -/// tracker) holding `span_ms` of one group's samples: a -/// window `x`, or the lookback `L` for a query's merge accumulator. +/// tracker) holding `span_ms` of one `grouping` group's samples: a window `x` +/// of `G_d`, or the lookback `L` of `G_r` for a query's merge accumulator. /// DDSketch on a metric with a known value range holds one store (values are /// positive) of [`dd_bucket_count`] buckets, capped by the values it holds, /// `λ · span / card(G)`, as `dd_footprint` caps them by count. The range is the metric's, so this is @@ -124,14 +129,15 @@ pub(crate) fn instance_memory_bytes( config: &AtomicCostEntry, deployment: &Deployment, facts: &WorkloadFacts, + grouping: &LabelSet, span_ms: Millis, ) -> f64 { let metric = &facts[&deployment.metric]; let alpha = config.sketch_config["params"]["alpha"].as_f64(); match (config.sketch.as_str(), metric.value_range, alpha) { ("dd", Some((lo, hi)), Some(alpha)) => { - let values = - metric.arrival_rate_per_sec() * secs(span_ms) / group_count(deployment, facts); + let values = metric.arrival_rate_per_sec() * secs(span_ms) + / group_count(deployment, grouping, facts); dd_bucket_count(lo, hi, alpha).min(values.ceil().max(1.0)) * DD_BYTES_PER_BUCKET } _ => config.mem_bytes_per_instance, @@ -158,6 +164,36 @@ fn merged_window_count(raqe: &Raqe, deployment: &Deployment) -> f64 { .expect("only eligible pairs are costed") as f64 } +/// States one query of `raqe` ends with on `part`: one per `G_r` group, or +/// one for a sketch shared by all groups. +fn answered_instances( + raqe: &Raqe, + deployment: &Deployment, + facts: &WorkloadFacts, + part: Part, +) -> f64 { + if part == Part::Sketch && deployment.properties().one_fixed_size_sketch_for_all_groups { + 1.0 + } else { + group_count(deployment, &raqe.grouping_labels, facts) + } +} + +/// Merges one query of `raqe` does on `part`, which holds `sketch_instances` +/// per window. Each folds two states into one, so it is the states read, +/// `sketch_instances · L/x`, less the `answered_instances` left. Without a +/// roll-up, `card(G) · (L/x − 1)`. +fn merge_count( + raqe: &Raqe, + deployment: &Deployment, + facts: &WorkloadFacts, + sketch_instances: f64, + part: Part, +) -> f64 { + sketch_instances * merged_window_count(raqe, deployment) + - answered_instances(raqe, deployment, facts, part) +} + /// Per part: CPU `λ · (x/y) · c_ins`; memory `instances · m · (x/y)`. pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { let open_windows = open_window_count(deployment); @@ -167,28 +203,39 @@ pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCos cost += PhaseCost { cpu_secs_per_sec: arrival_rate * open_windows * config.insert_cpu_secs, memory_bytes: instances - * instance_memory_bytes(config, deployment, facts, deployment.window_ms) + * instance_memory_bytes( + config, + deployment, + facts, + &deployment.grouping_labels, + deployment.window_ms, + ) * open_windows, }; } cost } -/// Per part: CPU `instances · (L/x − 1) · c_mrg / T`; memory `instances · m`, -/// every merged accumulator held at once, each holding the whole lookback. A -/// direct query (`L == x`) merges nothing and costs neither. +/// Per part: CPU [`merge_count`]` · c_mrg / T`; memory `answered_instances · +/// m`, every merged accumulator held at once, each holding the whole lookback. +/// A direct query (`L == x`) without a roll-up merges nothing and costs neither. pub(crate) fn merge(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let merges_per_instance = merged_window_count(raqe, deployment) - 1.0; - if merges_per_instance == 0.0 { - return PhaseCost::default(); - } let mut cost = PhaseCost::default(); - for (config, instances, _) in priced_parts(deployment, facts) { + for (config, sketch_instances, part) in priced_parts(deployment, facts) { + let merges = merge_count(raqe, deployment, facts, sketch_instances, part); + if merges == 0.0 { + continue; + } cost += PhaseCost { - cpu_secs_per_sec: instances * merges_per_instance * config.merge_cpu_secs - / secs(raqe.interval_ms), - memory_bytes: instances - * instance_memory_bytes(config, deployment, facts, raqe.lookback_ms), + cpu_secs_per_sec: merges * config.merge_cpu_secs / secs(raqe.interval_ms), + memory_bytes: answered_instances(raqe, deployment, facts, part) + * instance_memory_bytes( + config, + deployment, + facts, + &raqe.grouping_labels, + raqe.lookback_ms, + ), }; } cost @@ -206,10 +253,10 @@ fn query_cpu_secs(raqe: &Raqe, config: &AtomicCostEntry, part: Part) -> f64 { } } -/// CPU `card(G) · Σ c_qry / T`, one probe per group of each part; memory -/// `card(G) ·` output bytes per group. +/// CPU `card(G_r) · Σ c_qry / T`, one probe per answered group of each part; +/// memory `card(G_r) ·` output bytes per group. pub(crate) fn query(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let groups = group_count(deployment, facts); + let groups = group_count(deployment, &raqe.grouping_labels, facts); let output_bytes_per_group = match raqe.capability { Capability::TopKByValue | Capability::TopKByCount => { crate::answered_k(&deployment.config) as f64 * OUTPUT_BYTES_PER_TOPK_ENTRY @@ -234,22 +281,28 @@ pub(crate) fn storage_bytes(raqe: &Raqe, deployment: &Deployment, facts: &Worklo priced_parts(deployment, facts) .map(|(config, instances, _)| { instances - * instance_memory_bytes(config, deployment, facts, deployment.window_ms) + * instance_memory_bytes( + config, + deployment, + facts, + &deployment.grouping_labels, + deployment.window_ms, + ) * closed_windows }) .sum() } /// Serial CPU time of one query, in ms, summed over parts: -/// `card(G) · c_qry + instances · (L/x − 1) · c_mrg`. +/// `card(G_r) · c_qry + `[`merge_count`]` · c_mrg`. pub(crate) fn query_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { - let groups = group_count(deployment, facts); - let merges_per_instance = merged_window_count(raqe, deployment) - 1.0; + let groups = group_count(deployment, &raqe.grouping_labels, facts); 1000.0 * priced_parts(deployment, facts) - .map(|(config, instances, part)| { + .map(|(config, sketch_instances, part)| { groups * query_cpu_secs(raqe, config, part) - + instances * merges_per_instance * config.merge_cpu_secs + + merge_count(raqe, deployment, facts, sketch_instances, part) + * config.merge_cpu_secs }) .sum::() } @@ -365,7 +418,7 @@ mod tests { let window = |d: &Deployment| d.window_ms; assert_eq!( - instance_memory_bytes(&dd.config, &dd, &ranged, window(&dd)), + instance_memory_bytes(&dd.config, &dd, &ranged, &dd.grouping_labels, window(&dd)), 80.0 ); // 10 buckets × 8 B assert_eq!(ingest(&dd, &ranged).memory_bytes, 80.0); @@ -390,12 +443,24 @@ mod tests { // No range, or not DDSketch: the measured size. assert_eq!( - instance_memory_bytes(&dd.config, &dd, &facts(1, 1), window(&dd)), + instance_memory_bytes( + &dd.config, + &dd, + &facts(1, 1), + &dd.grouping_labels, + window(&dd) + ), 1_000.0 ); let cms = deployment(1_000.0, 0.0, 0.0, 0.0, 60_000, 60_000); assert_eq!( - instance_memory_bytes(&cms.config, &cms, &ranged, window(&cms)), + instance_memory_bytes( + &cms.config, + &cms, + &ranged, + &cms.grouping_labels, + window(&cms) + ), 1_000.0 ); } @@ -515,4 +580,36 @@ mod tests { deployment.config.sketch = "hydra-kll".into(); ingest(&deployment, &facts(1, 1)); } + + /// p99 by service from KLL by (service, endpoint), every per-instance + /// cost 1: each query reads 50 fine states per window and leaves 5. + #[test] + fn a_roll_up_merges_every_fine_window_into_its_coarse_group() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + let hourly = quantile_by(&["service"], 3_600_000, 60_000); + let merges = 50.0 * 60.0 - 5.0; + assert_eq!( + merge(&hourly, &by_endpoint, &facts), + PhaseCost { + cpu_secs_per_sec: merges / 60.0, + memory_bytes: 5.0, + } + ); + assert_eq!( + query(&hourly, &by_endpoint, &facts).cpu_secs_per_sec, + 5.0 / 60.0 + ); + assert_eq!( + query_latency_ms(&hourly, &by_endpoint, &facts), + 1000.0 * (5.0 + merges) + ); + // A direct query still folds each service's 10 endpoints into one. + let direct = quantile_by(&["service"], 60_000, 60_000); + assert_eq!( + merge(&direct, &by_endpoint, &facts).cpu_secs_per_sec, + 45.0 / 60.0 + ); + } } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 89d35fac..c346764e 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -60,8 +60,15 @@ fn measured_at_group_count(config: &AtomicCostEntry, groups: u64) -> bool { /// 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) +/// is `mergeable_across_groups`. Their windows, slides and heaps come from +/// `group`, the RAQEs they may serve. fn candidate_deployments( group: &[&Raqe], + grouping: &LabelSet, + mergeable_across_groups: bool, costs: &[AtomicCostEntry], metric_facts: &MetricFacts, allow_undeployable_families: bool, @@ -89,6 +96,8 @@ 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 }) .collect(); let heap_rows = heap_rows_by_shape(&family_rows); @@ -152,7 +161,7 @@ fn candidate_deployments( capability, metric: group[0].metric.clone(), spatial_filter: group[0].spatial_filter.clone(), - grouping_labels: group[0].grouping_labels.clone(), + grouping_labels: grouping.clone(), config: config.clone(), window_ms, slide_ms, @@ -319,8 +328,34 @@ pub fn build_all_candidates_unpruned( } groups .iter() - .flat_map(|(&(_, metric, _, _), group)| { - candidate_deployments(group, costs, &facts[metric], allow_undeployable_families) + .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 + .iter() + .filter(|r| { + r.capability == capability + && r.metric == metric + && r.spatial_filter == filter + && r.grouping_labels.is_subset(grouping) + }) + .collect(); + [ + (exact_group.as_slice(), false), + (subset_group.as_slice(), true), + ] + .into_iter() + .flat_map(|(group, mergeable_across_groups)| { + candidate_deployments( + group, + grouping, + mergeable_across_groups, + costs, + &facts[metric], + allow_undeployable_families, + ) + }) + .collect::>() }) .collect() } @@ -502,7 +537,9 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A r.capability == d.capability && r.metric == d.metric && r.spatial_filter == d.spatial_filter - && r.grouping_labels == d.grouping_labels + && (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) @@ -1037,4 +1074,108 @@ mod tests { &table_accuracy, ); } + + #[test] + fn a_mergeable_deployment_serves_a_coarser_grouping_only() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let serves = |d: &Deployment, grouping: &[&str]| { + is_eligible( + &quantile_by(grouping, 60_000, 60_000), + d, + &facts, + &table_accuracy, + ) + }; + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + assert!(serves(&by_endpoint, &["service", "endpoint"])); + assert!(serves(&by_endpoint, &["service"])); + assert!(serves(&by_endpoint, &[])); + assert!(!serves(&by_endpoint, &["pod"])); + assert!(!serves( + &kll_by(&["service"], 60_000), + &["service", "endpoint"] + )); + } + + #[test] + fn a_rate_serves_only_its_own_grouping() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + let increase_by_endpoint = Deployment { + capability: Capability::RateOrIncrease, + config: AtomicCostEntry { + sketch: "exact-increase".into(), + accuracy_metric: metric_of("exact-increase"), + ..by_endpoint.config.clone() + }, + ..by_endpoint + }; + let rate_by = |grouping: &[&str]| Raqe { + capability: Capability::RateOrIncrease, + ..quantile_by(grouping, 60_000, 60_000) + }; + let serves = |r: &Raqe| is_eligible(r, &increase_by_endpoint, &facts, &table_accuracy); + assert!(serves(&rate_by(&["service", "endpoint"]))); + assert!(!serves(&rate_by(&["service"]))); + } + + #[test] + fn top_k_serves_only_its_own_grouping() { + use crate::test_support::{deployment, label_set, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = Deployment { + grouping_labels: label_set(&["service", "endpoint"]), + ..deployment(1.0, 1.0, 1.0, 1.0, 60_000, 60_000) + }; + let serves = |grouping: &[&str]| { + let r = Raqe { + grouping_labels: label_set(grouping), + ..raqe("r", 60_000, 60_000) + }; + is_eligible(&r, &by_endpoint, &facts, &table_accuracy) + }; + assert!(serves(&["service", "endpoint"])); + assert!(!serves(&["service"])); + } + + /// A 1 h fine RAQE alone never yields a 90 min window. Its 90 min coarse + /// sibling does, but only for the family that can serve both. + #[test] + fn fine_candidates_take_windows_from_coarser_raqes() { + use crate::test_support::{label_set, quantile_by, service_endpoint_facts}; + const HOUR: Millis = 3_600_000; + const NINETY_MINUTES: Millis = 5_400_000; + let fine = ["service", "endpoint"]; + let topk_by = |grouping: &[&str], lookback_ms| Raqe { + grouping_labels: label_set(grouping), + ..raqe("r", lookback_ms, lookback_ms) + }; + let raqes = [ + quantile_by(&fine, HOUR, HOUR), + quantile_by(&["service"], NINETY_MINUTES, NINETY_MINUTES), + topk_by(&fine, HOUR), + topk_by(&["service"], NINETY_MINUTES), + ]; + let kll = AtomicCostEntry { + sketch: "kll-percall".into(), + sketch_config: serde_json::json!({"params": {"k": 200}}), + accuracy_metric: metric_of("kll-percall"), + ..cost() + }; + let candidates = + build_all_candidates_unpruned(&raqes, &[kll, cost()], &service_endpoint_facts(), false); + let fine_windows = |sketch: &str| { + candidates + .iter() + .filter(|d| d.config.sketch == sketch && d.grouping_labels == label_set(&fine)) + .map(|d| d.window_ms) + .collect::>() + }; + assert!(fine_windows("kll-percall").contains(&NINETY_MINUTES)); + let topk_windows = fine_windows("cms-heap-topk-fastpath-vector2d"); + assert!(topk_windows.contains(&HOUR)); + assert!(!topk_windows.contains(&NINETY_MINUTES)); + } } diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 666cf5a1..18a8253f 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -1,11 +1,11 @@ //! Brute-force search over full mappings (§4, §7 step 2). //! //! A mapping is one deployment choice per RAQE (§4's only constraint is -//! `Σ_D x_{i,D} = 1`; `y_D` is derived). No RAQE is eligible outside its own -//! `(capability, metric, spatial_filter, grouping_labels)` group, so choices are independent and the search -//! space is exactly the cartesian product of the per-RAQE eligible lists -- -//! nothing to prune against. Sharing falls out when two choices land on the -//! same index. +//! `Σ_D x_{i,D} = 1`; `y_D` is derived). Choices are independent, so the +//! search space is exactly the cartesian product of the per-RAQE eligible +//! lists -- nothing to prune against. Sharing falls out when two choices land +//! on the same index, including a fine deployment chosen by a RAQE that rolls +//! up to a coarser grouping. //! //! An ILP would replace this module alone: `Mapping` already encodes //! `x_{i,D}` and `y_D`. diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 44429a81..cec9b55e 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -32,7 +32,9 @@ pub(crate) fn secs(ms: Millis) -> f64 { ms as f64 / 1000.0 } -/// A group-by key, compared as a set (§3's `labels_i == labels_D` rule). +/// A group-by key, compared as a set: a deployment serves a RAQE with the +/// same one, or a subset of it when the family is +/// [`mergeable_across_groups`](FamilyProperties::mergeable_across_groups). pub type LabelSet = BTreeSet; /// What an RAQE's statistic needs (§1). A variant becomes a candidate only @@ -209,6 +211,10 @@ pub fn heap_capacity(config: &AtomicCostEntry) -> Option { pub struct FamilyProperties { /// Windows fold into one. A family without it only serves `L == x`. pub mergeable_across_windows: bool, + /// Groups' states fold into their parent group's: a deployment grouped by + /// `G` serves a RAQE grouped by any subset of `G` (a roll-up). Not top-k, + /// whose heaps drop items that are in the parent's top k but no child's. + pub mergeable_across_groups: bool, /// One sketch of fixed size holds every group: the design doc's Shared + /// Fixed cell. Memory, merge and storage don't scale with `card(G)`. /// Exact accumulators are Shared + PerKey and `false` here, because the @@ -232,6 +238,7 @@ pub fn family_properties(variant: &str) -> FamilyProperties { use AccuracyDirection::{HigherIsBetter, LowerIsBetter}; let one_sketch_per_group = |metric, direction| FamilyProperties { mergeable_across_windows: true, + mergeable_across_groups: true, one_fixed_size_sketch_for_all_groups: false, needs_delta_set_key_tracker: false, exact: false, @@ -243,7 +250,12 @@ pub fn family_properties(variant: &str) -> FamilyProperties { ..one_sketch_per_group("relative_error", LowerIsBetter) }; match variant { - "exact-sum" | "exact-min" | "exact-max" | "exact-increase" => exact, + "exact-sum" | "exact-min" | "exact-max" => exact, + // A rate rolled up to a coarser grouping is not a meaningful query. + "exact-increase" => FamilyProperties { + mergeable_across_groups: false, + ..exact + }, KEY_TRACKER_FAMILY => FamilyProperties { accuracy: None, ..exact @@ -253,9 +265,13 @@ pub fn family_properties(variant: &str) -> FamilyProperties { "dd" => one_sketch_per_group("mean_relative_value_error", LowerIsBetter), "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" - | "univmon-topk" => one_sketch_per_group("precision_at_k", HigherIsBetter), + | "univmon-topk" => 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, @@ -275,6 +291,7 @@ pub struct MetricFacts { pub scrape_interval_ms: Millis, /// `card(X)`: distinct value combinations of each label set `X` in use. /// Must include `labels` itself, whose cardinality is the series count. + /// A label set never has more groups than any superset of it. pub cardinality: BTreeMap, /// `(lo, hi)`: smallest and largest positive sample value, if known. /// Sizes DDSketch; without it, DDSketch keeps the measured memory. @@ -365,13 +382,16 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec false, }; } - if let (Some(&groups), Some(&series)) = - (cardinality.get(grouping), cardinality.get(all_labels)) - { - if groups > series { - problems.insert(format!( - "{metric}: {grouping:?} has {groups} groups but only {series} series" - )); + // Dropping labels never adds groups. A roll-up's merge count, + // `card(G_d) · L/x − card(G_r)`, relies on it. + for (coarse, &coarse_groups) in cardinality { + for (fine, &fine_groups) in cardinality { + if coarse.is_subset(fine) && coarse_groups > fine_groups { + problems.insert(format!( + "{metric}: {coarse:?} has {coarse_groups} groups but its superset \ + {fine:?} only {fine_groups}" + )); + } } } } @@ -652,6 +672,51 @@ pub(crate) mod test_support { key_tracker: None, } } + + pub fn label_set(names: &[&str]) -> LabelSet { + names.iter().map(|name| name.to_string()).collect() + } + + /// 5 services × 10 endpoints, one series per endpoint, scraped every + /// second: the coarse and fine groupings of a roll-up. + pub fn service_endpoint_facts() -> WorkloadFacts { + let service = label_set(&["service"]); + let service_endpoint = label_set(&["service", "endpoint"]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: service_endpoint.clone(), + scrape_interval_ms: 1_000, + cardinality: BTreeMap::from([(service, 5), (service_endpoint, 50)]), + value_range: None, + data_shape: BTreeMap::new(), + }, + )]) + } + + /// A per-group KLL deployment by `grouping`, every per-instance cost 1. + pub fn kll_by(grouping: &[&str], window_ms: Millis) -> Deployment { + let base = deployment(1.0, 1.0, 1.0, 1.0, window_ms, window_ms); + Deployment { + capability: Capability::Quantile, + grouping_labels: label_set(grouping), + config: AtomicCostEntry { + sketch: "kll-percall".into(), + sketch_config: serde_json::json!({"params": {"k": 200}}), + accuracy_metric: metric_of("kll-percall"), + ..base.config + }, + ..base + } + } + + pub fn quantile_by(grouping: &[&str], lookback_ms: Millis, interval_ms: Millis) -> Raqe { + Raqe { + capability: Capability::Quantile, + grouping_labels: label_set(grouping), + ..raqe(lookback_ms, interval_ms) + } + } } #[cfg(test)] @@ -865,16 +930,18 @@ mod tests { ); } + /// Every label set, not just the full one, bounds its subsets' groups. #[test] - fn rejects_more_groups_than_series() { + fn rejects_a_label_set_with_more_groups_than_its_superset() { let facts = WorkloadFacts::from([( METRIC.to_string(), MetricFacts { - labels: labels(&["service", "endpoint"]), + labels: labels(&["service", "endpoint", "pod"]), scrape_interval_ms: 15_000, cardinality: BTreeMap::from([ (labels(&["service"]), 60), (labels(&["service", "endpoint"]), 50), + (labels(&["service", "endpoint", "pod"]), 30_000), ]), value_range: None, data_shape: BTreeMap::new(), @@ -884,7 +951,12 @@ mod tests { grouping_labels: labels(&["service"]), ..raqe(60_000, 60_000) }; - let problems = validate_facts(&[r], &facts).unwrap_err(); - assert!(problems[0].contains("60 groups but only 50 series")); + assert_eq!( + validate_facts(&[r], &facts).unwrap_err(), + [format!( + "{METRIC}: {{\"service\"}} has 60 groups but its superset \ + {{\"endpoint\", \"service\"}} only 50" + )] + ); } } diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index 81ebf849..a6785d43 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -446,7 +446,9 @@ impl SaturationCurves { return table_accuracy(raqe, deployment).map(|v| (v, AccuracySource::Measured)); } let metric_facts = &facts[&deployment.metric]; - let grouping = &deployment.grouping_labels; + // The answered groups: the RAQE's, coarser than the deployment's on a + // roll-up, whose answer is the merged coarse group's. + let grouping = &raqe.grouping_labels; let shape = metric_facts.data_shape.get(grouping)?; let k = raqe.topk_k(); let base = with_topk_k(&config_params(&deployment.config)?, TOPK_K); @@ -464,7 +466,12 @@ impl SaturationCurves { let covered = items_per_group(metric_facts, grouping, raqe.lookback_ms); let (_, direction) = accuracy_key(&deployment.config.sketch); let merges = if merges_lossily(&deployment.config.sketch) { - let merges = deployment.query_instance_count(raqe.lookback_ms)?; + // A roll-up also merges each coarse group's children, the average + // `card(G_d) / card(G_r)` of them. + // ponytail: average fan-out; the largest group's is sketch-bench#189. + let fan_out = metric_facts.cardinality[&deployment.grouping_labels] + .div_ceil(metric_facts.cardinality[grouping]); + let merges = deployment.query_instance_count(raqe.lookback_ms)? * fan_out; // A heap of m · k merged from m windows reads as one sketch: the // merged heaps are taken to still hold the true top k. match ( @@ -984,6 +991,45 @@ mod tests { assert_eq!(at(100_000), None); } + /// p99 by service from KLL by (service, endpoint) reads the coarse + /// group's shape and items, merged from its 10 endpoints. + #[test] + fn a_kll_roll_up_reads_the_merge_curve_at_fan_out_times_windows() { + 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"), + shape: MeasuredShape::Pareto { tail_index: 2.0 }, + error_metric: "mean_rank_err".into(), + n_sat: None, + curve: curve(0.01), + merged: BTreeMap::from([(4, curve(0.02)), (16, curve(0.05))]), + }; + let curves = SaturationCurves { + points_by_sketch: BTreeMap::from([("kll-percall".to_string(), vec![kll])]), + }; + let mut facts = service_endpoint_facts(); + let metric = facts.get_mut(METRIC).unwrap(); + // Only the coarse grouping's shape is on the grid. + metric + .data_shape + .insert(label_set(&["service"]), shape(1.0, 1.0)); + metric.data_shape.insert( + label_set(&["service", "endpoint"]), + DataShape { + tail_index: 9.0, + ..shape(1.0, 1.0) + }, + ); + // 10 series per service × 100 s = 1e3 items, in one window. + let by_service = quantile_by(&["service"], 100_000, 100_000); + let accuracy = + |grouping: &[&str]| curves.accuracy(&by_service, &kll_by(grouping, 100_000), &facts); + assert_eq!(accuracy(&["service"]), Some(0.01)); + // 10 merged endpoints sit between 4 and 16 shards: the worse, 16. + assert_eq!(accuracy(&["service", "endpoint"]), Some(0.05)); + } + /// A heap of m · k merged from m windows reads as one sketch: the plain /// curve, not the merge curve, and no merge curve is needed. #[test] diff --git a/rqe-optimizer/tests/mixed_grouping.rs b/rqe-optimizer/tests/mixed_grouping.rs new file mode 100644 index 00000000..b33c564d --- /dev/null +++ b/rqe-optimizer/tests/mixed_grouping.rs @@ -0,0 +1,166 @@ +//! A workload asking the same question at two groupings, `(service, +//! endpoint)` and `(service)`, solved end to end. A family whose states merge +//! across groups serves both from one fine deployment; one whose don't keeps a +//! deployment per grouping (sketch-bench#187). + +use std::collections::BTreeMap; + +use aqpbm_core::MeasuredAt; +use rqe_optimizer::candidates::build_all_candidates; +use rqe_optimizer::milp::{minimize, MilpSolution, Objective}; +use rqe_optimizer::{ + accuracy_key, validate_facts, AccuracyDirection, AtomicCostEntry, Capability, Deployment, + LabelSet, MetricFacts, Raqe, WorkloadFacts, +}; + +const METRIC: &str = "http_request_duration_seconds"; +const HOUR_MS: u64 = 3_600_000; +const MINUTE_MS: u64 = 60_000; + +fn labels(names: &[&str]) -> LabelSet { + names.iter().map(|name| name.to_string()).collect() +} + +/// 5 services × 10 endpoints × 600 pods = 30,000 series, scraped every 15 s. +fn facts() -> WorkloadFacts { + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint", "pod"]), + scrape_interval_ms: 15_000, + cardinality: BTreeMap::from([ + (labels(&["service"]), 5), + (labels(&["service", "endpoint"]), 50), + (labels(&["service", "endpoint", "pod"]), 30_000), + ]), + value_range: None, + data_shape: BTreeMap::new(), + }, + )]) +} + +fn raqe(id: &str, capability: Capability, grouping: &[&str], accuracy_sla: f64) -> Raqe { + Raqe { + id: id.into(), + capability, + lookback_ms: HOUR_MS, + interval_ms: MINUTE_MS, + metric: METRIC.into(), + spatial_filter: String::new(), + grouping_labels: labels(grouping), + accuracy_sla, + latency_sla_ms: None, + topk_k: None, + } +} + +fn raqes() -> Vec { + vec![ + raqe( + "p99_by_endpoint", + Capability::Quantile, + &["service", "endpoint"], + 0.05, + ), + raqe("p99_by_service", Capability::Quantile, &["service"], 0.05), + raqe( + "top_by_endpoint", + Capability::TopKByValue, + &["service", "endpoint"], + 0.9, + ), + raqe("top_by_service", Capability::TopKByValue, &["service"], 0.9), + ] +} + +/// Ingest dominates merge and query, as it does in the measured table, so +/// sharing one deployment is cheaper than keeping two whenever it is allowed. +fn cost_row(sketch: &str, params: serde_json::Value) -> AtomicCostEntry { + let (accuracy_metric, _) = accuracy_key(sketch); + AtomicCostEntry { + sketch: sketch.into(), + sketch_config: serde_json::json!({ "params": params }), + mem_bytes_per_instance: 1_000.0, + insert_cpu_secs: 1e-6, + merge_cpu_secs: 1e-6, + query_cpu_secs: 1e-6, + query_accuracy: BTreeMap::from([(accuracy_metric.to_string(), 0.0)]), + accuracy_metric: accuracy_metric.into(), + measured_at: MeasuredAt { + items_per_instance: 1_000_000, + keys_per_instance: Some(10_000), + value_range: None, + merge_operand_items: None, + distribution: None, + }, + } +} + +fn cost_table() -> Vec { + vec![ + cost_row("kll-percall", serde_json::json!({ "k": 200 })), + // A heap large enough for any merge, so heap size never decides the plan. + cost_row( + "cms-heap-topk-fastpath-vector2d", + serde_json::json!({ "rows": 3, "cols": 1024, "heap": 1u64 << 40 }), + ), + ] +} + +/// Every candidate meets every SLA, so the plan is decided by eligibility and +/// cost alone. +fn perfect_accuracy(_: &Raqe, deployment: &Deployment) -> Option { + match accuracy_key(&deployment.config.sketch).1 { + AccuracyDirection::LowerIsBetter => Some(0.0), + AccuracyDirection::HigherIsBetter => Some(1.0), + } +} + +fn solve(raqes: &[Raqe]) -> MilpSolution { + let facts = facts(); + validate_facts(raqes, &facts).expect("valid workload facts"); + let candidates = build_all_candidates(raqes, &cost_table(), &facts, false, &perfect_accuracy); + minimize( + raqes, + &candidates, + &facts, + Objective::default(), + &perfect_accuracy, + ) + .expect("feasible plan") +} + +/// The planned deployment serving the RAQE named `id`. +fn deployment_serving<'a>(solution: &'a MilpSolution, raqes: &[Raqe], id: &str) -> &'a Deployment { + let index = raqes.iter().position(|raqe| raqe.id == id).unwrap(); + &solution.deployments[solution.raqes[index].deployment].deployment +} + +#[test] +fn a_fine_kll_deployment_serves_both_quantile_raqes() { + let raqes = raqes(); + let solution = solve(&raqes); + let by_endpoint = deployment_serving(&solution, &raqes, "p99_by_endpoint"); + let by_service = deployment_serving(&solution, &raqes, "p99_by_service"); + assert_eq!( + by_endpoint, by_service, + "one KLL deployment should serve both groupings" + ); + assert_eq!( + by_endpoint.grouping_labels, + labels(&["service", "endpoint"]) + ); +} + +#[test] +fn top_k_never_rolls_up() { + let raqes = raqes(); + let solution = solve(&raqes); + let by_endpoint = deployment_serving(&solution, &raqes, "top_by_endpoint"); + let by_service = deployment_serving(&solution, &raqes, "top_by_service"); + assert_eq!( + by_endpoint.grouping_labels, + labels(&["service", "endpoint"]) + ); + assert_eq!(by_service.grouping_labels, labels(&["service"])); +} From 8e255d50b7b69fc721b77ddd0ca8ec5c06c5aea3 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Fri, 9 Oct 2026 15:38:08 -0400 Subject: [PATCH 02/13] docs: split RQE optimizer design by concern --- docs/rqe_optimizer_candidates.md | 267 ++++++++ docs/rqe_optimizer_cost_model.md | 448 +++++++++++++ docs/rqe_sketch_deployment_v1.md | 632 +----------------- rqe-optimizer/examples/autosketch_vs_asap.rs | 4 +- .../README.md | 2 +- .../autosketch-vs-asap-synthetic/README.md | 2 +- rqe-optimizer/src/lib.rs | 9 +- rqe-optimizer/src/milp.rs | 5 +- rqe-optimizer/src/usage.rs | 2 +- scripts/plot_autosketch_vs_asap_sla.py | 2 +- scripts/plot_autosketch_vs_asap_synthetic.py | 2 +- 11 files changed, 740 insertions(+), 635 deletions(-) create mode 100644 docs/rqe_optimizer_candidates.md create mode 100644 docs/rqe_optimizer_cost_model.md diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md new file mode 100644 index 00000000..4d0b9ff2 --- /dev/null +++ b/docs/rqe_optimizer_candidates.md @@ -0,0 +1,267 @@ +# RQE optimizer: candidate generation and mapping + +This document is the canonical design for candidate construction, eligibility, dominance pruning, finer-to-coarser roll-ups, and the assignment MILP. + +## Candidate deployments + +A candidate deployment is: + +```text +D = (capability, configuration, metric, G, x, y) +``` + +Candidates may be generated from individual RAQEs, then deduplicated. This is +only a way to construct the candidate set: when solving a workload, one +selected deployment may serve multiple compatible RAQEs. + +Intuition: candidates are built in two steps, and each drops only candidates +that another candidate beats, so the best plan is never lost. Generation uses +no measurements. It keeps every legal window and configuration, and drops only +slides that a coarser slide beats for the same RAQEs. Pruning then attaches the +measured costs and drops a candidate when another serves all of its RAQEs and +is no worse on every cost. + +For each (capability, metric, G) group, generate candidates as follows: + +```text +for each window x that divides some S_i and is a multiple of the scrape interval: + g = { g_i = gcd(x, T_i) : RAQE i with S_i divisible by x } + slides = { gcd(A) : A is a non-empty subset of g } + for each y in slides that is a multiple of the scrape interval: + for each configuration that serves the capability: + add (capability, configuration, metric, G, x, y) +``` + +`g_i = gcd(x, T_i)` is the largest slide that serves RAQE `i`. + +**Windows.** An RAQE merges `S_i / x` whole windows, so `x` must divide `S_i`. +Windows and slides finer than the scrape interval would only split one +scrape's samples. + +**Slides.** A slide `y` serves RAQE `i` when it divides both `x` and `T_i`, +that is, when it divides `g_i`. A finer slide serves no more RAQEs but holds +more open windows (`x / y`) and more closed ones, so it costs more ingest and +storage at the same latency. Hence: + +- for one RAQE, `y = g_i` is strictly better than every finer slide that serves + it; +- for a set `A` of RAQEs sharing a deployment, `y = gcd(A)`, the largest slide + dividing every `g_i` in `A`, is strictly better than every finer slide that + serves them all. + +Which RAQEs share is the solver's choice, so every subset's gcd is a candidate. +Every other divisor of `x` is strictly worse than one of these. + +Example: `x = 60`, RAQE `a` every 20 s, RAQE `b` every 30 s. + +| Served RAQEs | `y` | Open windows `x / y` | +|---|---|---| +| `a` | gcd(60, 20) = 20 | 3 | +| `b` | gcd(60, 30) = 30 | 2 | +| `a` and `b` | gcd(20, 30) = 10 | 6 | + +The slides are `{10, 20, 30}`. `y = 5` would also serve both, but holds 12 open +windows instead of 6. With a 15 s scrape interval only `y = 30` remains: no +multiple of 15 divides both 20 and 30, so `a` and `b` cannot share at +`x = 60`. + +The subset gcds take one pass, without listing subsets: keep the gcds found so +far, and for each new `g` add `g` and `gcd(found, g)` for every `found`. For +`{20, 30}`: `{20}`, then `{20, 30, 10}`. One pass suffices because +`gcd(A ∪ {g}) = gcd(gcd(A), g)`. + +An RAQE `r_i` is eligible for a candidate `D` when: + +1. `cap_i = D.capability`, `metric_i = D.metric` and `G_i = D.G`. +2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. +3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family + (`family_properties`, which also gives the direction), clears `tol_i`. + +Exact accumulators take that accuracy from the cost table; they merge without +loss, so the window size doesn't matter. Sketches take it +from the saturation study's error-vs-N curves (`SaturationCurves`, #156), +read at the number of items one group receives over the RAQE's whole +lookback: series per group times scrapes per lookback. + +- The curve is the configuration's at the metric's fitted `data_shape` for + `G` (zipf θ and keys `K`, or tail index `a` for quantiles). Between grid + points, the worst bracketing point; outside the grid, or with no fit, no + accuracy. +- Between checkpoints, the worse neighbour. Below the first checkpoint, no + accuracy. Past the last, the plateau if the point saturated, else none. +- The curve's `error_metric` must be the family's metric; `SaturationCurves::load` + refuses a curve for another metric as a stale study. +- For sketches that merge exactly, the window size doesn't matter: a merged + answer reads the curve at the lookback's item count, like a single sketch. + KLL and top-k merge lossily (#131): an answer merged from `m = S_i / D.x` + windows reads the study's merge curve (`saturation_merge_curve.csv`, the + sketch merged from `m` shards of the same items) at the lookback's item + count. Between measured shard counts, the worse. Past the largest + measured count, or without a merge curve, a merged KLL or top-k answer has + no accuracy: the study must measure the merge counts a workload needs + (`--merge-shards-list`) up to the N it reads at: past the merge curve's + last N, the merged answer has no accuracy either (#158). + `SaturationCurves::load` refuses a study with no merge curves for a + candidate KLL sketch. +- A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap + top-k (CMS-heap, CountSketch-heap) keeps a heap of `m · k` in a deployment + answering from `m = S_i / D.x` merged windows (`m = 1` gives `k`). + Candidates carry one heap per distinct `m · k` among the RAQEs on a window, + and a RAQE is eligible only where the heap holds its `m · k`. Such a merged answer reads as one sketch: the + plain curve, then the guarantee fallback. It assumes the merged heaps still + hold the true top `k`; it is not a guarantee. So heap top-k needs no merge + curves. Costs come from the cost table's rows at heaps 32, 128, 512 and + 2048 (`heap=`), linear in the heap between them and past them. Curves are + measured per `k` (`topk_k=` in the config; 10, 32 and 100 by default) at a + heap of `k`, and larger heaps read the same curve. A RAQE reads the curve + at its `k`, else at the next larger measured `k` (harder); past every + measured `k`, only the guarantee at its `k`. Its query outputs `k` + entries per group. +- Where the study measured nothing for a bracketing point at or above its + first N (past an unsaturated curve, past the measured merge counts or N, + or with no merge curve), the accuracy falls back to the algorithm's + guarantee at 95% confidence (`rqe_optimizer::theory`; two-sided for + rank and relative errors, one-sided for CMS overestimates). It is never + better than the worst last measurement of the curves it extends. The fallbacks are: + - KLL: rank error `2.296 / k^0.9723` (DataSketches' 99% value), scaled + to 95% two-sided; + - DDSketch: relative value error `α` (unbounded store); + - HLL: `1.96 · 1.04 / sqrt(2^lg_k)`; + - CMS-heap top-k, unmerged: the share of the top `k` Zipf(θ, K) keys kept + ranked for every key at once. With Markov per row, independent rows, + and a union bound over the `K − k` other keys, key `i` fails with + probability at most `(cols · (p_i − p_{k+1}))^−rows`. Keys are counted + from the most frequent while the summed failure stays within 5%. It + assumes the heap ranks keys by their final CMS estimates. + + A sketch with no published bound, a merged top-k answer, a point below + the first N, or a shape outside the grid stays unknown. + `accuracy_with_source` reports which points used a bound. + +The cost table's sketch accuracies are not read, but they are one point on +each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto +`a`) is a grid point's key. `SaturationCurves::check_cost_table` reports every +row whose `accuracy_metric` is not its family's or not its curve's +`error_metric`, whose configuration is not in the grid, or whose accuracy +disagrees with the curve at `measured_at` (beyond 3 seed standard errors plus +5%). The study adds the cost table's shape to the grid as a full row and +column (θ = 1.1 at every K, K = 1e4 at every θ), so every sketch row has a +grid point and the grid stays a full cross. `SaturationCurves::load` +refuses curves whose Zipf grid isn't a full cross of its θ and K values and +names the missing points: a hole would leave every shape around it without +accuracy (for example, curves from `--points-from` or a narrowed `--resume`). A row without a grid point (a study run +with `--no-cost-shape`) is reported as unchecked. `small_problem` refuses to plan +when any row disagrees. + +For lower-is-better metrics, passing means `measured <= tol_i`. For +higher-is-better metrics, passing means `measured >= tol_i`. Direction is +explicit on the RAQE; it is never inferred from a metric name. A missing metric +does not pass. + +Before mapping, prune a candidate only if another candidate can serve every +RAQE it can and is no worse in ingest CPU and memory, and in latency, merge +memory and stored memory for each such RAQE. This is safe because any mapping using +the removed candidate can substitute the remaining one without weakening a +modeled objective. + +Closed instances must be stored long enough to answer the RAQEs assigned to a +deployment. Retention is not a candidate parameter: a deployment stores the +history needed by the largest assigned query window, costed as the storage +phase (below). + +## Workload mapping + +Let `z_{i,D}` be 1 when RAQE `i` uses candidate deployment `D`; let `u_D` be 1 +when deployment `D` is active. + +```text +Σ_D z_{i,D} = 1 for every RAQE i +z_{i,D} <= u_D for every eligible pair (i, D) +``` + +Every RAQE selects exactly one eligible deployment. Multiple RAQEs may select +the same deployment and therefore share its ingest work. A query may merge +multiple instances from its selected deployment, but v1 does not combine +results from several deployments to satisfy one RAQE. + +### MILP formulation + +Let `E` be the eligible `(i, D)` pairs. The solver has one binary `z_{i,D}` +for each pair in `E`, one binary `u_D` for each candidate, and a continuous +`stored_D` for each candidate's closed-window storage. + +```text +z_{i,D} ∈ {0, 1} for (i, D) ∈ E +u_D ∈ {0, 1} for D ∈ candidates +stored_D ≥ 0 + +Σ_{D: (i,D) ∈ E} z_{i,D} = 1 for every RAQE i +z_{i,D} ≤ u_D for (i, D) ∈ E +u_D ≤ Σ_{i: (i,D) ∈ E} z_{i,D} for every candidate D +stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E +``` + +The `u_D ≤ Σ z` constraint prevents a deployment from becoming active when no +RAQE selected it. It is not required for feasibility, but makes ingest cost +unambiguous. `stored_D` is a linearized max: a deployment stores enough for +the longest lookback it serves. + +The only objective, `Objective::AUCCost { w_cpu, w_mem }`, weighs each phase +cost (below) as `w(c) = w_cpu × c.cpu + w_mem × c.memory_GiB`: + +```text +minimize Σ_D w(ingest_D) × u_D + + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} + + Σ_D stored_D +``` + +CPU is the area under the CPU curve (mean CPU-sec/sec), so plans are sized +for the mean load, not for bursts. Memory sums every phase, as if every query +evaluates at once. The default weights are `(1, 0)`: CPU only. + +Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver +never enumerates full mappings. + + +## Fine-to-coarse group roll-ups (#190) + +### Vocabulary + +A deployment has a source grouping `G_d`; a RAQE asks for a result grouped by `G_r`. `C_d = card(G_d)` and `C_r = card(G_r)`. A conventional, per-group sketch can answer `G_r subseteq G_d` by merging the fine states that belong to each coarse group. We call that operation a *roll-up*. + +Hydra is different. It ingests a labelled record into one shared grid and answers a subpopulation predicate from that grid. It does not expose one KLL per fine group for the optimizer to merge. A coarse Hydra answer, if the Hydra layout supports its predicate, is a direct query of the shared sketch, not the generic roll-up operation. + +### What #190 guarantees today + +For the families marked `mergeable_across_groups`, #190 permits `G_r subseteq G_d`. Thus, one can never use a coarse deployment for a fine RAQE. The eligible families are exact sum/min/max, HLL, cardinality UnivMon, KLL, and DDSketch. Rate/increase and top-k remain exact-grouping only i.e. `G_r == G_d`. + +For a conventional per-group sketch, a query over `L` using base windows `x` folds this many states: + +```text +M = C_d * L/x - C_r +``` + +Thus merge CPU is `M * c_mrg / T`, merge memory is `C_r * m(L)`, and query CPU and output are priced at `C_r`. Ingest and retained base-window storage remain priced at `C_d`. This reduces to the old model when the groupings are equal, and it correctly charges a direct roll-up (`L = x`) for `C_d - C_r` merges. + +Eligibility also reads accuracy at the requested grouping: its data shape and item count are those of `G_r`. For KLL, the measured merge curve is read at the average fan-out `ceil(C_d / C_r) * L/x`. That is an empirical estimate, not a worst-group bound. +This is a known cost-modeling issue caused due to uneven fan-out, logged in #189. + +### Future Hydra candidate strategy + +The existing candidate map remains the right shape for conventional roll-ups: generate a deployment at every RAQE grouping already present; for a mergeable family let that deployment consider RAQEs at subset groupings when choosing windows and slides; then add one eligible edge `(RAQE, deployment)` for every SLA-valid subset relation. The MILP itself is unchanged: one `z[i,D]` per eligible edge, one `u[D]` per deployment, and the same assignment and activation constraints. Its coefficients use the roll-up costs above. + +Hydra should enter through a distinct candidate/read strategy, for example `DirectSubpopulationQuery`, with these properties: + +- candidate identity includes the complete label schema `H`, Hydra config, window and slide, plus its group-enumeration strategy; +- it may cover a RAQE only when `G_r` is a supported predicate/grouping of `H`, its exact measurement clears the RAQE SLA, and its merge depth was measured; +- its edge coefficients use the [Hydra cost model](rqe_optimizer_cost_model.md#proposed-hydra-cost-model) plus any tracker costs; +- it is not marked `mergeable_across_groups`, and is never charged or validated as a fine-state roll-up. + +This keeps candidate generation, eligibility, cost scoring, enumeration, and the MILP on one shared edge set while making the meaning of an edge explicit. The first Hydra implementation can conservatively support only `G_r = H` (or only explicitly benchmarked prefix groupings), then expand the supported predicate relation as measurements land. + +### Decisions needed + +1. Is coarse Hydra group enumeration derived from a fine DeltaSet, or do we store keys at every requested grouping? +2. Which predicates are legal: only prefix label groupings, or arbitrary subsets once the IR has a label-to-layout mapping? +3. Do we require an observed worst-parent fan-out curve (issue #189) before admitting Hydra, or accept an average-fan-out planning estimate like #190's KLL model? +4. What interpolation/extrapolation, if any, is permitted between measured Hydra saturation points? diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md new file mode 100644 index 00000000..d8c9eb84 --- /dev/null +++ b/docs/rqe_optimizer_cost_model.md @@ -0,0 +1,448 @@ +# RQE optimizer: cost models + +This document is the canonical design for cost-by-use, batch latency, the analytical phase model, and the measurements required before Hydra can participate. + +## Cost by use and batch latency + +Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in +`rqe-optimizer/src/usage.rs` (resource use, cost, latency) and +`milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by +use, in two versions: + +- **Version 1, no latency constraint:** the cheapest plan; its latency is + reported. Sweeping an optional latency bound traces each method's + cost–latency Pareto frontier. +- **Version 2, a batch latency SLA:** the cheapest plan whose batch latency, + from the job placement (§6), is at most the SLA `L`, for a grid of SLAs. +Evaluated first on the synthetic mixed template set; methods: ASAP (this +MILP, with sharing), PerQuery (the same MILP without sharing) and +AutoSketch-Adapted (fixed configs chosen by memory). + +#### 1. Definitions + +| Symbol | Meaning | +|---|---| +| `D`, `i` | a candidate deployment; a RAQE | +| `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | +| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | +| `card(G)` | groups of `D`'s grouping | +| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | +| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | +| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | +| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | +| `n_{i,D} = S_i / x_D` | windows a query merges | +| batch | all query jobs issued at one instant | + +**Measurement assumption (sketch-bench as is).** Every sketch operation is +single-threaded and compute-bound: sketch-bench's CPU time equals its wall +time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses +at most one core and, on a full core, takes its CPU time. The cost table's +`*_cpu_secs` are all the model needs. + +#### 2. Cost model + +`cost = w1 · AUC(CPU) + w2 · AUC(memory)`: the mean vCPUs and GiB over time, +priced per vCPU and per GiB (CPU only: `(1, 0)`; Fargate's prices). CPU is +elastic: a job gets a core whenever it is ready. + +This is billing by use, as on fine-grained autoscaling platforms (Cloud Run +with request-based billing, Dataflow streaming, Flink on Kubernetes with an +autoscaler), idealized: capacity follows the load at once. Billing for +provisioned capacity (VMs, or containers billed by allocation such as +Fargate) is not modeled. Since a job holds its memory only while it runs, its +memory × time is the same whenever it runs, and queueing a job would save +nothing. + +#### 3. CPU: parts and how each is computed + +Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, +over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, +over which every job pattern repeats exactly. A part with `w` CPU-seconds per +event every `P` seconds runs `H / P` times per hyperperiod, so its mean is +`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. + +| Part | When | CPU-seconds | Mean vCPUs | +|---|---|---|---| +| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | +| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | +| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | + +- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at + most one core), **split by sample**: each worker reads a share of the input + (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so + it keeps its own open window instance of every group it sees. +- When a window closes (the watermark passes its end), a **compaction** job + merges the `k_D` partial instances of each group into one stored instance. + With `k_D = 1` there is none. +- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` + stored instances of each group for the query window, then estimate. Merging + is part of the query. It reads the newest window, which closes at the firing + time, so it starts after that window's compaction. + +`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already +a rate; only compaction (per window close, every `y_D`) and queries (per +firing, every `T_i`) are divided by their period. It is fixed by the plan, +whatever the schedule. + +In words: + +- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already + inside `λ_D`), and each is inserted into the `x_D / y_D` windows still + open, at `c_ins` CPU-seconds each: CPU-seconds per second. +- `c_D`: closing a window merges, for every instance, the `k_D` workers' + partial copies into one, which takes `k_D − 1` merges. This happens once + per slide. +- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows + (`n − 1` merges per instance), then answers once per group. This happens + once per interval. (A sketch shared by all groups merges one instance but + still answers every group.) +- `AUC(CPU)` adds the three rates: work per second, in vCPUs. + +#### 4. Memory: parts and how each is computed + +Each part is counted once: a window counts as ingest memory while open and as +storage once compacted, and a query reads stored instances in place. + +| Part | What | Bytes | Held | +|---|---|---|---| +| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | +| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | +| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | +| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | + +`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) ++ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its +own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. + +In words: + +- `I_D`: every worker keeps one instance per group for each of the + `x_D / y_D` windows still open, and there are `k_D` workers. +- `stored_D`: closed windows are kept until the longest lookback that `D` + serves no longer needs them. That is `(S − x)/y + 1` windows per group. +- Compaction: when a window closes, a new one opens, so ingest still holds + `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in + memory until the compaction has merged them. The merged copy takes the + storage slot that the oldest window frees at the same moment, so it is not + counted twice. +- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, + with `n = 1`, reads the stored window and needs none), plus the answer for + every group. +- `AUC(memory)`: ingest and storage are held all the time. A compaction's + and a query's memory are held only while they run, a fraction + `run time / y_D` or `run time / T_i` of the time. + +#### 5. Batch latency and the SLA + +A batch's **latency** is the time from its issue until its last query job +finishes, compaction included. A plan's **query latency** is its worst batch +latency, given by the job placement (§6). Version 1 reports it; version 2 +requires it to be at most the SLA `L`. Per-RAQE latency bounds +(`Raqe::latency_sla_ms`) are not used. + +CPU is elastic, so no job waits for a core, and a batch's latency is its +longest **chain**: the newest window's compaction, then the query, each on a +full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query +latency is the longest chain over its RAQEs. + +In words: the trade-off between cost and latency comes from the plan. A cheap +plan keeps short windows and merges many of them at query time (long +chains); a faster one precomputes more at ingest (more open windows, more CPU +and memory). With no bound the MILP picks the cheapest plan, whatever its +latency; a bound `L` asks for the cheapest plan at least that fast. + +#### 6. Job placement algorithm + +The job placement decides when each job runs on the available CPU, and so +gives every batch's latency. It is defined for any CPU capacity; billing by +use makes CPU elastic, so it runs with unlimited capacity. + +```text +capacity for jobs K = C − Σ_D ρ_D (C = ∞ when CPU is elastic) +event-driven, over the hyperperiod H = lcm(T_i, y_D), twice +(events: query issues, window closes, completions): + ready = compaction jobs (triggered at window closes) + + query jobs whose newest window is compacted + order: issue / trigger time (older first), then compaction before query + (it unblocks queries), then longest remaining work first + give rates in that order: job j gets a_j = min(1, K − rates already given) + a job at rate a_j finishes when its remaining work / a_j elapses + recompute the rates at every event +outputs: per-RAQE and per-batch latency, worst batch latency +``` + +In words: + +1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs; the + rest, `K`, is shared by compaction and query jobs. +2. **Issue jobs.** Each window close triggers a compaction job for its + deployment. Each firing issues a query job, which becomes ready only once + its deployment's newest window is compacted. +3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. + Within a batch, compaction runs before queries, because queries wait for + it. Then the longest remaining work runs first, so a long job doesn't end + up running alone at the end of the batch. +4. **Share capacity as rates.** In that order, each job gets up to one core + (a single-threaded job can't use more) from the capacity still free. The + last one served may get only a fraction and runs slower in proportion. +5. **Advance to the next event.** Time jumps to the next query issue, window + close or completion; remaining work drops by rate × elapsed time, and the + rates are recomputed. +6. **Read off the results.** A query's latency is its finish minus its + issue, and a batch's latency is that of its last query. + +With elastic CPU (`K = ∞`) every job starts as soon as it is ready on its own +core, so the placement has a closed form: a compaction runs for `c_D`, a +query for `ℓ_{i,D}`, and a batch's latency is its longest chain +`c_D + ℓ_{i,D}`. The code uses this closed form (`usage::usage_cost`), and +it is what makes both MILP versions exact. + +#### 7. MILP formulation + +Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), +`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and +pair are §3 and §4's. + +```text +minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +s.t. Σ_D z_{i,D} = 1 for every RAQE i + z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E + stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} +version 2, a batch latency SLA L (or version 1's frontier bound L): + z_{i,D} = 0 if c_D + ℓ_{i,D} > L +``` + +In words: + +- The objective is the price of the mean vCPUs (ingest and compaction per + active deployment, plus each RAQE's query work per second), plus the price + of the mean memory (ingest and storage per active deployment, each + compaction's partial copies for the fraction of time it runs, and each + query's memory for the fraction of time it runs). +- Every RAQE is served by exactly one eligible deployment. +- A deployment is active if and only if some RAQE uses it, so its ingest is + paid once, however many RAQEs share it. +- A deployment stores enough closed windows for the longest lookback it + serves (a linearized max). +- Version 2 (and version 1's frontier bound): a pair whose chain (the newest + window's compaction, then the query, each on a full core) is longer than + `L` is ruled out. By the placement's closed form, the plan's batch latency + is then at most `L`, exactly: the SLA is met. Chains are + compared with `L` with a relative slack of `1e-9`, so float error can't rule + out a chain equal to `L`. + +#### 8. Solution method + +Every term is linear in `u` and `z`, with or without a bound, so the MILP is +solved exactly +(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair +so the solver sees magnitudes near 1). The solved plan's cost and latency are +then computed from its resource use (`usage::usage_cost`). + +- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` + takes `allowed`, the candidate indices each RAQE may use. PerQuery gives + each RAQE its own candidates, with a separate copy of any deployment that + two RAQEs could both use. Two RAQEs share a deployment only by choosing the + same candidate index (`u_D` is per index), so their copies stay apart and + each pays its own ingest. +- **AutoSketch** keeps its memory-chosen configs and is priced by the same + function: its cost by use and its latency, the longest chain. It ignores + latency, so it is one point, not a frontier. +- **Version 1:** ASAP and PerQuery are solved with no bound (the cheapest + plan), and for a sweep of bounds `L` from the smallest feasible one (the + largest, over RAQEs, of each RAQE's fastest chain) up to the unbounded + plan's latency. Each solve gives a (latency, cost) point; together they are + the method's frontier. `L` = AutoSketch's latency gives each method's cost + at no more than AutoSketch's latency. +- **Version 2:** ASAP and PerQuery are solved at each SLA of a fixed grid; + an SLA below the smallest feasible bound has no plan. AutoSketch ignores + the SLA; its latency either meets it or not. + +#### 9. Outputs + +Per (method, weight setting, bound or SLA): cost; mean CPU and memory, by +part; query latency and per-RAQE latency; planning time. Figures: version 1, +each method's cost–latency frontier for each workload (ASAP and PerQuery as +lines, AutoSketch as a point); version 2, each method's cost at each SLA. + +## Analytical cost model + +The analytical model combines the empirical per-operation Sketch Bench +measurements with workload properties such as group cardinality, arrival rate, +window size, and query frequency. + +For deployment `D` serving RAQE `i`: + +- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. +- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window (one for a shared fixed-size sketch; see below). +- `x`, `y`: `D`'s window and slide. +- `a_D = x / y`: open windows; each sample is inserted into `a_D` instances of its group. +- `S_i`, `T_i`: RAQE `i`'s lookback and interval. +- `n_i = S_i / x`: windows merged per query. +- `m`: memory per instance, measured. For DDSketch on a metric with a + `value_range`, `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` + bytes instead: one bucket count per `gamma`-power in the range, capped by + the values one instance sees (`λ · x / card(G)` for a window, `λ · L / card(G)` + for a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. The range is the metric's, so `m` is an upper + bound for a group whose own values span less. +- `c_ins`: CPU per insert, measured. +- `c_mrg`: CPU per pairwise merge, measured. +- `c_qry`: CPU per query of one instance, measured. + +Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory +(bytes): + +| Phase | CPU | Memory | +|---|---|---| +| Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | +| Merge, per RAQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | +| Query, per RAQE | `card(G) × c_qry / T_i` | `card(G) ×` output bytes | +| Storage, per active `D` | 0 | `card(G) × m × ((max_i S_i − x) / y + 1)` (closed windows) | + +Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence +`(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. +Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group for +top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. + +### Instance shape and size law + +Each row of the cost table (from +[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py)) +is measured on one instance, at whatever key count the benchmark fed it +(`measured_keys`). A key is one distinct entry an instance stores exactly, +such as one group's running sum in an exact accumulator. Turning a row into a +deployment's cost needs two properties of the family: + +- **Shape**: instances per window. `PerGroup` keeps one per group, so + `card(G)`; `Shared` keeps one for all groups. +- **Law**: how one instance's size grows. `Fixed` is set by the configuration + (e.g. CMS rows × columns); `PerKey` stores one entry per key, so it grows + linearly with keys. + +Memory per window is instances × instance size: + +| | Fixed | PerKey | +|---|---|---| +| **PerGroup** | `card(G) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | +| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | + +The same factor scales merge and query CPU. Insert CPU is per sample and does +not scale. + +Quantile sketches have no keys, but are not strictly fixed either: KLL grows +slowly with the number of values inserted (about `k × log(n / k)`), and +DDSketch with the range of values. The model treats KLL as Fixed at the size +the export measured (1,000,000 values per instance), so it misstates instances +that see far fewer or far more values. DDSketch is sized from the metric's +`value_range` when given (capped by values per instance), else from the +measured size. + +The model uses `I × m`, where `I` is instances per window: + +- PerGroup + Fixed: `I = card(G)`. +- Shared + PerKey reduces to `I = card(G)` because the export divides the + exact accumulators' memory and merge cost by `measured_keys` + (`groups_per_instance`), making `m` a per-group cost. Their query cost is + already per group. +- Shared + Fixed: `I = 1`. In code this is the family property + `one_fixed_size_sketch_for_all_groups`, true only for HydraKLL. It applies + to memory and merge; query stays `card(G) × c_qry`, one probe per group. + A fixed-size sketch degrades as groups grow, so it is eligible only when + `card(G)` 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). + +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 +with keys below the group: a per-service top-k CMS costs the same however +many endpoints it counts. + +Side by side, with `G = card(G)` and `C` closed windows: + +| | KLL (per group) | exact-sum (per-group normalized) | HydraKLL (shared, fixed) | +|---|---|---|---| +| `m`, `c_mrg` in the row | one group's | whole ÷ groups | whole sketch | +| Ingest CPU | `λ·a_D·c_ins` | `λ·a_D·c_ins` | `λ·a_D·c_ins` | +| Ingest memory | `G·m·a_D` | `G·m·a_D` | `m·a_D` | +| Merge CPU | `G·(n_i−1)·c_mrg/T_i` | same | `(n_i−1)·c_mrg/T_i` | +| Merge memory | `G·m` | same | `m` | +| Query CPU | `G·c_qry/T_i` | same | `G·c_qry/T_i` | +| Query memory | `G ×` output bytes | same | `G ×` output bytes | +| Storage memory | `G·m·C` | same | `m·C` | +| Latency | `G·(c_qry + (n_i−1)·c_mrg)` | same | `(n_i−1)·c_mrg + G·c_qry` | + +### Family properties and key tracker + +Each family has properties, hardcoded by variant in `family_properties` +(an unknown variant panics rather than getting a default): + +- `mergeable_across_windows`: a family without it only serves `S_i = x`. + Every family in use merges. +- `one_fixed_size_sketch_for_all_groups`: the Shared + Fixed cell above. +- `needs_delta_set_key_tracker`: the sketch can't list its groups, so a + DeltaSet (`exact-delta-set`) records each window's keys for the query to + probe. True for HydraKLL. A candidate needing one carries the DeltaSet row + and is dropped if the cost table has none; a deployment without its tracker + is never eligible. The cost table may hold at most one DeltaSet row. + +The tracker is priced as an exact accumulator on the same `x`, `y` and `G`, +in every phase: ingest, merge (union of the `n_i` windows' key sets), query +(enumerate keys) and storage. Its `m` is per key, so it adds `card(G) × m_ds` +per window. The AutoSketch baseline skips shared fixed-size families for now +(sketch-bench#159). + +Per-RAQE latency is the serial CPU time of one query: + +```text +latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg +``` + +summed over the sketch and its key tracker, if any. + +On its own it is not a wall-clock SLA: it assumes no parallel execution across +groups and no cheaper k-way merge. In "Cost by use and batch latency" above it +is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. + + +## Future Hydra cost and measurement requirements + +It does not make sense to apply the "fine-to-coarse rollup strategy" to Hydra. + +The required accuracy contract is an empirical predicate: + +```text +hydra_error(config, schema H, requested grouping G_r, + target-shape(G_r), items per target group, + subpopulation population/fan-out, merged_windows) + <= RAQE accuracy SLA +``` + +The result must be reported in the family metric (for Hydra-KLL, `mean_rank_err`) with the same direction as the RAQE SLA. It is insufficient to record only a single `subpopulations` ceiling: two target groupings with the same cardinality can have different skew, fan-out, and query selectivity. No analytic composition from the KLL cell's guarantee to the Hydra grid's error is assumed. In particular, cross-window Hydra merge accuracy must be measured for every allowed merge depth; until then a Hydra candidate may serve only `L == x`. + +### Proposed Hydra cost model + +Let `m_h`, `c_ins,h`, `c_mrg,h`, and `c_probe,h(G_r)` be measured for a particular Hydra configuration and label schema. Hydra's shared grid has one state per open window, so for slide `y` it has `a = x/y` live states. + +| Phase | CPU | Memory | +| --- | --- | --- | +| Ingest | `lambda * a * c_ins,h` | `a * m_h` | +| Merge a RAQE | `(L/x - 1) * c_mrg,h / T` | `m_h` when `L/x > 1` | +| Query a RAQE | `C_r * c_probe,h(G_r) / T` | `C_r * output_bytes` | +| Storage | `0` | `ceil((max L - x)/y + 1) * m_h` | + +This is deliberately not the #190 formula: a Hydra merge combines whole windows, not `C_d` independently addressable states. It assumes the measured merge cost does not depend on the number of requested probes; Sketch Bench must confirm that assumption or report a probe-count term. + +Hydra also needs a way to enumerate the groups to query. If it still relies on `exact-delta-set`, the plan must add that tracker's ingest, merge, query, and storage costs. A fine-group tracker used to derive coarse group keys may cost `C_d`, not `C_r`; alternatively, a per-requested-group tracker must be specified and measured. This is a design choice, not a free operation. + +### Sketch Bench requirements before admitting Hydra + +1. Accept a named label schema and query grouping/predicate, rather than interpreting semicolon position as the meaning of a grouping. Preserve label names and their order in the emitted record. +2. Generate hierarchical data with exact answers for every queried grouping; include cardinality, per-parent fan-out, skew, total items, and each target group's item count in the result metadata. +3. Sweep Hydra configuration (outer grid and cell parameters), schema width, target grouping, cardinality/fan-out, and distribution shape. Measure accuracy separately for each target grouping. +4. Measure insert, footprint, one-window query, and merges over the intended shard counts. For a merged query, measure both sketch merge and the requested number of probes, so the planner can distinguish a whole-sketch merge from per-group probe work. +5. Benchmark and export the key-enumeration path. State whether it uses a DeltaSet, what grouping it stores, and its exact input/output cardinality. +6. Emit a machine-readable saturation key containing the fields in the accuracy contract above. The optimizer must reject a Hydra candidate when no matching point (or explicitly approved interpolation) exists; it must not borrow a KLL or a different-grouping curve. +7. Add regression fixtures for equal grouping, a direct coarse predicate, and a multi-window coarse predicate. Each fixture must compare to exact answers and assert the exported accuracy and cost dimensions. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 8f8c83a7..ee17e33b 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -35,7 +35,7 @@ and per-RAQE latency. CPU and memory: **ingest** (inserting samples into open instances), **merge** (folding a query's windows into an accumulator), **query** (reading the merged result) and **storage** (keeping closed instances, no - CPU). See [Analytical cost model](#analytical-cost-model). + CPU). See [Cost model](rqe_optimizer_cost_model.md). ## Inputs @@ -77,7 +77,7 @@ The cost table, measured by - CPU per pairwise merge; - the comparator's accuracy scores, and `accuracy_metric`, the one that is the row's accuracy (only exact accumulators read it; see - [eligibility](#candidate-deployments)); and + [eligibility](rqe_optimizer_candidates.md#candidate-deployments)); and - `measured_at`, the data it was measured on. The study measures every configuration once, serially, at one data shape: @@ -139,629 +139,15 @@ non-overlapping two-minute instances. We assume all RAQEs share a common time origin. Query phase offsets are not modeled. -## Candidate deployments +## Planning design -A candidate deployment is: +The optimizer has two companion design documents: -```text -D = (capability, configuration, metric, G, x, y) -``` - -Candidates may be generated from individual RAQEs, then deduplicated. This is -only a way to construct the candidate set: when solving a workload, one -selected deployment may serve multiple compatible RAQEs. - -Intuition: candidates are built in two steps, and each drops only candidates -that another candidate beats, so the best plan is never lost. Generation uses -no measurements. It keeps every legal window and configuration, and drops only -slides that a coarser slide beats for the same RAQEs. Pruning then attaches the -measured costs and drops a candidate when another serves all of its RAQEs and -is no worse on every cost. - -For each (capability, metric, G) group, generate candidates as follows: - -```text -for each window x that divides some S_i and is a multiple of the scrape interval: - g = { g_i = gcd(x, T_i) : RAQE i with S_i divisible by x } - slides = { gcd(A) : A is a non-empty subset of g } - for each y in slides that is a multiple of the scrape interval: - for each configuration that serves the capability: - add (capability, configuration, metric, G, x, y) -``` - -`g_i = gcd(x, T_i)` is the largest slide that serves RAQE `i`. - -**Windows.** An RAQE merges `S_i / x` whole windows, so `x` must divide `S_i`. -Windows and slides finer than the scrape interval would only split one -scrape's samples. - -**Slides.** A slide `y` serves RAQE `i` when it divides both `x` and `T_i`, -that is, when it divides `g_i`. A finer slide serves no more RAQEs but holds -more open windows (`x / y`) and more closed ones, so it costs more ingest and -storage at the same latency. Hence: - -- for one RAQE, `y = g_i` is strictly better than every finer slide that serves - it; -- for a set `A` of RAQEs sharing a deployment, `y = gcd(A)`, the largest slide - dividing every `g_i` in `A`, is strictly better than every finer slide that - serves them all. - -Which RAQEs share is the solver's choice, so every subset's gcd is a candidate. -Every other divisor of `x` is strictly worse than one of these. - -Example: `x = 60`, RAQE `a` every 20 s, RAQE `b` every 30 s. - -| Served RAQEs | `y` | Open windows `x / y` | -|---|---|---| -| `a` | gcd(60, 20) = 20 | 3 | -| `b` | gcd(60, 30) = 30 | 2 | -| `a` and `b` | gcd(20, 30) = 10 | 6 | - -The slides are `{10, 20, 30}`. `y = 5` would also serve both, but holds 12 open -windows instead of 6. With a 15 s scrape interval only `y = 30` remains: no -multiple of 15 divides both 20 and 30, so `a` and `b` cannot share at -`x = 60`. - -The subset gcds take one pass, without listing subsets: keep the gcds found so -far, and for each new `g` add `g` and `gcd(found, g)` for every `found`. For -`{20, 30}`: `{20}`, then `{20, 30, 10}`. One pass suffices because -`gcd(A ∪ {g}) = gcd(gcd(A), g)`. - -An RAQE `r_i` is eligible for a candidate `D` when: - -1. `cap_i = D.capability`, `metric_i = D.metric` and `G_i = D.G`. -2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. -3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family - (`family_properties`, which also gives the direction), clears `tol_i`. - -Exact accumulators take that accuracy from the cost table; they merge without -loss, so the window size doesn't matter. Sketches take it -from the saturation study's error-vs-N curves (`SaturationCurves`, #156), -read at the number of items one group receives over the RAQE's whole -lookback: series per group times scrapes per lookback. - -- The curve is the configuration's at the metric's fitted `data_shape` for - `G` (zipf θ and keys `K`, or tail index `a` for quantiles). Between grid - points, the worst bracketing point; outside the grid, or with no fit, no - accuracy. -- Between checkpoints, the worse neighbour. Below the first checkpoint, no - accuracy. Past the last, the plateau if the point saturated, else none. -- The curve's `error_metric` must be the family's metric; `SaturationCurves::load` - refuses a curve for another metric as a stale study. -- For sketches that merge exactly, the window size doesn't matter: a merged - answer reads the curve at the lookback's item count, like a single sketch. - KLL and top-k merge lossily (#131): an answer merged from `m = S_i / D.x` - windows reads the study's merge curve (`saturation_merge_curve.csv`, the - sketch merged from `m` shards of the same items) at the lookback's item - count. Between measured shard counts, the worse. Past the largest - measured count, or without a merge curve, a merged KLL or top-k answer has - no accuracy: the study must measure the merge counts a workload needs - (`--merge-shards-list`) up to the N it reads at: past the merge curve's - last N, the merged answer has no accuracy either (#158). - `SaturationCurves::load` refuses a study with no merge curves for a - candidate KLL sketch. -- A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap - top-k (CMS-heap, CountSketch-heap) keeps a heap of `m · k` in a deployment - answering from `m = S_i / D.x` merged windows (`m = 1` gives `k`). - Candidates carry one heap per distinct `m · k` among the RAQEs on a window, - and a RAQE is eligible only where the heap holds its `m · k`. Such a merged answer reads as one sketch: the - plain curve, then the guarantee fallback. It assumes the merged heaps still - hold the true top `k`; it is not a guarantee. So heap top-k needs no merge - curves. Costs come from the cost table's rows at heaps 32, 128, 512 and - 2048 (`heap=`), linear in the heap between them and past them. Curves are - measured per `k` (`topk_k=` in the config; 10, 32 and 100 by default) at a - heap of `k`, and larger heaps read the same curve. A RAQE reads the curve - at its `k`, else at the next larger measured `k` (harder); past every - measured `k`, only the guarantee at its `k`. Its query outputs `k` - entries per group. -- Where the study measured nothing for a bracketing point at or above its - first N (past an unsaturated curve, past the measured merge counts or N, - or with no merge curve), the accuracy falls back to the algorithm's - guarantee at 95% confidence (`rqe_optimizer::theory`; two-sided for - rank and relative errors, one-sided for CMS overestimates). It is never - better than the worst last measurement of the curves it extends. The fallbacks are: - - KLL: rank error `2.296 / k^0.9723` (DataSketches' 99% value), scaled - to 95% two-sided; - - DDSketch: relative value error `α` (unbounded store); - - HLL: `1.96 · 1.04 / sqrt(2^lg_k)`; - - CMS-heap top-k, unmerged: the share of the top `k` Zipf(θ, K) keys kept - ranked for every key at once. With Markov per row, independent rows, - and a union bound over the `K − k` other keys, key `i` fails with - probability at most `(cols · (p_i − p_{k+1}))^−rows`. Keys are counted - from the most frequent while the summed failure stays within 5%. It - assumes the heap ranks keys by their final CMS estimates. - - A sketch with no published bound, a merged top-k answer, a point below - the first N, or a shape outside the grid stays unknown. - `accuracy_with_source` reports which points used a bound. - -The cost table's sketch accuracies are not read, but they are one point on -each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto -`a`) is a grid point's key. `SaturationCurves::check_cost_table` reports every -row whose `accuracy_metric` is not its family's or not its curve's -`error_metric`, whose configuration is not in the grid, or whose accuracy -disagrees with the curve at `measured_at` (beyond 3 seed standard errors plus -5%). The study adds the cost table's shape to the grid as a full row and -column (θ = 1.1 at every K, K = 1e4 at every θ), so every sketch row has a -grid point and the grid stays a full cross. `SaturationCurves::load` -refuses curves whose Zipf grid isn't a full cross of its θ and K values and -names the missing points: a hole would leave every shape around it without -accuracy (for example, curves from `--points-from` or a narrowed `--resume`). A row without a grid point (a study run -with `--no-cost-shape`) is reported as unchecked. `small_problem` refuses to plan -when any row disagrees. - -For lower-is-better metrics, passing means `measured <= tol_i`. For -higher-is-better metrics, passing means `measured >= tol_i`. Direction is -explicit on the RAQE; it is never inferred from a metric name. A missing metric -does not pass. - -Before mapping, prune a candidate only if another candidate can serve every -RAQE it can and is no worse in ingest CPU and memory, and in latency, merge -memory and stored memory for each such RAQE. This is safe because any mapping using -the removed candidate can substitute the remaining one without weakening a -modeled objective. - -Closed instances must be stored long enough to answer the RAQEs assigned to a -deployment. Retention is not a candidate parameter: a deployment stores the -history needed by the largest assigned query window, costed as the storage -phase (below). - -## Workload mapping - -Let `z_{i,D}` be 1 when RAQE `i` uses candidate deployment `D`; let `u_D` be 1 -when deployment `D` is active. - -```text -Σ_D z_{i,D} = 1 for every RAQE i -z_{i,D} <= u_D for every eligible pair (i, D) -``` - -Every RAQE selects exactly one eligible deployment. Multiple RAQEs may select -the same deployment and therefore share its ingest work. A query may merge -multiple instances from its selected deployment, but v1 does not combine -results from several deployments to satisfy one RAQE. - -### MILP formulation - -Let `E` be the eligible `(i, D)` pairs. The solver has one binary `z_{i,D}` -for each pair in `E`, one binary `u_D` for each candidate, and a continuous -`stored_D` for each candidate's closed-window storage. - -```text -z_{i,D} ∈ {0, 1} for (i, D) ∈ E -u_D ∈ {0, 1} for D ∈ candidates -stored_D ≥ 0 - -Σ_{D: (i,D) ∈ E} z_{i,D} = 1 for every RAQE i -z_{i,D} ≤ u_D for (i, D) ∈ E -u_D ≤ Σ_{i: (i,D) ∈ E} z_{i,D} for every candidate D -stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E -``` - -The `u_D ≤ Σ z` constraint prevents a deployment from becoming active when no -RAQE selected it. It is not required for feasibility, but makes ingest cost -unambiguous. `stored_D` is a linearized max: a deployment stores enough for -the longest lookback it serves. - -The only objective, `Objective::AUCCost { w_cpu, w_mem }`, weighs each phase -cost (below) as `w(c) = w_cpu × c.cpu + w_mem × c.memory_GiB`: - -```text -minimize Σ_D w(ingest_D) × u_D - + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} - + Σ_D stored_D -``` - -CPU is the area under the CPU curve (mean CPU-sec/sec), so plans are sized -for the mean load, not for bursts. Memory sums every phase, as if every query -evaluates at once. The default weights are `(1, 0)`: CPU only. - -Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver -never enumerates full mappings. - -### Cost by use and batch latency - -Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in -`rqe-optimizer/src/usage.rs` (resource use, cost, latency) and -`milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by -use, in two versions: - -- **Version 1, no latency constraint:** the cheapest plan; its latency is - reported. Sweeping an optional latency bound traces each method's - cost–latency Pareto frontier. -- **Version 2, a batch latency SLA:** the cheapest plan whose batch latency, - from the job placement (§6), is at most the SLA `L`, for a grid of SLAs. -Evaluated first on the synthetic mixed template set; methods: ASAP (this -MILP, with sharing), PerQuery (the same MILP without sharing) and -AutoSketch-Adapted (fixed configs chosen by memory). - -#### 1. Definitions - -| Symbol | Meaning | -|---|---| -| `D`, `i` | a candidate deployment; a RAQE | -| `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | -| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | -| `card(G)` | groups of `D`'s grouping | -| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | -| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | -| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | -| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | -| `n_{i,D} = S_i / x_D` | windows a query merges | -| batch | all query jobs issued at one instant | - -**Measurement assumption (sketch-bench as is).** Every sketch operation is -single-threaded and compute-bound: sketch-bench's CPU time equals its wall -time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses -at most one core and, on a full core, takes its CPU time. The cost table's -`*_cpu_secs` are all the model needs. - -#### 2. Cost model - -`cost = w1 · AUC(CPU) + w2 · AUC(memory)`: the mean vCPUs and GiB over time, -priced per vCPU and per GiB (CPU only: `(1, 0)`; Fargate's prices). CPU is -elastic: a job gets a core whenever it is ready. - -This is billing by use, as on fine-grained autoscaling platforms (Cloud Run -with request-based billing, Dataflow streaming, Flink on Kubernetes with an -autoscaler), idealized: capacity follows the load at once. Billing for -provisioned capacity (VMs, or containers billed by allocation such as -Fargate) is not modeled. Since a job holds its memory only while it runs, its -memory × time is the same whenever it runs, and queueing a job would save -nothing. - -#### 3. CPU: parts and how each is computed - -Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, -over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, -over which every job pattern repeats exactly. A part with `w` CPU-seconds per -event every `P` seconds runs `H / P` times per hyperperiod, so its mean is -`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. - -| Part | When | CPU-seconds | Mean vCPUs | -|---|---|---|---| -| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | -| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | -| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | - -- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at - most one core), **split by sample**: each worker reads a share of the input - (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so - it keeps its own open window instance of every group it sees. -- When a window closes (the watermark passes its end), a **compaction** job - merges the `k_D` partial instances of each group into one stored instance. - With `k_D = 1` there is none. -- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` - stored instances of each group for the query window, then estimate. Merging - is part of the query. It reads the newest window, which closes at the firing - time, so it starts after that window's compaction. - -`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already -a rate; only compaction (per window close, every `y_D`) and queries (per -firing, every `T_i`) are divided by their period. It is fixed by the plan, -whatever the schedule. - -In words: - -- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already - inside `λ_D`), and each is inserted into the `x_D / y_D` windows still - open, at `c_ins` CPU-seconds each: CPU-seconds per second. -- `c_D`: closing a window merges, for every instance, the `k_D` workers' - partial copies into one, which takes `k_D − 1` merges. This happens once - per slide. -- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows - (`n − 1` merges per instance), then answers once per group. This happens - once per interval. (A sketch shared by all groups merges one instance but - still answers every group.) -- `AUC(CPU)` adds the three rates: work per second, in vCPUs. - -#### 4. Memory: parts and how each is computed - -Each part is counted once: a window counts as ingest memory while open and as -storage once compacted, and a query reads stored instances in place. - -| Part | What | Bytes | Held | -|---|---|---|---| -| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | -| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | -| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | -| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | - -`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) -+ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its -own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. - -In words: - -- `I_D`: every worker keeps one instance per group for each of the - `x_D / y_D` windows still open, and there are `k_D` workers. -- `stored_D`: closed windows are kept until the longest lookback that `D` - serves no longer needs them. That is `(S − x)/y + 1` windows per group. -- Compaction: when a window closes, a new one opens, so ingest still holds - `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in - memory until the compaction has merged them. The merged copy takes the - storage slot that the oldest window frees at the same moment, so it is not - counted twice. -- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, - with `n = 1`, reads the stored window and needs none), plus the answer for - every group. -- `AUC(memory)`: ingest and storage are held all the time. A compaction's - and a query's memory are held only while they run, a fraction - `run time / y_D` or `run time / T_i` of the time. - -#### 5. Batch latency and the SLA - -A batch's **latency** is the time from its issue until its last query job -finishes, compaction included. A plan's **query latency** is its worst batch -latency, given by the job placement (§6). Version 1 reports it; version 2 -requires it to be at most the SLA `L`. Per-RAQE latency bounds -(`Raqe::latency_sla_ms`) are not used. - -CPU is elastic, so no job waits for a core, and a batch's latency is its -longest **chain**: the newest window's compaction, then the query, each on a -full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query -latency is the longest chain over its RAQEs. - -In words: the trade-off between cost and latency comes from the plan. A cheap -plan keeps short windows and merges many of them at query time (long -chains); a faster one precomputes more at ingest (more open windows, more CPU -and memory). With no bound the MILP picks the cheapest plan, whatever its -latency; a bound `L` asks for the cheapest plan at least that fast. - -#### 6. Job placement algorithm - -The job placement decides when each job runs on the available CPU, and so -gives every batch's latency. It is defined for any CPU capacity; billing by -use makes CPU elastic, so it runs with unlimited capacity. - -```text -capacity for jobs K = C − Σ_D ρ_D (C = ∞ when CPU is elastic) -event-driven, over the hyperperiod H = lcm(T_i, y_D), twice -(events: query issues, window closes, completions): - ready = compaction jobs (triggered at window closes) - + query jobs whose newest window is compacted - order: issue / trigger time (older first), then compaction before query - (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given) - a job at rate a_j finishes when its remaining work / a_j elapses - recompute the rates at every event -outputs: per-RAQE and per-batch latency, worst batch latency -``` - -In words: - -1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs; the - rest, `K`, is shared by compaction and query jobs. -2. **Issue jobs.** Each window close triggers a compaction job for its - deployment. Each firing issues a query job, which becomes ready only once - its deployment's newest window is compacted. -3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. - Within a batch, compaction runs before queries, because queries wait for - it. Then the longest remaining work runs first, so a long job doesn't end - up running alone at the end of the batch. -4. **Share capacity as rates.** In that order, each job gets up to one core - (a single-threaded job can't use more) from the capacity still free. The - last one served may get only a fraction and runs slower in proportion. -5. **Advance to the next event.** Time jumps to the next query issue, window - close or completion; remaining work drops by rate × elapsed time, and the - rates are recomputed. -6. **Read off the results.** A query's latency is its finish minus its - issue, and a batch's latency is that of its last query. - -With elastic CPU (`K = ∞`) every job starts as soon as it is ready on its own -core, so the placement has a closed form: a compaction runs for `c_D`, a -query for `ℓ_{i,D}`, and a batch's latency is its longest chain -`c_D + ℓ_{i,D}`. The code uses this closed form (`usage::usage_cost`), and -it is what makes both MILP versions exact. - -#### 7. MILP formulation - -Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), -`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and -pair are §3 and §4's. - -```text -minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) - + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] -s.t. Σ_D z_{i,D} = 1 for every RAQE i - z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E - stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} -version 2, a batch latency SLA L (or version 1's frontier bound L): - z_{i,D} = 0 if c_D + ℓ_{i,D} > L -``` - -In words: - -- The objective is the price of the mean vCPUs (ingest and compaction per - active deployment, plus each RAQE's query work per second), plus the price - of the mean memory (ingest and storage per active deployment, each - compaction's partial copies for the fraction of time it runs, and each - query's memory for the fraction of time it runs). -- Every RAQE is served by exactly one eligible deployment. -- A deployment is active if and only if some RAQE uses it, so its ingest is - paid once, however many RAQEs share it. -- A deployment stores enough closed windows for the longest lookback it - serves (a linearized max). -- Version 2 (and version 1's frontier bound): a pair whose chain (the newest - window's compaction, then the query, each on a full core) is longer than - `L` is ruled out. By the placement's closed form, the plan's batch latency - is then at most `L`, exactly: the SLA is met. Chains are - compared with `L` with a relative slack of `1e-9`, so float error can't rule - out a chain equal to `L`. - -#### 8. Solution method - -Every term is linear in `u` and `z`, with or without a bound, so the MILP is -solved exactly -(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair -so the solver sees magnitudes near 1). The solved plan's cost and latency are -then computed from its resource use (`usage::usage_cost`). - -- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` - takes `allowed`, the candidate indices each RAQE may use. PerQuery gives - each RAQE its own candidates, with a separate copy of any deployment that - two RAQEs could both use. Two RAQEs share a deployment only by choosing the - same candidate index (`u_D` is per index), so their copies stay apart and - each pays its own ingest. -- **AutoSketch** keeps its memory-chosen configs and is priced by the same - function: its cost by use and its latency, the longest chain. It ignores - latency, so it is one point, not a frontier. -- **Version 1:** ASAP and PerQuery are solved with no bound (the cheapest - plan), and for a sweep of bounds `L` from the smallest feasible one (the - largest, over RAQEs, of each RAQE's fastest chain) up to the unbounded - plan's latency. Each solve gives a (latency, cost) point; together they are - the method's frontier. `L` = AutoSketch's latency gives each method's cost - at no more than AutoSketch's latency. -- **Version 2:** ASAP and PerQuery are solved at each SLA of a fixed grid; - an SLA below the smallest feasible bound has no plan. AutoSketch ignores - the SLA; its latency either meets it or not. - -#### 9. Outputs - -Per (method, weight setting, bound or SLA): cost; mean CPU and memory, by -part; query latency and per-RAQE latency; planning time. Figures: version 1, -each method's cost–latency frontier for each workload (ASAP and PerQuery as -lines, AutoSketch as a point); version 2, each method's cost at each SLA. - -## Analytical cost model - -The analytical model combines the empirical per-operation Sketch Bench -measurements with workload properties such as group cardinality, arrival rate, -window size, and query frequency. - -For deployment `D` serving RAQE `i`: - -- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. -- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window (one for a shared fixed-size sketch; see below). -- `x`, `y`: `D`'s window and slide. -- `a_D = x / y`: open windows; each sample is inserted into `a_D` instances of its group. -- `S_i`, `T_i`: RAQE `i`'s lookback and interval. -- `n_i = S_i / x`: windows merged per query. -- `m`: memory per instance, measured. For DDSketch on a metric with a - `value_range`, `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` - bytes instead: one bucket count per `gamma`-power in the range, capped by - the values one instance sees (`λ · x / card(G)` for a window, `λ · L / card(G)` - for a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. The range is the metric's, so `m` is an upper - bound for a group whose own values span less. -- `c_ins`: CPU per insert, measured. -- `c_mrg`: CPU per pairwise merge, measured. -- `c_qry`: CPU per query of one instance, measured. - -Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory -(bytes): - -| Phase | CPU | Memory | -|---|---|---| -| Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RAQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | -| Query, per RAQE | `card(G) × c_qry / T_i` | `card(G) ×` output bytes | -| Storage, per active `D` | 0 | `card(G) × m × ((max_i S_i − x) / y + 1)` (closed windows) | - -Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence -`(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. -Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group for -top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. - -### Instance shape and size law - -Each row of the cost table (from -[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py)) -is measured on one instance, at whatever key count the benchmark fed it -(`measured_keys`). A key is one distinct entry an instance stores exactly, -such as one group's running sum in an exact accumulator. Turning a row into a -deployment's cost needs two properties of the family: - -- **Shape**: instances per window. `PerGroup` keeps one per group, so - `card(G)`; `Shared` keeps one for all groups. -- **Law**: how one instance's size grows. `Fixed` is set by the configuration - (e.g. CMS rows × columns); `PerKey` stores one entry per key, so it grows - linearly with keys. - -Memory per window is instances × instance size: - -| | Fixed | PerKey | -|---|---|---| -| **PerGroup** | `card(G) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | -| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | - -The same factor scales merge and query CPU. Insert CPU is per sample and does -not scale. - -Quantile sketches have no keys, but are not strictly fixed either: KLL grows -slowly with the number of values inserted (about `k × log(n / k)`), and -DDSketch with the range of values. The model treats KLL as Fixed at the size -the export measured (1,000,000 values per instance), so it misstates instances -that see far fewer or far more values. DDSketch is sized from the metric's -`value_range` when given (capped by values per instance), else from the -measured size. - -The model uses `I × m`, where `I` is instances per window: - -- PerGroup + Fixed: `I = card(G)`. -- Shared + PerKey reduces to `I = card(G)` because the export divides the - exact accumulators' memory and merge cost by `measured_keys` - (`groups_per_instance`), making `m` a per-group cost. Their query cost is - already per group. -- Shared + Fixed: `I = 1`. In code this is the family property - `one_fixed_size_sketch_for_all_groups`, true only for HydraKLL. It applies - to memory and merge; query stays `card(G) × c_qry`, one probe per group. - A fixed-size sketch degrades as groups grow, so it is eligible only when - `card(G)` 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). - -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 -with keys below the group: a per-service top-k CMS costs the same however -many endpoints it counts. - -Side by side, with `G = card(G)` and `C` closed windows: - -| | KLL (per group) | exact-sum (per-group normalized) | HydraKLL (shared, fixed) | -|---|---|---|---| -| `m`, `c_mrg` in the row | one group's | whole ÷ groups | whole sketch | -| Ingest CPU | `λ·a_D·c_ins` | `λ·a_D·c_ins` | `λ·a_D·c_ins` | -| Ingest memory | `G·m·a_D` | `G·m·a_D` | `m·a_D` | -| Merge CPU | `G·(n_i−1)·c_mrg/T_i` | same | `(n_i−1)·c_mrg/T_i` | -| Merge memory | `G·m` | same | `m` | -| Query CPU | `G·c_qry/T_i` | same | `G·c_qry/T_i` | -| Query memory | `G ×` output bytes | same | `G ×` output bytes | -| Storage memory | `G·m·C` | same | `m·C` | -| Latency | `G·(c_qry + (n_i−1)·c_mrg)` | same | `(n_i−1)·c_mrg + G·c_qry` | - -### Family properties and key tracker - -Each family has properties, hardcoded by variant in `family_properties` -(an unknown variant panics rather than getting a default): - -- `mergeable_across_windows`: a family without it only serves `S_i = x`. - Every family in use merges. -- `one_fixed_size_sketch_for_all_groups`: the Shared + Fixed cell above. -- `needs_delta_set_key_tracker`: the sketch can't list its groups, so a - DeltaSet (`exact-delta-set`) records each window's keys for the query to - probe. True for HydraKLL. A candidate needing one carries the DeltaSet row - and is dropped if the cost table has none; a deployment without its tracker - is never eligible. The cost table may hold at most one DeltaSet row. - -The tracker is priced as an exact accumulator on the same `x`, `y` and `G`, -in every phase: ingest, merge (union of the `n_i` windows' key sets), query -(enumerate keys) and storage. Its `m` is per key, so it adds `card(G) × m_ds` -per window. The AutoSketch baseline skips shared fixed-size families for now -(sketch-bench#159). - -Per-RAQE latency is the serial CPU time of one query: - -```text -latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg -``` +- [Candidate generation and mapping](rqe_optimizer_candidates.md): candidate construction, eligibility, finer-to-coarser roll-ups, dominance pruning, and the assignment MILP. +- [Cost models](rqe_optimizer_cost_model.md): cost-by-use, batch latency, the analytical phase model, and the measurements required before Hydra can participate. -summed over the sketch and its key tracker, if any. +The v1 implementation supports only the conventional roll-up path described in the candidate and cost-model documents. Hydra is not part of #190. -On its own it is not a wall-clock SLA: it assumes no parallel execution across -groups and no cheaper k-way merge. In "Cost by use and batch latency" above it -is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. ## Procedure @@ -809,7 +195,9 @@ each phase's CPU and memory, together with the selected deployment mapping. generation and pruning, eligibility checks, analytical objectives, and streaming Pareto filtering. The separation between candidate generation, enumeration, objectives, and Pareto filtering remains the intended boundary -for future solver work. +for future solver work. The candidate and cost-model documents also distinguish +these conventional fine-state roll-ups from the future Hydra +shared-subpopulation deployment. Exporter bugs, benchmark-dataset choices, and historic run counts belong in `rqe_optimizer_TODO.md` or issue tracking, not in this problem statement. diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index d9479f45..027947b3 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -13,7 +13,7 @@ //! ``` //! //! Every plan is priced by use (`usage::usage_cost`, sketch-bench -//! `docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch latency"): +//! `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency"): //! `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, at each weight //! setting of #777 §4 (CPU only; Fargate's per-vCPU and per-GB prices). A //! batch's latency is its longest chain (the newest window's compaction, @@ -670,7 +670,7 @@ fn frontier_bounds(lo: f64, hi: f64, n: usize, extra: f64) -> Vec { } /// Every method's plan for `w`, priced by use at each weight setting, with -/// its latency (`docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +/// its latency (`docs/rqe_optimizer_cost_model.md`, "Cost by use and batch /// latency"): version 1 (no latency constraint; frontier) in `results`, /// version 2 (each SLA of `slas`) in `sla_results`. fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64]) -> Value { diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md index 8b0d512c..3c6ca699 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md @@ -1,7 +1,7 @@ # Synthetic mixed set: AutoSketch vs. ASAP under a batch latency SLA (version 2) Version 2 of the evaluation in ProjectASAP/ASAPQuery#777, with the cost model -of sketch-bench `docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +of sketch-bench `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency": - **Cost by use:** `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, for diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index 280de391..462edace 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -7,7 +7,7 @@ template set per metric, 50 · m RQEs). One accuracy level, p95: 95% in each family's own metric (rank, relative value and relative error at most 0.05; top-k precision at least 0.95). -**Cost model: cost by use** (sketch-bench `docs/rqe_sketch_deployment_v1.md`, +**Cost model: cost by use** (sketch-bench `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency", #188): `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, at two weight settings (CPU only, in vCPU; AWS Fargate's per-vCPU and per-GB prices, in $/hour). CPU covers ingest (on diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index cec9b55e..8b485871 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -1,10 +1,11 @@ //! v1 brute-force solver for the RAQE -> sketch-deployment mapping problem. -//! `docs/rqe_sketch_deployment_v1.md` is the problem statement; doc comments -//! cite its section numbers. +//! `docs/rqe_sketch_deployment_v1.md` is the problem statement; +//! `rqe_optimizer_candidates.md` and `rqe_optimizer_cost_model.md` hold the +//! detailed planning design. //! //! Three independent stages, so an ILP can replace [`enumerate`] alone: -//! [`candidates`] builds 𝒟 and per-RAQE eligibility (§3), [`enumerate`] -//! searches (§4), [`analytical_cost_model`] scores (§5). +//! [`candidates`] builds 𝒟 and per-RAQE eligibility, [`enumerate`] searches, +//! and [`analytical_cost_model`] scores. //! //! Every number the algorithm uses is caller-supplied, except the query //! output size estimates in [`analytical_cost_model`]. diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 99cb9b52..8a2952df 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -1,6 +1,7 @@ //! MILP solver for one scalarized RAQE deployment optimization (§4). //! -//! The model is documented in `docs/rqe_sketch_deployment_v1.md`. It avoids +//! Candidate construction is documented in `docs/rqe_optimizer_candidates.md` +//! and the cost model in `docs/rqe_optimizer_cost_model.md`. It avoids //! enumerating the Cartesian product of eligible deployment choices. use crate::analytical_cost_model::{self, score, PhaseCost, PlanCost, BYTES_PER_GIB}; @@ -242,7 +243,7 @@ pub struct UsageSolution { } /// Minimize the cost billed by use, `w_cpu · AUC(CPU) + w_mem · AUC(memory)` -/// (per vCPU, per GiB; `docs/rqe_sketch_deployment_v1.md`, "Cost by use and +/// (per vCPU, per GiB; `docs/rqe_optimizer_cost_model.md`, "Cost by use and /// batch latency"). The latency is reported. `latency_bound_ms`, when given, /// rules out every pair whose chain (`analytical_cost_model::chain_ms`) /// exceeds it, so sweeping it traces the cost–latency Pareto frontier; it is diff --git a/rqe-optimizer/src/usage.rs b/rqe-optimizer/src/usage.rs index 649c7b21..349cd3b7 100644 --- a/rqe-optimizer/src/usage.rs +++ b/rqe-optimizer/src/usage.rs @@ -1,5 +1,5 @@ //! A plan's resource use over time, its cost billed by use, and its batch -//! latency (`docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +//! latency (`docs/rqe_optimizer_cost_model.md`, "Cost by use and batch //! latency"). //! //! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. diff --git a/scripts/plot_autosketch_vs_asap_sla.py b/scripts/plot_autosketch_vs_asap_sla.py index 2d2dc89b..103b1294 100644 --- a/scripts/plot_autosketch_vs_asap_sla.py +++ b/scripts/plot_autosketch_vs_asap_sla.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Plot version 2 (a batch latency SLA) of the AutoSketch vs. ASAP evaluation -(ProjectASAP/ASAPQuery#777; sketch-bench docs/rqe_sketch_deployment_v1.md, +(ProjectASAP/ASAPQuery#777; sketch-bench docs/rqe_optimizer_cost_model.md, "Cost by use and batch latency") from the `sla_results` of `autosketch_vs_asap synthetic` runs. diff --git a/scripts/plot_autosketch_vs_asap_synthetic.py b/scripts/plot_autosketch_vs_asap_synthetic.py index 6af54b4d..72849e2c 100644 --- a/scripts/plot_autosketch_vs_asap_synthetic.py +++ b/scripts/plot_autosketch_vs_asap_synthetic.py @@ -2,7 +2,7 @@ """Plot the synthetic AutoSketch vs. ASAP evaluation (ProjectASAP/ASAPQuery#777, section 7) from the JSON files of `autosketch_vs_asap synthetic`. -Every plan is priced by use (sketch-bench docs/rqe_sketch_deployment_v1.md, +Every plan is priced by use (sketch-bench docs/rqe_optimizer_cost_model.md, "Cost by use and batch latency"): w_cpu * AUC(CPU) + w_mem * AUC(memory), with CPU elastic, and its query latency (the longest chain) is reported. ASAP and PerQuery-CostAware are solved without a bound and for a sweep of latency From bbdb066fdaf5f60d66039175e380a625d676ef44 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Fri, 9 Oct 2026 15:51:15 -0400 Subject: [PATCH 03/13] docs: clarify RQE optimizer cost model status --- docs/rqe_optimizer_cost_model.md | 33 ++++++++++++++++++++++++++++++-- docs/rqe_sketch_deployment_v1.md | 4 +++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index d8c9eb84..2020906d 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -1,6 +1,26 @@ # RQE optimizer: cost models -This document is the canonical design for cost-by-use, batch latency, the analytical phase model, and the measurements required before Hydra can participate. +This document distinguishes the optimizer's canonical cost-by-use design from +its still-supported snapshot-AUC objective, and records the measurements +required before Hydra can participate. + +## Model status and relationship + +- **Cost by use and batch latency** is the canonical model for the current + ASAP-versus-AutoSketch evaluation. It accounts for ingest workers, + window-close compaction, transient memory over its holding time, elastic CPU, + and a batch-latency bound. +- **Resource primitives and the snapshot-AUC objective** remain supported for + the original generic optimizer. They define the measured per-operation and + per-instance inputs used everywhere, then use the older snapshot accounting: + 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. Its proposed accuracy and cost contract below is + not admitted by #190 or the current optimizer. + +The two implemented objectives share the same resource primitives; they differ +only in how they account for those primitives over time. ## Cost by use and batch latency @@ -267,7 +287,13 @@ part; query latency and per-RAQE latency; planning time. Figures: version 1, each method's cost–latency frontier for each workload (ASAP and PerQuery as lines, AutoSketch as a point); version 2, each method's cost at each SLA. -## Analytical cost model +## Resource primitives and supported snapshot-AUC objective + +This section supplies the common per-operation resource primitives—instance +memory and insert, merge, and query CPU—and documents the supported older +snapshot-AUC objective. The cost-by-use model above consumes the same +primitives, but adds worker fan-out, compaction, time-weighted transient +memory, and batch latency instead of the accounting below. The analytical model combines the empirical per-operation Sketch Bench measurements with workload properties such as group cardinality, arrival rate, @@ -409,6 +435,9 @@ is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. ## Future Hydra cost and measurement requirements +This is a future admission contract, not a model used by either implemented +optimizer objective. Hydra remains outside #190. + It does not make sense to apply the "fine-to-coarse rollup strategy" to Hydra. The required accuracy contract is an empirical predicate: diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index ee17e33b..de5a96e6 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -144,7 +144,9 @@ modeled. The optimizer has two companion design documents: - [Candidate generation and mapping](rqe_optimizer_candidates.md): candidate construction, eligibility, finer-to-coarser roll-ups, dominance pruning, and the assignment MILP. -- [Cost models](rqe_optimizer_cost_model.md): cost-by-use, batch latency, the analytical phase model, and the measurements required before Hydra can participate. +- [Cost models](rqe_optimizer_cost_model.md): the canonical cost-by-use and + batch-latency model, the supported snapshot-AUC objective and shared + resource primitives, and the future Hydra admission requirements. The v1 implementation supports only the conventional roll-up path described in the candidate and cost-model documents. Hydra is not part of #190. From 067c65c76a9685a15d44369c557baaa79458f16e Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 9 Oct 2026 21:18:49 +0000 Subject: [PATCH 04/13] docs: one cost table for every phase, with roll-ups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merge the cost-by-use CPU and memory tables into one table per phase (ingest, compaction, query job, storage) in terms of I_d and I_r, so roll-ups (G_r ⊂ G_d) are priced as the code prices them: ℓ = card(G_r)·c_qry + (I_d·n − I_r)·c_mrg, accumulators at G_r. The snapshot-AUC section now lists only how it differs (k = 1, query memory always held, per-RAQE serial latency) instead of repeating the table; the shape/size-law side-by-side gives each family's I_d, I_r and tracker; the proposed Hydra cost model is §3's table with I_d = I_r = 1, adding compaction and using the doc's symbols. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_cost_model.md | 298 +++++++++++++++---------------- 1 file changed, 146 insertions(+), 152 deletions(-) diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index 2020906d..fa6e3034 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -44,13 +44,18 @@ AutoSketch-Adapted (fixed configs chosen by memory). |---|---| | `D`, `i` | a candidate deployment; a RAQE | | `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | +| `a_D = x_D / y_D` | open windows; each sample is inserted into `a_D` instances | | `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | -| `card(G)` | groups of `D`'s grouping | -| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | +| `G_d`, `G_r` | `D`'s grouping; RAQE `i`'s grouping, equal to `G_d` or, for a family that merges across groups, a subset of it (a **roll-up**) | +| `card(G)` | groups of grouping `G` | +| part | the sketch, plus a key tracker if the family needs one; every cost below is summed over parts | +| `I_d` | a part's instances per window: `card(G_d)`, or 1 for a sketch shared by all groups | +| `I_r` | the states a query of `i` ends with: `card(G_r)`, or 1 for a sketch shared by all groups | | `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | | `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | -| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | +| `m` | measured bytes per instance; `w_D = Σ_parts I_d · m`, one window of all instances | | `n_{i,D} = S_i / x_D` | windows a query merges | +| `k_D = ⌈ρ_D⌉` | ingest workers (at least one), from ingest CPU `ρ_D` (§3) | | batch | all query jobs issued at one instant | **Measurement assumption (sketch-bench as is).** Every sketch operation is @@ -73,84 +78,90 @@ Fargate) is not modeled. Since a job holds its memory only while it runs, its memory × time is the same whenever it runs, and queueing a job would save nothing. -#### 3. CPU: parts and how each is computed - -Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, -over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, -over which every job pattern repeats exactly. A part with `w` CPU-seconds per -event every `P` seconds runs `H / P` times per hyperperiod, so its mean is -`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. - -| Part | When | CPU-seconds | Mean vCPUs | -|---|---|---|---| -| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | -| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | -| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | - -- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at - most one core), **split by sample**: each worker reads a share of the input - (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so - it keeps its own open window instance of every group it sees. +#### 3. Cost of each phase: CPU and memory + +This is the one cost table: every phase, with its CPU and its memory. Each +cell is per part; a phase's cost is the sum over parts. + +| Phase | When | CPU-seconds per event | Mean vCPUs | Memory (bytes) | Held | +|---|---|---|---|---|---| +| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · a_D · c_ins` | `ingest_D = I_d · m · a_D · k_D` (open windows, one copy per worker) | always | +| Compaction | at each window close | `c_D = (k_D − 1) · I_d · c_mrg` | `c_D / y_D` | `k_D · I_d · m` (the closed window's partial copies; 0 when `k_D = 1`) | while it runs: `c_D` | +| Query job of RAQE `i` (merge, then estimate) | at each firing | `ℓ_{i,D} = card(G_r) · c_qry + (I_d · n_{i,D} − I_r) · c_mrg` | `ℓ_{i,D} / T_i` | `q_{i,D} = I_r · m(S_i) · [merges > 0] + card(G_r) · output bytes` | while it runs: `ℓ_{i,D}` | +| Storage | always | — | 0 | `stored_D = max_i I_d · m · ((S_i − x_D) / y_D + 1)` (closed windows, one compacted copy) | always | + +- **No roll-up** (`G_r = G_d`, so `I_r = I_d`): the query merges + `I_d · (n − 1)` times, and a direct query (`n = 1`) merges nothing and + holds no accumulator. +- **Roll-up** (`G_r ⊂ G_d`): a query reads `I_d · n` states and ends with + `I_r`, and each merge folds two into one, so it merges `I_d · n − I_r` + times, even when direct. Ingest, compaction and storage stay at `G_d`; + the query's accumulators, answers and output are at `G_r`. +- `m(S_i)` is an accumulator holding the lookback of one `G_r` group (it + differs from `m` only for DDSketch on a metric with a value range, which is + sized from the values it holds). +- Ingest runs on `k_D` parallel workers (each uses at most one core), + **split by sample**: each worker reads a share of the input (e.g. some + Kafka partitions or scrape targets) with no shuffle by group, so it keeps + its own open window instance of every group it sees. - When a window closes (the watermark passes its end), a **compaction** job merges the `k_D` partial instances of each group into one stored instance. - With `k_D = 1` there is none. + With `k_D = 1` there is none. The merged copy takes the storage slot that + the oldest window frees at the same moment, so it is not counted twice. - Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` - stored instances of each group for the query window, then estimate. Merging - is part of the query. It reads the newest window, which closes at the firing - time, so it starts after that window's compaction. - -`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already -a rate; only compaction (per window close, every `y_D`) and queries (per -firing, every `T_i`) are divided by their period. It is fixed by the plan, -whatever the schedule. + stored instances of each group for the query window, then estimate. + Merging is part of the query. It reads the newest window, which closes at + the firing time, so it starts after that window's compaction. It reads + stored instances in place. +- Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence + `(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. +- Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group + for top-k (sketch-bench's heap size, with 64-bit key hashes); it is not + measured. In words: - `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already - inside `λ_D`), and each is inserted into the `x_D / y_D` windows still - open, at `c_ins` CPU-seconds each: CPU-seconds per second. + inside `λ_D`), and each is inserted into the `a_D` windows still open, at + `c_ins` CPU-seconds each: CPU-seconds per second. - `c_D`: closing a window merges, for every instance, the `k_D` workers' partial copies into one, which takes `k_D − 1` merges. This happens once per slide. -- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows - (`n − 1` merges per instance), then answers once per group. This happens - once per interval. (A sketch shared by all groups merges one instance but - still answers every group.) -- `AUC(CPU)` adds the three rates: work per second, in vCPUs. - -#### 4. Memory: parts and how each is computed +- `ℓ_{i,D}`: a query merges the stored windows it reads down to one state per + answered group, then answers once per `G_r` group. This happens once per + interval. (A sketch shared by all groups merges one instance but still + answers every group.) +- `ingest_D`: every worker keeps one instance per group for each of the `a_D` + windows still open, and there are `k_D` workers. +- `stored_D`: closed windows are kept until the longest lookback that `D` + serves no longer needs them. +- `q_{i,D}`: a merge builds one accumulator per answered group, plus the + answer for every group. -Each part is counted once: a window counts as ingest memory while open and as -storage once compacted, and a query reads stored instances in place. +#### 4. AUC(CPU) and AUC(memory) -| Part | What | Bytes | Held | -|---|---|---|---| -| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | -| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | -| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | -| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | +Every "mean vCPUs" is a long-run average rate, CPU-seconds per second, over +the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, over +which every job pattern repeats exactly. A part with `w` CPU-seconds per +event every `P` seconds runs `H / P` times per hyperperiod, so its mean is +`(H / P) · w / H = w / P`; ingest is already a rate. So the columns add. -`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) -+ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its -own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. +```text +AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i +AUC(memory) = Σ_D (ingest_D + stored_D + k_D · w_D · c_D / y_D) + + Σ_i q_{i,D} · ℓ_{i,D} / T_i +``` -In words: +CPU is elastic, so every job runs on its own core: a compaction runs for +`c_D` and a query for `ℓ_{i,D}`. Both AUCs are fixed by the plan, whatever +the schedule. -- `I_D`: every worker keeps one instance per group for each of the - `x_D / y_D` windows still open, and there are `k_D` workers. -- `stored_D`: closed windows are kept until the longest lookback that `D` - serves no longer needs them. That is `(S − x)/y + 1` windows per group. -- Compaction: when a window closes, a new one opens, so ingest still holds - `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in - memory until the compaction has merged them. The merged copy takes the - storage slot that the oldest window frees at the same moment, so it is not - counted twice. -- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, - with `n = 1`, reads the stored window and needs none), plus the answer for - every group. -- `AUC(memory)`: ingest and storage are held all the time. A compaction's - and a query's memory are held only while they run, a fraction - `run time / y_D` or `run time / T_i` of the time. +In words: `AUC(CPU)` adds the three rates, work per second in vCPUs; ingest +is already a rate, and only compaction (per window close, every `y_D`) and +queries (per firing, every `T_i`) are divided by their period. +`AUC(memory)` holds ingest and storage all the time, and a compaction's and +a query's memory only while they run, a fraction `run time / y_D` or +`run time / T_i` of the time. #### 5. Batch latency and the SLA @@ -225,7 +236,7 @@ pair are §3 and §4's. ```text minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + w2 · [ Σ_D ((ingest_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] s.t. Σ_D z_{i,D} = 1 for every RAQE i z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E @@ -287,50 +298,32 @@ part; query latency and per-RAQE latency; planning time. Figures: version 1, each method's cost–latency frontier for each workload (ASAP and PerQuery as lines, AutoSketch as a point); version 2, each method's cost at each SLA. -## Resource primitives and supported snapshot-AUC objective - -This section supplies the common per-operation resource primitives—instance -memory and insert, merge, and query CPU—and documents the supported older -snapshot-AUC objective. The cost-by-use model above consumes the same -primitives, but adds worker fan-out, compaction, time-weighted transient -memory, and batch latency instead of the accounting below. - -The analytical model combines the empirical per-operation Sketch Bench -measurements with workload properties such as group cardinality, arrival rate, -window size, and query frequency. - -For deployment `D` serving RAQE `i`: - -- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. -- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window (one for a shared fixed-size sketch; see below). -- `x`, `y`: `D`'s window and slide. -- `a_D = x / y`: open windows; each sample is inserted into `a_D` instances of its group. -- `S_i`, `T_i`: RAQE `i`'s lookback and interval. -- `n_i = S_i / x`: windows merged per query. -- `m`: memory per instance, measured. For DDSketch on a metric with a - `value_range`, `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` - bytes instead: one bucket count per `gamma`-power in the range, capped by - the values one instance sees (`λ · x / card(G)` for a window, `λ · L / card(G)` - for a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. The range is the metric's, so `m` is an upper - bound for a group whose own values span less. -- `c_ins`: CPU per insert, measured. -- `c_mrg`: CPU per pairwise merge, measured. -- `c_qry`: CPU per query of one instance, measured. - -Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory -(bytes): - -| Phase | CPU | Memory | -|---|---|---| -| Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RAQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | -| Query, per RAQE | `card(G) × c_qry / T_i` | `card(G) ×` output bytes | -| Storage, per active `D` | 0 | `card(G) × m × ((max_i S_i − x) / y + 1)` (closed windows) | +## Resource primitives and the snapshot-AUC objective -Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence -`(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. -Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group for -top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. +The measured per-operation primitives (`m`, `c_ins`, `c_mrg`, `c_qry`, from +the cost table) and how they scale with a deployment (instance shape and size +law, below) are shared by both objectives; the one cost table is §3's. + +`m` is measured per instance, except for DDSketch on a metric with a +`value_range`: `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` +bytes, one bucket count per `gamma`-power in the range, capped by the values +one instance holds (`λ · x / card(G_d)` for a window, `λ · S / card(G_r)` for +a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. +The range is the metric's, so `m` is an upper bound for a group whose own +values span less. + +**Snapshot-AUC objective** (`milp::minimize`, `analytical_cost_model::score`; +still supported). It prices §3's table with older accounting: + +- one ingest worker (`k_D = 1`), so no compaction; +- each RAQE's merge and query memory (`q_{i,D}`) held all the time, as if + every query ran at once, instead of for `ℓ_{i,D} / T_i` of the time; +- a RAQE's latency is its query job's serial CPU time `ℓ_{i,D}`, with no + compaction before it, checked against the RAQE's own + `latency_sla_ms` (no batch latency). + +Its CPU (`ρ_D`, `ℓ_{i,D} / T_i`) and its ingest and storage memory are §3's +with `k_D = 1`, roll-ups included. ### Instance shape and size law @@ -342,7 +335,7 @@ such as one group's running sum in an exact accumulator. Turning a row into a deployment's cost needs two properties of the family: - **Shape**: instances per window. `PerGroup` keeps one per group, so - `card(G)`; `Shared` keeps one for all groups. + `card(G_d)`; `Shared` keeps one for all groups. - **Law**: how one instance's size grows. `Fixed` is set by the configuration (e.g. CMS rows × columns); `PerKey` stores one entry per key, so it grows linearly with keys. @@ -351,8 +344,8 @@ Memory per window is instances × instance size: | | Fixed | PerKey | |---|---|---| -| **PerGroup** | `card(G) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | -| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | +| **PerGroup** | `card(G_d) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G_d) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | +| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G_d) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | The same factor scales merge and query CPU. Insert CPU is per sample and does not scale. @@ -365,18 +358,18 @@ that see far fewer or far more values. DDSketch is sized from the metric's `value_range` when given (capped by values per instance), else from the measured size. -The model uses `I × m`, where `I` is instances per window: +The model uses `I_d × m`, where `I_d` is instances per window: -- PerGroup + Fixed: `I = card(G)`. -- Shared + PerKey reduces to `I = card(G)` because the export divides the +- PerGroup + Fixed: `I_d = card(G_d)`. +- Shared + PerKey reduces to `I_d = card(G_d)` because the export divides the exact accumulators' memory and merge cost by `measured_keys` (`groups_per_instance`), making `m` a per-group cost. Their query cost is already per group. -- Shared + Fixed: `I = 1`. In code this is the family property +- 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 - to memory and merge; query stays `card(G) × c_qry`, one probe per group. + 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)` is at most the `subpopulations` its row was measured at. This + `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). @@ -386,19 +379,20 @@ PerGroup + PerKey is deferred until a family needs it: it needs the key labels with keys below the group: a per-service top-k CMS costs the same however many endpoints it counts. -Side by side, with `G = card(G)` and `C` closed windows: +Side by side, what each family puts into §3's table (every phase then +follows from it): | | KLL (per group) | exact-sum (per-group normalized) | HydraKLL (shared, fixed) | |---|---|---|---| | `m`, `c_mrg` in the row | one group's | whole ÷ groups | whole sketch | -| Ingest CPU | `λ·a_D·c_ins` | `λ·a_D·c_ins` | `λ·a_D·c_ins` | -| Ingest memory | `G·m·a_D` | `G·m·a_D` | `m·a_D` | -| Merge CPU | `G·(n_i−1)·c_mrg/T_i` | same | `(n_i−1)·c_mrg/T_i` | -| Merge memory | `G·m` | same | `m` | -| Query CPU | `G·c_qry/T_i` | same | `G·c_qry/T_i` | -| Query memory | `G ×` output bytes | same | `G ×` output bytes | -| Storage memory | `G·m·C` | same | `m·C` | -| Latency | `G·(c_qry + (n_i−1)·c_mrg)` | same | `(n_i−1)·c_mrg + G·c_qry` | +| `I_d` (instances per window) | `card(G_d)` | `card(G_d)` | 1 | +| `I_r` (states a query ends with) | `card(G_r)` | `card(G_r)` | 1 | +| probes per query (`c_qry`) | `card(G_r)` | `card(G_r)` | `card(G_r)` | +| key tracker part | none | none | DeltaSet, `I_d = card(G_d)` | +| rolls up (`G_r ⊂ G_d`) | yes | yes | no | + +HydraKLL is in the code but not in the evaluation; admitting it needs the +measurements in "Future Hydra cost and measurement requirements". ### Family properties and key tracker @@ -416,22 +410,15 @@ Each family has properties, hardcoded by variant in `family_properties` The tracker is priced as an exact accumulator on the same `x`, `y` and `G`, in every phase: ingest, merge (union of the `n_i` windows' key sets), query -(enumerate keys) and storage. Its `m` is per key, so it adds `card(G) × m_ds` +(enumerate keys) and storage. Its `m` is per key, so it adds `card(G_d) × m_ds` per window. The AutoSketch baseline skips shared fixed-size families for now (sketch-bench#159). -Per-RAQE latency is the serial CPU time of one query: - -```text -latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg -``` - -summed over the sketch and its key tracker, if any. - -On its own it is not a wall-clock SLA: it assumes no parallel execution across -groups and no cheaper k-way merge. In "Cost by use and batch latency" above it -is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. - +A query job's serial CPU time, `ℓ_{i,D}` (§3), summed over the sketch and +its key tracker, is a RAQE's latency in the snapshot-AUC objective and the +query half of its chain in cost by use. On its own it is not a wall-clock +SLA: it assumes no parallel execution across groups and no cheaper k-way +merge. ## Future Hydra cost and measurement requirements @@ -453,18 +440,25 @@ The result must be reported in the family metric (for Hydra-KLL, `mean_rank_err` ### Proposed Hydra cost model -Let `m_h`, `c_ins,h`, `c_mrg,h`, and `c_probe,h(G_r)` be measured for a particular Hydra configuration and label schema. Hydra's shared grid has one state per open window, so for slide `y` it has `a = x/y` live states. +Hydra is priced by §3's table, with no separate formula. Let `m_h`, +`c_ins,h`, `c_mrg,h` and `c_probe,h(G_r)` be measured for one Hydra +configuration and label schema. Its shared grid is one instance per window, +so `I_d = I_r = 1`, and a query probes it once per `card(G_r)` group: -| Phase | CPU | Memory | -| --- | --- | --- | -| Ingest | `lambda * a * c_ins,h` | `a * m_h` | -| Merge a RAQE | `(L/x - 1) * c_mrg,h / T` | `m_h` when `L/x > 1` | -| Query a RAQE | `C_r * c_probe,h(G_r) / T` | `C_r * output_bytes` | -| Storage | `0` | `ceil((max L - x)/y + 1) * m_h` | - -This is deliberately not the #190 formula: a Hydra merge combines whole windows, not `C_d` independently addressable states. It assumes the measured merge cost does not depend on the number of requested probes; Sketch Bench must confirm that assumption or report a probe-count term. - -Hydra also needs a way to enumerate the groups to query. If it still relies on `exact-delta-set`, the plan must add that tracker's ingest, merge, query, and storage costs. A fine-group tracker used to derive coarse group keys may cost `C_d`, not `C_r`; alternatively, a per-requested-group tracker must be specified and measured. This is a design choice, not a free operation. +| Phase | CPU-seconds per event | Mean vCPUs | Memory (bytes) | +|---|---|---|---| +| Ingest | — | `λ · a_D · c_ins,h` | `m_h · a_D · k_D` | +| Compaction | `(k_D − 1) · c_mrg,h` | `/ y_D` | `k_D · m_h`, while it runs | +| Query job | `card(G_r) · c_probe,h(G_r) + (n_{i,D} − 1) · c_mrg,h` | `/ T_i` | `m_h · [n_{i,D} > 1] + card(G_r) · output bytes`, while it runs | +| Storage | — | 0 | `m_h · ((max_i S_i − x_D) / y_D + 1)` | + +plus the key tracker's part, if any (below). A Hydra merge combines whole +windows, not `card(G_d)` independently addressable states, which is what +`I_d = 1` says. It assumes the measured merge cost does not depend on the +number of requested probes; Sketch Bench must confirm that assumption or +report a probe-count term. + +Hydra also needs a way to enumerate the groups to query. If it still relies on `exact-delta-set`, the plan must add that tracker's ingest, merge, query, and storage costs. A fine-group tracker used to derive coarse group keys may cost `card(G_d)`, not `card(G_r)`; alternatively, a per-requested-group tracker must be specified and measured. This is a design choice, not a free operation. ### Sketch Bench requirements before admitting Hydra From b0cb5a73195ac734b6c94a131076218b7822585c Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 9 Oct 2026 21:26:41 +0000 Subject: [PATCH 05/13] docs: KLL's memory is sketch-bench's nominal footprint, not measured at 1e6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cost table's KLL m is kll_footprint = 4·k·sizeof(T), independent of the item count (1600 B at k = 50 for 1e3, 1e6 and 1e8 items), so it is not "the size measured at 1e6 values" and does not grow with n. Say so, and how it compares with asap_sketchlib's preallocated capacity. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_cost_model.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index fa6e3034..f1054ad0 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -350,13 +350,16 @@ Memory per window is instances × instance size: The same factor scales merge and query CPU. Insert CPU is per sample and does not scale. -Quantile sketches have no keys, but are not strictly fixed either: KLL grows -slowly with the number of values inserted (about `k × log(n / k)`), and -DDSketch with the range of values. The model treats KLL as Fixed at the size -the export measured (1,000,000 values per instance), so it misstates instances -that see far fewer or far more values. DDSketch is sized from the metric's -`value_range` when given (capped by values per instance), else from the -measured size. +Quantile sketches have no keys. KLL's `m` is Fixed exactly as reported: +sketch-bench reports a nominal footprint, `4 · k · sizeof(T)` bytes +(`kll_footprint`; 1600 B at `k = 50`, 6400 B at `k = 200`), the same at every +item count (the cost table's rows were run at 1e6 items, and the same `k` +reports the same bytes at 1e3 and 1e8). It is not the allocation: +`asap_sketchlib::KLL` preallocates its maximum capacity over 61 levels, about +2.9× the nominal footprint at `k = 50`, 1.25× at `k = 200` and 0.87× at +`k = 800`, as `aqpbm-planeval`'s `kll_max_capacity` replica computes it. +DDSketch is sized from the metric's `value_range` when given (capped by +values per instance), else from the measured size. The model uses `I_d × m`, where `I_d` is instances per window: From 5eac9b9d5d3845124a447330cfcb1eb8ffef72a4 Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 9 Oct 2026 21:50:41 +0000 Subject: [PATCH 06/13] rqe-optimizer: prune on every cost cost-by-use bills; fix stale comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dominance pruning compared ingest, query latency, merge memory and storage. Cost by use also bills compaction (per window in every chain, per slide in CPU and byte-seconds) and query output memory, which differs between top-k configs answering different k. A direct RAQE never merges at query time, so a candidate with cheaper ingest but costlier merges could prune one that is cheaper by use. Compare those too; the new test fails without it. Also: workload_scenarios no longer says groupings never share; the exact-increase exclusion states its real (conservative) reason; merged_instance_count notes roll-ups; a circular doc comment; stale §N citations now name the docs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- rqe-optimizer/examples/workload_scenarios.rs | 9 +-- rqe-optimizer/src/analytical_cost_model.rs | 2 +- rqe-optimizer/src/candidates.rs | 58 ++++++++++++++++---- rqe-optimizer/src/enumerate.rs | 6 +- rqe-optimizer/src/lib.rs | 12 ++-- rqe-optimizer/src/milp.rs | 4 +- 6 files changed, 65 insertions(+), 26 deletions(-) diff --git a/rqe-optimizer/examples/workload_scenarios.rs b/rqe-optimizer/examples/workload_scenarios.rs index 8faa735e..09e0bcc4 100644 --- a/rqe-optimizer/examples/workload_scenarios.rs +++ b/rqe-optimizer/examples/workload_scenarios.rs @@ -4,10 +4,11 @@ //! one workload solved with the MILP and printed as the deployments it runs //! and the queries each one serves. //! -//! A deployment serves only queries with its own capability, metric and -//! grouping (`candidates::is_eligible`), so the mixed-grouping and -//! mixed-type sweeps cost the same as solving each part alone. They are -//! baselines for when the model shares across groupings. +//! A deployment serves only queries with its own capability and metric, and +//! its own grouping or, for a family that merges across groups, a subset of +//! it (a roll-up; `candidates::is_eligible`). So the mixed-type sweeps cost +//! the same as solving each part alone, while the mixed-grouping sweeps can +//! share one fine deployment across groupings. //! //! Run: //! `cargo run --release -p rqe-optimizer --example workload_scenarios -- diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 834099be..8c7eb932 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -1,4 +1,4 @@ -//! Analytical scoring built from measured per-operation costs (§5). +//! Analytical scoring built from measured per-operation costs (`docs/rqe_optimizer_cost_model.md`). //! //! Costs split into four phases, each with CPU and memory: //! - ingest: inserts into open windows, and their state; diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index c346764e..ceeaf6bc 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,4 +1,4 @@ -//! Candidate generation and eligibility (§3). +//! Candidate generation and eligibility (`docs/rqe_optimizer_candidates.md`). use crate::analytical_cost_model; use crate::{ @@ -63,7 +63,7 @@ fn measured_at_group_count(config: &AtomicCostEntry, groups: u64) -> bool { /// /// Deployments are grouped by `grouping` and built from the families whose /// [`mergeable_across_groups`](crate::FamilyProperties::mergeable_across_groups) -/// is `mergeable_across_groups`. Their windows, slides and heaps come from +/// equals `mergeable_across_groups`. Their windows, slides and heaps come from /// `group`, the RAQEs they may serve. fn candidate_deployments( group: &[&Raqe], @@ -364,10 +364,12 @@ pub fn build_all_candidates_unpruned( /// mapping without making any modeled objective worse. /// /// This comparison is local to a (capability, metric, spatial_filter, -/// grouping) group, where query output size is common. It compares ingest CPU -/// and memory, then latency (merge and query CPU), merge memory and stored -/// memory for each RAQE the dominated candidate can serve, all as the -/// analytical cost model prices them: a sketch shared by all groups and a +/// grouping) group. It compares ingest CPU and memory; compaction per window +/// (it starts every chain) and per second (CPU-seconds and byte-seconds per +/// slide, as cost by use bills it); then, for each RAQE the dominated +/// candidate can serve, the query job's CPU (merge and query, its latency), +/// its memory (merge accumulators and output) and stored memory. All are as +/// the analytical cost model prices them: a sketch shared by all groups and a /// sketch per group don't scale alike with `card(G)`. pub fn prune_dominated_candidates( raqes: &[Raqe], @@ -408,10 +410,12 @@ pub fn prune_dominated_candidates( /// One candidate's costs, computed once for every pairwise comparison. struct CandidateCosts { - /// Ingest CPU and memory. - ingest: [f64; 2], - /// Per RAQE: latency, merge memory and stored memory if the candidate - /// serves it, else `None`. + /// Per deployment: ingest CPU and memory; compaction CPU-seconds per + /// window (it starts every chain); and compaction CPU and byte-seconds + /// per second, as cost by use bills them every slide. + ingest: [f64; 5], + /// Per RAQE: latency, query memory (merge and output) and stored memory + /// if the candidate serves it, else `None`. per_raqe: Vec>, } @@ -423,20 +427,30 @@ impl CandidateCosts { accuracy: &Accuracy, ) -> Self { let ingest = analytical_cost_model::ingest(candidate, facts); + let compaction_secs = analytical_cost_model::compaction_secs(candidate, facts); + let slide_secs = crate::secs(candidate.slide_ms); let per_raqe = raqes .iter() .map(|raqe| { is_eligible(raqe, candidate, facts, accuracy).then(|| { [ analytical_cost_model::query_latency_ms(raqe, candidate, facts), - analytical_cost_model::merge(raqe, candidate, facts).memory_bytes, + analytical_cost_model::merge(raqe, candidate, facts).memory_bytes + + analytical_cost_model::query(raqe, candidate, facts).memory_bytes, analytical_cost_model::storage_bytes(raqe, candidate, facts), ] }) }) .collect(); Self { - ingest: [ingest.cpu_secs_per_sec, ingest.memory_bytes], + ingest: [ + ingest.cpu_secs_per_sec, + ingest.memory_bytes, + compaction_secs, + compaction_secs / slide_secs, + analytical_cost_model::compaction_bytes(candidate, facts) * compaction_secs + / slide_secs, + ], per_raqe, } } @@ -925,6 +939,26 @@ mod tests { assert_eq!(retained, vec![coarse]); } + #[test] + fn retains_candidate_with_cheaper_compaction() { + // A direct RAQE never merges at query time, so merge CPU shows up only + // in compaction. `cheap_ingest` ingests on 2 workers (ρ = 2) and + // compacts for 100 s; `cheap_compaction` ingests on 3 (ρ = 3) and + // compacts for 2 s. Neither is no worse on every cost. + let r = raqe("r", 60_000, 60_000); + let cheap_ingest = crate::test_support::deployment(1.0, 1.0, 100.0, 1.0, 60_000, 60_000); + let cheap_compaction = crate::test_support::deployment(1.0, 1.5, 1.0, 1.0, 60_000, 60_000); + + let retained = prune_dominated_candidates( + &[r], + &facts(1, 2), + vec![cheap_ingest.clone(), cheap_compaction.clone()], + &table_accuracy, + ); + + assert_eq!(retained, vec![cheap_ingest, cheap_compaction]); + } + #[test] fn retains_candidate_with_lower_query_latency() { let r = raqe("r", 60_000, 60_000); diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 18a8253f..dd614b2b 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -1,6 +1,6 @@ -//! Brute-force search over full mappings (§4, §7 step 2). +//! Brute-force search over full mappings. //! -//! A mapping is one deployment choice per RAQE (§4's only constraint is +//! A mapping is one deployment choice per RAQE (the MILP's only constraint is //! `Σ_D x_{i,D} = 1`; `y_D` is derived). Choices are independent, so the //! search space is exactly the cartesian product of the per-RAQE eligible //! lists -- nothing to prune against. Sharing falls out when two choices land @@ -14,7 +14,7 @@ use crate::{ candidates::eligible_deployments_for, Accuracy, Deployment, Mapping, Raqe, WorkloadFacts, }; -/// RAQEs nothing in `deployments` can serve (§3.4). Surfaced separately from +/// RAQEs nothing in `deployments` can serve. Surfaced separately from /// `brute_force`: an unservable RAQE is a modeling gap (tolerance too tight, /// no such config), not a normal empty result. pub fn unservable( diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 8b485871..07df21f8 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -38,7 +38,7 @@ pub(crate) fn secs(ms: Millis) -> f64 { /// [`mergeable_across_groups`](FamilyProperties::mergeable_across_groups). pub type LabelSet = BTreeSet; -/// What an RAQE's statistic needs (§1). A variant becomes a candidate only +/// What an RAQE's statistic needs. A variant becomes a candidate only /// if it is in both `families()` and [`DEPLOYABLE_FAMILIES`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Capability { @@ -252,7 +252,9 @@ pub fn family_properties(variant: &str) -> FamilyProperties { }; match variant { "exact-sum" | "exact-min" | "exact-max" => exact, - // A rate rolled up to a coarser grouping is not a meaningful query. + // Not rolled up, conservatively: summing per-series increases would + // give the coarse answer, but whether ASAPQuery's increase + // accumulator keeps them per series is unconfirmed. "exact-increase" => FamilyProperties { mergeable_across_groups: false, ..exact @@ -418,7 +420,7 @@ pub enum AccuracyDirection { HigherIsBetter, } -/// One repeating query expression (§1). +/// One repeating query expression. #[derive(Debug, Clone)] pub struct Raqe { pub id: String, @@ -508,7 +510,7 @@ pub fn row_accuracy(config: &AtomicCostEntry) -> f64 { }) } -/// A candidate deployment (§3): one configuration, one grouped stream, and a +/// A candidate deployment (`docs/rqe_optimizer_candidates.md`): one configuration, one grouped stream, and a /// sliding sketch window. Retention is an execution/storage concern, not an /// optimizer candidate dimension. #[derive(Debug, Clone, PartialEq)] @@ -569,7 +571,7 @@ impl Deployment { /// A full mapping: one deployment index (into the `deployments` slice passed /// to `enumerate::brute_force`) per RAQE, aligned with the `raqes` slice's /// order. `z_{i,D} = 1 <=> mapping[i] == D`'s index; `u_D = 1 <=>` `D`'s -/// index appears anywhere in `mapping` (§4) -- `y` is never stored +/// index appears anywhere in `mapping` -- `y` is never stored /// separately, it's always derived from `mapping`. pub type Mapping = Vec; diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 8a2952df..165d654b 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -1,4 +1,4 @@ -//! MILP solver for one scalarized RAQE deployment optimization (§4). +//! MILP solver for one scalarized RAQE deployment optimization. //! //! Candidate construction is documented in `docs/rqe_optimizer_candidates.md` //! and the cost model in `docs/rqe_optimizer_cost_model.md`. It avoids @@ -69,6 +69,8 @@ pub struct PlannedRaqe { /// Index into [`MilpSolution::deployments`]. pub deployment: usize, /// `n = L/x` windows merged per query; 1 means Direct, more means Merge. + /// A roll-up (the RAQE's grouping differs from its deployment's) also + /// merges each coarse group's fine groups, even when `n = 1`. pub merged_instance_count: u64, } From 3995c78e6a6018a39dc3047917cff0ac5b17be91 Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 9 Oct 2026 21:50:41 +0000 Subject: [PATCH 07/13] docs: consolidate the optimizer docs; add the Hydra admission design - candidates: eligibility allows subset groupings for families that merge across groups; generation shows the roll-up RAQE sets; accuracy is read at G_r with KLL's fan-out merge count, and past the measured merge counts the guarantee applies, floored by the last measurement; pruning lists every compared cost; the MILP lives only in the cost doc; one roll-up section. - cost model: top-k output and query CPU scale with k; k_D sums parts; mergeable_across_groups listed; KLL footprint points at #191/#192; Hydra moved out. - v1 and TODO: phases include compaction and the query job; TODOs match cost by use. - rqe_optimizer_hydra.md (new): Hydra in sketch-bench, accuracy bounds per combination (CMS, CountSketch, HLL, UnivMon, KLL) checked against the paper's Theorem 2 and the library (correlated inner seeds, fixed column hash, few rows), cost model, candidates and MILP edges, sketch-bench requirements and open decisions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_TODO.md | 8 +- docs/rqe_optimizer_candidates.md | 194 +++++++++------------ docs/rqe_optimizer_cost_model.md | 101 ++++------- docs/rqe_optimizer_hydra.md | 279 +++++++++++++++++++++++++++++++ docs/rqe_sketch_deployment_v1.md | 64 ++++--- 5 files changed, 425 insertions(+), 221 deletions(-) create mode 100644 docs/rqe_optimizer_hydra.md diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index abeb8e76..d2f62855 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -53,11 +53,11 @@ implemented, what is next, and what is intentionally deferred. ## Explicitly deferred - Query-result sharing across RQEs. -- Real query concurrency; memory assumes every query runs at once. +- Real query concurrency in the snapshot objective, whose memory assumes every + query runs at once (cost by use holds query memory only while it runs). - Bursty load; CPU is a mean over time. -- A per-family instance shape for families holding every group in one - fixed-size instance (HydraKLL, sketch-bench#142). -- Top-k `k` other than the benchmark's 32, and key labels `K`. +- Admitting Hydra ([rqe_optimizer_hydra.md](rqe_optimizer_hydra.md)). +- Key labels `K` (PerGroup + PerKey sizes). - RQE churn, replanning, and migration cost. - Precomputed rollups; v1 merges selected base instances at query time. - A policy for choosing one mapping from the reported Pareto frontier. diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index 4d0b9ff2..520eac85 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -1,6 +1,10 @@ # RQE optimizer: candidate generation and mapping -This document is the canonical design for candidate construction, eligibility, dominance pruning, finer-to-coarser roll-ups, and the assignment MILP. +This document is the canonical design for candidate construction, eligibility +(accuracy included), finer-to-coarser roll-ups and dominance pruning. What a +candidate costs, and the MILP that maps RAQEs to candidates, are in +[Cost models](rqe_optimizer_cost_model.md); Hydra is in +[Hydra](rqe_optimizer_hydra.md). ## Candidate deployments @@ -21,10 +25,16 @@ slides that a coarser slide beats for the same RAQEs. Pruning then attaches the measured costs and drops a candidate when another serves all of its RAQEs and is no worse on every cost. -For each (capability, metric, G) group, generate candidates as follows: +Deployments exist only at groupings some RAQE asks for. For each (capability, +metric, spatial filter, grouping `G`), let `R(G)` be the RAQEs a deployment at +`G` may serve: those grouped exactly by `G` for a family that does not merge +across groups, and those grouped by any subset of `G` (roll-ups included) for +a family that does (`mergeable_across_groups`). A coarse RAQE so contributes +its lookback and interval to the fine deployment's windows and slides. Top-k +doesn't roll up, so its heaps come from exact-grouping RAQEs only. Then: ```text -for each window x that divides some S_i and is a multiple of the scrape interval: +for each RAQE set R(G), and each window x that divides some S_i in it and is a multiple of the scrape interval: g = { g_i = gcd(x, T_i) : RAQE i with S_i divisible by x } slides = { gcd(A) : A is a non-empty subset of g } for each y in slides that is a multiple of the scrape interval: @@ -72,7 +82,10 @@ far, and for each new `g` add `g` and `gcd(found, g)` for every `found`. For An RAQE `r_i` is eligible for a candidate `D` when: -1. `cap_i = D.capability`, `metric_i = D.metric` and `G_i = D.G`. +1. `cap_i = D.capability`, `metric_i = D.metric`, the same spatial filter, + and `G_i = D.G`, or `G_i ⊂ D.G` when `D`'s family has + `mergeable_across_groups` (a roll-up; see below). A coarse deployment never + serves a finer RAQE. 2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. 3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family (`family_properties`, which also gives the direction), clears `tol_i`. @@ -80,11 +93,13 @@ An RAQE `r_i` is eligible for a candidate `D` when: Exact accumulators take that accuracy from the cost table; they merge without loss, so the window size doesn't matter. Sketches take it from the saturation study's error-vs-N curves (`SaturationCurves`, #156), -read at the number of items one group receives over the RAQE's whole -lookback: series per group times scrapes per lookback. +read at the number of items one answered group receives over the RAQE's +whole lookback: series per `G_i` group times scrapes per lookback. On a +roll-up the answered group is the RAQE's coarse one. - The curve is the configuration's at the metric's fitted `data_shape` for - `G` (zipf θ and keys `K`, or tail index `a` for quantiles). Between grid + the RAQE's grouping `G_i` (zipf θ and keys `K`, or tail index `a` for + quantiles). Between grid points, the worst bracketing point; outside the grid, or with no fit, no accuracy. - Between checkpoints, the worse neighbour. Below the first checkpoint, no @@ -93,21 +108,22 @@ lookback: series per group times scrapes per lookback. refuses a curve for another metric as a stale study. - For sketches that merge exactly, the window size doesn't matter: a merged answer reads the curve at the lookback's item count, like a single sketch. - KLL and top-k merge lossily (#131): an answer merged from `m = S_i / D.x` - windows reads the study's merge curve (`saturation_merge_curve.csv`, the - sketch merged from `m` shards of the same items) at the lookback's item - count. Between measured shard counts, the worse. Past the largest - measured count, or without a merge curve, a merged KLL or top-k answer has - no accuracy: the study must measure the merge counts a workload needs - (`--merge-shards-list`) up to the N it reads at: past the merge curve's - last N, the merged answer has no accuracy either (#158). - `SaturationCurves::load` refuses a study with no merge curves for a - candidate KLL sketch. + KLL merges lossily (#131): an answer merged from `n = S_i / D.x` windows, + times the average fan-out `⌈card(D.G) / card(G_i)⌉` on a roll-up, reads + the study's merge curve (`saturation_merge_curve.csv`, the sketch merged + from `n` shards of the same items) at the lookback's item count. Between + measured shard counts, the worse. Past the largest measured count, or past + a merge curve's last N, the curves say nothing, so the answer takes the + guarantee below, no better than the largest count's last measurement; the + study should measure the merge counts a workload needs + (`--merge-shards-list`) so the guarantee isn't what decides (#158). `SaturationCurves::load` refuses a study with no merge curves for + a candidate KLL sketch. The fan-out is the average; the largest group's is + #189. - A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap - top-k (CMS-heap, CountSketch-heap) keeps a heap of `m · k` in a deployment - answering from `m = S_i / D.x` merged windows (`m = 1` gives `k`). - Candidates carry one heap per distinct `m · k` among the RAQEs on a window, - and a RAQE is eligible only where the heap holds its `m · k`. Such a merged answer reads as one sketch: the + top-k (CMS-heap, CountSketch-heap) keeps a heap of `n · k` in a deployment + answering from `n = S_i / D.x` merged windows (`n = 1` gives `k`). + Candidates carry one heap per distinct `n · k` among the RAQEs on a window, + and a RAQE is eligible only where the heap holds its `n · k`. Such a merged answer reads as one sketch: the plain curve, then the guarantee fallback. It assumes the merged heaps still hold the true top `k`; it is not a guarantee. So heap top-k needs no merge curves. Costs come from the cost table's rows at heaps 32, 128, 512 and @@ -158,110 +174,50 @@ higher-is-better metrics, passing means `measured >= tol_i`. Direction is explicit on the RAQE; it is never inferred from a metric name. A missing metric does not pass. -Before mapping, prune a candidate only if another candidate can serve every -RAQE it can and is no worse in ingest CPU and memory, and in latency, merge -memory and stored memory for each such RAQE. This is safe because any mapping using -the removed candidate can substitute the remaining one without weakening a -modeled objective. +Before mapping, prune a candidate only if another candidate with the same +capability, metric, spatial filter and grouping can serve every RAQE it can, +and is no worse in ingest CPU and memory, in compaction (CPU-seconds per +window, and CPU and byte-seconds per second), and, for each RAQE it serves, +in query-job CPU (`ℓ`), query memory (merge accumulators and output) and +stored memory. Every cost in both objectives, and every chain (compaction, then +query), is monotone in these, so any mapping using the removed candidate can +substitute the remaining one without raising cost or latency. Closed instances must be stored long enough to answer the RAQEs assigned to a deployment. Retention is not a candidate parameter: a deployment stores the history needed by the largest assigned query window, costed as the storage -phase (below). +phase ([Cost models](rqe_optimizer_cost_model.md), §3). ## Workload mapping -Let `z_{i,D}` be 1 when RAQE `i` uses candidate deployment `D`; let `u_D` be 1 -when deployment `D` is active. - -```text -Σ_D z_{i,D} = 1 for every RAQE i -z_{i,D} <= u_D for every eligible pair (i, D) -``` - -Every RAQE selects exactly one eligible deployment. Multiple RAQEs may select -the same deployment and therefore share its ingest work. A query may merge -multiple instances from its selected deployment, but v1 does not combine -results from several deployments to satisfy one RAQE. - -### MILP formulation - -Let `E` be the eligible `(i, D)` pairs. The solver has one binary `z_{i,D}` -for each pair in `E`, one binary `u_D` for each candidate, and a continuous -`stored_D` for each candidate's closed-window storage. - -```text -z_{i,D} ∈ {0, 1} for (i, D) ∈ E -u_D ∈ {0, 1} for D ∈ candidates -stored_D ≥ 0 - -Σ_{D: (i,D) ∈ E} z_{i,D} = 1 for every RAQE i -z_{i,D} ≤ u_D for (i, D) ∈ E -u_D ≤ Σ_{i: (i,D) ∈ E} z_{i,D} for every candidate D -stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E -``` - -The `u_D ≤ Σ z` constraint prevents a deployment from becoming active when no -RAQE selected it. It is not required for feasibility, but makes ingest cost -unambiguous. `stored_D` is a linearized max: a deployment stores enough for -the longest lookback it serves. - -The only objective, `Objective::AUCCost { w_cpu, w_mem }`, weighs each phase -cost (below) as `w(c) = w_cpu × c.cpu + w_mem × c.memory_GiB`: - -```text -minimize Σ_D w(ingest_D) × u_D - + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} - + Σ_D stored_D -``` - -CPU is the area under the CPU curve (mean CPU-sec/sec), so plans are sized -for the mean load, not for bursts. Memory sums every phase, as if every query -evaluates at once. The default weights are `(1, 0)`: CPU only. - -Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver +Every RAQE selects exactly one eligible candidate; several RAQEs may select +the same one and so share its ingest. A query may merge several instances +of its candidate, but v1 never combines results from several deployments to +answer one RAQE. The MILP over the eligible pairs, its objective and its +latency bound are in [Cost models](rqe_optimizer_cost_model.md) (§7 for cost +by use; the snapshot objective changes only its coefficients). The solver never enumerates full mappings. - -## Fine-to-coarse group roll-ups (#190) - -### Vocabulary - -A deployment has a source grouping `G_d`; a RAQE asks for a result grouped by `G_r`. `C_d = card(G_d)` and `C_r = card(G_r)`. A conventional, per-group sketch can answer `G_r subseteq G_d` by merging the fine states that belong to each coarse group. We call that operation a *roll-up*. - -Hydra is different. It ingests a labelled record into one shared grid and answers a subpopulation predicate from that grid. It does not expose one KLL per fine group for the optimizer to merge. A coarse Hydra answer, if the Hydra layout supports its predicate, is a direct query of the shared sketch, not the generic roll-up operation. - -### What #190 guarantees today - -For the families marked `mergeable_across_groups`, #190 permits `G_r subseteq G_d`. Thus, one can never use a coarse deployment for a fine RAQE. The eligible families are exact sum/min/max, HLL, cardinality UnivMon, KLL, and DDSketch. Rate/increase and top-k remain exact-grouping only i.e. `G_r == G_d`. - -For a conventional per-group sketch, a query over `L` using base windows `x` folds this many states: - -```text -M = C_d * L/x - C_r -``` - -Thus merge CPU is `M * c_mrg / T`, merge memory is `C_r * m(L)`, and query CPU and output are priced at `C_r`. Ingest and retained base-window storage remain priced at `C_d`. This reduces to the old model when the groupings are equal, and it correctly charges a direct roll-up (`L = x`) for `C_d - C_r` merges. - -Eligibility also reads accuracy at the requested grouping: its data shape and item count are those of `G_r`. For KLL, the measured merge curve is read at the average fan-out `ceil(C_d / C_r) * L/x`. That is an empirical estimate, not a worst-group bound. -This is a known cost-modeling issue caused due to uneven fan-out, logged in #189. - -### Future Hydra candidate strategy - -The existing candidate map remains the right shape for conventional roll-ups: generate a deployment at every RAQE grouping already present; for a mergeable family let that deployment consider RAQEs at subset groupings when choosing windows and slides; then add one eligible edge `(RAQE, deployment)` for every SLA-valid subset relation. The MILP itself is unchanged: one `z[i,D]` per eligible edge, one `u[D]` per deployment, and the same assignment and activation constraints. Its coefficients use the roll-up costs above. - -Hydra should enter through a distinct candidate/read strategy, for example `DirectSubpopulationQuery`, with these properties: - -- candidate identity includes the complete label schema `H`, Hydra config, window and slide, plus its group-enumeration strategy; -- it may cover a RAQE only when `G_r` is a supported predicate/grouping of `H`, its exact measurement clears the RAQE SLA, and its merge depth was measured; -- its edge coefficients use the [Hydra cost model](rqe_optimizer_cost_model.md#proposed-hydra-cost-model) plus any tracker costs; -- it is not marked `mergeable_across_groups`, and is never charged or validated as a fine-state roll-up. - -This keeps candidate generation, eligibility, cost scoring, enumeration, and the MILP on one shared edge set while making the meaning of an edge explicit. The first Hydra implementation can conservatively support only `G_r = H` (or only explicitly benchmarked prefix groupings), then expand the supported predicate relation as measurements land. - -### Decisions needed - -1. Is coarse Hydra group enumeration derived from a fine DeltaSet, or do we store keys at every requested grouping? -2. Which predicates are legal: only prefix label groupings, or arbitrary subsets once the IR has a label-to-layout mapping? -3. Do we require an observed worst-parent fan-out curve (issue #189) before admitting Hydra, or accept an average-fan-out planning estimate like #190's KLL model? -4. What interpolation/extrapolation, if any, is permitted between measured Hydra saturation points? +## Fine-to-coarse group roll-ups + +A deployment grouped by `G_d` can answer a RAQE grouped by `G_r ⊂ G_d` when +its family merges across groups (`mergeable_across_groups`): at query time, +the fine instances of each coarse group are merged into one, then answered. +This is a **roll-up**. Families that do: exact sum/min/max, HLL, +univmon-cardinality, KLL and DDSketch. Rate/increase and top-k (CMS-heap, +CountSketch-heap, univmon-topk) serve only `G_r = G_d`. Hydra never rolls +up: it would answer subsets of its schema directly +([Hydra](rqe_optimizer_hydra.md)). + +- **Cost**: ingest, compaction and storage stay at `G_d`; the query job merges + `I_d · n − I_r` times and answers `card(G_r)` groups + ([Cost models](rqe_optimizer_cost_model.md), §3). A direct roll-up + (`n = 1`) still merges `card(G_d) − card(G_r)` instances. +- **Accuracy**: read at `G_r`: its `data_shape`, and its items per group over + the lookback. KLL's merge curve is read at `⌈card(G_d)/card(G_r)⌉ · n` + merged instances, the average fan-out, an estimate rather than a + worst-group bound (uneven fan-out is #189). +- **Facts**: `validate_facts` requires `card(X) ≤ card(Y)` for every pair + `X ⊂ Y` of label sets, so a merge count is never negative. +- **Plan output**: a RAQE rolls up exactly when its grouping differs from its + deployment's. diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index f1054ad0..0f6a5fdc 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -1,8 +1,10 @@ # RQE optimizer: cost models -This document distinguishes the optimizer's canonical cost-by-use design from -its still-supported snapshot-AUC objective, and records the measurements -required before Hydra can participate. +This document is the one home for what a candidate costs (§3's table), the +canonical cost-by-use model with its MILP, and the still-supported +snapshot-AUC objective. Candidates and eligibility are in +[Candidate generation and eligibility](rqe_optimizer_candidates.md); Hydra +is in [Hydra](rqe_optimizer_hydra.md). ## Model status and relationship @@ -16,11 +18,12 @@ required before Hydra can participate. 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. Its proposed accuracy and cost contract below is - not admitted by #190 or the current optimizer. +- **Hydra** is future work, not a candidate today; see + [Hydra](rqe_optimizer_hydra.md). -The two implemented objectives share the same resource primitives; they differ -only in how they account for those primitives over time. +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 +(a batch's longest chain vs. each RAQE's serial query time). ## Cost by use and batch latency @@ -115,9 +118,12 @@ cell is per part; a phase's cost is the sum over parts. stored instances in place. - Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence `(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. -- Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group - for top-k (sketch-bench's heap size, with 64-bit key hashes); it is not - measured. +- Query output is estimated at 8 bytes per group, or `k` × 16 bytes per group + for top-k (`k` the deployment's answered top-k, 32 by default, with 64-bit + key hashes); it is not measured. A top-k sketch's `c_qry` is measured at + `k = 32` and scaled by `k / 32`. +- `k_D = ⌈ρ_D⌉` takes the deployment's whole ingest CPU, summed over its + parts (sketch and key tracker). In words: @@ -268,8 +274,8 @@ In words: Every term is linear in `u` and `z`, with or without a bound, so the MILP is solved exactly -(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair -so the solver sees magnitudes near 1). The solved plan's cost and latency are +(`milp::minimize_usage_cost`; costs are divided by the sum, over RAQEs, of +each RAQE's cheapest pair on its own, so the solver sees magnitudes near 1). The solved plan's cost and latency are then computed from its resource use (`usage::usage_cost`). - **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` @@ -350,14 +356,12 @@ Memory per window is instances × instance size: The same factor scales merge and query CPU. Insert CPU is per sample and does not scale. -Quantile sketches have no keys. KLL's `m` is Fixed exactly as reported: -sketch-bench reports a nominal footprint, `4 · k · sizeof(T)` bytes -(`kll_footprint`; 1600 B at `k = 50`, 6400 B at `k = 200`), the same at every -item count (the cost table's rows were run at 1e6 items, and the same `k` -reports the same bytes at 1e3 and 1e8). It is not the allocation: -`asap_sketchlib::KLL` preallocates its maximum capacity over 61 levels, about -2.9× the nominal footprint at `k = 50`, 1.25× at `k = 200` and 0.87× at -`k = 800`, as `aqpbm-planeval`'s `kll_max_capacity` replica computes it. +Quantile sketches have no keys. KLL's `m` is Fixed, and the same at every +item count, because `asap_sketchlib::KLL` allocates once at construction. +Until #192 the cost table's KLL rows report a nominal `4 · k · sizeof(T)` +(1600 B at `k = 50`), not that allocation (5536 B at `k = 50`: item slots, +level index and merge buffer; 1.58× at `k = 200`, 1.14× at `k = 800`), so +KLL memory is understated (#191). DDSketch is sized from the metric's `value_range` when given (capped by values per instance), else from the measured size. @@ -394,8 +398,8 @@ follows from it): | key tracker part | none | none | DeltaSet, `I_d = card(G_d)` | | rolls up (`G_r ⊂ G_d`) | yes | yes | no | -HydraKLL is in the code but not in the evaluation; admitting it needs the -measurements in "Future Hydra cost and measurement requirements". +HydraKLL has `FamilyProperties` but is in no capability's family list, so it +is never a candidate; see [Hydra](rqe_optimizer_hydra.md). ### Family properties and key tracker @@ -404,6 +408,9 @@ Each family has properties, hardcoded by variant in `family_properties` - `mergeable_across_windows`: a family without it only serves `S_i = x`. Every family in use merges. +- `mergeable_across_groups`: it can serve a RAQE at a subset grouping (a + roll-up, [candidates](rqe_optimizer_candidates.md#fine-to-coarse-group-roll-ups)). + True for exact sum/min/max, HLL, univmon-cardinality, KLL and DDSketch. - `one_fixed_size_sketch_for_all_groups`: the Shared + Fixed cell above. - `needs_delta_set_key_tracker`: the sketch can't list its groups, so a DeltaSet (`exact-delta-set`) records each window's keys for the query to @@ -422,53 +429,3 @@ its key tracker, is a RAQE's latency in the snapshot-AUC objective and the query half of its chain in cost by use. On its own it is not a wall-clock SLA: it assumes no parallel execution across groups and no cheaper k-way merge. - -## Future Hydra cost and measurement requirements - -This is a future admission contract, not a model used by either implemented -optimizer objective. Hydra remains outside #190. - -It does not make sense to apply the "fine-to-coarse rollup strategy" to Hydra. - -The required accuracy contract is an empirical predicate: - -```text -hydra_error(config, schema H, requested grouping G_r, - target-shape(G_r), items per target group, - subpopulation population/fan-out, merged_windows) - <= RAQE accuracy SLA -``` - -The result must be reported in the family metric (for Hydra-KLL, `mean_rank_err`) with the same direction as the RAQE SLA. It is insufficient to record only a single `subpopulations` ceiling: two target groupings with the same cardinality can have different skew, fan-out, and query selectivity. No analytic composition from the KLL cell's guarantee to the Hydra grid's error is assumed. In particular, cross-window Hydra merge accuracy must be measured for every allowed merge depth; until then a Hydra candidate may serve only `L == x`. - -### Proposed Hydra cost model - -Hydra is priced by §3's table, with no separate formula. Let `m_h`, -`c_ins,h`, `c_mrg,h` and `c_probe,h(G_r)` be measured for one Hydra -configuration and label schema. Its shared grid is one instance per window, -so `I_d = I_r = 1`, and a query probes it once per `card(G_r)` group: - -| Phase | CPU-seconds per event | Mean vCPUs | Memory (bytes) | -|---|---|---|---| -| Ingest | — | `λ · a_D · c_ins,h` | `m_h · a_D · k_D` | -| Compaction | `(k_D − 1) · c_mrg,h` | `/ y_D` | `k_D · m_h`, while it runs | -| Query job | `card(G_r) · c_probe,h(G_r) + (n_{i,D} − 1) · c_mrg,h` | `/ T_i` | `m_h · [n_{i,D} > 1] + card(G_r) · output bytes`, while it runs | -| Storage | — | 0 | `m_h · ((max_i S_i − x_D) / y_D + 1)` | - -plus the key tracker's part, if any (below). A Hydra merge combines whole -windows, not `card(G_d)` independently addressable states, which is what -`I_d = 1` says. It assumes the measured merge cost does not depend on the -number of requested probes; Sketch Bench must confirm that assumption or -report a probe-count term. - -Hydra also needs a way to enumerate the groups to query. If it still relies on `exact-delta-set`, the plan must add that tracker's ingest, merge, query, and storage costs. A fine-group tracker used to derive coarse group keys may cost `card(G_d)`, not `card(G_r)`; alternatively, a per-requested-group tracker must be specified and measured. This is a design choice, not a free operation. - -### Sketch Bench requirements before admitting Hydra - -1. Accept a named label schema and query grouping/predicate, rather than interpreting semicolon position as the meaning of a grouping. Preserve label names and their order in the emitted record. -2. Generate hierarchical data with exact answers for every queried grouping; include cardinality, per-parent fan-out, skew, total items, and each target group's item count in the result metadata. -3. Sweep Hydra configuration (outer grid and cell parameters), schema width, target grouping, cardinality/fan-out, and distribution shape. Measure accuracy separately for each target grouping. -4. Measure insert, footprint, one-window query, and merges over the intended shard counts. For a merged query, measure both sketch merge and the requested number of probes, so the planner can distinguish a whole-sketch merge from per-group probe work. -5. Benchmark and export the key-enumeration path. State whether it uses a DeltaSet, what grouping it stores, and its exact input/output cardinality. -6. Emit a machine-readable saturation key containing the fields in the accuracy contract above. The optimizer must reject a Hydra candidate when no matching point (or explicitly approved interpolation) exists; it must not borrow a KLL or a different-grouping curve. -7. Add regression fixtures for equal grouping, a direct coarse predicate, and a multi-window coarse predicate. Each fixture must compare to exact answers and assert the exported accuracy and cost dimensions. diff --git a/docs/rqe_optimizer_hydra.md b/docs/rqe_optimizer_hydra.md new file mode 100644 index 00000000..fa4e777c --- /dev/null +++ b/docs/rqe_optimizer_hydra.md @@ -0,0 +1,279 @@ +# RQE optimizer: admitting Hydra + +Status: design, not implemented. Hydra is never a candidate today: +`hydra-kll` has `FamilyProperties` (`rqe-optimizer/src/lib.rs`) but is in no +capability's family list, and the other four Hydra variants have none. This +document says, for each Hydra combination sketch-bench benchmarks, what +accuracy guarantee it has, how it is costed, how it would enter the +candidates and the MILP, and what sketch-bench must measure first. Symbols +follow [Cost models](rqe_optimizer_cost_model.md) §1; `Λ` is a Hydra +schema (the hyperperiod there is `H`). + +## 1. What Hydra is in sketch-bench + +All five combinations wrap `asap_sketchlib::Hydra` (0.3.0; Manousis et al., +VLDB 2022, arXiv:2208.04927). The `polars` rows of the same names are exact +baselines. + +- **Grid.** `R` rows × `W` columns of cells, each an inner sketch, over a + schema `Λ` of label columns (`hydra_shared.rs`). +- **Insert fans out.** A record with `|Λ| = d` labels is inserted into the + cell of every non-empty label subset (`2^d − 1` subkeys, each tagged with + its column names), in every row: `R · (2^d − 1)` inner inserts per record + (`hydra.rs` `update`, masks `1..2^d`). The empty grouping (the whole + stream) is not inserted. +- **Query.** A subpopulation (values for a subset `G_r ⊆ Λ`, the rest + unconstrained) hashes to one cell per row; the answer is the **median** + over the `R` rows of each cell's inner answer (`query_key`). The library + answers any non-empty subset of `Λ`; sketch-bench's wrapper constrains + only leading columns (`hydra_shared.rs` `query`), so it can ask only + prefix groupings. +- **No keys.** Hydra stores no subpopulation keys. To answer every group of + `G_r`, something else must list them (in the optimizer, a DeltaSet key + tracker). +- **Merge** is cell by cell, needing the same dimensions, cell type and + schema; every row's column comes from one seeded hash (`HYDRA_SEED`), so + two grids built apart line up. + +| Variant | Inner cell (canonical) | Counter bytes | +|---|---|---| +| `hydra-cms` | Count-Min, cell 3 × 512 i32; grid 3 × 128 | `R·W·cell_rows·cell_cols·4` | +| `hydra-cs` | Count Sketch, same shape | same | +| `hydra-hll` | HLL, `p = 14` fixed | `R·W·2^14` | +| `hydra-kll` | KLL, `cell_k = 200` | `R·W·(slots(k)·8 + 62·8)` (no merge buffer; #191) | +| `hydra-univmon` | UnivMon: heap 1000, 5 × 2048, 8 layers; grid 2 × 8 | `R·W·layers·((sr·sc + sr)·8 + heap·entry)` | + +`hydra-univmon` is registered as four statistics: cardinality, L1, L2 and +entropy. Each footprint adds `(R·W + 1)` cell headers. + +## 2. Accuracy guarantee per combination + +### 2.1 The source of error + +For a subpopulation `q` (one group of `G_r`), in row `j` its cell also holds +every other subkey hashed there, the colliders `C_j`. Let: + +- `N_q`: items of `q`; `N_C`: items of the colliders in one row's cell; +- `M`: items inserted into one row, after fan-out: `N · (2^d − 1)` for `N` + records. A coarser label subset is inserted too, so every label added to + `Λ` roughly doubles `M`; +- `β`: a Markov factor. Modeling the column hash as random, + `E[N_C] = Σ_{s≠q} N_s / W ≤ M / W`, so `N_C ≤ β·M/W` in a row with + probability at least `1 − 1/β`; +- `δ_in`: the inner sketch's failure probability. + +The answer is the median over rows (the mean when `R = 2`). If more than +half the rows give answers inside one common interval, so does the median, +so a bound below holds when more than half the rows are **good**: their +contamination is within `β·M/W` and their inner sketch is within its own +bound. + +**Hydra's Theorem 2** (§4.5, checked against the paper): if each cell +estimates a **monotone G-sum** within `(1 ± ε_US)` with probability +`1 − δ_US`, then with `W = c(1 + ε_US)/ε` columns for a `c` with +`1 − δ_US − 1/c > 1/2`, and `R = O(log 1/δ)` rows, with probability +`1 − δ`, `G_q(1 − ε_US) ≤ Ĝ_q ≤ G_q(1 + ε_US) + ε·G_S`, where `G_S` is the +G-sum of the whole (fanned-out) stream. The proof takes the rows as +i.i.d. Three things about this library weaken it: + +- **Inner errors are correlated across rows.** Every cell is a clone of one + template, so the inner sketches hash with the same seeds (CMS and Count + Sketch matrix seed, HLL's seed, KLL's RNG state): `q`'s own items collide + the same way in every row. Only the contamination is independent across + rows. A sound confidence is + `P[Binomial(R, 1 − 1/β) > R/2] − R·δ_in`. +- **One fixed hash.** Columns come from one seeded hash (`HYDRA_SEED`), not + a random family, so the probabilities are a random-oracle heuristic, and + a group that collides badly collides in every window, merge and + deployment. For `W` not a power of two the column is not uniform (at + `W = 100` some columns get 1.56/W of the keys), so use the worst column's + share in place of `1/W`. +- **Few rows.** It is asymptotic in `R`. The canonical `hydra-cms`, + `hydra-cs`, `hydra-hll` and `hydra-kll` grids have `R = 3`: with + `β = 4` and `δ_in = 0.05` the bounds hold with probability about + `0.84 − 0.15 = 0.69`. The canonical `hydra-univmon` grid has `R = 2`, + `W = 8`: both rows must be good, and `β·M/W = 1.5·N`, so even its form is + vacuous. + +The error is **additive in the global mass** (`ε·G_S`, here `β·M/W`), not +relative to `q`. So a bound is useful only for groups large against +`β·M/W`. For the canonical `W = 128`, `d = 2` (`M = 3N`) and `β = 4`, +`β·M/W ≈ 0.094·N`: a group holding 1% of the records gets a contamination +term about 9× its own size. + +### 2.2 Bounds + +Derived from the setup above; only Theorem 2 is the paper's. `F_v` is the +fanned-out frequency of value `v` over all subkeys, `ΣD` the sum over all +subkeys of their distinct counts, and `D_q` the distinct count of `q`. + +| Combination | Statistic (sketch-bench metric) | Bound in a good row, so for the median | Closed form usable for planning? | +|---|---|---|---| +| `hydra-cms` | frequency of `v` in `q` (top-k ARE/AAE) | `f_q(v) ≤ f̂ ≤ f_q(v) + ε_c·N_q + β·(F_v + ε_c·M)/W`, `ε_c = e/cell_cols`, `δ_in = e^−cell_rows`. One-sided: never under. | Yes, for heavy (`q`, `v`) pairs; vacuous for small `f_q(v)`. | +| `hydra-cs` | same | `f̂ − f_q(v) ∈ [−ε_s·(L2_q + X), ε_s·L2_q + X']` with `ε_s ≈ 1/√cell_cols`, where the colliders' terms `X = L2_C` and `X' = f_C(v) + ε_s·L2_C` are bounded together by one Markov event (`E[F2_C] ≤ F2/W`, `E[f_C(v)] ≤ F_v/W`). Two-sided, biased upward by `f_C(v) ≥ 0`. | Yes, same caveat; not unbiased for `q`. | +| `hydra-hll` | distinct count of `q` (relative error) | `(1 − ε_h)·D_q ≤ D̂ ≤ (1 + ε_h)·(D_q + β·ΣD/W)`, `ε_h ≈ z·1.04/√2^14` (a normal approximation, not a hard bound). Cardinality is a monotone G-sum, so Theorem 2 applies. | Yes. The median removes contamination, not HLL noise (§2.1). | +| `hydra-univmon` cardinality, L1, L2 | `Σ 1[f>0]`, `Σ f`, `√Σ f²` | Theorem 2 directly (L2 via `F2 = Σ f²`: `√` of the bound). | Form only: `ε_US` for concrete heap, layers and widths is not known in closed form (UnivMon's Theorem 1 is asymptotic). Empirical. | +| `hydra-univmon` entropy | `log L1 − (Σ f log f)/L1` | None: a nonlinear combination of two G-sums, and contamination moves both. | No. Empirical only. | +| `hydra-kll` | rank error of `q`'s quantiles (`mean_rank_err`) | `|rank_q(x̂)/N_q − φ| ≤ ε_k + (1 + ε_k)·N_C/N_q`, `N_C ≤ β·M/W`: the cell answers the quantile of a mixture. | No: vacuous unless `N_q ≫ β·M/W`, and the real error depends on how the colliders' values overlap `q`'s. The paper states quantiles cannot be directly estimated by Hydra. Empirical only. | + +The KLL bound: the cell's KLL returns `x̂` with +`|rank_cell(x̂) − φ·N_cell| ≤ ε_k·N_cell`, `N_cell = N_q + N_C`, and +`rank_q(x̂) = rank_cell(x̂) − rank_C(x̂)` with `0 ≤ rank_C ≤ N_C`. + +So **no Hydra combination has a closed-form guarantee the planner can use +for every group**: CMS, CountSketch and HLL have bounds that are vacuous for +small groups; UnivMon and KLL have none. Admission must be empirical (§2.4), +and these bounds serve as sanity checks on the measurements. + +### 2.3 Merges and coarse groupings + +- **Across windows and ingest workers.** CMS and CountSketch add counters, + and HLL takes register maxima; with the shared seeds, a merged grid equals + one built from all the records, so merged accuracy is the single-grid + accuracy at the merged mass. KLL cells merge lossily (as `kll-percall`, + #131) and UnivMon rebuilds heaps from the union of candidates, so both + need measured merge curves. +- **Coarse groupings.** A grouping inside `Λ` is answered directly, because + its subkey was inserted; Hydra never rolls up, which is why + `mergeable_across_groups` is false. The cost is mass: every coarser subset + inserted adds to `M`, and so to every group's contamination. A grouping + not inside `Λ` cannot be answered. + +### 2.4 The accuracy predicate + +Because only empirical accuracy is usable, a Hydra edge is eligible only if +a measurement covers it: + +```text +hydra_error(variant, config (R, W, inner), |Λ|, G_r, shape(G_r), + N_q distribution, M, merged windows) <= the RAQE's SLA +``` + +in the family's metric and direction, with no borrowing from a +non-Hydra curve or another grouping. One `subpopulations` ceiling (today's +`hydra-kll` eligibility) is not enough: two groupings of equal cardinality +differ in skew and fan-out. Since error is driven by `N_q / (M / W)`, the +measurement should report error by group size, and the SLA must say which +groups it covers (§6). + +## 3. Cost model + +Hydra is priced by [Cost models](rqe_optimizer_cost_model.md) §3's table, +with no separate formula. One grid is one instance per window, so +`I_d = I_r = 1`, and a query probes it once per `card(G_r)` group. Let +`m_h`, `c_ins,h`, `c_mrg,h` and `c_probe,h(G_r)` be measured for one +variant, configuration and schema width `|Λ|`; `c_ins,h` is per record, fan-out +included (`R · (2^|Λ| − 1)` inner inserts). + +| Phase | CPU-seconds per event | Mean vCPUs | Memory (bytes) | +|---|---|---|---| +| Ingest | — | `λ · a_D · c_ins,h` | `m_h · a_D · k_D` | +| Compaction | `(k_D − 1) · c_mrg,h` | `/ y_D` | `k_D · m_h`, while it runs | +| Query job | `card(G_r) · c_probe,h(G_r) + (n_{i,D} − 1) · c_mrg,h` | `/ T_i` | `m_h · [n_{i,D} > 1] + card(G_r) · output bytes`, while it runs | +| Storage | — | 0 | `m_h · ((max_i S_i − x_D) / y_D + 1)` | + +plus the key tracker's part. A Hydra merge combines whole grids, not +`card(G_d)` addressable states, which is what `I_d = 1` says. This assumes +the merge cost does not depend on the number of probes; sketch-bench must +confirm it or report a probe-count term. + +**Key tracker.** If groups are listed by a DeltaSet (`exact-delta-set`), its +ingest, compaction, merge, query and storage are added as a part. A tracker +at `Λ` that derives coarse keys costs `card(Λ)` per window, not +`card(G_r)`; a tracker per requested grouping costs `card(G_r)` each but +multiplies trackers. This is a decision (§6), not a free operation. + +## 4. Candidates and the MILP + +The MILP does not change: one binary `z_{i,D}` per eligible edge, one +`u_D` per candidate, `stored_D`, the same constraints and objective +([Cost models](rqe_optimizer_cost_model.md) §7). Hydra adds candidates and +edges with their own eligibility and coefficients. + +- **Candidate identity.** `(capability, variant + config, metric, spatial + filter, Λ, x, y, key tracker)`: the schema `Λ` takes the place of the + grouping. `Λ` is an ordered list: the library encodes subkeys in its + declaration order, merges only grids of the same order, and the wrapper's + prefix queries depend on it. So `Λ` needs its own ordered field (a + `LabelSet` loses the order), plus a new family property (e.g. + `answers_any_subgrouping`) that marks Hydra. +- **Generation.** For each (capability, metric, filter), `Λ` ranges over + every distinct RAQE grouping and their union (more schemas cost more, + since `M` and `c_ins,h` grow with `|Λ|`). Windows and slides come, as for + roll-ups, from the RAQEs whose grouping is a non-empty subset of `Λ`. +- **Edge `(i, D)`.** Same capability, metric and filter; `∅ ≠ G_i ⊆ Λ` + (a prefix of `Λ` until the wrapper queries any subset); window alignment + as today; and the §2.4 predicate measured and passing. +- **Linearity.** An edge's accuracy depends only on the candidate (`Λ`, + config, window) and the metric's mass, never on which other RAQEs share + it: everything on the metric and filter is inserted whatever is selected. + So eligibility stays a per-edge filter and the MILP stays linear. +- **Coefficients.** Per candidate: ingest, compaction, storage (§3, plus the + tracker). Per edge: the query job, with `c_probe,h(G_i)`. A Hydra edge is + never priced or validated as a roll-up. +- **Pruning.** Unchanged: candidates compare only at the same capability, + metric, filter and grouping (here `Λ`), on the costs listed in + [candidates](rqe_optimizer_candidates.md). +- **Competition.** A quantile RAQE by `(service)` can then be served by KLL + at `(service)`, by KLL at `(service, endpoint)` through a roll-up, or by + Hydra with `Λ ⊇ {service}`; the MILP picks the cheapest that passes. + +Code this needs, in order: `FamilyProperties` for the four other variants; +the new property and the Hydra branch in `is_eligible` and +`build_all_candidates_unpruned`; Hydra in `Capability::families` and +`DEPLOYABLE_FAMILIES`; the saturation lookup keyed as in §2.4; cost-table +rows. AutoSketch keeps skipping Hydra (#159). + +## 5. What sketch-bench must add + +Each item names what is missing today. These apply when Hydra admission is +taken up: current sketch-bench work does not measure or model `hydra-kll`. + +1. **Target grouping.** Comparators score only column 0 + (`aqpbm-cli/src/rows/mod.rs`); they must score any named subset of the + schema, and the wrapper must query any subset, not only prefixes + (`hydra_shared.rs` `query`). +2. **Exact baseline.** The `polars` baselines build untagged subkeys + (`polars_shared.rs`), so overlapping label values alias there but not in + the 0.3.0 sketch (#74); tag them the same way. +3. **Data.** Hierarchical labels with set cardinality per label, per-parent + fan-out and skew; the result records `|Λ|`, the target grouping's + cardinality, every group's `N_q`, and the fanned-out mass `M`. +4. **Sweep.** Grid (`R`, `W`), inner parameters, schema width, target + grouping, cardinality and fan-out, distribution. Report error per group + against `N_q / (M / W)`, and quantiles over groups, not only the mean. + The column hash has a fixed seed, so vary the label values (not only the + data seed) to see the spread over collision patterns. +5. **Bounds as checks.** For CMS, CountSketch and HLL, assert the measured + per-group error is within §2.2's bound at its confidence; a violation + means a bug. +6. **Merges.** Accuracy and cost of merged grids at the shard counts + workloads need, with records split by sample (interleaved), not only in + contiguous chunks (`sketch-bench/src/wrappers/mod.rs`); exactness checks + for CMS, CountSketch and HLL; merge curves for KLL and UnivMon cells. +7. **Cost table.** Hydra rows in `study_saturation.py` (`SKETCHES`, + `OPTIMIZER_FAMILIES`) and `approxbench atomic-costs`: `m_h` (including + each KLL cell's merge buffer, #191), `c_ins,h` per record at the schema + width, `c_mrg,h`, and `c_probe,h` per probe at the target grouping. +8. **Key enumeration.** Benchmark the chosen tracker (§6) at its grouping, + with its input and output cardinality. +9. **Saturation key.** Emit §2.4's fields machine-readably. The optimizer + rejects a Hydra edge with no matching point unless an interpolation rule + is approved (§6). +10. **Fixtures.** Equal grouping, a direct coarse subset, and a multi-window + merge, each against exact answers, asserting the exported accuracy and + cost fields. + +## 6. Decisions needed + +1. Group enumeration: one DeltaSet at `Λ` that derives coarse keys, or one + per requested grouping? +2. Groupings: prefixes of `Λ` only, or any non-empty subset once the wrapper + and comparators support it? +3. Which groups an SLA covers: every group (then Hydra almost never passes + for small groups), groups above a size, or a quantile over groups? +4. Interpolation between measured Hydra points: none, or the worse + bracketing point as for the other sketches? +5. Schemas generated per workload: each RAQE grouping and their union, or + more? +6. Whether `hydra-univmon` entropy, which has no bound, is admitted at all. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index de5a96e6..9cf7b80b 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -31,11 +31,16 @@ and per-RAQE latency. - **Deployment**: a configuration run over one metric, grouped by `G`, with window `x` and slide `y`. A **candidate** is a deployment the optimizer may choose. -- **Phase**: one of the four kinds of work a deployment does, each costed in - CPU and memory: **ingest** (inserting samples into open instances), - **merge** (folding a query's windows into an accumulator), **query** - (reading the merged result) and **storage** (keeping closed instances, no - CPU). See [Cost model](rqe_optimizer_cost_model.md). +- **Phase**: one of the kinds of work a deployment does, each costed in CPU + and memory: **ingest** (inserting samples into open instances), + **compaction** (merging the ingest workers' copies of a closed window), + the **query job** (merging a query's windows, and on a roll-up its fine + groups, then reading the result) and **storage** (keeping closed + instances, no CPU). The snapshot objective and `PlanCost` report the query + job as two phases, **merge** and **query**, and have no compaction. See + [Cost models](rqe_optimizer_cost_model.md). +- **Roll-up**: a deployment grouped by `G_d` serving a RAQE grouped by a + subset `G_r`, by merging each coarse group's fine instances at query time. ## Inputs @@ -141,21 +146,25 @@ modeled. ## Planning design -The optimizer has two companion design documents: +The optimizer has three companion design documents: -- [Candidate generation and mapping](rqe_optimizer_candidates.md): candidate construction, eligibility, finer-to-coarser roll-ups, dominance pruning, and the assignment MILP. -- [Cost models](rqe_optimizer_cost_model.md): the canonical cost-by-use and - batch-latency model, the supported snapshot-AUC objective and shared - resource primitives, and the future Hydra admission requirements. - -The v1 implementation supports only the conventional roll-up path described in the candidate and cost-model documents. Hydra is not part of #190. +- [Candidate generation and eligibility](rqe_optimizer_candidates.md): + candidate construction, eligibility (accuracy included), finer-to-coarser + roll-ups and dominance pruning. +- [Cost models](rqe_optimizer_cost_model.md): the one cost table, the + canonical cost-by-use and batch-latency model with its MILP, and the + supported snapshot-AUC objective. +- [Hydra](rqe_optimizer_hydra.md): what admitting Hydra needs (accuracy + guarantees per combination, cost model, candidates and MILP edges, and + sketch-bench measurements). Not implemented. ## Procedure 1. Generate candidate deployments for each input RAQE, then deduplicate them. 2. Build the eligible candidate–RAQE pairs. Reject pairs that fail capability, - metric, grouping, window alignment, or empirical accuracy. + metric, grouping (equal, or a subset for a roll-up), window alignment, or + accuracy. 3. Enumerate feasible workload mappings. Every RAQE must select one eligible candidate; a single selected candidate may serve multiple RAQEs. Small instances may retain every mapping eagerly; larger ones stream mappings @@ -169,25 +178,29 @@ The Pareto vector is: (CPU, memory, {latency_i}) ``` -CPU and memory are the sums over the four phases. The report also includes +CPU and memory are the sums over the snapshot objective's phases (ingest, merge, query, storage). The report also includes each phase's CPU and memory, together with the selected deployment mapping. ## v1 scope and TODOs -- **Accuracy after merging:** KLL and top-k are planned only up to the - largest shard count and N the study measured merge curves at (#158). +- **Accuracy after merging:** KLL reads its merge curves up to the largest + shard count and N the study measured; past them, the guarantee, no better + than the last measurement. Roll-ups multiply the merge count by the + fan-out, so they reach the guarantee sooner. Heap top-k reads its plain + curve (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. - **Latency SLAs:** `minimize` takes optional per-RAQE latency bounds; - `minimize_usage_cost` has none and reports the batch latency (above). The - enumerator reports latency but does not reject a mapping for it. -- **Memory model:** query memory sums every RAQE's merge and output memory, as - if all queries run at once; real concurrency is not modeled. Query output - size is an estimate. + `minimize_usage_cost` takes an optional batch-latency bound and reports the + batch latency. The enumerator reports latency but does not reject a + mapping for it. +- **Memory model:** cost by use holds query memory only while a query runs; + the snapshot objective sums every RAQE's merge and output memory as if all + queries ran at once. Query output size is an estimate. - **Bursts:** CPU is a mean over time, so plans are sized for average load. - **Static planning:** no RAQE churn, replanning, or migration cost. -- **Rollups:** v1 does not precompute merged rollups. Queries merge their - selected base instances when they run. +- **Temporal pre-merging:** v1 does not precompute merged windows. Queries + merge their selected base instances when they run. - **Selection policy:** the enumerator reports the Pareto frontier; the MILP selects one point by the `w_cpu`/`w_mem` weights. @@ -197,9 +210,8 @@ each phase's CPU and memory, together with the selected deployment mapping. generation and pruning, eligibility checks, analytical objectives, and streaming Pareto filtering. The separation between candidate generation, enumeration, objectives, and Pareto filtering remains the intended boundary -for future solver work. The candidate and cost-model documents also distinguish -these conventional fine-state roll-ups from the future Hydra -shared-subpopulation deployment. +for future solver work. Hydra, a shared-subpopulation deployment rather than +a fine-state roll-up, is designed in [Hydra](rqe_optimizer_hydra.md). Exporter bugs, benchmark-dataset choices, and historic run counts belong in `rqe_optimizer_TODO.md` or issue tracking, not in this problem statement. From f6ce9b7843292c38bb0ddfaad1e9592680338f76 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 02:03:11 +0000 Subject: [PATCH 08/13] rqe-optimizer: univmon-cardinality merges lossily; increase's real reason UnivMon's counters add exactly on merge, 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: a merged (or rolled-up) answer now reads merge curves, as KLL's does. exact-increase's accumulator merge joins two pieces of one counter in time, so merging two groups' counters is wrong; say so instead of "unconfirmed". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_candidates.md | 3 ++- rqe-optimizer/src/lib.rs | 7 ++++--- rqe-optimizer/src/saturation.rs | 18 ++++++++++++++++-- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index 520eac85..a88b5adc 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -108,7 +108,8 @@ roll-up the answered group is the RAQE's coarse one. refuses a curve for another metric as a stale study. - For sketches that merge exactly, the window size doesn't matter: a merged answer reads the curve at the lookback's item count, like a single sketch. - KLL merges lossily (#131): an answer merged from `n = S_i / D.x` windows, + KLL and univmon-cardinality merge lossily (#131; UnivMon rebuilds its + heavy-hitter heaps from the union of the merged heaps): an answer merged from `n = S_i / D.x` windows, times the average fan-out `⌈card(D.G) / card(G_i)⌉` on a roll-up, reads the study's merge curve (`saturation_merge_curve.csv`, the sketch merged from `n` shards of the same items) at the lookback's item count. Between diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 07df21f8..d4a40354 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -252,9 +252,10 @@ pub fn family_properties(variant: &str) -> FamilyProperties { }; match variant { "exact-sum" | "exact-min" | "exact-max" => exact, - // Not rolled up, conservatively: summing per-series increases would - // give the coarse answer, but whether ASAPQuery's increase - // accumulator keeps them per series is unconfirmed. + // Not rolled up: its merge joins two pieces of one counter in time + // (the later start after a drop is a reset), so merging two groups' + // counters is wrong. A coarse increase is the sum of per-series + // increases, which needs per-series state and a sum, not this merge. "exact-increase" => FamilyProperties { mergeable_across_groups: false, ..exact diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index a6785d43..76577b43 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -213,12 +213,16 @@ fn curve_error_at( } } -/// KLL and the heap top-k sketches lose accuracy when merged (#131): a -/// merged answer reads their merge curve. The other sketches merge exactly. +/// KLL, the heap top-k sketches and UnivMon lose accuracy when merged +/// (#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. fn merges_lossily(sketch: &str) -> bool { matches!( sketch, "kll-percall" + | "univmon-cardinality" | "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" | "univmon-topk" @@ -828,6 +832,16 @@ mod tests { const TOPK: &str = "cms-heap-topk-fastpath-vector2d"; + /// UnivMon's heaps are rebuilt on merge, so its cardinality reads merge + /// curves like KLL; HLL's register max and DDSketch's bucket sums are + /// exact. + #[test] + fn univmon_cardinality_merges_lossily_hll_and_dd_do_not() { + assert!(merges_lossily("univmon-cardinality")); + assert!(!merges_lossily("hll")); + assert!(!merges_lossily("dd")); + } + /// Top-k rows=3 cols=1024 at θ ∈ {1.0, 1.2}, K ∈ {1e3, 1e5}. Precision /// falls with N; θ = 1.0 is worse, and K = 1e5 never saturates. Merged /// from 4 shards it loses 0.02 more, from 16 shards 0.1. From d28910952020af15c7d45c52a88eadab9b55a583 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 02:28:32 +0000 Subject: [PATCH 09/13] rqe-optimizer: check group counts only between label sets a plan uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validate_facts compared every pair of label sets in a metric's cardinality map, so an inconsistent entry no RAQE groups by rejected the whole workload. The roll-up merge count only reads RAQE groupings and the full label set, so check X ⊂ Y among those. Docs: why rate/increase, top-k and Hydra don't roll up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_candidates.md | 26 +++++++++--- rqe-optimizer/src/lib.rs | 72 ++++++++++++++++++++++++-------- 2 files changed, 76 insertions(+), 22 deletions(-) diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index a88b5adc..3db82c21 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -205,10 +205,24 @@ A deployment grouped by `G_d` can answer a RAQE grouped by `G_r ⊂ G_d` when its family merges across groups (`mergeable_across_groups`): at query time, the fine instances of each coarse group are merged into one, then answered. This is a **roll-up**. Families that do: exact sum/min/max, HLL, -univmon-cardinality, KLL and DDSketch. Rate/increase and top-k (CMS-heap, -CountSketch-heap, univmon-topk) serve only `G_r = G_d`. Hydra never rolls -up: it would answer subsets of its schema directly -([Hydra](rqe_optimizer_hydra.md)). +univmon-cardinality, KLL and DDSketch. These don't, and serve only +`G_r = G_d`: + +- **Rate/increase** (`exact-increase`). A coarse increase is the sum of its + series' increases, `Σ_s increase_s`, so it is not the increase of the + summed counter: a reset in one series is hidden by the others' growth. + The accumulator tracks one counter, and its merge joins two pieces of it + in time (a drop at the seam is a reset), so merging two groups' counters + is wrong: A going 100 → 110 and B going 5 → 8 over the same minute merge + to 10, not 13. A roll-up would need per-series state and a sum of values, + not this merge. (ASAPQuery keys `MultipleIncrease` per series: it plans + only bare `rate`/`increase`, which keep every label.) +- **Top-k** (CMS-heap, CountSketch-heap, univmon-topk). A coarse group's top + `k` can hold keys that are in none of its fine groups' heaps. +- **Hydra**. It inserts every label subset of its schema, so a coarse + grouping inside the schema is answered directly from the grid, never by + merging fine groups; it is not a candidate today + ([Hydra](rqe_optimizer_hydra.md)). - **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 @@ -219,6 +233,8 @@ up: it would answer subsets of its schema directly merged instances, the average fan-out, an estimate rather than a worst-group bound (uneven fan-out is #189). - **Facts**: `validate_facts` requires `card(X) ≤ card(Y)` for every pair - `X ⊂ Y` of label sets, so a merge count is never negative. + `X ⊂ Y` among the label sets a plan can use (every RAQE grouping on the + metric, and its full label set), so a merge count is never negative. + Label sets no RAQE groups by are not checked. - **Plan output**: a RAQE rolls up exactly when its grouping differs from its deployment's. diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index d4a40354..1bcd3bca 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -386,15 +386,32 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec false, }; } - // Dropping labels never adds groups. A roll-up's merge count, - // `card(G_d) · L/x − card(G_r)`, relies on it. - for (coarse, &coarse_groups) in cardinality { - for (fine, &fine_groups) in cardinality { - if coarse.is_subset(fine) && coarse_groups > fine_groups { - problems.insert(format!( - "{metric}: {coarse:?} has {coarse_groups} groups but its superset \ - {fine:?} only {fine_groups}" - )); + } + // 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 + // the label sets a plan can use: every RAQE grouping on the metric, and + // its full label set. A label set no RAQE groups by is never read. + let mut used: BTreeMap<&str, BTreeSet<&LabelSet>> = BTreeMap::new(); + for raqe in raqes { + if let Some(metric_facts) = facts.get(&raqe.metric) { + used.entry(&raqe.metric) + .or_insert_with(|| BTreeSet::from([&metric_facts.labels])) + .insert(&raqe.grouping_labels); + } + } + for (metric, label_sets) in &used { + let cardinality = &facts[*metric].cardinality; + for coarse in label_sets { + for fine in label_sets { + if let (Some(&coarse_groups), Some(&fine_groups)) = + (cardinality.get(*coarse), cardinality.get(*fine)) + { + if coarse.is_subset(fine) && coarse_groups > fine_groups { + problems.insert(format!( + "{metric}: {coarse:?} has {coarse_groups} groups but its superset \ + {fine:?} only {fine_groups}" + )); + } } } } @@ -934,10 +951,10 @@ mod tests { ); } - /// Every label set, not just the full one, bounds its subsets' groups. - #[test] - fn rejects_a_label_set_with_more_groups_than_its_superset() { - let facts = WorkloadFacts::from([( + /// Facts where `(service)` has more groups than its superset + /// `(service, endpoint)`, and `(pod)` has none at all. + fn inconsistent_facts() -> WorkloadFacts { + WorkloadFacts::from([( METRIC.to_string(), MetricFacts { labels: labels(&["service", "endpoint", "pod"]), @@ -945,22 +962,43 @@ mod tests { cardinality: BTreeMap::from([ (labels(&["service"]), 60), (labels(&["service", "endpoint"]), 50), + (labels(&["pod"]), 0), (labels(&["service", "endpoint", "pod"]), 30_000), ]), value_range: None, data_shape: BTreeMap::new(), }, - )]); - let r = Raqe { - grouping_labels: labels(&["service"]), + )]) + } + + /// Between two RAQE groupings, the subset may not have more groups. + #[test] + fn rejects_a_used_label_set_with_more_groups_than_a_used_superset() { + let grouped = |l: &[&str]| Raqe { + grouping_labels: labels(l), ..raqe(60_000, 60_000) }; assert_eq!( - validate_facts(&[r], &facts).unwrap_err(), + validate_facts( + &[grouped(&["service"]), grouped(&["service", "endpoint"])], + &inconsistent_facts() + ) + .unwrap_err(), [format!( "{METRIC}: {{\"service\"}} has 60 groups but its superset \ {{\"endpoint\", \"service\"}} only 50" )] ); } + + /// Label sets no RAQE groups by are never read, so inconsistencies there + /// don't reject the workload. + #[test] + fn ignores_label_sets_no_raqe_uses() { + let r = Raqe { + grouping_labels: labels(&["service"]), + ..raqe(60_000, 60_000) + }; + assert_eq!(validate_facts(&[r], &inconsistent_facts()), Ok(())); + } } From 25b34b31c83747370b75bad0332f127d86762a11 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 02:44:36 +0000 Subject: [PATCH 10/13] docs(hydra): hydra-kll is measured in the same Hydra rerun Every Hydra measurement predates the admission requirements, so they are all rerun; hydra-kll goes in that run with the other four variants. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_hydra.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/rqe_optimizer_hydra.md b/docs/rqe_optimizer_hydra.md index fa4e777c..dc3b7945 100644 --- a/docs/rqe_optimizer_hydra.md +++ b/docs/rqe_optimizer_hydra.md @@ -226,8 +226,10 @@ rows. AutoSketch keeps skipping Hydra (#159). ## 5. What sketch-bench must add -Each item names what is missing today. These apply when Hydra admission is -taken up: current sketch-bench work does not measure or model `hydra-kll`. +Each item names what is missing today. Every Hydra measurement sketch-bench +has today predates these requirements, so admitting Hydra means rerunning +them all; `hydra-kll` is measured in that same run, alongside `hydra-cms`, +`hydra-cs`, `hydra-hll` and `hydra-univmon`, under every item below. 1. **Target grouping.** Comparators score only column 0 (`aqpbm-cli/src/rows/mod.rs`); they must score any named subset of the From c02a7dedef2ade9bf04bdc0596ad9f1006b1d51e Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 02:54:28 +0000 Subject: [PATCH 11/13] docs: move the Hydra admission design out of this PR Keep #190 to roll-ups. docs/rqe_optimizer_hydra.md and its links move to a separate PR stacked on this one; the docs here only say Hydra is future work and doesn't roll up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_TODO.md | 2 +- docs/rqe_optimizer_candidates.md | 6 +- docs/rqe_optimizer_cost_model.md | 8 +- docs/rqe_optimizer_hydra.md | 281 ------------------------------- docs/rqe_sketch_deployment_v1.md | 7 +- 5 files changed, 8 insertions(+), 296 deletions(-) delete mode 100644 docs/rqe_optimizer_hydra.md diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index d2f62855..8d230e00 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -56,7 +56,7 @@ implemented, what is next, and what is intentionally deferred. - Real query concurrency in the snapshot objective, whose memory assumes every query runs at once (cost by use holds query memory only while it runs). - Bursty load; CPU is a mean over time. -- Admitting Hydra ([rqe_optimizer_hydra.md](rqe_optimizer_hydra.md)). +- Admitting Hydra. - Key labels `K` (PerGroup + PerKey sizes). - RQE churn, replanning, and migration cost. - Precomputed rollups; v1 merges selected base instances at query time. diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index 3db82c21..da034e05 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -3,8 +3,7 @@ This document is the canonical design for candidate construction, eligibility (accuracy included), finer-to-coarser roll-ups and dominance pruning. What a candidate costs, and the MILP that maps RAQEs to candidates, are in -[Cost models](rqe_optimizer_cost_model.md); Hydra is in -[Hydra](rqe_optimizer_hydra.md). +[Cost models](rqe_optimizer_cost_model.md). ## Candidate deployments @@ -221,8 +220,7 @@ univmon-cardinality, KLL and DDSketch. These don't, and serve only `k` can hold keys that are in none of its fine groups' heaps. - **Hydra**. It inserts every label subset of its schema, so a coarse grouping inside the schema is answered directly from the grid, never by - merging fine groups; it is not a candidate today - ([Hydra](rqe_optimizer_hydra.md)). + merging fine groups; it is not a candidate today. - **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 0f6a5fdc..4e1830a8 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -3,8 +3,7 @@ This document is the one home for what a candidate costs (§3's table), the canonical cost-by-use model with its MILP, and the still-supported snapshot-AUC objective. Candidates and eligibility are in -[Candidate generation and eligibility](rqe_optimizer_candidates.md); Hydra -is in [Hydra](rqe_optimizer_hydra.md). +[Candidate generation and eligibility](rqe_optimizer_candidates.md). ## Model status and relationship @@ -18,8 +17,7 @@ is in [Hydra](rqe_optimizer_hydra.md). query memory is summed as if concurrent, there is no worker fan-out or compaction, and latency is serial query work. It is not the evaluation's billing model. -- **Hydra** is future work, not a candidate today; see - [Hydra](rqe_optimizer_hydra.md). +- **Hydra** is future work, not a candidate today. 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 @@ -399,7 +397,7 @@ follows from it): | 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; see [Hydra](rqe_optimizer_hydra.md). +is never a candidate. ### Family properties and key tracker diff --git a/docs/rqe_optimizer_hydra.md b/docs/rqe_optimizer_hydra.md deleted file mode 100644 index dc3b7945..00000000 --- a/docs/rqe_optimizer_hydra.md +++ /dev/null @@ -1,281 +0,0 @@ -# RQE optimizer: admitting Hydra - -Status: design, not implemented. Hydra is never a candidate today: -`hydra-kll` has `FamilyProperties` (`rqe-optimizer/src/lib.rs`) but is in no -capability's family list, and the other four Hydra variants have none. This -document says, for each Hydra combination sketch-bench benchmarks, what -accuracy guarantee it has, how it is costed, how it would enter the -candidates and the MILP, and what sketch-bench must measure first. Symbols -follow [Cost models](rqe_optimizer_cost_model.md) §1; `Λ` is a Hydra -schema (the hyperperiod there is `H`). - -## 1. What Hydra is in sketch-bench - -All five combinations wrap `asap_sketchlib::Hydra` (0.3.0; Manousis et al., -VLDB 2022, arXiv:2208.04927). The `polars` rows of the same names are exact -baselines. - -- **Grid.** `R` rows × `W` columns of cells, each an inner sketch, over a - schema `Λ` of label columns (`hydra_shared.rs`). -- **Insert fans out.** A record with `|Λ| = d` labels is inserted into the - cell of every non-empty label subset (`2^d − 1` subkeys, each tagged with - its column names), in every row: `R · (2^d − 1)` inner inserts per record - (`hydra.rs` `update`, masks `1..2^d`). The empty grouping (the whole - stream) is not inserted. -- **Query.** A subpopulation (values for a subset `G_r ⊆ Λ`, the rest - unconstrained) hashes to one cell per row; the answer is the **median** - over the `R` rows of each cell's inner answer (`query_key`). The library - answers any non-empty subset of `Λ`; sketch-bench's wrapper constrains - only leading columns (`hydra_shared.rs` `query`), so it can ask only - prefix groupings. -- **No keys.** Hydra stores no subpopulation keys. To answer every group of - `G_r`, something else must list them (in the optimizer, a DeltaSet key - tracker). -- **Merge** is cell by cell, needing the same dimensions, cell type and - schema; every row's column comes from one seeded hash (`HYDRA_SEED`), so - two grids built apart line up. - -| Variant | Inner cell (canonical) | Counter bytes | -|---|---|---| -| `hydra-cms` | Count-Min, cell 3 × 512 i32; grid 3 × 128 | `R·W·cell_rows·cell_cols·4` | -| `hydra-cs` | Count Sketch, same shape | same | -| `hydra-hll` | HLL, `p = 14` fixed | `R·W·2^14` | -| `hydra-kll` | KLL, `cell_k = 200` | `R·W·(slots(k)·8 + 62·8)` (no merge buffer; #191) | -| `hydra-univmon` | UnivMon: heap 1000, 5 × 2048, 8 layers; grid 2 × 8 | `R·W·layers·((sr·sc + sr)·8 + heap·entry)` | - -`hydra-univmon` is registered as four statistics: cardinality, L1, L2 and -entropy. Each footprint adds `(R·W + 1)` cell headers. - -## 2. Accuracy guarantee per combination - -### 2.1 The source of error - -For a subpopulation `q` (one group of `G_r`), in row `j` its cell also holds -every other subkey hashed there, the colliders `C_j`. Let: - -- `N_q`: items of `q`; `N_C`: items of the colliders in one row's cell; -- `M`: items inserted into one row, after fan-out: `N · (2^d − 1)` for `N` - records. A coarser label subset is inserted too, so every label added to - `Λ` roughly doubles `M`; -- `β`: a Markov factor. Modeling the column hash as random, - `E[N_C] = Σ_{s≠q} N_s / W ≤ M / W`, so `N_C ≤ β·M/W` in a row with - probability at least `1 − 1/β`; -- `δ_in`: the inner sketch's failure probability. - -The answer is the median over rows (the mean when `R = 2`). If more than -half the rows give answers inside one common interval, so does the median, -so a bound below holds when more than half the rows are **good**: their -contamination is within `β·M/W` and their inner sketch is within its own -bound. - -**Hydra's Theorem 2** (§4.5, checked against the paper): if each cell -estimates a **monotone G-sum** within `(1 ± ε_US)` with probability -`1 − δ_US`, then with `W = c(1 + ε_US)/ε` columns for a `c` with -`1 − δ_US − 1/c > 1/2`, and `R = O(log 1/δ)` rows, with probability -`1 − δ`, `G_q(1 − ε_US) ≤ Ĝ_q ≤ G_q(1 + ε_US) + ε·G_S`, where `G_S` is the -G-sum of the whole (fanned-out) stream. The proof takes the rows as -i.i.d. Three things about this library weaken it: - -- **Inner errors are correlated across rows.** Every cell is a clone of one - template, so the inner sketches hash with the same seeds (CMS and Count - Sketch matrix seed, HLL's seed, KLL's RNG state): `q`'s own items collide - the same way in every row. Only the contamination is independent across - rows. A sound confidence is - `P[Binomial(R, 1 − 1/β) > R/2] − R·δ_in`. -- **One fixed hash.** Columns come from one seeded hash (`HYDRA_SEED`), not - a random family, so the probabilities are a random-oracle heuristic, and - a group that collides badly collides in every window, merge and - deployment. For `W` not a power of two the column is not uniform (at - `W = 100` some columns get 1.56/W of the keys), so use the worst column's - share in place of `1/W`. -- **Few rows.** It is asymptotic in `R`. The canonical `hydra-cms`, - `hydra-cs`, `hydra-hll` and `hydra-kll` grids have `R = 3`: with - `β = 4` and `δ_in = 0.05` the bounds hold with probability about - `0.84 − 0.15 = 0.69`. The canonical `hydra-univmon` grid has `R = 2`, - `W = 8`: both rows must be good, and `β·M/W = 1.5·N`, so even its form is - vacuous. - -The error is **additive in the global mass** (`ε·G_S`, here `β·M/W`), not -relative to `q`. So a bound is useful only for groups large against -`β·M/W`. For the canonical `W = 128`, `d = 2` (`M = 3N`) and `β = 4`, -`β·M/W ≈ 0.094·N`: a group holding 1% of the records gets a contamination -term about 9× its own size. - -### 2.2 Bounds - -Derived from the setup above; only Theorem 2 is the paper's. `F_v` is the -fanned-out frequency of value `v` over all subkeys, `ΣD` the sum over all -subkeys of their distinct counts, and `D_q` the distinct count of `q`. - -| Combination | Statistic (sketch-bench metric) | Bound in a good row, so for the median | Closed form usable for planning? | -|---|---|---|---| -| `hydra-cms` | frequency of `v` in `q` (top-k ARE/AAE) | `f_q(v) ≤ f̂ ≤ f_q(v) + ε_c·N_q + β·(F_v + ε_c·M)/W`, `ε_c = e/cell_cols`, `δ_in = e^−cell_rows`. One-sided: never under. | Yes, for heavy (`q`, `v`) pairs; vacuous for small `f_q(v)`. | -| `hydra-cs` | same | `f̂ − f_q(v) ∈ [−ε_s·(L2_q + X), ε_s·L2_q + X']` with `ε_s ≈ 1/√cell_cols`, where the colliders' terms `X = L2_C` and `X' = f_C(v) + ε_s·L2_C` are bounded together by one Markov event (`E[F2_C] ≤ F2/W`, `E[f_C(v)] ≤ F_v/W`). Two-sided, biased upward by `f_C(v) ≥ 0`. | Yes, same caveat; not unbiased for `q`. | -| `hydra-hll` | distinct count of `q` (relative error) | `(1 − ε_h)·D_q ≤ D̂ ≤ (1 + ε_h)·(D_q + β·ΣD/W)`, `ε_h ≈ z·1.04/√2^14` (a normal approximation, not a hard bound). Cardinality is a monotone G-sum, so Theorem 2 applies. | Yes. The median removes contamination, not HLL noise (§2.1). | -| `hydra-univmon` cardinality, L1, L2 | `Σ 1[f>0]`, `Σ f`, `√Σ f²` | Theorem 2 directly (L2 via `F2 = Σ f²`: `√` of the bound). | Form only: `ε_US` for concrete heap, layers and widths is not known in closed form (UnivMon's Theorem 1 is asymptotic). Empirical. | -| `hydra-univmon` entropy | `log L1 − (Σ f log f)/L1` | None: a nonlinear combination of two G-sums, and contamination moves both. | No. Empirical only. | -| `hydra-kll` | rank error of `q`'s quantiles (`mean_rank_err`) | `|rank_q(x̂)/N_q − φ| ≤ ε_k + (1 + ε_k)·N_C/N_q`, `N_C ≤ β·M/W`: the cell answers the quantile of a mixture. | No: vacuous unless `N_q ≫ β·M/W`, and the real error depends on how the colliders' values overlap `q`'s. The paper states quantiles cannot be directly estimated by Hydra. Empirical only. | - -The KLL bound: the cell's KLL returns `x̂` with -`|rank_cell(x̂) − φ·N_cell| ≤ ε_k·N_cell`, `N_cell = N_q + N_C`, and -`rank_q(x̂) = rank_cell(x̂) − rank_C(x̂)` with `0 ≤ rank_C ≤ N_C`. - -So **no Hydra combination has a closed-form guarantee the planner can use -for every group**: CMS, CountSketch and HLL have bounds that are vacuous for -small groups; UnivMon and KLL have none. Admission must be empirical (§2.4), -and these bounds serve as sanity checks on the measurements. - -### 2.3 Merges and coarse groupings - -- **Across windows and ingest workers.** CMS and CountSketch add counters, - and HLL takes register maxima; with the shared seeds, a merged grid equals - one built from all the records, so merged accuracy is the single-grid - accuracy at the merged mass. KLL cells merge lossily (as `kll-percall`, - #131) and UnivMon rebuilds heaps from the union of candidates, so both - need measured merge curves. -- **Coarse groupings.** A grouping inside `Λ` is answered directly, because - its subkey was inserted; Hydra never rolls up, which is why - `mergeable_across_groups` is false. The cost is mass: every coarser subset - inserted adds to `M`, and so to every group's contamination. A grouping - not inside `Λ` cannot be answered. - -### 2.4 The accuracy predicate - -Because only empirical accuracy is usable, a Hydra edge is eligible only if -a measurement covers it: - -```text -hydra_error(variant, config (R, W, inner), |Λ|, G_r, shape(G_r), - N_q distribution, M, merged windows) <= the RAQE's SLA -``` - -in the family's metric and direction, with no borrowing from a -non-Hydra curve or another grouping. One `subpopulations` ceiling (today's -`hydra-kll` eligibility) is not enough: two groupings of equal cardinality -differ in skew and fan-out. Since error is driven by `N_q / (M / W)`, the -measurement should report error by group size, and the SLA must say which -groups it covers (§6). - -## 3. Cost model - -Hydra is priced by [Cost models](rqe_optimizer_cost_model.md) §3's table, -with no separate formula. One grid is one instance per window, so -`I_d = I_r = 1`, and a query probes it once per `card(G_r)` group. Let -`m_h`, `c_ins,h`, `c_mrg,h` and `c_probe,h(G_r)` be measured for one -variant, configuration and schema width `|Λ|`; `c_ins,h` is per record, fan-out -included (`R · (2^|Λ| − 1)` inner inserts). - -| Phase | CPU-seconds per event | Mean vCPUs | Memory (bytes) | -|---|---|---|---| -| Ingest | — | `λ · a_D · c_ins,h` | `m_h · a_D · k_D` | -| Compaction | `(k_D − 1) · c_mrg,h` | `/ y_D` | `k_D · m_h`, while it runs | -| Query job | `card(G_r) · c_probe,h(G_r) + (n_{i,D} − 1) · c_mrg,h` | `/ T_i` | `m_h · [n_{i,D} > 1] + card(G_r) · output bytes`, while it runs | -| Storage | — | 0 | `m_h · ((max_i S_i − x_D) / y_D + 1)` | - -plus the key tracker's part. A Hydra merge combines whole grids, not -`card(G_d)` addressable states, which is what `I_d = 1` says. This assumes -the merge cost does not depend on the number of probes; sketch-bench must -confirm it or report a probe-count term. - -**Key tracker.** If groups are listed by a DeltaSet (`exact-delta-set`), its -ingest, compaction, merge, query and storage are added as a part. A tracker -at `Λ` that derives coarse keys costs `card(Λ)` per window, not -`card(G_r)`; a tracker per requested grouping costs `card(G_r)` each but -multiplies trackers. This is a decision (§6), not a free operation. - -## 4. Candidates and the MILP - -The MILP does not change: one binary `z_{i,D}` per eligible edge, one -`u_D` per candidate, `stored_D`, the same constraints and objective -([Cost models](rqe_optimizer_cost_model.md) §7). Hydra adds candidates and -edges with their own eligibility and coefficients. - -- **Candidate identity.** `(capability, variant + config, metric, spatial - filter, Λ, x, y, key tracker)`: the schema `Λ` takes the place of the - grouping. `Λ` is an ordered list: the library encodes subkeys in its - declaration order, merges only grids of the same order, and the wrapper's - prefix queries depend on it. So `Λ` needs its own ordered field (a - `LabelSet` loses the order), plus a new family property (e.g. - `answers_any_subgrouping`) that marks Hydra. -- **Generation.** For each (capability, metric, filter), `Λ` ranges over - every distinct RAQE grouping and their union (more schemas cost more, - since `M` and `c_ins,h` grow with `|Λ|`). Windows and slides come, as for - roll-ups, from the RAQEs whose grouping is a non-empty subset of `Λ`. -- **Edge `(i, D)`.** Same capability, metric and filter; `∅ ≠ G_i ⊆ Λ` - (a prefix of `Λ` until the wrapper queries any subset); window alignment - as today; and the §2.4 predicate measured and passing. -- **Linearity.** An edge's accuracy depends only on the candidate (`Λ`, - config, window) and the metric's mass, never on which other RAQEs share - it: everything on the metric and filter is inserted whatever is selected. - So eligibility stays a per-edge filter and the MILP stays linear. -- **Coefficients.** Per candidate: ingest, compaction, storage (§3, plus the - tracker). Per edge: the query job, with `c_probe,h(G_i)`. A Hydra edge is - never priced or validated as a roll-up. -- **Pruning.** Unchanged: candidates compare only at the same capability, - metric, filter and grouping (here `Λ`), on the costs listed in - [candidates](rqe_optimizer_candidates.md). -- **Competition.** A quantile RAQE by `(service)` can then be served by KLL - at `(service)`, by KLL at `(service, endpoint)` through a roll-up, or by - Hydra with `Λ ⊇ {service}`; the MILP picks the cheapest that passes. - -Code this needs, in order: `FamilyProperties` for the four other variants; -the new property and the Hydra branch in `is_eligible` and -`build_all_candidates_unpruned`; Hydra in `Capability::families` and -`DEPLOYABLE_FAMILIES`; the saturation lookup keyed as in §2.4; cost-table -rows. AutoSketch keeps skipping Hydra (#159). - -## 5. What sketch-bench must add - -Each item names what is missing today. Every Hydra measurement sketch-bench -has today predates these requirements, so admitting Hydra means rerunning -them all; `hydra-kll` is measured in that same run, alongside `hydra-cms`, -`hydra-cs`, `hydra-hll` and `hydra-univmon`, under every item below. - -1. **Target grouping.** Comparators score only column 0 - (`aqpbm-cli/src/rows/mod.rs`); they must score any named subset of the - schema, and the wrapper must query any subset, not only prefixes - (`hydra_shared.rs` `query`). -2. **Exact baseline.** The `polars` baselines build untagged subkeys - (`polars_shared.rs`), so overlapping label values alias there but not in - the 0.3.0 sketch (#74); tag them the same way. -3. **Data.** Hierarchical labels with set cardinality per label, per-parent - fan-out and skew; the result records `|Λ|`, the target grouping's - cardinality, every group's `N_q`, and the fanned-out mass `M`. -4. **Sweep.** Grid (`R`, `W`), inner parameters, schema width, target - grouping, cardinality and fan-out, distribution. Report error per group - against `N_q / (M / W)`, and quantiles over groups, not only the mean. - The column hash has a fixed seed, so vary the label values (not only the - data seed) to see the spread over collision patterns. -5. **Bounds as checks.** For CMS, CountSketch and HLL, assert the measured - per-group error is within §2.2's bound at its confidence; a violation - means a bug. -6. **Merges.** Accuracy and cost of merged grids at the shard counts - workloads need, with records split by sample (interleaved), not only in - contiguous chunks (`sketch-bench/src/wrappers/mod.rs`); exactness checks - for CMS, CountSketch and HLL; merge curves for KLL and UnivMon cells. -7. **Cost table.** Hydra rows in `study_saturation.py` (`SKETCHES`, - `OPTIMIZER_FAMILIES`) and `approxbench atomic-costs`: `m_h` (including - each KLL cell's merge buffer, #191), `c_ins,h` per record at the schema - width, `c_mrg,h`, and `c_probe,h` per probe at the target grouping. -8. **Key enumeration.** Benchmark the chosen tracker (§6) at its grouping, - with its input and output cardinality. -9. **Saturation key.** Emit §2.4's fields machine-readably. The optimizer - rejects a Hydra edge with no matching point unless an interpolation rule - is approved (§6). -10. **Fixtures.** Equal grouping, a direct coarse subset, and a multi-window - merge, each against exact answers, asserting the exported accuracy and - cost fields. - -## 6. Decisions needed - -1. Group enumeration: one DeltaSet at `Λ` that derives coarse keys, or one - per requested grouping? -2. Groupings: prefixes of `Λ` only, or any non-empty subset once the wrapper - and comparators support it? -3. Which groups an SLA covers: every group (then Hydra almost never passes - for small groups), groups above a size, or a quantile over groups? -4. Interpolation between measured Hydra points: none, or the worse - bracketing point as for the other sketches? -5. Schemas generated per workload: each RAQE grouping and their union, or - more? -6. Whether `hydra-univmon` entropy, which has no bound, is admitted at all. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 9cf7b80b..d0ab9106 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -146,7 +146,7 @@ modeled. ## Planning design -The optimizer has three companion design documents: +The optimizer has two companion design documents: - [Candidate generation and eligibility](rqe_optimizer_candidates.md): candidate construction, eligibility (accuracy included), finer-to-coarser @@ -154,9 +154,6 @@ The optimizer has three companion design documents: - [Cost models](rqe_optimizer_cost_model.md): the one cost table, the canonical cost-by-use and batch-latency model with its MILP, and the supported snapshot-AUC objective. -- [Hydra](rqe_optimizer_hydra.md): what admitting Hydra needs (accuracy - guarantees per combination, cost model, candidates and MILP edges, and - sketch-bench measurements). Not implemented. ## Procedure @@ -211,7 +208,7 @@ generation and pruning, eligibility checks, analytical objectives, and streaming Pareto filtering. The separation between candidate generation, enumeration, objectives, and Pareto filtering remains the intended boundary for future solver work. Hydra, a shared-subpopulation deployment rather than -a fine-state roll-up, is designed in [Hydra](rqe_optimizer_hydra.md). +a fine-state roll-up, is future work. Exporter bugs, benchmark-dataset choices, and historic run counts belong in `rqe_optimizer_TODO.md` or issue tracking, not in this problem statement. From 6b1637a349396dec405020ca86063b86df5f11fd Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 03:09:10 +0000 Subject: [PATCH 12/13] rqe-optimizer: tests for roll-up DD memory, facts and pruning; doc fixes Tests that fail without their rule: - a DDSketch roll-up sizes its accumulator at the coarse grouping; - validate_facts rejects a RAQE grouping with more groups than series; - pruning drops a heap whose larger answered k only adds output memory. Docs: the KLL footprint paragraph now that #192 is in; univmon-cardinality reads merge curves like KLL (and has no guarantee past them); the TODO's done list covers roll-ups and the pruning costs; "temporal pre-merging"; enumerate.rs names the MILP variables z and u as the docs do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_TODO.md | 12 +++++++----- docs/rqe_optimizer_candidates.md | 10 ++++++---- docs/rqe_optimizer_cost_model.md | 10 ++++++---- docs/rqe_sketch_deployment_v1.md | 7 ++++--- rqe-optimizer/src/analytical_cost_model.rs | 22 ++++++++++++++++++++++ rqe-optimizer/src/candidates.rs | 20 ++++++++++++++++++++ rqe-optimizer/src/enumerate.rs | 4 ++-- rqe-optimizer/src/lib.rs | 19 +++++++++++++++++++ 8 files changed, 86 insertions(+), 18 deletions(-) diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index 8d230e00..302f123f 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -10,14 +10,16 @@ implemented, what is next, and what is intentionally deferred. - Workload facts are per metric: full label set, scrape interval, and cardinality per label set. The arrival rate is derived from them, and `validate_facts` reports bad facts up front. -- Eligibility enforces capability, metric, spatial filter, grouping, alignment, and the RQE's +- Eligibility enforces capability, metric, spatial filter, grouping (equal, + or a subset for a family that merges across groups: a roll-up), alignment, and the RQE's measured accuracy, by each family's own metric, against the RAQE's SLA. - Candidate generation uses legal windows and subset gcds of query intervals, keeping only multiples of the scrape interval. A deployment may serve multiple compatible RQEs. -- Candidate dominance safely removes a deployment only when another covers all - of its RQEs with no worse instance memory, ingest CPU and memory, per-RQE - latency, or stored memory. +- Candidate dominance safely removes a deployment only when another at the + same grouping covers all of its RQEs with no worse ingest CPU and memory, + compaction (per window and per slide), per-RQE query-job CPU, query memory + (merge and output), or stored memory. - The analytical model scores four phases, each with CPU and memory: ingest (open windows), merge, query, and storage (closed windows, `(S − x)/y + 1` for the longest lookback), plus per-RQE latency. @@ -59,6 +61,6 @@ implemented, what is next, and what is intentionally deferred. - Admitting Hydra. - Key labels `K` (PerGroup + PerKey sizes). - RQE churn, replanning, and migration cost. -- Precomputed rollups; v1 merges selected base instances at query time. +- Temporal pre-merging; v1 merges selected base instances at query time. - A policy for choosing one mapping from the reported Pareto frontier. - Additional capabilities beyond frequency, quantile, cardinality, and top-k. diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index da034e05..b771c97a 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -116,8 +116,10 @@ roll-up the answered group is the RAQE's coarse one. a merge curve's last N, the curves say nothing, so the answer takes the guarantee below, no better than the largest count's last measurement; the study should measure the merge counts a workload needs - (`--merge-shards-list`) so the guarantee isn't what decides (#158). `SaturationCurves::load` refuses a study with no merge curves for - a candidate KLL sketch. The fan-out is the average; the largest group's is + (`--merge-shards-list`) so the guarantee isn't what decides (#158); + univmon-cardinality has no guarantee, so past its curves it has no + accuracy. `SaturationCurves::load` refuses a study with no merge curves + for a lossy candidate sketch (KLL, univmon-cardinality). The fan-out is the average; the largest group's is #189. - A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap top-k (CMS-heap, CountSketch-heap) keeps a heap of `n · k` in a deployment @@ -227,8 +229,8 @@ univmon-cardinality, KLL and DDSketch. These don't, and serve only ([Cost models](rqe_optimizer_cost_model.md), §3). A direct roll-up (`n = 1`) still merges `card(G_d) − card(G_r)` instances. - **Accuracy**: read at `G_r`: its `data_shape`, and its items per group over - the lookback. KLL's merge curve is read at `⌈card(G_d)/card(G_r)⌉ · n` - merged instances, the average fan-out, an estimate rather than a + the lookback. KLL's and univmon-cardinality's merge curves are read at + `⌈card(G_d)/card(G_r)⌉ · n` merged instances, the average fan-out, an estimate rather than a worst-group bound (uneven fan-out is #189). - **Facts**: `validate_facts` requires `card(X) ≤ card(Y)` for every pair `X ⊂ Y` among the label sets a plan can use (every RAQE grouping on the diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md index 4e1830a8..02b4f162 100644 --- a/docs/rqe_optimizer_cost_model.md +++ b/docs/rqe_optimizer_cost_model.md @@ -356,10 +356,12 @@ not scale. Quantile sketches have no keys. KLL's `m` is Fixed, and the same at every item count, because `asap_sketchlib::KLL` allocates once at construction. -Until #192 the cost table's KLL rows report a nominal `4 · k · sizeof(T)` -(1600 B at `k = 50`), not that allocation (5536 B at `k = 50`: item slots, -level index and merge buffer; 1.58× at `k = 200`, 1.14× at `k = 800`), so -KLL memory is understated (#191). +Since #192 the cost table's KLL rows report that allocation: item slots, +level index and merge buffer, 5536 B at `k = 50`. Cost tables measured +before it, including the committed `autosketch-vs-asap-inputs`, carry a +nominal `4 · k · sizeof(T)` instead (1600 B at `k = 50`; the allocation is +1.58× that at `k = 200`, 1.14× at `k = 800`), so they understate KLL +memory (#191). DDSketch is sized from the metric's `value_range` when given (capped by values per instance), else from the measured size. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index d0ab9106..767f0858 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -180,9 +180,10 @@ each phase's CPU and memory, together with the selected deployment mapping. ## v1 scope and TODOs -- **Accuracy after merging:** KLL reads its merge curves up to the largest - shard count and N the study measured; past them, the guarantee, no better - than the last measurement. Roll-ups multiply the merge count by the +- **Accuracy after merging:** KLL and univmon-cardinality read their merge + curves up to the largest shard count and N the study measured; past them, + KLL's guarantee, no better than the last measurement (univmon-cardinality + has none, so no accuracy). Roll-ups multiply the merge count by the fan-out, so they reach the guarantee sooner. Heap top-k reads its plain curve (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 8c7eb932..9e8cd16e 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -612,4 +612,26 @@ mod tests { 45.0 / 60.0 ); } + + /// A roll-up's DDSketch accumulator holds a coarse group's values: 50 + /// samples/s over a 2 s lookback into 5 services is 20 values each, past + /// the 10-bucket range, so 80 B per service, not the 16 B two per-endpoint + /// values would need. + #[test] + fn a_dd_roll_up_sizes_its_accumulator_at_the_coarse_grouping() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let mut facts = service_endpoint_facts(); + facts + .get_mut(crate::test_support::METRIC) + .unwrap() + .value_range = Some((1.0, 1000.0)); + let mut by_endpoint = kll_by(&["service", "endpoint"], 1_000); + by_endpoint.config.sketch = "dd".into(); + by_endpoint.config.sketch_config = serde_json::json!({"params": {"alpha": 1.0 / 3.0}}); + let by_service = quantile_by(&["service"], 2_000, 2_000); + assert_eq!( + merge(&by_service, &by_endpoint, &facts).memory_bytes, + 5.0 * 80.0 + ); + } } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index ceeaf6bc..09afe4fa 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -939,6 +939,26 @@ mod tests { assert_eq!(retained, vec![coarse]); } + #[test] + fn prunes_the_candidate_with_larger_query_output() { + // Two heaps that differ only in the `k` they answer: the larger one + // outputs 100 entries per group, not 32, at the same CPU. + let r = raqe("r", 60_000, 60_000); + let answering = |k: u64| { + let mut d = crate::test_support::deployment(1.0, 1.0, 1.0, 0.0, 60_000, 60_000); + d.config.sketch_config = + serde_json::json!({"params": {"heap": 1u64 << 40, "topk_k": k}}); + d + }; + let retained = prune_dominated_candidates( + &[r], + &facts(1, 1), + vec![answering(100), answering(32)], + &table_accuracy, + ); + assert_eq!(retained, vec![answering(32)]); + } + #[test] fn retains_candidate_with_cheaper_compaction() { // A direct RAQE never merges at query time, so merge CPU shows up only diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index dd614b2b..8fe68f70 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -1,14 +1,14 @@ //! Brute-force search over full mappings. //! //! A mapping is one deployment choice per RAQE (the MILP's only constraint is -//! `Σ_D x_{i,D} = 1`; `y_D` is derived). Choices are independent, so the +//! `Σ_D z_{i,D} = 1`; `u_D` is derived). Choices are independent, so the //! search space is exactly the cartesian product of the per-RAQE eligible //! lists -- nothing to prune against. Sharing falls out when two choices land //! on the same index, including a fine deployment chosen by a RAQE that rolls //! up to a coarser grouping. //! //! An ILP would replace this module alone: `Mapping` already encodes -//! `x_{i,D}` and `y_D`. +//! `z_{i,D}` and `u_D`. use crate::{ candidates::eligible_deployments_for, Accuracy, Deployment, Mapping, Raqe, WorkloadFacts, diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 1bcd3bca..e7868d5d 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -991,6 +991,25 @@ mod tests { ); } + /// A RAQE grouping may not have more groups than the series. + #[test] + fn rejects_a_grouping_with_more_groups_than_series() { + let mut facts = inconsistent_facts(); + let cardinality = &mut facts.get_mut(METRIC).unwrap().cardinality; + cardinality.insert(labels(&["service", "endpoint", "pod"]), 40); + let r = Raqe { + grouping_labels: labels(&["service"]), + ..raqe(60_000, 60_000) + }; + assert_eq!( + validate_facts(&[r], &facts).unwrap_err(), + [format!( + "{METRIC}: {{\"service\"}} has 60 groups but its superset \ + {{\"endpoint\", \"pod\", \"service\"}} only 40" + )] + ); + } + /// Label sets no RAQE groups by are never read, so inconsistencies there /// don't reject the workload. #[test] From d288a5e8a94fc754952adabee9299cb2cf868579 Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 03:12:23 +0000 Subject: [PATCH 13/13] rqe-optimizer: name every lossy non-heap sketch that needs merge curves Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_optimizer_candidates.md | 3 ++- rqe-optimizer/src/saturation.rs | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md index b771c97a..fd0d9cee 100644 --- a/docs/rqe_optimizer_candidates.md +++ b/docs/rqe_optimizer_candidates.md @@ -119,7 +119,8 @@ roll-up the answered group is the RAQE's coarse one. (`--merge-shards-list`) so the guarantee isn't what decides (#158); univmon-cardinality has no guarantee, so past its curves it has no accuracy. `SaturationCurves::load` refuses a study with no merge curves - for a lossy candidate sketch (KLL, univmon-cardinality). The fan-out is the average; the largest group's is + for a lossy non-heap candidate sketch (KLL, univmon-cardinality, + univmon-topk). The fan-out is the average; the largest group's is #189. - A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap top-k (CMS-heap, CountSketch-heap) keeps a heap of `n · k` in a deployment diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index 76577b43..bbf623ee 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -366,8 +366,9 @@ impl SaturationCurves { // accuracy. let mut lossy: BTreeMap<&str, bool> = BTreeMap::new(); for (sketch, point) in points.values() { - // Heap top-k merges as one sketch when sized m · k, so only KLL - // needs the curves. + // Heap top-k merges as one sketch when sized m · k, so only the + // non-heap lossy sketches (KLL, univmon-cardinality, univmon-topk) + // need the curves. if is_candidate(sketch) && merges_lossily(sketch) && !has_heap(sketch) { *lossy.entry(sketch).or_default() |= !point.merged.is_empty(); }