From 3bc02263375dbda8a0f137d5c8ebe3b7acc19024 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Mon, 5 Oct 2026 15:16:55 -0400 Subject: [PATCH 01/18] rqe-optimizer: one MILP entry point with an Objective enum Replace minimize_tco/minimize_cost with minimize(..., Objective), where Objective::{Tco, Cost(&MachineFamily)} owns its scaling units, extra variables, rows and goal. The shared assignment/activation/bound rows no longer branch on the family, and TCO no longer adds an unused instances variable. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_optimizer_TODO.md | 2 +- docs/rqe_sketch_deployment_v1.md | 4 +- rqe-optimizer/examples/small_problem.rs | 13 +- rqe-optimizer/src/milp.rs | 162 +++++++++++++----------- 4 files changed, 96 insertions(+), 85 deletions(-) diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index 13f42e94..f7005dd8 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -32,7 +32,7 @@ implemented, what is next, and what is intentionally deferred. - A regression test confirms the MILP matches exhaustive minimum-TCO search on a tiny workload with shared deployment activation costs. - Retained memory (`(x + max S) / y` instances per active deployment) is - scored, and `milp::minimize_cost` minimizes the hourly price on one EC2 + scored, and `milp::minimize` with `Objective::Cost` minimizes the hourly price on one EC2 machine family in fractional instances. Prices are a committed snapshot from `scripts/fetch_ec2_pricing.py`; `small_problem --milp --machine-family NAME` uses it. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index cd1b8457..f320cdd0 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -137,7 +137,7 @@ substitute the remaining one without weakening a modeled objective. Historical instances must be retained long enough to answer the RQEs assigned to a deployment. Retention is not a candidate parameter: a deployment retains the history needed by the largest assigned query window. Its memory is scored -as retained memory (below) and priced by `minimize_cost`. +as retained memory (below) and priced by `Objective::Cost`. ## Workload mapping @@ -185,7 +185,7 @@ TCO_cpu = Σ_D ingest_cpu_D × u_D latency_i = Σ_{D: (i,D)∈E} latency_{i,D} × z_{i,D} ``` -`minimize_cost` instead prices the plan on one EC2 machine family `f` (vCPUs +`Objective::Cost` instead prices the plan on one EC2 machine family `f` (vCPUs `vcpu_f`, memory `gib_f`, hourly price `price_f`) in fractional instances `n_f`, with a continuous `R_D ≥ 0` for each candidate's retained GiB: diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 354c8967..31236cce 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -34,7 +34,7 @@ use rqe_optimizer::candidates::{ build_all_candidates, build_all_candidates_unpruned, eligible_deployments_for, }; use rqe_optimizer::enumerate::{brute_force, for_each_mapping, for_each_mapping_while, unservable}; -use rqe_optimizer::milp::{minimize_cost, minimize_tco, MilpBounds}; +use rqe_optimizer::milp::{minimize, MilpBounds, Objective}; use rqe_optimizer::objectives::{score, MachineFamily}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; use rqe_optimizer::{ @@ -346,11 +346,12 @@ fn main() { max_query_latency_secs: latency_bounds(&rqes), }; let family = machine_family(); - let solution = match &family { - Some(family) => minimize_cost(&rqes, &deployments, &label_sets, &bounds, family), - None => minimize_tco(&rqes, &deployments, &label_sets, &bounds), - } - .expect("small_problem MILP should be feasible"); + let objective = match &family { + Some(family) => Objective::Cost(family), + None => Objective::Tco, + }; + let solution = minimize(&rqes, &deployments, &label_sets, &bounds, objective) + .expect("small_problem MILP should be feasible"); if let Some(family) = &family { println!( "MILP minimum-cost solution on {}: ${:.4}/hour, {:.4} instances, \ diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index ccc5c00f..5147870b 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -7,12 +7,34 @@ use crate::candidates::eligible_deployments_for; use crate::objectives::{score, MachineFamily, Objectives, BYTES_PER_GIB}; use crate::{Deployment, LabelSetTable, Mapping, Rqe}; use good_lp::{ - default_solver, variable, Expression, ProblemVariables, ResolutionError, Solution, SolverModel, - Variable, + default_solver, variable, Constraint, Expression, ProblemVariables, ResolutionError, Solution, + SolverModel, Variable, }; -/// Optional hard bounds for a minimum-TCO solve. An empty latency vector means -/// no RQE has a latency bound; otherwise it is index-aligned with `rqes`. +/// What a [`minimize`] solve minimizes. Eligibility, assignment and activation +/// rows, and bounds are the same for every objective. +#[derive(Debug, Clone, Copy)] +pub enum Objective<'a> { + /// Total steady-state CPU, `tco_cpu_secs_per_sec`. + Tco, + /// Hourly price of running the plan on one machine family, in fractional + /// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. + Cost(&'a MachineFamily), +} + +impl Objective<'_> { + /// Per resource, the units the goal is measured in: CPU for TCO, and for a + /// family the vCPU and GiB of one instance. Memory is free under TCO. + fn units(self) -> (f64, f64) { + match self { + Objective::Tco => (1.0, f64::INFINITY), + Objective::Cost(family) => (family.vcpu, family.memory_gib), + } + } +} + +/// Optional hard bounds for a solve. An empty latency vector means no RQE has +/// a latency bound; otherwise it is index-aligned with `rqes`. #[derive(Debug, Clone, Default)] pub struct MilpBounds { pub max_peak_query_memory_bytes: Option, @@ -25,37 +47,15 @@ pub struct MilpSolution { pub objectives: Objectives, } -/// Minimize total steady-state CPU subject to optional memory and latency -/// bounds. Missing eligible deployments are a caller input error; use -/// `enumerate::unservable` to report them before calling this function. -pub fn minimize_tco( - rqes: &[Rqe], - deployments: &[Deployment], - label_sets: &LabelSetTable, - bounds: &MilpBounds, -) -> Result { - solve(rqes, deployments, label_sets, bounds, None) -} - -/// Minimize the hourly price of running the plan on `family`, in fractional -/// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. Same inputs -/// and bounds as [`minimize_tco`]. -pub fn minimize_cost( - rqes: &[Rqe], - deployments: &[Deployment], - label_sets: &LabelSetTable, - bounds: &MilpBounds, - family: &MachineFamily, -) -> Result { - solve(rqes, deployments, label_sets, bounds, Some(family)) -} - -fn solve( +/// Minimize `objective` subject to optional memory and latency bounds. Missing +/// eligible deployments are a caller input error; use `enumerate::unservable` +/// to report them before calling this function. +pub fn minimize( rqes: &[Rqe], deployments: &[Deployment], label_sets: &LabelSetTable, bounds: &MilpBounds, - family: Option<&MachineFamily>, + objective: Objective, ) -> Result { assert!( bounds.max_query_latency_secs.is_empty() @@ -108,12 +108,7 @@ fn solve( .expect("assignment only contains eligible deployments") as f64 / BYTES_PER_GIB }; - // Per resource, in the units the solve minimizes: CPU for TCO, and for a - // family the vCPU and GiB fractions of one instance. - let (cpu_unit, gib_unit) = match family { - Some(f) => (f.vcpu, f.memory_gib), - None => (1.0, f64::INFINITY), - }; + let (cpu_unit, gib_unit) = objective.units(); let reference: f64 = rqes .iter() .zip(&eligible) @@ -152,28 +147,37 @@ fn solve( } } - // Retained GiB per deployment, and fractional instances, priced only when - // a machine family is given. Both are in units of `reference`. - let retained_gib: Vec = match family { - Some(_) => deployments - .iter() - .map(|_| variables.add(variable().min(0))) - .collect(), - None => Vec::new(), - }; - let instances = variables.add(variable().min(0)); - // The price per instance is a positive constant, so minimizing instances - // minimizes the price. - let goal = match family { - Some(_) => Expression::from(instances), - None => cpu.clone(), + // The objective's own variables and rows, in units of `reference`. + let (goal, objective_rows): (Expression, Vec) = match objective { + Objective::Tco => (cpu, Vec::new()), + Objective::Cost(family) => { + // The price per instance is a positive constant, so minimizing + // fractional instances minimizes the price. + let instances = variables.add(variable().min(0)); + let retained_gib: Vec = deployments + .iter() + .map(|_| variables.add(variable().min(0))) + .collect(); + let total_gib: Expression = retained_gib.iter().sum(); + let mut rows = vec![ + (cpu / family.vcpu - instances).leq(0), + (total_gib / family.memory_gib - instances).leq(0), + ]; + // Linearized max over the RQEs a deployment serves. + for (rqe_index, choices) in assignments.iter().enumerate() { + for &(deployment_index, assignment) in choices { + let retained = + retained(&rqes[rqe_index], &deployments[deployment_index]) / reference; + rows.push((retained * assignment - retained_gib[deployment_index]).leq(0)); + } + } + (Expression::from(instances), rows) + } }; let mut model = variables.minimise(goal).using(default_solver); - if let Some(f) = family { - model.add_constraint((cpu / f.vcpu - instances).leq(0)); - let total_gib: Expression = retained_gib.iter().sum(); - model.add_constraint((total_gib / f.memory_gib - instances).leq(0)); + for row in objective_rows { + model.add_constraint(row); } for (rqe_index, choices) in assignments.iter().enumerate() { @@ -201,13 +205,6 @@ fn solve( { model.add_constraint(Expression::from(assignment).leq(0)); } - if family.is_some() { - // Linearized max over the RQEs a deployment serves. - let retained = retained(&rqes[rqe_index], deployment) / reference; - model.add_constraint( - (retained * assignment - retained_gib[deployment_index]).leq(0), - ); - } } } @@ -308,11 +305,17 @@ mod tests { }, )]); - let unconstrained = minimize_tco(&rqes, &deployments, &label_sets, &MilpBounds::default()) - .expect("feasible MILP"); + let unconstrained = minimize( + &rqes, + &deployments, + &label_sets, + &MilpBounds::default(), + Objective::Tco, + ) + .expect("feasible MILP"); assert_eq!(unconstrained.mapping, vec![0]); - let constrained = minimize_tco( + let constrained = minimize( &rqes, &deployments, &label_sets, @@ -320,6 +323,7 @@ mod tests { max_peak_query_memory_bytes: Some(10.0), max_query_latency_secs: Vec::new(), }, + Objective::Tco, ) .expect("feasible MILP under memory bound"); assert_eq!(constrained.mapping, vec![1]); @@ -352,8 +356,14 @@ mod tests { .expect("test workload is servable"); let expected = score(&rqes, &deployments, &brute_force_best, &label_sets); - let milp = minimize_tco(&rqes, &deployments, &label_sets, &MilpBounds::default()) - .expect("feasible MILP"); + let milp = minimize( + &rqes, + &deployments, + &label_sets, + &MilpBounds::default(), + Objective::Tco, + ) + .expect("feasible MILP"); assert_eq!(milp.mapping, brute_force_best); assert!( @@ -399,12 +409,12 @@ mod tests { }) .min_by(f64::total_cmp) .expect("test workload is servable"); - let milp = minimize_cost( + let milp = minimize( &rqes, &deployments, &label_sets, &MilpBounds::default(), - &family, + Objective::Cost(&family), ) .expect("feasible MILP"); assert!((family.usd_per_hour(&milp.objectives) - best).abs() < 1e-9); @@ -427,12 +437,12 @@ mod tests { }, )]); let solve = |memory_gib| { - minimize_cost( + minimize( &rqes, &deployments, &label_sets, &MilpBounds::default(), - &family(memory_gib), + Objective::Cost(&family(memory_gib)), ) .expect("feasible MILP") .mapping @@ -479,12 +489,12 @@ mod tests { }) .min_by(f64::total_cmp) .expect("test workload is servable"); - let milp = minimize_cost( + let milp = minimize( &rqes, &deployments, &label_sets, &MilpBounds::default(), - &family, + Objective::Cost(&family), ) .expect("feasible MILP"); let got = family.usd_per_hour(&milp.objectives); @@ -498,7 +508,7 @@ mod tests { deployment(tiny, tiny, 1.5e-7), deployment(10.0 * tiny, tiny, 0.5e-7), ]; - let milp = minimize_cost( + let milp = minimize( &rqes, &deployments, &label_sets, @@ -506,7 +516,7 @@ mod tests { max_peak_query_memory_bytes: None, max_query_latency_secs: vec![Some(1e-7)], }, - &family(8.0), + Objective::Cost(&family(8.0)), ) .expect("feasible MILP"); assert_eq!(milp.mapping, vec![1]); From ce6008d25b2a02a8eed6140b809d71e91edd6b2b Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Mon, 5 Oct 2026 16:37:37 -0400 Subject: [PATCH 02/18] rqe-optimizer: drop the Tco MILP objective, rename Cost to AUCCost The MILP now only minimizes hourly price on a machine family. AUCCost names what it prices: mean CPU-sec/sec, the area under the load curve, so bursts are not priced. small_problem --milp now requires --machine-family. The former TCO tests run under AUCCost with the same expected mappings. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_optimizer_TODO.md | 6 +-- docs/rqe_sketch_deployment_v1.md | 10 +++-- rqe-optimizer/examples/small_problem.rs | 43 +++++++++++----------- rqe-optimizer/src/milp.rs | 49 +++++++++++-------------- 4 files changed, 51 insertions(+), 57 deletions(-) diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index f7005dd8..fe427bfa 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -25,14 +25,14 @@ implemented, what is next, and what is intentionally deferred. can print initial example mappings. - `scripts/export_rqe_optimizer_costs.sh` exports the 18-row measured cost table used by `small_problem`, without changing ASAPQuery's exporter. -- The MILP uses HiGHS to minimize TCO without enumerating mappings. It accepts +- The MILP uses HiGHS to minimize hourly price without enumerating mappings. It accepts optional peak-memory and per-RQE latency bounds and returns a normal mapping. - `small_problem --milp` accepts repeatable per-RQE latency limits and includes 1-hour, 6-hour, and 1-day quantile RQEs to exercise those constraints. -- A regression test confirms the MILP matches exhaustive minimum-TCO search on +- A regression test confirms the MILP matches exhaustive minimum-price search on a tiny workload with shared deployment activation costs. - Retained memory (`(x + max S) / y` instances per active deployment) is - scored, and `milp::minimize` with `Objective::Cost` minimizes the hourly price on one EC2 + scored, and `Objective::AUCCost` minimizes the hourly price on one EC2 machine family in fractional instances. Prices are a committed snapshot from `scripts/fetch_ec2_pricing.py`; `small_problem --milp --machine-family NAME` uses it. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index f320cdd0..29dc92eb 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -137,7 +137,7 @@ substitute the remaining one without weakening a modeled objective. Historical instances must be retained long enough to answer the RQEs assigned to a deployment. Retention is not a candidate parameter: a deployment retains the history needed by the largest assigned query window. Its memory is scored -as retained memory (below) and priced by `Objective::Cost`. +as retained memory (below) and priced by `Objective::AUCCost`. ## Workload mapping @@ -185,7 +185,8 @@ TCO_cpu = Σ_D ingest_cpu_D × u_D latency_i = Σ_{D: (i,D)∈E} latency_{i,D} × z_{i,D} ``` -`Objective::Cost` instead prices the plan on one EC2 machine family `f` (vCPUs +The MILP's only objective, `Objective::AUCCost`, prices the plan on one EC2 +machine family `f` (vCPUs `vcpu_f`, memory `gib_f`, hourly price `price_f`) in fractional instances `n_f`, with a continuous `R_D ≥ 0` for each candidate's retained GiB: @@ -196,10 +197,11 @@ vcpu_f × n_f ≥ TCO_cpu gib_f × n_f ≥ Σ_D R_D ``` -Prices come from `rqe-optimizer/data/ec2-pricing-.json`, written by +`TCO_cpu` is the area under the CPU curve (mean CPU-sec/sec), so instances are +sized for the mean load, not for bursts. Prices come from `rqe-optimizer/data/ec2-pricing-.json`, written by `scripts/fetch_ec2_pricing.py`. Disk is not priced. -One solve needs a scalar objective, such as minimum `TCO_cpu` subject to +One solve needs a scalar objective, such as minimum hourly price subject to `M ≤ memory_budget` and optional `latency_i ≤ latency_budget_i`. To sample the Pareto frontier, repeat solves over memory and latency budgets, or use a normalized weighted objective. The solver never enumerates full mappings. diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 31236cce..15d92714 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -20,11 +20,10 @@ //! `--candidates-only` to inspect candidate pruning safely, without starting //! mapping enumeration. Streaming mode logs progress every one million //! mappings by default; pass `--progress-every N` to change that interval or -//! `--print-first N` to display example mappings. `--milp` solves the -//! minimum-TCO model without enumerating mappings. Repeat -//! `--latency-limit RQE_ID=SECONDS` to impose MILP latency bounds. Add -//! `--machine-family NAME` (`compute_optimized`, `general_purpose`, -//! `memory_optimized`) to minimize that EC2 family's hourly price instead. +//! `--print-first N` to display example mappings. `--milp --machine-family +//! NAME` (`compute_optimized`, `general_purpose`, `memory_optimized`) minimizes +//! that EC2 family's hourly price without enumerating mappings. Repeat +//! `--latency-limit RQE_ID=SECONDS` to impose MILP latency bounds. //! `--sample-mappings N` prints N feasible mappings and exits. use std::collections::BTreeSet; @@ -345,23 +344,23 @@ fn main() { max_peak_query_memory_bytes: None, max_query_latency_secs: latency_bounds(&rqes), }; - let family = machine_family(); - let objective = match &family { - Some(family) => Objective::Cost(family), - None => Objective::Tco, - }; - let solution = minimize(&rqes, &deployments, &label_sets, &bounds, objective) - .expect("small_problem MILP should be feasible"); - if let Some(family) = &family { - println!( - "MILP minimum-cost solution on {}: ${:.4}/hour, {:.4} instances, \ - retained_mem={:.0}MB", - family.family, - family.usd_per_hour(&solution.objectives), - family.instances(&solution.objectives), - solution.objectives.retained_memory_bytes / 1e6, - ); - } + let family = machine_family().expect("--milp needs --machine-family NAME"); + let solution = minimize( + &rqes, + &deployments, + &label_sets, + &bounds, + Objective::AUCCost(&family), + ) + .expect("small_problem MILP should be feasible"); + println!( + "MILP minimum-cost solution on {}: ${:.4}/hour, {:.4} instances, \ + retained_mem={:.0}MB", + family.family, + family.usd_per_hour(&solution.objectives), + family.instances(&solution.objectives), + solution.objectives.retained_memory_bytes / 1e6, + ); println!( "MILP solution: peak_query_mem={:.0}MB, ingest={:.3e}, \ merge={:.3e}, query={:.3e}, total={:.3e} cpu-sec/sec", diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 5147870b..d29d781d 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -15,20 +15,18 @@ use good_lp::{ /// rows, and bounds are the same for every objective. #[derive(Debug, Clone, Copy)] pub enum Objective<'a> { - /// Total steady-state CPU, `tco_cpu_secs_per_sec`. - Tco, /// Hourly price of running the plan on one machine family, in fractional - /// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. - Cost(&'a MachineFamily), + /// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. CPU is the + /// area under the load curve (mean CPU-sec/sec), so bursts are not priced. + AUCCost(&'a MachineFamily), } impl Objective<'_> { - /// Per resource, the units the goal is measured in: CPU for TCO, and for a - /// family the vCPU and GiB of one instance. Memory is free under TCO. + /// Per resource, the units the goal is measured in: the vCPU and GiB of + /// one instance. fn units(self) -> (f64, f64) { match self { - Objective::Tco => (1.0, f64::INFINITY), - Objective::Cost(family) => (family.vcpu, family.memory_gib), + Objective::AUCCost(family) => (family.vcpu, family.memory_gib), } } } @@ -149,8 +147,7 @@ pub fn minimize( // The objective's own variables and rows, in units of `reference`. let (goal, objective_rows): (Expression, Vec) = match objective { - Objective::Tco => (cpu, Vec::new()), - Objective::Cost(family) => { + Objective::AUCCost(family) => { // The price per instance is a positive constant, so minimizing // fractional instances minimizes the price. let instances = variables.add(variable().min(0)); @@ -294,7 +291,7 @@ mod tests { } #[test] - fn minimizes_cpu_and_respects_a_memory_bound() { + fn minimizes_cost_and_respects_a_memory_bound() { let rqes = vec![rqe()]; let deployments = vec![deployment(1.0, 20.0, 1.0), deployment(2.0, 10.0, 1.0)]; let label_sets = BTreeMap::from([( @@ -310,7 +307,7 @@ mod tests { &deployments, &label_sets, &MilpBounds::default(), - Objective::Tco, + Objective::AUCCost(&family(8.0)), ) .expect("feasible MILP"); assert_eq!(unconstrained.mapping, vec![0]); @@ -323,7 +320,7 @@ mod tests { max_peak_query_memory_bytes: Some(10.0), max_query_latency_secs: Vec::new(), }, - Objective::Tco, + Objective::AUCCost(&family(8.0)), ) .expect("feasible MILP under memory bound"); assert_eq!(constrained.mapping, vec![1]); @@ -346,29 +343,25 @@ mod tests { }, )]); + let price = |mapping: &Mapping| { + family(8.0).usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) + }; let brute_force_best = brute_force(&rqes, &deployments) .into_iter() - .min_by(|left, right| { - score(&rqes, &deployments, left, &label_sets) - .tco_cpu_secs_per_sec - .total_cmp(&score(&rqes, &deployments, right, &label_sets).tco_cpu_secs_per_sec) - }) + .min_by(|left, right| price(left).total_cmp(&price(right))) .expect("test workload is servable"); - let expected = score(&rqes, &deployments, &brute_force_best, &label_sets); let milp = minimize( &rqes, &deployments, &label_sets, &MilpBounds::default(), - Objective::Tco, + Objective::AUCCost(&family(8.0)), ) .expect("feasible MILP"); assert_eq!(milp.mapping, brute_force_best); - assert!( - (milp.objectives.tco_cpu_secs_per_sec - expected.tco_cpu_secs_per_sec).abs() < 1e-12 - ); + assert!((price(&milp.mapping) - price(&brute_force_best)).abs() < 1e-12); } fn family(memory_gib: f64) -> MachineFamily { @@ -381,7 +374,7 @@ mod tests { } #[test] - fn minimize_cost_matches_brute_force_minimum() { + fn minimize_cost_matches_brute_force_minimum_across_families() { let mut frequent = rqe(); frequent.id = "frequent".into(); let mut long = rqe(); @@ -414,7 +407,7 @@ mod tests { &deployments, &label_sets, &MilpBounds::default(), - Objective::Cost(&family), + Objective::AUCCost(&family), ) .expect("feasible MILP"); assert!((family.usd_per_hour(&milp.objectives) - best).abs() < 1e-9); @@ -442,7 +435,7 @@ mod tests { &deployments, &label_sets, &MilpBounds::default(), - Objective::Cost(&family(memory_gib)), + Objective::AUCCost(&family(memory_gib)), ) .expect("feasible MILP") .mapping @@ -494,7 +487,7 @@ mod tests { &deployments, &label_sets, &MilpBounds::default(), - Objective::Cost(&family), + Objective::AUCCost(&family), ) .expect("feasible MILP"); let got = family.usd_per_hour(&milp.objectives); @@ -516,7 +509,7 @@ mod tests { max_peak_query_memory_bytes: None, max_query_latency_secs: vec![Some(1e-7)], }, - Objective::Cost(&family(8.0)), + Objective::AUCCost(&family(8.0)), ) .expect("feasible MILP"); assert_eq!(milp.mapping, vec![1]); From 349035456e29adbc16f605b9dbd4ff5aeffecc70 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Mon, 5 Oct 2026 21:37:15 -0400 Subject: [PATCH 03/18] rqe-optimizer: per-phase cost model, workload facts, weighted AUCCost - Costs split into ingest, merge, query and storage, each with CPU and memory. objectives.rs holds the one copy of the formulas; score() and the MILP share it. - Storage counts closed windows as (L - x)/y + 1 for the longest lookback (#143 S7). Ingest memory is open windows only. - MetricFacts { labels, scrape_interval_secs, cardinality } replaces LabelSetInfo (#143 S2). The arrival rate is derived as card(labels) / scrape interval. validate_facts reports every bad fact. - Rqe and Deployment carry metric and grouping_labels. - Candidate windows and slides are multiples of the scrape interval (#143 S6, half). - Objective::AUCCost { w_cpu, w_mem } minimizes w_cpu * CPU + w_mem * memory GiB, default (1, 0). MachineFamily, the EC2 pricing snapshot and fetch_ec2_pricing.py are removed, as is the peak-memory bound (#143 S3). - Objectives is per phase; the Pareto vector is (CPU, memory, latencies). Co-Authored-By: Claude Opus 5.5 --- docs/rqe_optimizer_TODO.md | 58 ++- docs/rqe_sketch_deployment_v1.md | 203 ++++---- .../data/ec2-pricing-2026-10-04.json | 34 -- rqe-optimizer/examples/small_problem.rs | 192 ++++---- rqe-optimizer/src/autosketch.rs | 30 +- rqe-optimizer/src/candidates.rs | 158 ++++--- rqe-optimizer/src/enumerate.rs | 14 +- rqe-optimizer/src/lib.rs | 257 +++++++++- rqe-optimizer/src/milp.rs | 442 ++++++------------ rqe-optimizer/src/objectives.rs | 415 ++++++++-------- rqe-optimizer/src/pareto.rs | 22 +- scripts/fetch_ec2_pricing.py | 70 --- 12 files changed, 940 insertions(+), 955 deletions(-) delete mode 100644 rqe-optimizer/data/ec2-pricing-2026-10-04.json delete mode 100755 scripts/fetch_ec2_pricing.py diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index fe427bfa..348ab3c1 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -5,18 +5,23 @@ implemented, what is next, and what is intentionally deferred. ## Done in v1 -- Sliding deployments use `(capability, configuration, labels, x, y)`, where - `x` is window size and `y` is slide. -- Eligibility enforces capability, labels, alignment, and the RQE's measured - `accuracy_metric` constraint. -- Candidate generation uses legal windows and subset gcds of query intervals. - A deployment may serve multiple compatible RQEs. +- Sliding deployments use `(capability, configuration, metric, G, x, y)`, + where `x` is window size and `y` is slide. +- 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, grouping, alignment, and the RQE's + measured `accuracy_metric` constraint. +- 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 query memory, ingest CPU, or per-RQE latency. -- The analytical model combines measured per-operation costs with label-set - cardinality and arrival rate to score ingest CPU, query CPU, merge CPU, - total CPU, query memory, and per-RQE latency. -- The Pareto vector is `(peak_query_memory, TCO_cpu, {latency_i})`. + of its RQEs with no worse instance memory, ingest CPU and memory, per-RQE + latency, 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. +- The Pareto vector is `(CPU, memory, {latency_i})`. - Eager enumeration remains available for small inputs. Streaming enumeration retains only the incremental Pareto frontier. - `small_problem --candidates-only` reports generated and retained candidate @@ -25,30 +30,33 @@ implemented, what is next, and what is intentionally deferred. can print initial example mappings. - `scripts/export_rqe_optimizer_costs.sh` exports the 18-row measured cost table used by `small_problem`, without changing ASAPQuery's exporter. -- The MILP uses HiGHS to minimize hourly price without enumerating mappings. It accepts - optional peak-memory and per-RQE latency bounds and returns a normal mapping. -- `small_problem --milp` accepts repeatable per-RQE latency limits and includes - 1-hour, 6-hour, and 1-day quantile RQEs to exercise those constraints. -- A regression test confirms the MILP matches exhaustive minimum-price search on - a tiny workload with shared deployment activation costs. -- Retained memory (`(x + max S) / y` instances per active deployment) is - scored, and `Objective::AUCCost` minimizes the hourly price on one EC2 - machine family in fractional instances. Prices are a committed snapshot from - `scripts/fetch_ec2_pricing.py`; `small_problem --milp --machine-family NAME` - uses it. +- The MILP uses HiGHS to minimize `Objective::AUCCost { w_cpu, w_mem }`, + `w_cpu × CPU + w_mem × memory GiB` (default `(1, 0)`), without enumerating + mappings. It accepts optional per-RQE latency bounds and returns a normal + mapping. +- `small_problem --milp` takes `--w-cpu`/`--w-mem` and repeatable per-RQE + latency limits, and includes 1-hour, 6-hour, and 1-day quantile RQEs to + exercise those constraints. +- Regression tests confirm the MILP matches exhaustive search on tiny + workloads with shared deployments, at several weightings. ## Next - Add a hard `--max-mappings` limit to streaming experiments. - Validate accuracy after merging `S / x` sketch instances. V1 currently uses single-instance measurements, which do not establish final query accuracy. -- Add repeated MILP solves for Pareto exploration across memory and latency - budgets, or through normalized weighted objectives. +- Add repeated MILP solves for Pareto exploration across latency budgets or + weights. +- Set `w_cpu`/`w_mem` from real prices. ## Explicitly deferred - Query-result sharing across RQEs. -- Merge buffers and concurrent-query memory. +- Real query concurrency; memory assumes every query runs at once. +- 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`. - 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_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 29dc92eb..4a453cac 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -19,18 +19,28 @@ Let `R = {r_1, ..., r_n}` be the RQE workload. Each RQE `r_i` provides: | `cap_i` | Required capability: `freq`, `quantile`, `cardinality`, or `topk`. | | `S_i` | Query-window size. This is the current `lookback` field. | | `T_i` | Query slide: how often the RQE runs. This is the current `interval` field. | -| `labels_i` | Group-by label set. | +| `metric_i` | Metric the RQE reads. | +| `G_i` | Group-by label set (`grouping_labels`). | | `accuracy_metric_i` | Accuracy measurement to check. | | `tol_i` | Accuracy threshold. | | `direction_i` | Whether lower or higher values are better. | -For each label set, the caller provides: +For each metric, the caller provides `MetricFacts`: -- `card(labels)`: number of distinct label-value groups. -- `lambda(labels)`: aggregate item arrival rate across those groups, in - items/second. +- `labels`: every label the metric's series carry. +- `scrape_interval`: every series yields one sample per scrape. +- `card(X)`: distinct value combinations of each label set `X` in use, + including `labels` itself (the raw series count). + +The arrival rate is derived, never given, so it can't disagree with the +cardinalities: + +```text +lambda(metric) = card(metric.labels) / scrape_interval samples/second +``` These are inputs to the optimizer; estimating them is outside v1. +`validate_facts` reports every missing or inconsistent fact up front. Sketch Bench supplies empirical measurements for each sketch configuration: @@ -91,24 +101,28 @@ modeled. A candidate deployment is: ```text -D = (capability, configuration, labels, x, y) +D = (capability, configuration, metric, G, x, y) ``` Candidates may be generated from individual RQEs, then deduplicated. This is only a way to construct the candidate set: when solving a workload, one selected deployment may serve multiple compatible RQEs. -For each capability/label-set group, generate candidates as follows: +For each (capability, metric, G) group, generate candidates as follows: ```text -for each x that divides S_i for at least one RQE i in the group: +for each x that divides S_i for at least one RQE i in the group, + and is a multiple of the metric's scrape interval: let g_i = gcd(x, T_i) for every RQE i whose S_i is divisible by x let slides = every gcd reachable from a non-empty subset of {g_i} for each measured configuration that serves the group's capability: - for each y in slides: - add (capability, configuration, labels, x, y) + for each y in slides that is a multiple of the scrape interval: + add (capability, configuration, metric, G, x, y) ``` +Windows and slides finer than the scrape interval would only split one +scrape's samples. + For an RQE considered alone, its only useful slide for a fixed `x` is its largest legal slide, `gcd(x, T_i)`. A smaller slide adds ingest fan-out without improving that RQE's query cost or memory. A shared deployment may need a @@ -119,7 +133,7 @@ in which case it appears as another subset gcd. An RQE `r_i` is eligible for a candidate `D` when: -1. `cap_i = D.capability` and `labels_i = D.labels`. +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. `D.configuration` contains a measured value for `accuracy_metric_i` that clears `tol_i` in `direction_i`. @@ -130,14 +144,15 @@ explicit on the RQE; 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 -RQE it can and is no worse in query memory, ingest CPU, latency, and retained -memory for each such RQE. This is safe because any mapping using the removed candidate can -substitute the remaining one without weakening a modeled objective. +RQE it can and is no worse in instance memory, ingest CPU and memory, latency, +and stored memory for each such RQE. This is safe because any mapping using +the removed candidate can substitute the remaining one without weakening a +modeled objective. -Historical instances must be retained long enough to answer the RQEs assigned -to a deployment. Retention is not a candidate parameter: a deployment retains -the history needed by the largest assigned query window. Its memory is scored -as retained memory (below) and priced by `Objective::AUCCost`. +Closed instances must be stored long enough to answer the RQEs 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 @@ -158,53 +173,39 @@ results from several deployments to satisfy one RQE. 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 -variable `M` for peak query memory. It minimizes a chosen scalarization or -solves under supplied budgets. +`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 -M ≥ 0 +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 RQE i z_{i,D} ≤ u_D for (i, D) ∈ E u_D ≤ Σ_{i: (i,D) ∈ E} z_{i,D} for every candidate D -M ≥ query_memory_{i,D} × z_{i,D} for (i, D) ∈ E +stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E ``` -The final `u_D` constraint prevents a deployment from becoming active when no +The `u_D ≤ Σ z` constraint prevents a deployment from becoming active when no RQE selected it. It is not required for feasibility, but makes ingest cost -unambiguous. +unambiguous. `stored_D` is a linearized max: a deployment stores enough for +the longest lookback it serves. -All CPU and latency terms are constants for an eligible pair. The solver uses: +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 -TCO_cpu = Σ_D ingest_cpu_D × u_D - + Σ_(i,D)∈E (query_cpu_{i,D} + merge_cpu_{i,D}) / T_i × z_{i,D} - -latency_i = Σ_{D: (i,D)∈E} latency_{i,D} × z_{i,D} +minimize Σ_D w(ingest_D) × u_D + + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} + + Σ_D stored_D ``` -The MILP's only objective, `Objective::AUCCost`, prices the plan on one EC2 -machine family `f` (vCPUs -`vcpu_f`, memory `gib_f`, hourly price `price_f`) in fractional instances -`n_f`, with a continuous `R_D ≥ 0` for each candidate's retained GiB: - -```text -minimize price_f × n_f -R_D ≥ retained_gib_{i,D} × z_{i,D} for (i, D) ∈ E -vcpu_f × n_f ≥ TCO_cpu -gib_f × n_f ≥ Σ_D R_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. -`TCO_cpu` is the area under the CPU curve (mean CPU-sec/sec), so instances are -sized for the mean load, not for bursts. Prices come from `rqe-optimizer/data/ec2-pricing-.json`, written by -`scripts/fetch_ec2_pricing.py`. Disk is not priced. - -One solve needs a scalar objective, such as minimum hourly price subject to -`M ≤ memory_budget` and optional `latency_i ≤ latency_budget_i`. To sample the -Pareto frontier, repeat solves over memory and latency budgets, or use a -normalized weighted objective. The solver never enumerates full mappings. +Per-RQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver +never enumerates full mappings. ## Analytical cost model @@ -212,75 +213,47 @@ 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`, let `a_D = D.x / D.y`. Each incoming item is inserted into -`a_D` concurrently active sketch instances per group. - -### Query working memory - -v1 models query working memory, not retained-storage footprint. For RQE `i`: - -```text -query_memory_i = card(labels_i) × mem_bytes(D(i).configuration) -``` - -This assumes one instance per group is loaded and groups are processed -concurrently. It does not model merge buffers or concurrent queries. - -The mapping-level memory objective is the worst individual query: +A deployment `D` holds `card(D.G)` instances per window, one per group. Let +`a_D = D.x / D.y`: each sample is inserted into `a_D` concurrently open +instances of its group. For RQE `i` on `D`, let `n_i = S_i / D.x` windows be +merged per query. Write `m`, `c_ins`, `c_mrg`, `c_qry` for the +configuration's measured per-instance memory and insert, merge and query CPU. -```text -peak_query_memory = max_i query_memory_i -``` - -### Retained memory +Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory +(bytes): -A deployment holds `x / y` open instances plus the closed instances still -inside the longest lookback it serves: +| Phase | CPU | Memory | +|---|---|---| +| Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | +| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one merged instance per group) | +| Query, per RQE | `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) | -```text -retained_memory = Σ_{D: u_D=1} card(D.labels) × mem_bytes(D.configuration) - × (D.x + max_{i: D(i)=D} S_i) / D.y -``` +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. -### CPU - -Ingest CPU is paid once for every active deployment: - -```text -ingest_cpu = Σ_{D: u_D=1} - lambda(D.labels) × a_D × insert_cpu_secs(D.configuration) -``` +Exact multi-group accumulators are measured as one instance holding many +groups. The export divides their memory and merge cost by the measured group +count, so `card(G) ×` prices them correctly too. A family holding every group +in one fixed-size instance (HydraKLL) would need a per-family shape instead +(sketch-bench#142). -For RQE `i`, let `n_i = S_i / D(i).x`. One query performs one final estimate -and `n_i - 1` pairwise merges for each group: +Per-RQE latency is the serial CPU time of one query: ```text -query_cpu_i = card(labels_i) × query_cpu_secs(D(i).configuration) -merge_cpu_i = card(labels_i) × (n_i - 1) × merge_cpu_secs(D(i).configuration) -latency_i = query_cpu_i + merge_cpu_i +latency_i = card(G) × (c_qry + (n_i − 1) × c_mrg) ``` -`latency_i` is estimated serial CPU time for one query, not a wall-clock SLA. -It assumes no parallel execution across groups and no cheaper k-way merge. - -The repeating query load is: - -```text -query_cpu = Σ_i query_cpu_i / T_i -merge_cpu = Σ_i merge_cpu_i / T_i -``` - -Total steady-state CPU is: - -```text -TCO_cpu = ingest_cpu + merge_cpu + query_cpu -``` +It is not a wall-clock SLA: it assumes no parallel execution across groups and +no cheaper k-way merge. ## Procedure 1. Generate candidate deployments for each input RQE, then deduplicate them. 2. Build the eligible candidate–RQE pairs. Reject pairs that fail capability, - labels, window alignment, or empirical accuracy. + metric, grouping, window alignment, or empirical accuracy. 3. Enumerate feasible workload mappings. Every RQE must select one eligible candidate; a single selected candidate may serve multiple RQEs. Small instances may retain every mapping eagerly; larger ones stream mappings @@ -291,11 +264,11 @@ TCO_cpu = ingest_cpu + merge_cpu + query_cpu The Pareto vector is: ```text -(peak_query_memory, TCO_cpu, {latency_i}) +(CPU, memory, {latency_i}) ``` -The report also includes `ingest_cpu`, `merge_cpu`, and `query_cpu` as the -breakdown of `TCO_cpu`, together with the selected deployment mapping. +CPU and memory are the sums over the four phases. The report also includes +each phase's CPU and memory, together with the selected deployment mapping. ## v1 scope and TODOs @@ -304,15 +277,17 @@ breakdown of `TCO_cpu`, together with the selected deployment mapping. selected mapping as truly accuracy-feasible. - **Query-result sharing:** v1 charges every RQE its own query and merge CPU. Revisit when RQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** v1 reports per-RQE latency but does not reject a mapping - for exceeding a target. Add optional per-RQE maximum latency as a hard - constraint when workloads supply targets. -- **Memory model:** merge buffers and concurrent queries are not modeled. +- **Latency SLAs:** the MILP takes optional per-RQE latency bounds; the + enumerator reports latency but does not reject a mapping for it. +- **Memory model:** query memory sums every RQE's merge and output memory, as + if all queries run at once; real concurrency is not modeled. Query output + size is an estimate. +- **Bursts:** CPU is a mean over time, so plans are sized for average load. - **Static planning:** no RQE churn, replanning, or migration cost. - **Rollups:** v1 does not precompute merged rollups. Queries merge their selected base instances when they run. -- **Selection policy:** the optimizer reports the Pareto frontier; selecting a - single point through weights or budgets is deferred. +- **Selection policy:** the enumerator reports the Pareto frontier; the MILP + selects one point by the `w_cpu`/`w_mem` weights. ## Implementation status diff --git a/rqe-optimizer/data/ec2-pricing-2026-10-04.json b/rqe-optimizer/data/ec2-pricing-2026-10-04.json deleted file mode 100644 index 49741bbd..00000000 --- a/rqe-optimizer/data/ec2-pricing-2026-10-04.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "source": "https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/ec2/USD/current/ec2-ondemand-without-sec-sel/US%20East%20(N.%20Virginia)/Linux/index.json", - "region": "US East (N. Virginia)", - "operating_system": "Linux", - "pricing": "on-demand", - "publication_date": "2026-09-25T17:45:21Z", - "fetched": "2026-10-04", - "families": [ - { - "family": "compute_optimized", - "instance_type": "c7i.xlarge", - "vcpu": 4, - "memory_gib": 8.0, - "usd_per_hour": 0.1785, - "rate_code": "D8WVCVBE32N227KA.JRTCKXETXF.6YS6EN2CT7" - }, - { - "family": "general_purpose", - "instance_type": "m7i.xlarge", - "vcpu": 4, - "memory_gib": 16.0, - "usd_per_hour": 0.2016, - "rate_code": "W8MD4QK5G3J3QYWR.JRTCKXETXF.6YS6EN2CT7" - }, - { - "family": "memory_optimized", - "instance_type": "r7i.xlarge", - "vcpu": 4, - "memory_gib": 32.0, - "usd_per_hour": 0.2646, - "rate_code": "PRGSWU6294SJ3Z93.JRTCKXETXF.6YS6EN2CT7" - } - ] -} diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 15d92714..5fe76abc 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -9,9 +9,9 @@ //! no translation layer, since `rqe_optimizer::Deployment` embeds //! `AtomicCostEntry` directly. //! -//! Every other number this example uses (RQE definitions, label-set -//! cardinality/arrival-rate) lives in the two tables below (`label_sets`, -//! `rqes`) and nowhere else in this file. +//! Every other number this example uses (RQE definitions, metric labels, +//! cardinalities and scrape intervals) lives in the two tables below +//! (`facts`, `rqes`) and nowhere else in this file. //! //! Run: `scripts/export_rqe_optimizer_costs.sh` once. Do not run this example //! with no mode flag on a large workload: eager mode retains every feasible @@ -20,9 +20,9 @@ //! `--candidates-only` to inspect candidate pruning safely, without starting //! mapping enumeration. Streaming mode logs progress every one million //! mappings by default; pass `--progress-every N` to change that interval or -//! `--print-first N` to display example mappings. `--milp --machine-family -//! NAME` (`compute_optimized`, `general_purpose`, `memory_optimized`) minimizes -//! that EC2 family's hourly price without enumerating mappings. Repeat +//! `--print-first N` to display example mappings. `--milp` minimizes +//! `w_cpu · CPU + w_mem · memory GiB` without enumerating mappings; set the +//! weights with `--w-cpu X --w-mem Y` (default 1 and 0). Repeat //! `--latency-limit RQE_ID=SECONDS` to impose MILP latency bounds. //! `--sample-mappings N` prints N feasible mappings and exits. @@ -34,10 +34,11 @@ use rqe_optimizer::candidates::{ }; use rqe_optimizer::enumerate::{brute_force, for_each_mapping, for_each_mapping_while, unservable}; use rqe_optimizer::milp::{minimize, MilpBounds, Objective}; -use rqe_optimizer::objectives::{score, MachineFamily}; +use rqe_optimizer::objectives::{score, Objectives}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; use rqe_optimizer::{ - AccuracyDirection, AtomicCostTable, Capability, LabelSet, LabelSetInfo, LabelSetTable, Rqe, + validate_facts, AccuracyDirection, AtomicCostTable, Capability, LabelSet, MetricFacts, Rqe, + WorkloadFacts, }; /// Accuracy metric keys the real comparators actually report (checked @@ -56,22 +57,9 @@ const CARDINALITY_ERR: &str = "relative_error"; const TOPK_PRECISION: &str = "precision_at_k"; const COST_TABLE_PATH: &str = "out/rqe_atomic_costs.json"; -const EC2_PRICING: &str = include_str!("../data/ec2-pricing-2026-10-04.json"); -fn machine_family() -> Option { - let args: Vec<_> = std::env::args().collect(); - let name = args - .windows(2) - .find(|pair| pair[0] == "--machine-family") - .map(|pair| pair[1].clone())?; - let families = MachineFamily::from_pricing_json(EC2_PRICING).expect("committed snapshot"); - Some( - families - .into_iter() - .find(|family| family.family == name) - .unwrap_or_else(|| panic!("unknown --machine-family: {name}")), - ) -} +const REQUESTS: &str = "http_requests_total"; +const DURATION: &str = "http_request_duration_seconds"; fn label_set(names: &[&str]) -> LabelSet { names.iter().map(|s| s.to_string()).collect() @@ -88,36 +76,39 @@ fn load_cost_table() -> AtomicCostTable { .unwrap_or_else(|e| panic!("{COST_TABLE_PATH} isn't a valid AtomicCostTable: {e}")) } -fn label_sets() -> LabelSetTable { - let mut t = LabelSetTable::new(); - // labels cardinality arrival_rate (items/sec) - t.insert( - label_set(&["service", "endpoint"]), - LabelSetInfo { - cardinality: 50, - arrival_rate_per_sec: 2_000.0, - }, - ); - t.insert( - label_set(&["service"]), - LabelSetInfo { - cardinality: 5, - arrival_rate_per_sec: 2_000.0, - }, - ); - t +/// Both metrics: 5 services × 10 endpoints × 600 pods = 30,000 series +/// scraped every 15 s, so `λ` = 2,000 samples/sec each. +fn facts() -> WorkloadFacts { + let metric = || MetricFacts { + labels: label_set(&["service", "endpoint", "pod"]), + scrape_interval_secs: 15, + cardinality: [ + (label_set(&["service"]), 5), + (label_set(&["service", "endpoint"]), 50), + (label_set(&["service", "endpoint", "pod"]), 30_000), + ] + .into(), + }; + [ + (REQUESTS.to_string(), metric()), + (DURATION.to_string(), metric()), + ] + .into() } fn rqes() -> Vec { let se = label_set(&["service", "endpoint"]); let s = label_set(&["service"]); + let requests = || REQUESTS.to_string(); + let duration = || DURATION.to_string(); vec![ Rqe { id: "req_rate_1h".to_string(), capability: Capability::RateOrIncrease, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -127,7 +118,8 @@ fn rqes() -> Vec { capability: Capability::RateOrIncrease, lookback_secs: 86_400, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -137,7 +129,8 @@ fn rqes() -> Vec { capability: Capability::RateOrIncrease, lookback_secs: 3_600, interval_secs: 300, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -147,7 +140,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -157,7 +151,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 21_600, interval_secs: 300, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -167,7 +162,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 86_400, interval_secs: 60, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -177,7 +173,8 @@ fn rqes() -> Vec { capability: Capability::Cardinality, lookback_secs: 3_600, interval_secs: 60, - labels: s.clone(), + metric: requests(), + grouping_labels: s.clone(), accuracy_metric: CARDINALITY_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -191,7 +188,8 @@ fn rqes() -> Vec { capability: Capability::TopK, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: TOPK_PRECISION.to_string(), accuracy_tolerance: 0.9, accuracy_direction: AccuracyDirection::HigherIsBetter, @@ -235,10 +233,11 @@ fn print_mapping( fn print_candidate(candidate_number: usize, deployment: &rqe_optimizer::Deployment) { println!( - "candidate {candidate_number}: {} {} labels={:?} (x={}s, y={}s)", + "candidate {candidate_number}: {} {} {} by {:?} (x={}s, y={}s)", deployment.config.sketch, deployment.config.sketch_config, - deployment.labels, + deployment.metric, + deployment.grouping_labels, deployment.window_secs, deployment.slide_secs, ); @@ -268,15 +267,50 @@ fn latency_bounds(rqes: &[Rqe]) -> Vec> { bounds } +fn weight_flag(name: &str, default: f64) -> f64 { + let args: Vec<_> = std::env::args().collect(); + match args.iter().position(|arg| arg == name) { + Some(index) => args + .get(index + 1) + .and_then(|value| value.parse::().ok()) + .filter(|value| *value >= 0.0) + .unwrap_or_else(|| panic!("{name} requires a non-negative number")), + None => default, + } +} + +fn print_objectives(label: &str, objectives: &Objectives) { + println!( + "{label}: cpu={:.3e} cpu-sec/sec, memory={:.1}MB", + objectives.cpu_secs_per_sec(), + objectives.memory_bytes() / 1e6, + ); + for (phase, cost) in [ + ("ingest", &objectives.ingest), + ("merge", &objectives.merge), + ("query", &objectives.query), + ("storage", &objectives.storage), + ] { + println!( + " {phase:<7} cpu={:.3e} memory={:.1}MB", + cost.cpu_secs_per_sec, + cost.memory_bytes / 1e6, + ); + } +} + fn main() { let candidates_only = std::env::args().any(|arg| arg == "--candidates-only"); let rqes = rqes(); let cost_table = load_cost_table(); - let label_sets = label_sets(); + let facts = facts(); + if let Err(problems) = validate_facts(&rqes, &facts) { + panic!("invalid workload facts: {problems:#?}"); + } let unpruned_count = - candidates_only.then(|| build_all_candidates_unpruned(&rqes, &cost_table).len()); - let deployments = build_all_candidates(&rqes, &cost_table); + candidates_only.then(|| build_all_candidates_unpruned(&rqes, &cost_table, &facts).len()); + let deployments = build_all_candidates(&rqes, &cost_table, &facts); println!( "{} RQEs, {} candidate deployments (from {} real cost-table rows)", rqes.len(), @@ -341,35 +375,19 @@ fn main() { if std::env::args().any(|arg| arg == "--milp") { let bounds = MilpBounds { - max_peak_query_memory_bytes: None, max_query_latency_secs: latency_bounds(&rqes), }; - let family = machine_family().expect("--milp needs --machine-family NAME"); - let solution = minimize( - &rqes, - &deployments, - &label_sets, - &bounds, - Objective::AUCCost(&family), - ) - .expect("small_problem MILP should be feasible"); - println!( - "MILP minimum-cost solution on {}: ${:.4}/hour, {:.4} instances, \ - retained_mem={:.0}MB", - family.family, - family.usd_per_hour(&solution.objectives), - family.instances(&solution.objectives), - solution.objectives.retained_memory_bytes / 1e6, - ); + let objective = Objective::AUCCost { + w_cpu: weight_flag("--w-cpu", 1.0), + w_mem: weight_flag("--w-mem", 0.0), + }; + let solution = minimize(&rqes, &deployments, &facts, &bounds, objective) + .expect("small_problem MILP should be feasible"); println!( - "MILP solution: peak_query_mem={:.0}MB, ingest={:.3e}, \ - merge={:.3e}, query={:.3e}, total={:.3e} cpu-sec/sec", - solution.objectives.peak_query_memory_bytes / 1e6, - solution.objectives.ingest_cpu_secs_per_sec, - solution.objectives.merge_cpu_secs_per_sec, - solution.objectives.query_cpu_secs_per_sec, - solution.objectives.tco_cpu_secs_per_sec, + "MILP solution for {objective:?}: {:.3e}", + objective.value(&solution.objectives) ); + print_objectives(" totals", &solution.objectives); print_mapping(1, &solution.mapping, &rqes, &deployments); for (rqe, latency) in rqes.iter().zip(&solution.objectives.query_latency_secs) { println!(" {}: query_latency={latency:.3e} sec", rqe.id); @@ -384,7 +402,7 @@ fn main() { let started = Instant::now(); let mut processed = 0_u64; let mapping_count = for_each_mapping(&rqes, &deployments, |mapping| { - front.consider(mapping, score(&rqes, &deployments, mapping, &label_sets)); + front.consider(mapping, score(&rqes, &deployments, mapping, &facts)); processed += 1; if processed <= print_first { print_mapping(processed, mapping, &rqes, &deployments); @@ -415,7 +433,7 @@ fn main() { let objectives: Vec<_> = mappings .iter() - .map(|m| score(&rqes, &deployments, m, &label_sets)) + .map(|m| score(&rqes, &deployments, m, &facts)) .collect(); let front = pareto_front(&objectives); println!("{} on the Pareto front\n", front.len()); @@ -425,15 +443,9 @@ fn main() { for &i in &front { let obj = &objectives[i]; let distinct_deployments: BTreeSet = mappings[i].iter().copied().collect(); - println!( - "mapping {i}: {} deployments, peak_query_mem={:.0}MB, ingest={:.3e}, \ - merge={:.3e}, query={:.3e}, total={:.3e} cpu-sec/sec", - distinct_deployments.len(), - obj.peak_query_memory_bytes / 1e6, - obj.ingest_cpu_secs_per_sec, - obj.merge_cpu_secs_per_sec, - obj.query_cpu_secs_per_sec, - obj.tco_cpu_secs_per_sec, + print_objectives( + &format!("mapping {i}: {} deployments", distinct_deployments.len()), + obj, ); for (rqe, latency) in rqes.iter().zip(&obj.query_latency_secs) { let rqe_id = &rqe.id; diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index f650117c..8b98884d 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -72,7 +72,8 @@ pub fn plan( let (window_secs, slide_secs) = window_adapter(rqe); Deployment { capability: rqe.capability, - labels: rqe.labels.clone(), + metric: rqe.metric.clone(), + grouping_labels: rqe.grouping_labels.clone(), config: costs[s.selected.expect("unservable RQEs returned above")].clone(), window_secs, slide_secs, @@ -321,8 +322,9 @@ impl Rng { mod tests { use super::*; use crate::candidates::is_eligible; - use crate::objectives::score; - use crate::{AccuracyDirection, Capability, LabelSet, LabelSetInfo, LabelSetTable}; + use crate::objectives::{score, PhaseCost}; + use crate::test_support::{facts, METRIC}; + use crate::{AccuracyDirection, Capability, LabelSet}; use std::collections::BTreeSet; const ERR: &str = "err"; @@ -355,7 +357,8 @@ mod tests { capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: ERR.into(), accuracy_tolerance: tolerance, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -409,18 +412,15 @@ mod tests { assert_eq!(plan.deployments[0], plan.deployments[1]); assert_eq!(plan.mapping, vec![0, 1]); - let labels: LabelSetTable = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 10.0, - }, - )]); - let both = score(&rqes, &plan.deployments, &plan.mapping, &labels); - let one = score(&rqes[..1], &plan.deployments[..1], &vec![0], &labels); + let facts = facts(1, 10); + let both = score(&rqes, &plan.deployments, &plan.mapping, &facts); + let one = score(&rqes[..1], &plan.deployments[..1], &vec![0], &facts); assert_eq!( - both.ingest_cpu_secs_per_sec, - 2.0 * one.ingest_cpu_secs_per_sec + both.ingest, + PhaseCost { + cpu_secs_per_sec: 2.0 * one.ingest.cpu_secs_per_sec, + memory_bytes: 2.0 * one.ingest.memory_bytes, + } ); } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index e8dc0540..9e874f81 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,6 +1,6 @@ //! Candidate generation and eligibility (§3). -use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds}; +use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds, WorkloadFacts}; use std::collections::{BTreeMap, BTreeSet}; pub fn gcd(a: Seconds, b: Seconds) -> Seconds { @@ -39,15 +39,21 @@ fn subset_gcds(values: impl IntoIterator) -> BTreeSet { out } -fn candidate_deployments(group: &[&Rqe], costs: &[AtomicCostEntry]) -> Vec { +/// Windows and slides are multiples of the metric's scrape interval (#143 +/// S6): anything finer only splits one scrape's samples. +fn candidate_deployments( + group: &[&Rqe], + costs: &[AtomicCostEntry], + scrape_secs: Seconds, +) -> Vec { if group.is_empty() { return Vec::new(); } let capability = group[0].capability; - let labels = group[0].labels.clone(); let windows = group .iter() .flat_map(|r| divisors(r.lookback_secs)) + .filter(|w| w.is_multiple_of(scrape_secs)) .collect::>(); let mut deployments = Vec::new(); for window_secs in windows { @@ -61,48 +67,62 @@ fn candidate_deployments(group: &[&Rqe], costs: &[AtomicCostEntry]) -> Vec Vec { - prune_dominated_candidates(rqes, build_all_candidates_unpruned(rqes, costs)) +pub fn build_all_candidates( + rqes: &[Rqe], + costs: &[AtomicCostEntry], + facts: &WorkloadFacts, +) -> Vec { + prune_dominated_candidates(rqes, build_all_candidates_unpruned(rqes, costs, facts)) } /// Generate the complete v1 candidate set before dominance pruning. /// /// The public optimizer entry point is [`build_all_candidates`]. This helper /// exists so diagnostics can report exactly how much safe pruning removed. -pub fn build_all_candidates_unpruned(rqes: &[Rqe], costs: &[AtomicCostEntry]) -> Vec { - let mut groups: BTreeMap<(Capability, LabelSet), Vec<&Rqe>> = BTreeMap::new(); +pub fn build_all_candidates_unpruned( + rqes: &[Rqe], + costs: &[AtomicCostEntry], + facts: &WorkloadFacts, +) -> Vec { + let mut groups: BTreeMap<(Capability, &str, &LabelSet), Vec<&Rqe>> = BTreeMap::new(); for rqe in rqes { groups - .entry((rqe.capability, rqe.labels.clone())) + .entry((rqe.capability, &rqe.metric, &rqe.grouping_labels)) .or_default() .push(rqe); } groups - .values() - .flat_map(|group| candidate_deployments(group, costs)) + .iter() + .flat_map(|(&(_, metric, _), group)| { + candidate_deployments(group, costs, facts[metric].scrape_interval_secs) + }) .collect() } /// Remove a candidate only when another candidate can replace it in every /// mapping without making any modeled objective worse. /// -/// This comparison is deliberately local to a capability/label-set group. -/// Within such a group, label cardinality and arrival rate are common -/// multipliers, so comparing per-instance query memory and -/// `active_instances * insert_cost` is sufficient. Query latency and retained -/// memory are checked for each RQE the dominated candidate can serve. +/// This comparison is deliberately local to a (capability, metric, grouping) +/// group. Within such a group, `card(G)`, arrival rate and query output size +/// are common multipliers, so comparing per-instance memory (merge) and +/// `active_instances ×` insert cost and memory (ingest) is sufficient. Query +/// latency (merge and query CPU) and stored memory are checked for each RQE +/// the dominated candidate can serve. pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> Vec { let eligibility: Vec> = candidates .iter() @@ -147,16 +167,18 @@ fn candidate_dominates( original_coverage: &[bool], rqes: &[Rqe], ) -> bool { - if replacement.capability != original.capability || replacement.labels != original.labels { + if replacement.capability != original.capability + || replacement.metric != original.metric + || replacement.grouping_labels != original.grouping_labels + { return false; } - let replacement_ingest = replacement.active_instance_count().unwrap_or(u64::MAX) as f64 - * replacement.config.insert_cpu_secs; - let original_ingest = original.active_instance_count().unwrap_or(u64::MAX) as f64 - * original.config.insert_cpu_secs; replacement.config.mem_bytes_per_instance <= original.config.mem_bytes_per_instance - && replacement_ingest <= original_ingest + && ingest(replacement) + .iter() + .zip(ingest(original)) + .all(|(r, o)| *r <= o) && original_coverage .iter() .zip(replacement_coverage) @@ -168,8 +190,8 @@ fn candidate_dominates( !serves || (query_latency(replacement, &rqes[rqe_index]) <= query_latency(original, &rqes[rqe_index]) - && retained_memory(replacement, &rqes[rqe_index]) - <= retained_memory(original, &rqes[rqe_index])) + && stored_memory(replacement, &rqes[rqe_index]) + <= stored_memory(original, &rqes[rqe_index])) }) } @@ -180,12 +202,11 @@ fn strictly_better( original_coverage: &[bool], rqes: &[Rqe], ) -> bool { - let replacement_ingest = replacement.active_instance_count().unwrap_or(u64::MAX) as f64 - * replacement.config.insert_cpu_secs; - let original_ingest = original.active_instance_count().unwrap_or(u64::MAX) as f64 - * original.config.insert_cpu_secs; replacement.config.mem_bytes_per_instance < original.config.mem_bytes_per_instance - || replacement_ingest < original_ingest + || ingest(replacement) + .iter() + .zip(ingest(original)) + .any(|(r, o)| *r < o) || original_coverage .iter() .zip(replacement_coverage) @@ -197,11 +218,21 @@ fn strictly_better( serves && (query_latency(replacement, &rqes[rqe_index]) < query_latency(original, &rqes[rqe_index]) - || retained_memory(replacement, &rqes[rqe_index]) - < retained_memory(original, &rqes[rqe_index])) + || stored_memory(replacement, &rqes[rqe_index]) + < stored_memory(original, &rqes[rqe_index])) }) } +/// Ingest CPU and memory per group, up to the group's common `λ` / `card(G)`: +/// `active_instances ×` insert cost and instance size. +fn ingest(deployment: &Deployment) -> [f64; 2] { + let active = deployment.active_instance_count().unwrap_or(u64::MAX) as f64; + [ + active * deployment.config.insert_cpu_secs, + active * deployment.config.mem_bytes_per_instance, + ] +} + fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { let instances = deployment .query_instance_count(rqe.lookback_secs) @@ -210,11 +241,11 @@ fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { + instances.saturating_sub(1) as f64 * deployment.config.merge_cpu_secs } -/// Retained bytes per label group when serving `rqe`. Label cardinality is a -/// common multiplier within a group, so it is left out. -fn retained_memory(deployment: &Deployment, rqe: &Rqe) -> f64 { +/// Closed-window bytes per group when serving `rqe`. `card(G)` is a common +/// multiplier within a group, so it is left out. +fn stored_memory(deployment: &Deployment, rqe: &Rqe) -> f64 { deployment - .retained_instance_count(rqe.lookback_secs) + .closed_instance_count(rqe.lookback_secs) .expect("candidate coverage only contains exactly tiled RQEs") as f64 * deployment.config.mem_bytes_per_instance } @@ -230,7 +261,8 @@ pub fn eligible_deployments_for(r: &Rqe, deployments: &[Deployment]) -> Vec bool { r.capability == d.capability - && r.labels == d.labels + && r.metric == d.metric + && r.grouping_labels == d.grouping_labels && d.window_secs != 0 && d.slide_secs != 0 && d.window_secs.is_multiple_of(d.slide_secs) @@ -242,6 +274,7 @@ pub fn is_eligible(r: &Rqe, d: &Deployment) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::test_support::{facts, METRIC}; use crate::{AccuracyDirection, LabelSet}; use std::collections::BTreeMap; fn rqe(id: &str, lookback: Seconds, interval: Seconds) -> Rqe { @@ -250,7 +283,8 @@ mod tests { capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: "err".into(), accuracy_tolerance: 1.0, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -270,7 +304,7 @@ mod tests { #[test] fn shared_slide_comes_from_subset_gcd_not_all_divisors() { let rqes = vec![rqe("a", 60, 20), rqe("b", 60, 30)]; - let candidates = build_all_candidates(&rqes, &[cost()]); + let candidates = build_all_candidates(&rqes, &[cost()], &facts(1, 1)); let slides: BTreeSet<_> = candidates .iter() .filter(|d| d.window_secs == 60) @@ -279,6 +313,18 @@ mod tests { assert_eq!(slides, BTreeSet::from([10, 20, 30])); } #[test] + fn windows_and_slides_are_multiples_of_the_scrape_interval() { + let rqes = vec![rqe("a", 60, 20), rqe("b", 60, 30)]; + let mut facts = facts(1, 1); + facts.get_mut(METRIC).unwrap().scrape_interval_secs = 15; + let candidates = build_all_candidates_unpruned(&rqes, &[cost()], &facts); + assert!(!candidates.is_empty()); + // Without the filter, windows 1..60 and slides 10/20 would appear. + assert!(candidates + .iter() + .all(|d| d.window_secs % 15 == 0 && d.slide_secs % 15 == 0)); + } + #[test] fn a_min_query_is_only_offered_the_min_accumulator() { let r = Rqe { capability: Capability::Min, @@ -288,7 +334,11 @@ mod tests { sketch: sketch.into(), ..cost() }; - let candidates = build_all_candidates(&[r], &[named("exact-min"), named("exact-max")]); + let candidates = build_all_candidates( + &[r], + &[named("exact-min"), named("exact-max")], + &facts(1, 1), + ); assert!(!candidates.is_empty()); assert!(candidates.iter().all(|d| d.config.sketch == "exact-min")); } @@ -298,7 +348,8 @@ mod tests { let r = rqe("r", 600, 180); let d = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost(), window_secs: 120, slide_secs: 60, @@ -325,7 +376,8 @@ mod tests { let r = rqe("r", 60, 60); let coarse = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost(), window_secs: 60, slide_secs: 60, @@ -346,7 +398,8 @@ mod tests { let cost = cost(); let large_window = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost.clone(), window_secs: 60, slide_secs: 60, @@ -364,12 +417,13 @@ mod tests { } #[test] - fn retains_candidate_with_lower_retained_memory() { + fn retains_candidate_with_lower_stored_memory() { let r = rqe("r", 60, 60); - // Holds (60 + 60) / 60 = 2 instances of 10 bytes. + // Stores (60 − 60) / 60 + 1 = 1 closed instance of 10 bytes. let whole_window = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: AtomicCostEntry { mem_bytes_per_instance: 10.0, ..cost() @@ -377,7 +431,7 @@ mod tests { window_secs: 60, slide_secs: 60, }; - // Smaller, faster sketches, but (20 + 60) / 20 = 4 of them: 24 bytes. + // Smaller, faster sketches, but (60 − 20) / 20 + 1 = 3 of them: 18 bytes. let panes = Deployment { config: AtomicCostEntry { mem_bytes_per_instance: 6.0, diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 7b6b33db..5f435b9e 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -2,7 +2,7 @@ //! //! A mapping is one deployment choice per RQE (§4's only constraint is //! `Σ_D x_{i,D} = 1`; `y_D` is derived). No RQE is eligible outside its own -//! `(capability, labels)` group, so choices are independent and the search +//! `(capability, metric, grouping_labels)` group, so choices are independent and the search //! space is exactly the cartesian product of the per-RQE eligible lists -- //! nothing to prune against. Sharing falls out when two choices land on the //! same index. @@ -107,8 +107,9 @@ pub fn for_each_mapping_while( #[cfg(test)] mod tests { use super::*; - use crate::candidates::build_all_candidates; - use crate::{AtomicCostEntry, Capability, LabelSet}; + use crate::candidates; + use crate::test_support::{facts, METRIC}; + use crate::{AtomicCostEntry, Capability, Deployment, LabelSet}; use std::collections::BTreeMap; fn cost(sketch: &str) -> AtomicCostEntry { @@ -125,13 +126,18 @@ mod tests { } } + fn build_all_candidates(rqes: &[Rqe], costs: &[AtomicCostEntry]) -> Vec { + candidates::build_all_candidates(rqes, costs, &facts(1, 1)) + } + fn rqe(id: &str, interval: u64, lookback: u64) -> Rqe { Rqe { id: id.to_string(), capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: "err".to_string(), accuracy_tolerance: 1.0, accuracy_direction: crate::AccuracyDirection::LowerIsBetter, diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 338f1070..6faa2ed3 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -6,7 +6,8 @@ //! [`candidates`] builds 𝒟 and per-RQE eligibility (§3), [`enumerate`] //! searches (§4), [`objectives`] scores (§5). //! -//! Every number the algorithm uses is caller-supplied -- no constants here. +//! Every number the algorithm uses is caller-supplied, except the query +//! output size estimates in [`objectives`]. pub mod autosketch; pub mod candidates; @@ -70,16 +71,75 @@ impl Capability { } } -/// Property of a label set, not of an RQE (§1): RQEs sharing a label set -/// read the same grouped stream. Given as input, never estimated. -#[derive(Debug, Clone, Copy)] -pub struct LabelSetInfo { - /// `card(labels)`: distinct label-value combinations, i.e. how many - /// physical sketch instances one deployment for this label set needs. - pub cardinality: u64, - /// `λ(labels)`: aggregate items/sec flowing into this grouped stream, - /// across all of its groups. - pub arrival_rate_per_sec: f64, +/// Facts about one metric's stream, given as input (#143 S2). RQEs and +/// deployments on the same metric read the same samples, grouped by +/// `grouping_labels`. +#[derive(Debug, Clone)] +pub struct MetricFacts { + /// Every label the metric's series carry, so `cardinality[labels]` is the + /// raw series count. + pub labels: LabelSet, + /// Every series yields one sample per scrape. + pub scrape_interval_secs: Seconds, + /// `card(G)`: distinct value combinations of each label set in use, i.e. + /// how many instances a deployment grouped by `G` holds per window. Must + /// include `labels` itself. + pub cardinality: BTreeMap, +} + +impl MetricFacts { + /// `λ`: samples/sec across all of the metric's series. Derived, never + /// given, so it can't disagree with the cardinalities. + pub fn arrival_rate_per_sec(&self) -> f64 { + self.cardinality[&self.labels] as f64 / self.scrape_interval_secs as f64 + } +} + +/// [`MetricFacts`] keyed by metric name. +pub type WorkloadFacts = BTreeMap; + +/// Every problem with `facts` for serving `rqes`, so a caller sees them all +/// at once. The rest of the crate indexes `facts` without checks, so call +/// this first on caller input. +pub fn validate_facts(rqes: &[Rqe], facts: &WorkloadFacts) -> Result<(), Vec> { + let mut problems = BTreeSet::new(); + for rqe in rqes { + let (metric, grouping) = (&rqe.metric, &rqe.grouping_labels); + let Some(f) = facts.get(metric) else { + problems.insert(format!("{metric}: no facts for this metric")); + continue; + }; + if f.scrape_interval_secs == 0 { + problems.insert(format!("{metric}: scrape interval is 0")); + } + if !grouping.is_subset(&f.labels) { + problems.insert(format!( + "{metric}: grouping {grouping:?} is not a subset of its labels {:?}", + f.labels + )); + } + for labels in [grouping, &f.labels] { + match f.cardinality.get(labels) { + None => problems.insert(format!("{metric}: no cardinality for {labels:?}")), + Some(0) => problems.insert(format!("{metric}: cardinality of {labels:?} is 0")), + Some(_) => false, + }; + } + if let (Some(&groups), Some(&series)) = + (f.cardinality.get(grouping), f.cardinality.get(&f.labels)) + { + if groups > series { + problems.insert(format!( + "{metric}: {grouping:?} has {groups} groups but only {series} series" + )); + } + } + } + if problems.is_empty() { + Ok(()) + } else { + Err(problems.into_iter().collect()) + } } /// Which way an accuracy metric runs. Most comparators report an error @@ -106,7 +166,9 @@ pub struct Rqe { pub lookback_secs: Seconds, /// `T_i`: how often this RQE is queried. pub interval_secs: Seconds, - pub labels: LabelSet, + pub metric: String, + /// `G`: the query's group-by labels. + pub grouping_labels: LabelSet, /// Which `AtomicCostEntry::query_accuracy` key to check. Comparators /// name their metrics differently per capability, so the RQE picks. pub accuracy_metric: String, @@ -136,13 +198,15 @@ impl Rqe { } } -/// A candidate deployment (§3): one configuration, one label set, and a +/// A candidate deployment (§3): 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)] pub struct Deployment { pub capability: Capability, - pub labels: LabelSet, + pub metric: String, + /// `G`: one instance per group, per window. + pub grouping_labels: LabelSet, pub config: AtomicCostEntry, /// `x`: materialized sketch-window size. pub window_secs: Seconds, @@ -167,12 +231,13 @@ impl Deployment { Some(lookback_secs / self.window_secs) } - /// Instances held to serve a lookback: `x / y` open ones plus the closed - /// ones still inside the lookback, `(x + S) / y`. - pub fn retained_instance_count(&self, lookback_secs: Seconds) -> Option { + /// Closed instances held to serve a lookback (#143 S7): those lying + /// wholly inside it, which start in `[now − L, now − x]`, so + /// `(L − x) / y + 1`. Open instances are [`Self::active_instance_count`]. + pub fn closed_instance_count(&self, lookback_secs: Seconds) -> Option { self.query_instance_count(lookback_secs)?; self.active_instance_count()?; - Some((self.window_secs + lookback_secs) / self.slide_secs) + Some((lookback_secs - self.window_secs) / self.slide_secs + 1) } } @@ -183,6 +248,156 @@ impl Deployment { /// separately, it's always derived from `mapping`. pub type Mapping = Vec; -/// `LabelSetInfo` lookup used throughout -- keyed by the same `LabelSet` -/// type deployments and RQEs carry. -pub type LabelSetTable = BTreeMap; +/// Fixtures shared by the unit tests: one metric `m`, grouped by nothing, +/// served by top-k. +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + + pub const METRIC: &str = "m"; + + /// `groups` groups and `series` raw series scraped every second, so + /// `λ = series`. Not validated: unit tests set `groups` freely. + pub fn facts(groups: u64, series: u64) -> WorkloadFacts { + let labels = LabelSet::from(["series".to_string()]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels.clone(), + scrape_interval_secs: 1, + cardinality: BTreeMap::from([(LabelSet::new(), groups), (labels, series)]), + }, + )]) + } + + pub fn rqe(lookback_secs: Seconds, interval_secs: Seconds) -> Rqe { + Rqe { + id: "r".into(), + capability: Capability::TopK, + lookback_secs, + interval_secs, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + accuracy_metric: "err".into(), + accuracy_tolerance: 1.0, + accuracy_direction: AccuracyDirection::LowerIsBetter, + } + } + + /// Per-instance memory and insert/merge/query CPU, then window and slide. + pub fn deployment( + memory: f64, + insert: f64, + merge: f64, + query: f64, + window_secs: Seconds, + slide_secs: Seconds, + ) -> Deployment { + Deployment { + capability: Capability::TopK, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + config: AtomicCostEntry { + sketch: "cms-heap-topk-fastpath-vector2d".into(), + sketch_config: serde_json::json!(null), + mem_bytes_per_instance: memory, + insert_cpu_secs: insert, + merge_cpu_secs: merge, + query_cpu_secs: query, + query_accuracy: BTreeMap::from([("err".into(), 0.0)]), + }, + window_secs, + slide_secs, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use test_support::{deployment, rqe, METRIC}; + + fn labels(names: &[&str]) -> LabelSet { + names.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn closed_instances_lie_wholly_inside_the_lookback() { + // Windows of 10 min every 1 min over 1 h start in [now − 60, now − 10]. + let d = deployment(1.0, 1.0, 1.0, 1.0, 600, 60); + assert_eq!(d.closed_instance_count(3_600), Some(51)); + assert_eq!(d.closed_instance_count(600), Some(1)); + assert_eq!(d.closed_instance_count(900), None); // not tiled by x + } + + #[test] + fn valid_facts_pass() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint"]), + scrape_interval_secs: 15, + cardinality: BTreeMap::from([ + (labels(&["service"]), 5), + (labels(&["service", "endpoint"]), 50), + ]), + }, + )]); + let r = Rqe { + grouping_labels: labels(&["service"]), + ..rqe(60, 60) + }; + assert_eq!(validate_facts(&[r], &facts), Ok(())); + } + + #[test] + fn reports_every_problem_at_once() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service"]), + scrape_interval_secs: 0, + cardinality: BTreeMap::from([(labels(&["service"]), 0)]), + }, + )]); + let rqes = [ + Rqe { + metric: "missing".into(), + ..rqe(60, 60) + }, + Rqe { + grouping_labels: labels(&["pod"]), + ..rqe(60, 60) + }, + ]; + let problems = validate_facts(&rqes, &facts).unwrap_err(); + let has = |needle: &str| problems.iter().any(|p| p.contains(needle)); + assert!(has("missing: no facts")); + assert!(has("scrape interval is 0")); + assert!(has("not a subset")); + assert!(has("no cardinality for {\"pod\"}")); + assert!(has("cardinality of {\"service\"} is 0")); + assert_eq!(problems.len(), 5, "{problems:?}"); + } + + #[test] + fn rejects_more_groups_than_series() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint"]), + scrape_interval_secs: 15, + cardinality: BTreeMap::from([ + (labels(&["service"]), 60), + (labels(&["service", "endpoint"]), 50), + ]), + }, + )]); + let r = Rqe { + grouping_labels: labels(&["service"]), + ..rqe(60, 60) + }; + let problems = validate_facts(&[r], &facts).unwrap_err(); + assert!(problems[0].contains("60 groups but only 50 series")); + } +} diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index d29d781d..401f793a 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -4,38 +4,51 @@ //! enumerating the Cartesian product of eligible deployment choices. use crate::candidates::eligible_deployments_for; -use crate::objectives::{score, MachineFamily, Objectives, BYTES_PER_GIB}; -use crate::{Deployment, LabelSetTable, Mapping, Rqe}; +use crate::objectives::{self, score, Objectives, PhaseCost, BYTES_PER_GIB}; +use crate::{Deployment, Mapping, Rqe, WorkloadFacts}; use good_lp::{ - default_solver, variable, Constraint, Expression, ProblemVariables, ResolutionError, Solution, - SolverModel, Variable, + default_solver, variable, Expression, ProblemVariables, ResolutionError, Solution, SolverModel, + Variable, }; /// What a [`minimize`] solve minimizes. Eligibility, assignment and activation /// rows, and bounds are the same for every objective. -#[derive(Debug, Clone, Copy)] -pub enum Objective<'a> { - /// Hourly price of running the plan on one machine family, in fractional - /// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. CPU is the - /// area under the load curve (mean CPU-sec/sec), so bursts are not priced. - AUCCost(&'a MachineFamily), +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Objective { + /// `w_cpu · CPU + w_mem · memory`. CPU is mean CPU-sec/sec, the area under + /// the load curve, so bursts are not priced. Memory is GiB summed over + /// every phase, as if every query evaluates at once. + AUCCost { w_cpu: f64, w_mem: f64 }, } -impl Objective<'_> { - /// Per resource, the units the goal is measured in: the vCPU and GiB of - /// one instance. - fn units(self) -> (f64, f64) { - match self { - Objective::AUCCost(family) => (family.vcpu, family.memory_gib), +impl Default for Objective { + /// CPU only, until memory gets a price. + fn default() -> Self { + Objective::AUCCost { + w_cpu: 1.0, + w_mem: 0.0, } } } +impl Objective { + pub fn value(&self, objectives: &Objectives) -> f64 { + self.weigh(PhaseCost { + cpu_secs_per_sec: objectives.cpu_secs_per_sec(), + memory_bytes: objectives.memory_bytes(), + }) + } + + fn weigh(&self, cost: PhaseCost) -> f64 { + let Objective::AUCCost { w_cpu, w_mem } = *self; + w_cpu * cost.cpu_secs_per_sec + w_mem * cost.memory_bytes / BYTES_PER_GIB + } +} + /// Optional hard bounds for a solve. An empty latency vector means no RQE has /// a latency bound; otherwise it is index-aligned with `rqes`. #[derive(Debug, Clone, Default)] pub struct MilpBounds { - pub max_peak_query_memory_bytes: Option, pub max_query_latency_secs: Vec>, } @@ -45,13 +58,14 @@ pub struct MilpSolution { pub objectives: Objectives, } -/// Minimize `objective` subject to optional memory and latency bounds. Missing -/// eligible deployments are a caller input error; use `enumerate::unservable` -/// to report them before calling this function. +/// Minimize `objective` subject to optional latency bounds. `facts` must pass +/// [`crate::validate_facts`]. Missing eligible deployments are a caller input +/// error; use `enumerate::unservable` to report them before calling this +/// function. pub fn minimize( rqes: &[Rqe], deployments: &[Deployment], - label_sets: &LabelSetTable, + facts: &WorkloadFacts, bounds: &MilpBounds, objective: Objective, ) -> Result { @@ -84,40 +98,43 @@ pub fn minimize( .collect() }) .collect(); + // Weighted closed-window storage per deployment: a linearized max over the + // RQEs it serves. + let stored: Vec = deployments + .iter() + .map(|_| variables.add(variable().min(0))) + .collect(); - // Real plans cost ~1e-6 $/hour and read in microseconds, below HiGHS's - // absolute gap (1e-6) and feasibility tolerance (1e-7). So every row is - // scaled to O(1) by `reference`, a plan's resource demand without sharing - // (each RQE on its cheapest deployment); per-RQE bounds become exclusions. Results are re-scored on - // real costs below, so the scaling never leaks out. - let ingest = |deployment: &Deployment| { - let fanout = deployment - .active_instance_count() - .expect("candidate window and slide align") as f64; - label_sets[&deployment.labels].arrival_rate_per_sec - * fanout - * deployment.config.insert_cpu_secs + // Weighted costs: ingest once per active deployment; merge and query once + // per assignment; storage as the max over a deployment's assignments. + let ingest: Vec = deployments + .iter() + .map(|d| objective.weigh(objectives::ingest(d, facts))) + .collect(); + let per_assignment = |r: &Rqe, d: &Deployment| { + objective.weigh(objectives::merge(r, d, facts)) + + objective.weigh(objectives::query(r, d, facts)) }; - let retained = |rqe: &Rqe, deployment: &Deployment| { - label_sets[&deployment.labels].cardinality as f64 - * deployment.config.mem_bytes_per_instance - * deployment - .retained_instance_count(rqe.lookback_secs) - .expect("assignment only contains eligible deployments") as f64 - / BYTES_PER_GIB + let storage = |r: &Rqe, d: &Deployment| { + objective.weigh(PhaseCost { + cpu_secs_per_sec: 0.0, + memory_bytes: objectives::storage_bytes(r, d, facts), + }) }; - let (cpu_unit, gib_unit) = objective.units(); + + // Real plans cost ~1e-6 CPU-sec/sec and read in microseconds, below + // HiGHS's absolute gap (1e-6) and feasibility tolerance (1e-7). So every + // row is scaled to O(1) by `reference`, a plan's cost without sharing + // (each RQE on its cheapest deployment); per-RQE bounds become exclusions. + // Results are re-scored on real costs below, so the scaling never leaks out. let reference: f64 = rqes .iter() .zip(&eligible) - .map(|(rqe, choices)| { + .map(|(r, choices)| { choices .iter() .map(|&d| { - let deployment = &deployments[d]; - let cpu = ingest(deployment) - + query_and_merge_cpu_per_sec(rqe, deployment, label_sets); - cpu / cpu_unit + retained(rqe, deployment) / gib_unit + ingest[d] + per_assignment(r, &deployments[d]) + storage(r, &deployments[d]) }) .fold(f64::INFINITY, f64::min) }) @@ -128,77 +145,42 @@ pub fn minimize( 1.0 }; - let mut cpu = Expression::with_capacity(deployments.len() + rqes.len()); - for (deployment, &active_variable) in deployments.iter().zip(&active) { - cpu.add_mul(ingest(deployment) / reference, active_variable); + let mut goal: Expression = stored.iter().sum(); + for (&cost, &active_variable) in ingest.iter().zip(&active) { + goal.add_mul(cost / reference, active_variable); } for (rqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { - cpu.add_mul( - query_and_merge_cpu_per_sec( - &rqes[rqe_index], - &deployments[deployment_index], - label_sets, - ) / reference, + goal.add_mul( + per_assignment(&rqes[rqe_index], &deployments[deployment_index]) / reference, assignment, ); } } - // The objective's own variables and rows, in units of `reference`. - let (goal, objective_rows): (Expression, Vec) = match objective { - Objective::AUCCost(family) => { - // The price per instance is a positive constant, so minimizing - // fractional instances minimizes the price. - let instances = variables.add(variable().min(0)); - let retained_gib: Vec = deployments - .iter() - .map(|_| variables.add(variable().min(0))) - .collect(); - let total_gib: Expression = retained_gib.iter().sum(); - let mut rows = vec![ - (cpu / family.vcpu - instances).leq(0), - (total_gib / family.memory_gib - instances).leq(0), - ]; - // Linearized max over the RQEs a deployment serves. - for (rqe_index, choices) in assignments.iter().enumerate() { - for &(deployment_index, assignment) in choices { - let retained = - retained(&rqes[rqe_index], &deployments[deployment_index]) / reference; - rows.push((retained * assignment - retained_gib[deployment_index]).leq(0)); - } - } - (Expression::from(instances), rows) - } - }; - let mut model = variables.minimise(goal).using(default_solver); - for row in objective_rows { - model.add_constraint(row); - } - for (rqe_index, choices) in assignments.iter().enumerate() { let assignment_sum: Expression = choices.iter().map(|(_, variable)| *variable).sum(); model.add_constraint(assignment_sum.eq(1)); for &(deployment_index, assignment) in choices { + let rqe = &rqes[rqe_index]; let deployment = &deployments[deployment_index]; model.add_constraint((assignment - active[deployment_index]).leq(0)); + let stored_cost = storage(rqe, deployment) / reference; + if stored_cost > 0.0 { + model.add_constraint((stored_cost * assignment - stored[deployment_index]).leq(0)); + } // Each RQE takes exactly one deployment, so a per-RQE bound just // forbids the choices over it. Comparing in f64 here, not in the // solver, keeps µs latencies clear of its feasibility tolerance. - let memory = label_sets[&deployment.labels].cardinality as f64 - * deployment.config.mem_bytes_per_instance; - let latency = query_latency_secs(&rqes[rqe_index], deployment, label_sets); + let latency = objectives::query_latency_secs(rqe, deployment, facts); if bounds - .max_peak_query_memory_bytes - .is_some_and(|limit| memory > limit) - || bounds - .max_query_latency_secs - .get(rqe_index) - .copied() - .flatten() - .is_some_and(|limit| latency > limit) + .max_query_latency_secs + .get(rqe_index) + .copied() + .flatten() + .is_some_and(|limit| latency > limit) { model.add_constraint(Expression::from(assignment).leq(0)); } @@ -227,234 +209,118 @@ pub fn minimize( .expect("MILP assigns exactly one deployment to every RQE") }) .collect(); - let objectives = score(rqes, deployments, &mapping, label_sets); + let objectives = score(rqes, deployments, &mapping, facts); Ok(MilpSolution { mapping, objectives, }) } -fn query_and_merge_cpu_per_sec( - rqe: &Rqe, - deployment: &Deployment, - label_sets: &LabelSetTable, -) -> f64 { - query_latency_secs(rqe, deployment, label_sets) / rqe.interval_secs as f64 -} - -fn query_latency_secs(rqe: &Rqe, deployment: &Deployment, label_sets: &LabelSetTable) -> f64 { - let instances = deployment - .query_instance_count(rqe.lookback_secs) - .expect("assignment only contains eligible deployments"); - let cardinality = label_sets[&deployment.labels].cardinality as f64; - cardinality - * (deployment.config.query_cpu_secs - + instances.saturating_sub(1) as f64 * deployment.config.merge_cpu_secs) -} - #[cfg(test)] mod tests { use super::*; use crate::enumerate::brute_force; - use crate::{AccuracyDirection, AtomicCostEntry, Capability, LabelSet, LabelSetInfo}; - use std::collections::BTreeMap; + use crate::test_support::{self, facts}; + /// Window and slide 60 s, merge 1 CPU-sec. fn deployment(insert_cpu_secs: f64, memory: f64, query_cpu_secs: f64) -> Deployment { - Deployment { - capability: Capability::TopK, - labels: LabelSet::new(), - config: AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: memory, - insert_cpu_secs, - merge_cpu_secs: 1.0, - query_cpu_secs, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }, - window_secs: 60, - slide_secs: 60, - } + test_support::deployment(memory, insert_cpu_secs, 1.0, query_cpu_secs, 60, 60) } - fn rqe() -> Rqe { + fn rqe(id: &str, lookback_secs: u64) -> Rqe { Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs: 60, - interval_secs: 60, - labels: LabelSet::new(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, + id: id.into(), + ..test_support::rqe(lookback_secs, 60) } } - #[test] - fn minimizes_cost_and_respects_a_memory_bound() { - let rqes = vec![rqe()]; - let deployments = vec![deployment(1.0, 20.0, 1.0), deployment(2.0, 10.0, 1.0)]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - let unconstrained = minimize( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - Objective::AUCCost(&family(8.0)), - ) - .expect("feasible MILP"); - assert_eq!(unconstrained.mapping, vec![0]); + fn weights(w_cpu: f64, w_mem: f64) -> Objective { + Objective::AUCCost { w_cpu, w_mem } + } - let constrained = minimize( - &rqes, - &deployments, - &label_sets, - &MilpBounds { - max_peak_query_memory_bytes: Some(10.0), - max_query_latency_secs: Vec::new(), - }, - Objective::AUCCost(&family(8.0)), - ) - .expect("feasible MILP under memory bound"); - assert_eq!(constrained.mapping, vec![1]); + /// The MILP's plan scores as well as the best of every mapping. + fn assert_matches_brute_force(rqes: &[Rqe], deployments: &[Deployment], objective: Objective) { + let facts = facts(1, 1); + let best = brute_force(rqes, deployments) + .iter() + .map(|mapping| objective.value(&score(rqes, deployments, mapping, &facts))) + .min_by(f64::total_cmp) + .expect("test workload is servable"); + let milp = minimize(rqes, deployments, &facts, &MilpBounds::default(), objective) + .expect("feasible MILP"); + let got = objective.value(&milp.objectives); + assert!( + (got - best).abs() <= 1e-9 * best, + "{objective:?}: {got} vs {best}" + ); } #[test] - fn matches_brute_force_minimum_with_shared_deployment_costs() { - let mut frequent = rqe(); - frequent.id = "frequent".into(); - frequent.interval_secs = 60; - let mut infrequent = rqe(); - infrequent.id = "infrequent".into(); - let rqes = vec![frequent, infrequent]; - let deployments = vec![deployment(1.0, 10.0, 400.0), deployment(3.0, 10.0, 1.0)]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - let price = |mapping: &Mapping| { - family(8.0).usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) + fn minimizes_cpu_and_respects_a_latency_bound() { + let rqes = vec![rqe("r", 60)]; + // CPU 1 + 3/60 with latency 3, or 2 + 1/60 with latency 1. + let deployments = vec![deployment(1.0, 20.0, 3.0), deployment(2.0, 10.0, 1.0)]; + let solve = |bounds: &MilpBounds| { + minimize( + &rqes, + &deployments, + &facts(1, 1), + bounds, + Objective::default(), + ) + .expect("feasible MILP") + .mapping }; - let brute_force_best = brute_force(&rqes, &deployments) - .into_iter() - .min_by(|left, right| price(left).total_cmp(&price(right))) - .expect("test workload is servable"); - - let milp = minimize( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - Objective::AUCCost(&family(8.0)), - ) - .expect("feasible MILP"); - assert_eq!(milp.mapping, brute_force_best); - assert!((price(&milp.mapping) - price(&brute_force_best)).abs() < 1e-12); - } - - fn family(memory_gib: f64) -> MachineFamily { - MachineFamily { - family: format!("{memory_gib} GiB"), - vcpu: 4.0, - memory_gib, - usd_per_hour: 1.0, - } + assert_eq!(solve(&MilpBounds::default()), vec![0]); + let bounded = MilpBounds { + max_query_latency_secs: vec![Some(2.0)], + }; + assert_eq!(solve(&bounded), vec![1]); } #[test] - fn minimize_cost_matches_brute_force_minimum_across_families() { - let mut frequent = rqe(); - frequent.id = "frequent".into(); - let mut long = rqe(); - long.id = "long".into(); - long.lookback_secs = 600; - let rqes = vec![frequent, long]; + fn matches_brute_force_with_shared_deployment_costs() { + let rqes = vec![rqe("frequent", 60), rqe("long", 600)]; let deployments = vec![ deployment(1.0, 0.5 * BYTES_PER_GIB, 400.0), deployment(3.0, 0.1 * BYTES_PER_GIB, 1.0), deployment(0.2, 2.0 * BYTES_PER_GIB, 1.0), ]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - for family in [family(8.0), family(32.0)] { - let best = brute_force(&rqes, &deployments) - .iter() - .map(|mapping| { - family.usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) - }) - .min_by(f64::total_cmp) - .expect("test workload is servable"); - let milp = minimize( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - Objective::AUCCost(&family), - ) - .expect("feasible MILP"); - assert!((family.usd_per_hour(&milp.objectives) - best).abs() < 1e-9); + for objective in [weights(1.0, 0.0), weights(0.0, 1.0), weights(1.0, 4.0)] { + assert_matches_brute_force(&rqes, &deployments, objective); } } #[test] - fn binding_resource_decides_the_plan_per_family() { - let rqes = vec![rqe()]; - // Holds 2 instances: CPU-heavy with 2 GiB, or CPU-light with 4 GiB. + fn memory_weight_trades_cpu_for_memory() { + let rqes = vec![rqe("r", 60)]; + // CPU-heavy and small, or CPU-light and twice the size. let deployments = vec![ deployment(1.0, 1.0 * BYTES_PER_GIB, 0.0), deployment(0.05, 2.0 * BYTES_PER_GIB, 0.0), ]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - let solve = |memory_gib| { + let solve = |objective| { minimize( &rqes, &deployments, - &label_sets, + &facts(1, 1), &MilpBounds::default(), - Objective::AUCCost(&family(memory_gib)), + objective, ) .expect("feasible MILP") .mapping }; - assert_eq!(solve(8.0), vec![0]); // memory is scarce: 0.25 vs 0.5 instances - assert_eq!(solve(32.0), vec![1]); // CPU is scarce: 0.25 vs 0.125 instances + assert_eq!(solve(weights(1.0, 0.0)), vec![1]); + assert_eq!(solve(weights(0.0, 1.0)), vec![0]); } #[test] fn tiny_magnitudes_match_brute_force_and_respect_latency_bounds() { - // Real W2 plans cost ~1e-6 $/hour with µs latencies: below HiGHS's + // Real plans cost ~1e-6 CPU-sec/sec with µs latencies: below HiGHS's // absolute gap and feasibility tolerances unless the model is scaled. - let mut frequent = rqe(); - frequent.id = "frequent".into(); - let mut long = rqe(); - long.id = "long".into(); - long.lookback_secs = 600; - let rqes = vec![frequent, long]; + let rqes = vec![rqe("frequent", 60), rqe("long", 600)]; let tiny = 1e-9; let deployments = vec![ deployment(1.0 * tiny, 0.5 * tiny * BYTES_PER_GIB, 400.0 * tiny), @@ -467,36 +333,13 @@ mod tests { d }) .collect::>(); - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - for family in [family(8.0), family(32.0)] { - let best = brute_force(&rqes, &deployments) - .iter() - .map(|mapping| { - family.usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) - }) - .min_by(f64::total_cmp) - .expect("test workload is servable"); - let milp = minimize( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - Objective::AUCCost(&family), - ) - .expect("feasible MILP"); - let got = family.usd_per_hour(&milp.objectives); - assert!((got - best).abs() <= 1e-9 * best, "{got} vs {best}"); + for objective in [weights(1.0, 0.0), weights(1.0, 4.0)] { + assert_matches_brute_force(&rqes, &deployments, objective); } // The cheap deployment's latency is 1.5e-7 s, over a 1e-7 s bound by // less than HiGHS's absolute feasibility tolerance. - let rqes = vec![rqe()]; + let rqes = vec![rqe("r", 60)]; let deployments = vec![ deployment(tiny, tiny, 1.5e-7), deployment(10.0 * tiny, tiny, 0.5e-7), @@ -504,12 +347,11 @@ mod tests { let milp = minimize( &rqes, &deployments, - &label_sets, + &facts(1, 1), &MilpBounds { - max_peak_query_memory_bytes: None, max_query_latency_secs: vec![Some(1e-7)], }, - Objective::AUCCost(&family(8.0)), + Objective::default(), ) .expect("feasible MILP"); assert_eq!(milp.mapping, vec![1]); diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs index ab41aa8e..2cb46db2 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/objectives.rs @@ -1,29 +1,151 @@ //! Analytical scoring built from measured per-operation costs (§5). +//! +//! Costs split into four phases, each with CPU and memory: ingest (open +//! windows), merge and query (per evaluation), and storage (closed windows, +//! no CPU). The per-phase functions here are the one copy of the formulas; +//! [`score`] and the MILP both use them. +//! +//! Every measured cost is per instance, and a deployment holds `card(G)` +//! instances per window. Exact multi-group accumulators are measured as one +//! instance over many groups, but the export divides their memory and merge +//! by `groups_per_instance` (`aqpbm_core::atomic_costs`), so `card(G) ×` +//! prices them right too. +// ponytail: a family holding every group in one fixed-size instance (HydraKLL, +// sketch-bench#142) needs a per-family shape so it isn't multiplied by card(G). -use crate::{Deployment, LabelSetTable, Mapping, Rqe}; +use crate::{Capability, Deployment, Mapping, Rqe, WorkloadFacts}; use std::collections::{BTreeMap, BTreeSet}; pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; +/// Query output per group: one f64 (one quantile for Quantile). +// ponytail: an estimate, not measured; tiny next to sketch state. +pub const OUTPUT_BYTES_PER_VALUE: f64 = 8.0; +/// Query output per top-k entry: a 64-bit key hash and a count. +pub const OUTPUT_BYTES_PER_TOPK_ENTRY: f64 = 16.0; +/// Top-k entries per group: sketch-bench's `CMS_HEAP_TOP_K`, the heap size +/// every top-k row was measured at. +// ponytail: fixed k. The RQE has no `k`, and the heap is left out of measured +// memory; a large k needs both, plus a benchmark that varies the heap. +pub const TOPK_ENTRIES: f64 = 32.0; + +/// One phase's resource use. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct PhaseCost { + /// Mean CPU-seconds per second: the area under the CPU curve over time. + pub cpu_secs_per_sec: f64, + pub memory_bytes: f64, +} + +impl std::ops::AddAssign for PhaseCost { + fn add_assign(&mut self, other: Self) { + self.cpu_secs_per_sec += other.cpu_secs_per_sec; + self.memory_bytes += other.memory_bytes; + } +} + #[derive(Debug, Clone)] pub struct Objectives { - pub peak_query_memory_bytes: f64, - pub ingest_cpu_secs_per_sec: f64, - pub merge_cpu_secs_per_sec: f64, - pub query_cpu_secs_per_sec: f64, - pub tco_cpu_secs_per_sec: f64, - /// State held by all active deployments: each keeps the instances needed - /// by the longest lookback it serves. - pub retained_memory_bytes: f64, + /// Inserts into open windows, and the open windows' state. + pub ingest: PhaseCost, + /// Folding each query's windows together, and the merged state, summed + /// over RQEs as if every query evaluates at once. + pub merge: PhaseCost, + /// Reading the merged state, and the output, summed like `merge`. + pub query: PhaseCost, + /// Closed windows still inside the longest lookback each deployment + /// serves. No CPU. + pub storage: PhaseCost, /// Index-aligned with the input RQE slice; display IDs need not be unique. pub query_latency_secs: Vec, } +impl Objectives { + pub fn cpu_secs_per_sec(&self) -> f64 { + self.phases().map(|p| p.cpu_secs_per_sec).sum() + } + + pub fn memory_bytes(&self) -> f64 { + self.phases().map(|p| p.memory_bytes).sum() + } + + fn phases(&self) -> impl Iterator { + [&self.ingest, &self.merge, &self.query, &self.storage].into_iter() + } +} + +/// `card(G)`: instances per window. +fn groups(d: &Deployment, facts: &WorkloadFacts) -> f64 { + facts[&d.metric].cardinality[&d.grouping_labels] as f64 +} + +fn open_windows(d: &Deployment) -> f64 { + d.active_instance_count() + .expect("candidate window and slide align") as f64 +} + +/// `L / x`: windows merged for one evaluation. +fn merged_windows(r: &Rqe, d: &Deployment) -> f64 { + d.query_instance_count(r.lookback_secs) + .expect("only eligible pairs are costed") as f64 +} + +/// Every sample goes into its group's instance in each open window: +/// `λ · (x/y) · c_ins` CPU, `card(G) · m · x/y` memory. +pub(crate) fn ingest(d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + PhaseCost { + cpu_secs_per_sec: facts[&d.metric].arrival_rate_per_sec() + * open_windows(d) + * d.config.insert_cpu_secs, + memory_bytes: groups(d, facts) * d.config.mem_bytes_per_instance * open_windows(d), + } +} + +/// Per group, `L/x − 1` folds every `T`, holding one merged instance: +/// `card(G) · (L/x − 1) · c_mrg / T` CPU, `card(G) · m` memory. +pub(crate) fn merge(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = groups(d, facts); + PhaseCost { + cpu_secs_per_sec: groups * (merged_windows(r, d) - 1.0) * d.config.merge_cpu_secs + / r.interval_secs as f64, + memory_bytes: groups * d.config.mem_bytes_per_instance, + } +} + +/// Per group, one query every `T` and its output: +/// `card(G) · c_qry / T` CPU, `card(G) ·` output bytes memory. +pub(crate) fn query(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = groups(d, facts); + let output_bytes = match r.capability { + Capability::TopK => TOPK_ENTRIES * OUTPUT_BYTES_PER_TOPK_ENTRY, + _ => OUTPUT_BYTES_PER_VALUE, + }; + PhaseCost { + cpu_secs_per_sec: groups * d.config.query_cpu_secs / r.interval_secs as f64, + memory_bytes: groups * output_bytes, + } +} + +/// Closed windows `d` holds so `r` can be answered: `card(G) · m · +/// ((L − x)/y + 1)`. A deployment holds the most any of its RQEs needs. +pub(crate) fn storage_bytes(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> f64 { + groups(d, facts) + * d.config.mem_bytes_per_instance + * d.closed_instance_count(r.lookback_secs) + .expect("only eligible pairs are costed") as f64 +} + +/// One evaluation's wall time on one core: `card(G) · (c_qry + (L/x − 1) · c_mrg)`. +pub(crate) fn query_latency_secs(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> f64 { + groups(d, facts) + * (d.config.query_cpu_secs + (merged_windows(r, d) - 1.0) * d.config.merge_cpu_secs) +} + pub fn score( rqes: &[Rqe], deployments: &[Deployment], mapping: &Mapping, - label_sets: &LabelSetTable, + facts: &WorkloadFacts, ) -> Objectives { assert_eq!( mapping.len(), @@ -31,242 +153,97 @@ pub fn score( "mapping must have one deployment per RQE" ); let active: BTreeSet = mapping.iter().copied().collect(); - let ingest_cpu_secs_per_sec = active - .iter() - .map(|&di| { - let d = &deployments[di]; - let fanout = - d.active_instance_count() - .expect("eligible deployment aligns window and slide") as f64; - label_sets[&d.labels].arrival_rate_per_sec * fanout * d.config.insert_cpu_secs - }) - .sum(); - - let mut retained_instances: BTreeMap = BTreeMap::new(); - for (r, &di) in rqes.iter().zip(mapping) { - let count = deployments[di] - .retained_instance_count(r.lookback_secs) - .expect("mapping only contains eligible pairs"); - let held = retained_instances.entry(di).or_default(); - *held = (*held).max(count); + let mut ingest_cost = PhaseCost::default(); + for &di in &active { + ingest_cost += ingest(&deployments[di], facts); } - let retained_memory_bytes = retained_instances - .iter() - .map(|(&di, &count)| { - let d = &deployments[di]; - label_sets[&d.labels].cardinality as f64 - * d.config.mem_bytes_per_instance - * count as f64 - }) - .sum(); - let mut peak_query_memory_bytes = 0.0_f64; - let mut merge_cpu_secs_per_sec = 0.0; - let mut query_cpu_secs_per_sec = 0.0; + let mut stored: BTreeMap = BTreeMap::new(); + let mut merge_cost = PhaseCost::default(); + let mut query_cost = PhaseCost::default(); let query_latency_secs = rqes .iter() .zip(mapping) .map(|(r, &di)| { let d = &deployments[di]; - let card = label_sets[&d.labels].cardinality as f64; - peak_query_memory_bytes = - peak_query_memory_bytes.max(card * d.config.mem_bytes_per_instance); - let instances = d - .query_instance_count(r.lookback_secs) - .expect("mapping only contains eligible pairs"); - let query = card * d.config.query_cpu_secs; - let merge = card * instances.saturating_sub(1) as f64 * d.config.merge_cpu_secs; - query_cpu_secs_per_sec += query / r.interval_secs as f64; - merge_cpu_secs_per_sec += merge / r.interval_secs as f64; - query + merge + let held = stored.entry(di).or_default(); + *held = held.max(storage_bytes(r, d, facts)); + merge_cost += merge(r, d, facts); + query_cost += query(r, d, facts); + query_latency_secs(r, d, facts) }) .collect(); - let tco_cpu_secs_per_sec = - ingest_cpu_secs_per_sec + merge_cpu_secs_per_sec + query_cpu_secs_per_sec; + Objectives { - peak_query_memory_bytes, - ingest_cpu_secs_per_sec, - merge_cpu_secs_per_sec, - query_cpu_secs_per_sec, - tco_cpu_secs_per_sec, - retained_memory_bytes, + ingest: ingest_cost, + merge: merge_cost, + query: query_cost, + storage: PhaseCost { + cpu_secs_per_sec: 0.0, + memory_bytes: stored.values().sum(), + }, query_latency_secs, } } -/// One instance type standing for an EC2 machine family (§4 of the -/// evaluation plan, ProjectASAP/ASAPQuery#777). -#[derive(Debug, Clone, PartialEq)] -pub struct MachineFamily { - pub family: String, - pub vcpu: f64, - pub memory_gib: f64, - pub usd_per_hour: f64, -} - -impl MachineFamily { - /// Reads the `families` of a `scripts/fetch_ec2_pricing.py` snapshot. - pub fn from_pricing_json(json: &str) -> Result, String> { - let snapshot: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?; - let families = snapshot["families"] - .as_array() - .ok_or("pricing snapshot has no families array")?; - families - .iter() - .map(|f| { - let number = |key: &str| { - f[key] - .as_f64() - .ok_or_else(|| format!("family is missing numeric {key}")) - }; - Ok(Self { - family: f["family"] - .as_str() - .ok_or("family is missing its name")? - .to_string(), - vcpu: number("vcpu")?, - memory_gib: number("memory_gib")?, - usd_per_hour: number("usd_per_hour")?, - }) - }) - .collect() - } - - /// Fractional instances needed for the plan: whichever of CPU or memory - /// runs out first. - pub fn instances(&self, objectives: &Objectives) -> f64 { - (objectives.tco_cpu_secs_per_sec / self.vcpu) - .max(objectives.retained_memory_bytes / BYTES_PER_GIB / self.memory_gib) - } - - pub fn usd_per_hour(&self, objectives: &Objectives) -> f64 { - self.usd_per_hour * self.instances(objectives) - } -} - #[cfg(test)] mod tests { use super::*; - use crate::{AccuracyDirection, AtomicCostEntry, Capability, LabelSet, LabelSetInfo}; - use std::collections::BTreeMap; + use crate::test_support::{deployment, facts, rqe}; #[test] - fn scores_overlapping_ingest_and_non_overlapping_query_merges() { - let labels = LabelSet::new(); - let config = AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: 10.0, - insert_cpu_secs: 2.0, - merge_cpu_secs: 3.0, - query_cpu_secs: 5.0, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }; - let deployment = Deployment { - capability: Capability::TopK, - labels: labels.clone(), - config, - window_secs: 20, - slide_secs: 10, - }; - let rqe = Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs: 60, - interval_secs: 30, - labels: labels.clone(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, - }; - let tables = BTreeMap::from([( - labels, - LabelSetInfo { - cardinality: 4, - arrival_rate_per_sec: 7.0, - }, - )]); - let result = score(&[rqe], &[deployment], &vec![0], &tables); - assert_eq!(result.peak_query_memory_bytes, 40.0); - assert_eq!(result.ingest_cpu_secs_per_sec, 28.0); // 7 items × 2 active × 2 CPU - assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 query + 2 merges × 3) - assert_eq!(result.query_cpu_secs_per_sec, 20.0 / 30.0); - assert_eq!(result.merge_cpu_secs_per_sec, 24.0 / 30.0); - assert_eq!(result.retained_memory_bytes, 320.0); // 4 × 10 × (20 + 60) / 10 + fn scores_each_phase() { + // 4 groups, 7 samples/sec; window 20 s sliding by 10 s, so 2 open + // windows; lookback 60 s every 30 s, so 3 windows merged and + // (60 − 20)/10 + 1 = 5 closed windows held. + let d = deployment(10.0, 2.0, 3.0, 5.0, 20, 10); + let r = rqe(60, 30); + let result = score(&[r], &[d], &vec![0], &facts(4, 7)); + + assert_eq!(result.ingest.cpu_secs_per_sec, 28.0); // 7 × 2 × 2 + assert_eq!(result.ingest.memory_bytes, 80.0); // 4 × 10 × 2 + assert_eq!(result.merge.cpu_secs_per_sec, 24.0 / 30.0); // 4 × 2 × 3 / 30 + assert_eq!(result.merge.memory_bytes, 40.0); // 4 × 10 + assert_eq!(result.query.cpu_secs_per_sec, 20.0 / 30.0); // 4 × 5 / 30 + assert_eq!(result.query.memory_bytes, 4.0 * 32.0 * 16.0); // top-k output + assert_eq!(result.storage.cpu_secs_per_sec, 0.0); + assert_eq!(result.storage.memory_bytes, 200.0); // 4 × 10 × 5 + assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 + 2 × 3) + assert!((result.cpu_secs_per_sec() - (28.0 + 44.0 / 30.0)).abs() < 1e-12); + assert_eq!(result.memory_bytes(), 80.0 + 40.0 + 2048.0 + 200.0); } #[test] - fn shared_deployment_retains_for_its_longest_lookback() { - let labels = LabelSet::new(); - let deployment = Deployment { - capability: Capability::TopK, - labels: labels.clone(), - config: AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: 10.0, - insert_cpu_secs: 1.0, - merge_cpu_secs: 1.0, - query_cpu_secs: 1.0, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }, - window_secs: 10, - slide_secs: 10, - }; - let rqe = |lookback_secs| Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs, - interval_secs: 10, - labels: labels.clone(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, - }; - let tables = BTreeMap::from([( - labels.clone(), - LabelSetInfo { - cardinality: 2, - arrival_rate_per_sec: 1.0, - }, - )]); - let result = score(&[rqe(60), rqe(600)], &[deployment], &vec![0, 0], &tables); - // One copy of state, sized for the 600 s lookback: 2 × 10 × (10 + 600) / 10. - assert_eq!(result.retained_memory_bytes, 1220.0); + fn a_direct_query_holds_one_closed_window() { + // L == x: one closed window, nothing to merge. + let d = deployment(10.0, 1.0, 1.0, 1.0, 60, 60); + let result = score(&[rqe(60, 60)], &[d], &vec![0], &facts(1, 1)); + assert_eq!(result.storage.memory_bytes, 10.0); + assert_eq!(result.merge.cpu_secs_per_sec, 0.0); } #[test] - fn machine_family_is_sized_by_its_binding_resource() { - let family = MachineFamily { - family: "f".into(), - vcpu: 4.0, - memory_gib: 8.0, - usd_per_hour: 2.0, - }; - let mut objectives = Objectives { - peak_query_memory_bytes: 0.0, - ingest_cpu_secs_per_sec: 0.0, - merge_cpu_secs_per_sec: 0.0, - query_cpu_secs_per_sec: 0.0, - tco_cpu_secs_per_sec: 2.0, - retained_memory_bytes: BYTES_PER_GIB, - query_latency_secs: Vec::new(), - }; - assert_eq!(family.instances(&objectives), 0.5); // CPU binds - objectives.retained_memory_bytes = 16.0 * BYTES_PER_GIB; - assert_eq!(family.usd_per_hour(&objectives), 4.0); // memory binds: 2 instances + fn shared_deployment_stores_for_its_longest_lookback() { + let d = deployment(10.0, 1.0, 1.0, 1.0, 10, 10); + let result = score( + &[rqe(60, 10), rqe(600, 10)], + &[d], + &vec![0, 0], + &facts(2, 2), + ); + // One copy of state, sized for 600 s: 2 × 10 × ((600 − 10)/10 + 1). + assert_eq!(result.storage.memory_bytes, 1200.0); + // Ingest is paid once; merge and query once per RQE. + assert_eq!(result.ingest.cpu_secs_per_sec, 2.0); + assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 10.0); } #[test] - fn reads_committed_pricing_snapshot() { - let families = - MachineFamily::from_pricing_json(include_str!("../data/ec2-pricing-2026-10-04.json")) - .expect("committed snapshot parses"); - let names: Vec<_> = families.iter().map(|f| f.family.as_str()).collect(); - assert_eq!( - names, - ["compute_optimized", "general_purpose", "memory_optimized"] - ); - assert!(families.iter().all(|f| f.usd_per_hour > 0.0)); + fn arrival_rate_is_series_over_scrape_interval() { + let mut f = facts(4, 600); + f.get_mut(crate::test_support::METRIC) + .unwrap() + .scrape_interval_secs = 15; + assert_eq!(f[crate::test_support::METRIC].arrival_rate_per_sec(), 40.0); } } diff --git a/rqe-optimizer/src/pareto.rs b/rqe-optimizer/src/pareto.rs index a48b6181..fa326791 100644 --- a/rqe-optimizer/src/pareto.rs +++ b/rqe-optimizer/src/pareto.rs @@ -1,4 +1,4 @@ -//! Non-dominated filtering for `(peak memory, TCO CPU, per-RQE latency)`. +//! Non-dominated filtering for `(CPU, memory, per-RQE latency)`. use crate::{objectives::Objectives, Mapping}; @@ -16,10 +16,7 @@ fn dominates(a: &[f64], b: &[f64]) -> bool { } fn objective_vector(objectives: &Objectives) -> Vec { - let mut vector = vec![ - objectives.peak_query_memory_bytes, - objectives.tco_cpu_secs_per_sec, - ]; + let mut vector = vec![objectives.cpu_secs_per_sec(), objectives.memory_bytes()]; vector.extend(&objectives.query_latency_secs); vector } @@ -78,15 +75,18 @@ pub fn pareto_front(objs: &[Objectives]) -> Vec { #[cfg(test)] mod tests { use super::*; + use crate::objectives::PhaseCost; fn objectives(memory: f64, cpu: f64, latency: f64) -> Objectives { + let phase = PhaseCost { + cpu_secs_per_sec: cpu, + memory_bytes: memory, + }; Objectives { - peak_query_memory_bytes: memory, - retained_memory_bytes: 0.0, - ingest_cpu_secs_per_sec: 0.0, - merge_cpu_secs_per_sec: 0.0, - query_cpu_secs_per_sec: 0.0, - tco_cpu_secs_per_sec: cpu, + ingest: phase, + merge: PhaseCost::default(), + query: PhaseCost::default(), + storage: PhaseCost::default(), query_latency_secs: vec![latency], } } diff --git a/scripts/fetch_ec2_pricing.py b/scripts/fetch_ec2_pricing.py deleted file mode 100755 index f33cba19..00000000 --- a/scripts/fetch_ec2_pricing.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python3 -"""Snapshot on-demand EC2 prices for the rqe-optimizer machine families. - -Reads the public price file behind aws.amazon.com/ec2/pricing/on-demand -(us-east-1, Linux, shared tenancy) and writes the three instance types the -optimizer prices plans with. Never edit the output by hand; rerun this. - -Usage: - scripts/fetch_ec2_pricing.py rqe-optimizer/data/ec2-pricing-$(date +%F).json -""" -import datetime -import gzip -import json -import sys -import urllib.request - -SOURCE = ( - "https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/ec2/USD/current/" - "ec2-ondemand-without-sec-sel/US%20East%20(N.%20Virginia)/Linux/index.json" -) -REGION = "US East (N. Virginia)" -# One size per family: plans are priced in fractional instances, so the size -# within a family does not change the result. -INSTANCE_TYPES = { - "compute_optimized": "c7i.xlarge", - "general_purpose": "m7i.xlarge", - "memory_optimized": "r7i.xlarge", -} - - -def main(out_path): - with urllib.request.urlopen(SOURCE) as response: - body = response.read() - if body[:2] == b"\x1f\x8b": - body = gzip.decompress(body) - data = json.loads(body) - rows = {row["Instance Type"]: row for row in data["regions"][REGION].values()} - - families = [] - for family, instance_type in INSTANCE_TYPES.items(): - row = rows[instance_type] - memory, unit = row["Memory"].split() - assert unit == "GiB", row["Memory"] - families.append( - { - "family": family, - "instance_type": instance_type, - "vcpu": int(row["vCPU"]), - "memory_gib": float(memory), - "usd_per_hour": float(row["price"]), - "rate_code": row["rateCode"], - } - ) - - snapshot = { - "source": SOURCE, - "region": REGION, - "operating_system": "Linux", - "pricing": "on-demand", - "publication_date": data["manifest"]["hawkFilePublicationDate"], - "fetched": datetime.date.today().isoformat(), - "families": families, - } - with open(out_path, "w") as out: - json.dump(snapshot, out, indent=2) - out.write("\n") - - -if __name__ == "__main__": - main(sys.argv[1]) From 974300c75e10c101c2c7b204766e9f8e95105c3c Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Mon, 5 Oct 2026 22:14:35 -0400 Subject: [PATCH 04/18] docs: state what each rqe-optimizer cost is counted per Per deployment or per RQE, per group, per window and per key, plus what is not shared between RQEs. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 4a453cac..c1d5158c 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -249,6 +249,43 @@ latency_i = card(G) × (c_qry + (n_i − 1) × c_mrg) It is not a wall-clock SLA: it assumes no parallel execution across groups and no cheaper k-way merge. +### What each cost is counted per + +| Cost | Shared by RQEs on one deployment? | × groups `card(G)` | × windows | Per key inside an instance | +|---|---|---|---|---| +| Ingest CPU | yes, paid once per deployment | no, `lambda` already totals all groups | × `x/y` open | each sample is one insert, whatever the family | +| Ingest memory | yes | yes | × `x/y` open | not modeled | +| Storage memory | yes, sized for the longest `S` it serves | yes | × `(S−x)/y + 1` closed | not modeled | +| Merge CPU | no, per RQE | yes | × `(S/x − 1)` folds | not modeled | +| Merge memory | no, per RQE | yes | × 1 merged instance | not modeled | +| Query CPU | no, per RQE | yes | — | one probe per group | +| Query memory | no, per RQE | yes | — | 8 B, or 32 × 16 B for top-k | +| Latency | per RQE | yes | `S/x − 1` merges | — | + +Keys inside an instance: + +- **Sketches** (CMS, CountSketch, KLL, DDSketch, HLL, UnivMon) keep one + fixed-size instance per group. The keys inside it, such as the endpoints a + per-service top-k counts, change neither memory nor CPU. The top-k heap is + fixed at the benchmark's k = 32. +- **Exact accumulators** keep one value per group, so keys are groups. The + export divides their measured memory and merge cost by the group count, so + `m` is per group. +- Nothing scales with keys below the group. Key labels `K` (the metric's + labels minus `G`) would matter only for a family whose size grows with keys + inside a group, such as an exact top-k map; none exists yet. + +Not shared, though it may look shareable: + +- **The stream read.** Two deployments on the same metric each pay full + ingest. Only RQEs on the same deployment share it. +- **Merges and query results.** Two RQEs with the same lookback on one + deployment each pay their own merge and query. +- **Groupings.** A `{service, endpoint}` deployment does not serve + `by (service)`: `G` must match exactly, with no regrouping at query time. +- **Capabilities.** RQEs with different capabilities never share a + deployment, even on the same metric and `G`. + ## Procedure 1. Generate candidate deployments for each input RQE, then deduplicate them. From 232cfb253ffed4ae95c7848e83b408510ff0e41b Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 08:42:16 -0400 Subject: [PATCH 05/18] rqe-optimizer: readability pass on the cost model Descriptive names in place of single letters, named ingest helpers in candidate pruning, and shorter comments without issue references. Co-Authored-By: Claude Opus 5.5 --- rqe-optimizer/examples/small_problem.rs | 6 +- rqe-optimizer/src/candidates.rs | 76 ++++----- rqe-optimizer/src/lib.rs | 65 ++++---- rqe-optimizer/src/milp.rs | 61 ++++---- rqe-optimizer/src/objectives.rs | 199 +++++++++++------------- 5 files changed, 205 insertions(+), 202 deletions(-) diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 5fe76abc..9fb5be5b 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -79,7 +79,7 @@ fn load_cost_table() -> AtomicCostTable { /// Both metrics: 5 services × 10 endpoints × 600 pods = 30,000 series /// scraped every 15 s, so `λ` = 2,000 samples/sec each. fn facts() -> WorkloadFacts { - let metric = || MetricFacts { + let http_metric_facts = || MetricFacts { labels: label_set(&["service", "endpoint", "pod"]), scrape_interval_secs: 15, cardinality: [ @@ -90,8 +90,8 @@ fn facts() -> WorkloadFacts { .into(), }; [ - (REQUESTS.to_string(), metric()), - (DURATION.to_string(), metric()), + (REQUESTS.to_string(), http_metric_facts()), + (DURATION.to_string(), http_metric_facts()), ] .into() } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 9e874f81..6b35f5ca 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -39,12 +39,12 @@ fn subset_gcds(values: impl IntoIterator) -> BTreeSet { out } -/// Windows and slides are multiples of the metric's scrape interval (#143 -/// S6): anything finer only splits one scrape's samples. +/// Windows and slides are multiples of the metric's scrape interval: anything +/// finer only splits one scrape's samples. fn candidate_deployments( group: &[&Rqe], costs: &[AtomicCostEntry], - scrape_secs: Seconds, + scrape_interval_secs: Seconds, ) -> Vec { if group.is_empty() { return Vec::new(); @@ -53,7 +53,7 @@ fn candidate_deployments( let windows = group .iter() .flat_map(|r| divisors(r.lookback_secs)) - .filter(|w| w.is_multiple_of(scrape_secs)) + .filter(|window_secs| window_secs.is_multiple_of(scrape_interval_secs)) .collect::>(); let mut deployments = Vec::new(); for window_secs in windows { @@ -67,16 +67,18 @@ fn candidate_deployments( .iter() .filter(|c| capability.families().contains(&c.sketch.as_str())) { - deployments.extend(slides.iter().filter(|s| s.is_multiple_of(scrape_secs)).map( - |&slide_secs| Deployment { - capability, - metric: group[0].metric.clone(), - grouping_labels: group[0].grouping_labels.clone(), - config: config.clone(), - window_secs, - slide_secs, - }, - )); + for &slide_secs in &slides { + if slide_secs.is_multiple_of(scrape_interval_secs) { + deployments.push(Deployment { + capability, + metric: group[0].metric.clone(), + grouping_labels: group[0].grouping_labels.clone(), + config: config.clone(), + window_secs, + slide_secs, + }); + } + } } } deployments @@ -118,11 +120,10 @@ pub fn build_all_candidates_unpruned( /// mapping without making any modeled objective worse. /// /// This comparison is deliberately local to a (capability, metric, grouping) -/// group. Within such a group, `card(G)`, arrival rate and query output size -/// are common multipliers, so comparing per-instance memory (merge) and -/// `active_instances ×` insert cost and memory (ingest) is sufficient. Query -/// latency (merge and query CPU) and stored memory are checked for each RQE -/// the dominated candidate can serve. +/// group, where `card(G)`, arrival rate and query output size are common +/// multipliers. So it compares instance size (merge memory) and ingest CPU and +/// memory per group, then latency (merge and query CPU) and stored memory for +/// each RQE the dominated candidate can serve. pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> Vec { let eligibility: Vec> = candidates .iter() @@ -175,10 +176,8 @@ fn candidate_dominates( } replacement.config.mem_bytes_per_instance <= original.config.mem_bytes_per_instance - && ingest(replacement) - .iter() - .zip(ingest(original)) - .all(|(r, o)| *r <= o) + && ingest_cpu(replacement) <= ingest_cpu(original) + && ingest_memory(replacement) <= ingest_memory(original) && original_coverage .iter() .zip(replacement_coverage) @@ -203,10 +202,8 @@ fn strictly_better( rqes: &[Rqe], ) -> bool { replacement.config.mem_bytes_per_instance < original.config.mem_bytes_per_instance - || ingest(replacement) - .iter() - .zip(ingest(original)) - .any(|(r, o)| *r < o) + || ingest_cpu(replacement) < ingest_cpu(original) + || ingest_memory(replacement) < ingest_memory(original) || original_coverage .iter() .zip(replacement_coverage) @@ -223,14 +220,20 @@ fn strictly_better( }) } -/// Ingest CPU and memory per group, up to the group's common `λ` / `card(G)`: -/// `active_instances ×` insert cost and instance size. -fn ingest(deployment: &Deployment) -> [f64; 2] { - let active = deployment.active_instance_count().unwrap_or(u64::MAX) as f64; - [ - active * deployment.config.insert_cpu_secs, - active * deployment.config.mem_bytes_per_instance, - ] +fn open_window_count(deployment: &Deployment) -> f64 { + deployment.active_instance_count().unwrap_or(u64::MAX) as f64 +} + +/// Insert CPU per sample. Arrival rate is a common multiplier within a group, +/// so it is left out. +fn ingest_cpu(deployment: &Deployment) -> f64 { + open_window_count(deployment) * deployment.config.insert_cpu_secs +} + +/// Open-window bytes per group. `card(G)` is a common multiplier within a +/// group, so it is left out. +fn ingest_memory(deployment: &Deployment) -> f64 { + open_window_count(deployment) * deployment.config.mem_bytes_per_instance } fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { @@ -241,8 +244,7 @@ fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { + instances.saturating_sub(1) as f64 * deployment.config.merge_cpu_secs } -/// Closed-window bytes per group when serving `rqe`. `card(G)` is a common -/// multiplier within a group, so it is left out. +/// Closed-window bytes per group when serving `rqe`. fn stored_memory(deployment: &Deployment, rqe: &Rqe) -> f64 { deployment .closed_instance_count(rqe.lookback_secs) diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 6faa2ed3..f1f750b3 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -71,25 +71,21 @@ impl Capability { } } -/// Facts about one metric's stream, given as input (#143 S2). RQEs and -/// deployments on the same metric read the same samples, grouped by -/// `grouping_labels`. +/// Facts about one metric, given as input. RQEs and deployments on the same +/// metric read the same samples. #[derive(Debug, Clone)] pub struct MetricFacts { - /// Every label the metric's series carry, so `cardinality[labels]` is the - /// raw series count. + /// Every label the metric's series carry. pub labels: LabelSet, - /// Every series yields one sample per scrape. + /// Each series yields one sample per scrape. pub scrape_interval_secs: Seconds, - /// `card(G)`: distinct value combinations of each label set in use, i.e. - /// how many instances a deployment grouped by `G` holds per window. Must - /// include `labels` itself. + /// `card(X)`: distinct value combinations of each label set `X` in use. + /// Must include `labels` itself, whose cardinality is the series count. pub cardinality: BTreeMap, } impl MetricFacts { - /// `λ`: samples/sec across all of the metric's series. Derived, never - /// given, so it can't disagree with the cardinalities. + /// `λ`: samples/sec across all of the metric's series. pub fn arrival_rate_per_sec(&self) -> f64 { self.cardinality[&self.labels] as f64 / self.scrape_interval_secs as f64 } @@ -98,35 +94,35 @@ impl MetricFacts { /// [`MetricFacts`] keyed by metric name. pub type WorkloadFacts = BTreeMap; -/// Every problem with `facts` for serving `rqes`, so a caller sees them all -/// at once. The rest of the crate indexes `facts` without checks, so call -/// this first on caller input. +/// Every problem with `facts` for serving `rqes`. The rest of the crate +/// indexes `facts` without checks, so call this first on caller input. pub fn validate_facts(rqes: &[Rqe], facts: &WorkloadFacts) -> Result<(), Vec> { let mut problems = BTreeSet::new(); for rqe in rqes { let (metric, grouping) = (&rqe.metric, &rqe.grouping_labels); - let Some(f) = facts.get(metric) else { + let Some(metric_facts) = facts.get(metric) else { problems.insert(format!("{metric}: no facts for this metric")); continue; }; - if f.scrape_interval_secs == 0 { + let all_labels = &metric_facts.labels; + let cardinality = &metric_facts.cardinality; + if metric_facts.scrape_interval_secs == 0 { problems.insert(format!("{metric}: scrape interval is 0")); } - if !grouping.is_subset(&f.labels) { + if !grouping.is_subset(all_labels) { problems.insert(format!( - "{metric}: grouping {grouping:?} is not a subset of its labels {:?}", - f.labels + "{metric}: grouping {grouping:?} is not a subset of its labels {all_labels:?}" )); } - for labels in [grouping, &f.labels] { - match f.cardinality.get(labels) { + for labels in [grouping, all_labels] { + match cardinality.get(labels) { None => problems.insert(format!("{metric}: no cardinality for {labels:?}")), Some(0) => problems.insert(format!("{metric}: cardinality of {labels:?} is 0")), Some(_) => false, }; } if let (Some(&groups), Some(&series)) = - (f.cardinality.get(grouping), f.cardinality.get(&f.labels)) + (cardinality.get(grouping), cardinality.get(all_labels)) { if groups > series { problems.insert(format!( @@ -231,9 +227,8 @@ impl Deployment { Some(lookback_secs / self.window_secs) } - /// Closed instances held to serve a lookback (#143 S7): those lying - /// wholly inside it, which start in `[now − L, now − x]`, so - /// `(L − x) / y + 1`. Open instances are [`Self::active_instance_count`]. + /// Closed instances kept to serve a lookback: those wholly inside it, + /// which start in `[now − L, now − x]`, so `(L − x) / y + 1`. pub fn closed_instance_count(&self, lookback_secs: Seconds) -> Option { self.query_instance_count(lookback_secs)?; self.active_instance_count()?; @@ -323,11 +318,21 @@ mod tests { #[test] fn closed_instances_lie_wholly_inside_the_lookback() { - // Windows of 10 min every 1 min over 1 h start in [now − 60, now − 10]. - let d = deployment(1.0, 1.0, 1.0, 1.0, 600, 60); - assert_eq!(d.closed_instance_count(3_600), Some(51)); - assert_eq!(d.closed_instance_count(600), Some(1)); - assert_eq!(d.closed_instance_count(900), None); // not tiled by x + // 10-minute windows every minute, over an hour: starts in minutes + // [now − 60, now − 10]. + let sliding = deployment(1.0, 1.0, 1.0, 1.0, 600, 60); + assert_eq!(sliding.closed_instance_count(3_600), Some(51)); + assert_eq!(sliding.closed_instance_count(600), Some(1)); + assert_eq!(sliding.closed_instance_count(900), None); // not tiled by x + } + + #[test] + fn arrival_rate_is_series_over_scrape_interval() { + let metric_facts = MetricFacts { + scrape_interval_secs: 15, + ..test_support::facts(4, 600)[METRIC].clone() + }; + assert_eq!(metric_facts.arrival_rate_per_sec(), 40.0); } #[test] diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 401f793a..d462199a 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -98,43 +98,45 @@ pub fn minimize( .collect() }) .collect(); - // Weighted closed-window storage per deployment: a linearized max over the - // RQEs it serves. - let stored: Vec = deployments + // Weighted storage cost per deployment: the max over the RQEs it serves. + let storage: Vec = deployments .iter() .map(|_| variables.add(variable().min(0))) .collect(); - // Weighted costs: ingest once per active deployment; merge and query once - // per assignment; storage as the max over a deployment's assignments. - let ingest: Vec = deployments + // Ingest is paid once per active deployment, merge and query once per + // assignment, and storage once per deployment for its longest lookback. + let ingest_cost: Vec = deployments .iter() - .map(|d| objective.weigh(objectives::ingest(d, facts))) + .map(|deployment| objective.weigh(objectives::ingest(deployment, facts))) .collect(); - let per_assignment = |r: &Rqe, d: &Deployment| { - objective.weigh(objectives::merge(r, d, facts)) - + objective.weigh(objectives::query(r, d, facts)) + let assignment_cost = |rqe: &Rqe, deployment: &Deployment| { + objective.weigh(objectives::merge(rqe, deployment, facts)) + + objective.weigh(objectives::query(rqe, deployment, facts)) }; - let storage = |r: &Rqe, d: &Deployment| { + let storage_cost = |rqe: &Rqe, deployment: &Deployment| { objective.weigh(PhaseCost { cpu_secs_per_sec: 0.0, - memory_bytes: objectives::storage_bytes(r, d, facts), + memory_bytes: objectives::storage_bytes(rqe, deployment, facts), }) }; // Real plans cost ~1e-6 CPU-sec/sec and read in microseconds, below - // HiGHS's absolute gap (1e-6) and feasibility tolerance (1e-7). So every - // row is scaled to O(1) by `reference`, a plan's cost without sharing - // (each RQE on its cheapest deployment); per-RQE bounds become exclusions. - // Results are re-scored on real costs below, so the scaling never leaks out. + // HiGHS's absolute gap (1e-6) and feasibility tolerance (1e-7). So costs + // are divided by `reference`, a plan's cost without sharing (each RQE on + // its cheapest deployment), and per-RQE bounds become exclusions. The + // result is re-scored on real costs. let reference: f64 = rqes .iter() .zip(&eligible) - .map(|(r, choices)| { + .map(|(rqe, choices)| { choices .iter() - .map(|&d| { - ingest[d] + per_assignment(r, &deployments[d]) + storage(r, &deployments[d]) + .map(|&deployment_index| { + let deployment = &deployments[deployment_index]; + ingest_cost[deployment_index] + + assignment_cost(rqe, deployment) + + storage_cost(rqe, deployment) }) .fold(f64::INFINITY, f64::min) }) @@ -145,14 +147,14 @@ pub fn minimize( 1.0 }; - let mut goal: Expression = stored.iter().sum(); - for (&cost, &active_variable) in ingest.iter().zip(&active) { + let mut goal: Expression = storage.iter().sum(); + for (&cost, &active_variable) in ingest_cost.iter().zip(&active) { goal.add_mul(cost / reference, active_variable); } for (rqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { goal.add_mul( - per_assignment(&rqes[rqe_index], &deployments[deployment_index]) / reference, + assignment_cost(&rqes[rqe_index], &deployments[deployment_index]) / reference, assignment, ); } @@ -167,9 +169,12 @@ pub fn minimize( let rqe = &rqes[rqe_index]; let deployment = &deployments[deployment_index]; model.add_constraint((assignment - active[deployment_index]).leq(0)); - let stored_cost = storage(rqe, deployment) / reference; - if stored_cost > 0.0 { - model.add_constraint((stored_cost * assignment - stored[deployment_index]).leq(0)); + // Zero when `w_mem` is 0; such a row can never bind. + let rqe_storage_cost = storage_cost(rqe, deployment) / reference; + if rqe_storage_cost > 0.0 { + model.add_constraint( + (rqe_storage_cost * assignment - storage[deployment_index]).leq(0), + ); } // Each RQE takes exactly one deployment, so a per-RQE bound just // forbids the choices over it. Comparing in f64 here, not in the @@ -328,9 +333,9 @@ mod tests { deployment(0.2 * tiny, 2.0 * tiny * BYTES_PER_GIB, 1.0 * tiny), ] .into_iter() - .map(|mut d| { - d.config.merge_cpu_secs = tiny; - d + .map(|mut candidate| { + candidate.config.merge_cpu_secs = tiny; + candidate }) .collect::>(); for objective in [weights(1.0, 0.0), weights(1.0, 4.0)] { diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs index 2cb46db2..79562e51 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/objectives.rs @@ -1,16 +1,18 @@ //! Analytical scoring built from measured per-operation costs (§5). //! -//! Costs split into four phases, each with CPU and memory: ingest (open -//! windows), merge and query (per evaluation), and storage (closed windows, -//! no CPU). The per-phase functions here are the one copy of the formulas; -//! [`score`] and the MILP both use them. +//! Costs split into four phases, each with CPU and memory: +//! - ingest: inserts into open windows, and their state; +//! - merge: folding a query's windows, and the merged state; +//! - query: reading the merged state, and the output; +//! - storage: closed windows kept for lookbacks (no CPU). //! -//! Every measured cost is per instance, and a deployment holds `card(G)` -//! instances per window. Exact multi-group accumulators are measured as one -//! instance over many groups, but the export divides their memory and merge -//! by `groups_per_instance` (`aqpbm_core::atomic_costs`), so `card(G) ×` -//! prices them right too. -// ponytail: a family holding every group in one fixed-size instance (HydraKLL, +//! [`score`] and the MILP share the per-phase functions below. +//! +//! Measured costs are per instance, and a deployment holds `card(G)` instances +//! per window. 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. +// ponytail: a family with one fixed-size instance for all groups (HydraKLL, // sketch-bench#142) needs a per-family shape so it isn't multiplied by card(G). use crate::{Capability, Deployment, Mapping, Rqe, WorkloadFacts}; @@ -18,15 +20,15 @@ use std::collections::{BTreeMap, BTreeSet}; pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; -/// Query output per group: one f64 (one quantile for Quantile). -// ponytail: an estimate, not measured; tiny next to sketch state. +/// Query output per group: one f64. +// ponytail: estimated, not measured; tiny next to sketch state. pub const OUTPUT_BYTES_PER_VALUE: f64 = 8.0; /// Query output per top-k entry: a 64-bit key hash and a count. pub const OUTPUT_BYTES_PER_TOPK_ENTRY: f64 = 16.0; -/// Top-k entries per group: sketch-bench's `CMS_HEAP_TOP_K`, the heap size -/// every top-k row was measured at. -// ponytail: fixed k. The RQE has no `k`, and the heap is left out of measured -// memory; a large k needs both, plus a benchmark that varies the heap. +/// Top-k entries per group: the heap size every top-k cost row was measured +/// at (sketch-bench's `CMS_HEAP_TOP_K`). +// ponytail: fixed k. A large k needs `k` on the RQE and a benchmark that +// varies the heap, whose memory the export leaves out. pub const TOPK_ENTRIES: f64 = 32.0; /// One phase's resource use. @@ -46,15 +48,13 @@ impl std::ops::AddAssign for PhaseCost { #[derive(Debug, Clone)] pub struct Objectives { - /// Inserts into open windows, and the open windows' state. + /// Paid once per active deployment. pub ingest: PhaseCost, - /// Folding each query's windows together, and the merged state, summed - /// over RQEs as if every query evaluates at once. + /// Paid per RQE; memory as if every query runs at once. pub merge: PhaseCost, - /// Reading the merged state, and the output, summed like `merge`. + /// Paid per RQE; memory as if every query runs at once. pub query: PhaseCost, - /// Closed windows still inside the longest lookback each deployment - /// serves. No CPU. + /// Paid once per active deployment, sized for its longest lookback. pub storage: PhaseCost, /// Index-aligned with the input RQE slice; display IDs need not be unique. pub query_latency_secs: Vec, @@ -62,11 +62,11 @@ pub struct Objectives { impl Objectives { pub fn cpu_secs_per_sec(&self) -> f64 { - self.phases().map(|p| p.cpu_secs_per_sec).sum() + self.phases().map(|phase| phase.cpu_secs_per_sec).sum() } pub fn memory_bytes(&self) -> f64 { - self.phases().map(|p| p.memory_bytes).sum() + self.phases().map(|phase| phase.memory_bytes).sum() } fn phases(&self) -> impl Iterator { @@ -75,70 +75,74 @@ impl Objectives { } /// `card(G)`: instances per window. -fn groups(d: &Deployment, facts: &WorkloadFacts) -> f64 { - facts[&d.metric].cardinality[&d.grouping_labels] as f64 +fn group_count(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + facts[&deployment.metric].cardinality[&deployment.grouping_labels] as f64 } -fn open_windows(d: &Deployment) -> f64 { - d.active_instance_count() +/// `x / y`: windows each sample is inserted into. +fn open_window_count(deployment: &Deployment) -> f64 { + deployment + .active_instance_count() .expect("candidate window and slide align") as f64 } -/// `L / x`: windows merged for one evaluation. -fn merged_windows(r: &Rqe, d: &Deployment) -> f64 { - d.query_instance_count(r.lookback_secs) +/// `L / x`: windows merged per query. +fn merged_window_count(rqe: &Rqe, deployment: &Deployment) -> f64 { + deployment + .query_instance_count(rqe.lookback_secs) .expect("only eligible pairs are costed") as f64 } -/// Every sample goes into its group's instance in each open window: -/// `λ · (x/y) · c_ins` CPU, `card(G) · m · x/y` memory. -pub(crate) fn ingest(d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { +/// CPU `λ · (x/y) · c_ins`; memory `card(G) · m · (x/y)`. +pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let open_windows = open_window_count(deployment); PhaseCost { - cpu_secs_per_sec: facts[&d.metric].arrival_rate_per_sec() - * open_windows(d) - * d.config.insert_cpu_secs, - memory_bytes: groups(d, facts) * d.config.mem_bytes_per_instance * open_windows(d), + cpu_secs_per_sec: facts[&deployment.metric].arrival_rate_per_sec() + * open_windows + * deployment.config.insert_cpu_secs, + memory_bytes: group_count(deployment, facts) + * deployment.config.mem_bytes_per_instance + * open_windows, } } -/// Per group, `L/x − 1` folds every `T`, holding one merged instance: -/// `card(G) · (L/x − 1) · c_mrg / T` CPU, `card(G) · m` memory. -pub(crate) fn merge(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let groups = groups(d, facts); +/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `card(G) · m`. +pub(crate) fn merge(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = group_count(deployment, facts); + let merges_per_group = merged_window_count(rqe, deployment) - 1.0; PhaseCost { - cpu_secs_per_sec: groups * (merged_windows(r, d) - 1.0) * d.config.merge_cpu_secs - / r.interval_secs as f64, - memory_bytes: groups * d.config.mem_bytes_per_instance, + cpu_secs_per_sec: groups * merges_per_group * deployment.config.merge_cpu_secs + / rqe.interval_secs as f64, + memory_bytes: groups * deployment.config.mem_bytes_per_instance, } } -/// Per group, one query every `T` and its output: -/// `card(G) · c_qry / T` CPU, `card(G) ·` output bytes memory. -pub(crate) fn query(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let groups = groups(d, facts); - let output_bytes = match r.capability { +/// CPU `card(G) · c_qry / T`; memory `card(G) ·` output bytes per group. +pub(crate) fn query(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = group_count(deployment, facts); + let output_bytes_per_group = match rqe.capability { Capability::TopK => TOPK_ENTRIES * OUTPUT_BYTES_PER_TOPK_ENTRY, _ => OUTPUT_BYTES_PER_VALUE, }; PhaseCost { - cpu_secs_per_sec: groups * d.config.query_cpu_secs / r.interval_secs as f64, - memory_bytes: groups * output_bytes, + cpu_secs_per_sec: groups * deployment.config.query_cpu_secs / rqe.interval_secs as f64, + memory_bytes: groups * output_bytes_per_group, } } -/// Closed windows `d` holds so `r` can be answered: `card(G) · m · -/// ((L − x)/y + 1)`. A deployment holds the most any of its RQEs needs. -pub(crate) fn storage_bytes(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> f64 { - groups(d, facts) - * d.config.mem_bytes_per_instance - * d.closed_instance_count(r.lookback_secs) - .expect("only eligible pairs are costed") as f64 +/// Closed windows kept to answer `rqe`: `card(G) · m · ((L − x)/y + 1)`. +pub(crate) fn storage_bytes(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let closed_windows = deployment + .closed_instance_count(rqe.lookback_secs) + .expect("only eligible pairs are costed") as f64; + group_count(deployment, facts) * deployment.config.mem_bytes_per_instance * closed_windows } -/// One evaluation's wall time on one core: `card(G) · (c_qry + (L/x − 1) · c_mrg)`. -pub(crate) fn query_latency_secs(r: &Rqe, d: &Deployment, facts: &WorkloadFacts) -> f64 { - groups(d, facts) - * (d.config.query_cpu_secs + (merged_windows(r, d) - 1.0) * d.config.merge_cpu_secs) +/// Serial CPU time of one query: `card(G) · (c_qry + (L/x − 1) · c_mrg)`. +pub(crate) fn query_latency_secs(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let merges_per_group = merged_window_count(rqe, deployment) - 1.0; + group_count(deployment, facts) + * (deployment.config.query_cpu_secs + merges_per_group * deployment.config.merge_cpu_secs) } pub fn score( @@ -152,25 +156,27 @@ pub fn score( rqes.len(), "mapping must have one deployment per RQE" ); - let active: BTreeSet = mapping.iter().copied().collect(); + let active_deployments: BTreeSet = mapping.iter().copied().collect(); let mut ingest_cost = PhaseCost::default(); - for &di in &active { - ingest_cost += ingest(&deployments[di], facts); + for &deployment_index in &active_deployments { + ingest_cost += ingest(&deployments[deployment_index], facts); } - let mut stored: BTreeMap = BTreeMap::new(); + let mut storage_bytes_by_deployment: BTreeMap = BTreeMap::new(); let mut merge_cost = PhaseCost::default(); let mut query_cost = PhaseCost::default(); let query_latency_secs = rqes .iter() .zip(mapping) - .map(|(r, &di)| { - let d = &deployments[di]; - let held = stored.entry(di).or_default(); - *held = held.max(storage_bytes(r, d, facts)); - merge_cost += merge(r, d, facts); - query_cost += query(r, d, facts); - query_latency_secs(r, d, facts) + .map(|(rqe, &deployment_index)| { + let deployment = &deployments[deployment_index]; + let stored = storage_bytes_by_deployment + .entry(deployment_index) + .or_default(); + *stored = stored.max(storage_bytes(rqe, deployment, facts)); + merge_cost += merge(rqe, deployment, facts); + query_cost += query(rqe, deployment, facts); + query_latency_secs(rqe, deployment, facts) }) .collect(); @@ -180,7 +186,7 @@ pub fn score( query: query_cost, storage: PhaseCost { cpu_secs_per_sec: 0.0, - memory_bytes: stored.values().sum(), + memory_bytes: storage_bytes_by_deployment.values().sum(), }, query_latency_secs, } @@ -193,19 +199,18 @@ mod tests { #[test] fn scores_each_phase() { - // 4 groups, 7 samples/sec; window 20 s sliding by 10 s, so 2 open - // windows; lookback 60 s every 30 s, so 3 windows merged and - // (60 − 20)/10 + 1 = 5 closed windows held. - let d = deployment(10.0, 2.0, 3.0, 5.0, 20, 10); - let r = rqe(60, 30); - let result = score(&[r], &[d], &vec![0], &facts(4, 7)); + // 4 groups and 7 samples/sec. Window 20 s sliding by 10 s: 2 open + // windows. Lookback 60 s every 30 s: 3 windows merged, and + // (60 − 20)/10 + 1 = 5 closed windows stored. + let deployment = deployment(10.0, 2.0, 3.0, 5.0, 20, 10); + let result = score(&[rqe(60, 30)], &[deployment], &vec![0], &facts(4, 7)); assert_eq!(result.ingest.cpu_secs_per_sec, 28.0); // 7 × 2 × 2 assert_eq!(result.ingest.memory_bytes, 80.0); // 4 × 10 × 2 assert_eq!(result.merge.cpu_secs_per_sec, 24.0 / 30.0); // 4 × 2 × 3 / 30 assert_eq!(result.merge.memory_bytes, 40.0); // 4 × 10 assert_eq!(result.query.cpu_secs_per_sec, 20.0 / 30.0); // 4 × 5 / 30 - assert_eq!(result.query.memory_bytes, 4.0 * 32.0 * 16.0); // top-k output + assert_eq!(result.query.memory_bytes, 2048.0); // 4 × 32 × 16 assert_eq!(result.storage.cpu_secs_per_sec, 0.0); assert_eq!(result.storage.memory_bytes, 200.0); // 4 × 10 × 5 assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 + 2 × 3) @@ -214,36 +219,22 @@ mod tests { } #[test] - fn a_direct_query_holds_one_closed_window() { - // L == x: one closed window, nothing to merge. - let d = deployment(10.0, 1.0, 1.0, 1.0, 60, 60); - let result = score(&[rqe(60, 60)], &[d], &vec![0], &facts(1, 1)); + fn a_direct_query_stores_one_closed_window_and_never_merges() { + let deployment = deployment(10.0, 1.0, 1.0, 1.0, 60, 60); + let result = score(&[rqe(60, 60)], &[deployment], &vec![0], &facts(1, 1)); assert_eq!(result.storage.memory_bytes, 10.0); assert_eq!(result.merge.cpu_secs_per_sec, 0.0); } #[test] fn shared_deployment_stores_for_its_longest_lookback() { - let d = deployment(10.0, 1.0, 1.0, 1.0, 10, 10); - let result = score( - &[rqe(60, 10), rqe(600, 10)], - &[d], - &vec![0, 0], - &facts(2, 2), - ); - // One copy of state, sized for 600 s: 2 × 10 × ((600 − 10)/10 + 1). + let deployment = deployment(10.0, 1.0, 1.0, 1.0, 10, 10); + let rqes = [rqe(60, 10), rqe(600, 10)]; + let result = score(&rqes, &[deployment], &vec![0, 0], &facts(2, 2)); + // 2 groups × 10 bytes × ((600 − 10)/10 + 1) closed windows. assert_eq!(result.storage.memory_bytes, 1200.0); - // Ingest is paid once; merge and query once per RQE. + // Ingest is paid once; merge once per RQE. assert_eq!(result.ingest.cpu_secs_per_sec, 2.0); assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 10.0); } - - #[test] - fn arrival_rate_is_series_over_scrape_interval() { - let mut f = facts(4, 600); - f.get_mut(crate::test_support::METRIC) - .unwrap() - .scrape_interval_secs = 15; - assert_eq!(f[crate::test_support::METRIC].arrival_rate_per_sec(), 40.0); - } } From af65fc404621c7312475258e9f7e9b9f4ae1aa52 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:17:54 -0400 Subject: [PATCH 06/18] rqe-optimizer: explain candidate slides with an example State that gcd(x, T) is the largest slide serving an RQE, why each subset of RQEs gets the gcd of theirs, and why one pass computes all of them. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 65 ++++++++++++++++++++------------ rqe-optimizer/src/candidates.rs | 17 +++++---- 2 files changed, 50 insertions(+), 32 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index c1d5158c..647481fb 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -6,10 +6,6 @@ Given a workload of repeating query expressions (RQEs), find sketch deployments that can serve it and report the trade-offs among query working memory, CPU, and per-RQE latency. -v1 is static and small-scale. It enumerates feasible mappings rather than -calling an ILP solver, but states the problem in solver-friendly terms so that -enumeration can be replaced later. - ## Inputs Let `R = {r_1, ..., r_n}` be the RQE workload. Each RQE `r_i` provides: @@ -32,17 +28,15 @@ For each metric, the caller provides `MetricFacts`: - `card(X)`: distinct value combinations of each label set `X` in use, including `labels` itself (the raw series count). -The arrival rate is derived, never given, so it can't disagree with the -cardinalities: +The arrival rate is derived as follows (not provided by the user): ```text lambda(metric) = card(metric.labels) / scrape_interval samples/second ``` -These are inputs to the optimizer; estimating them is outside v1. `validate_facts` reports every missing or inconsistent fact up front. -Sketch Bench supplies empirical measurements for each sketch configuration: +sketch-bench supplies empirical measurements for each sketch configuration: - memory per sketch instance; - insert CPU per item; @@ -86,14 +80,13 @@ For a query ending at time `t`, use the instances: ``` They exactly cover the query window and do not overlap. The deployment may -have produced other, overlapping instances between these starts; this query -does not merge them. +have produced other, overlapping instances between these starts. That is okay. Those overlapping instances are not used for this query. `S % T == 0` is not required. For example, a 10-minute window running every 3 minutes can use `x = 2 minutes` and `y = 1 minute`; each query merges five non-overlapping two-minute instances. -v1 assumes all RQEs share a common time origin. Query phase offsets are not +We assume all RQEs share a common time origin. Query phase offsets are not modeled. ## Candidate deployments @@ -111,25 +104,47 @@ selected deployment may serve multiple compatible RQEs. For each (capability, metric, G) group, generate candidates as follows: ```text -for each x that divides S_i for at least one RQE i in the group, - and is a multiple of the metric's scrape interval: - let g_i = gcd(x, T_i) for every RQE i whose S_i is divisible by x - let slides = every gcd reachable from a non-empty subset of {g_i} - for each measured configuration that serves the group's capability: - for each y in slides that is a multiple of the scrape interval: - add (capability, configuration, metric, G, x, y) +for each window x that divides some S_i and is a multiple of the scrape interval: + for each RQE i whose S_i is divisible by x: + g_i = gcd(x, T_i) # the largest slide that serves RQE i + slides = { gcd(A) : A a non-empty subset of {g_i} } + for each configuration serving the capability, + and each y in slides that is a multiple of the scrape interval: + add (capability, configuration, metric, G, x, y) ``` +**Windows.** An RQE 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. -For an RQE considered alone, its only useful slide for a fixed `x` is its -largest legal slide, `gcd(x, T_i)`. A smaller slide adds ingest fan-out without -improving that RQE's query cost or memory. A shared deployment may need a -smaller slide: for example, two RQEs with `gcd(x, T)` values of 20 and 30 need -`y = 10` to share. Subset gcds include that slide without enumerating every -divisor. Any still-finer slide is useful only if it aligns an additional RQE, -in which case it appears as another subset gcd. +**Slides.** A slide `y` serves RQE `i` when it divides both `x` and `T_i`, +that is, when it divides `g_i`. A smaller `y` only adds open windows (`x / y`), +which costs ingest and storage for no gain. So: + +- one RQE alone wants `y = g_i`; +- a set `A` of RQEs sharing a deployment wants the largest `y` dividing every + `g_i` in `A`, which is `gcd(A)`. + +Which RQEs share is the solver's choice, so every subset's gcd is a candidate. +Every other divisor of `x` is dominated by one of these. + +Example: `x = 60`, RQE `a` every 20 s, RQE `b` every 30 s. + +| Served RQEs | `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 RQE `r_i` is eligible for a candidate `D` when: diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 6b35f5ca..fc8a849c 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -27,16 +27,17 @@ fn divisors(value: Seconds) -> Vec { out } -/// Every gcd reachable from a non-empty subset, folded incrementally rather -/// than by enumerating the powerset. +/// The gcd of every non-empty subset of `values`, in one pass without listing +/// subsets: `gcd(A ∪ {v}) = gcd(gcd(A), v)`, so each new value extends every +/// gcd found so far. fn subset_gcds(values: impl IntoIterator) -> BTreeSet { - let mut out = BTreeSet::new(); + let mut gcds = BTreeSet::new(); for value in values { - let extensions: Vec<_> = out.iter().map(|&previous| gcd(previous, value)).collect(); - out.insert(value); - out.extend(extensions); + let extended: Vec<_> = gcds.iter().map(|&found| gcd(found, value)).collect(); + gcds.insert(value); + gcds.extend(extended); } - out + gcds } /// Windows and slides are multiples of the metric's scrape interval: anything @@ -57,6 +58,8 @@ fn candidate_deployments( .collect::>(); let mut deployments = Vec::new(); for window_secs in windows { + // gcd(x, T) is the largest slide that serves an RQE. RQEs sharing a + // deployment need the gcd of theirs, and any subset might share. let slides = subset_gcds( group .iter() From d0598d14f0dedc8c1f705b33b35acbb23edef669 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:18:31 -0400 Subject: [PATCH 07/18] docs: frame candidate slides as strictly better than finer ones Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 15 +++++++++------ rqe-optimizer/src/candidates.rs | 5 +++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 647481fb..272f61e9 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -118,15 +118,18 @@ Windows and slides finer than the scrape interval would only split one scrape's samples. **Slides.** A slide `y` serves RQE `i` when it divides both `x` and `T_i`, -that is, when it divides `g_i`. A smaller `y` only adds open windows (`x / y`), -which costs ingest and storage for no gain. So: +that is, when it divides `g_i`. A finer slide serves no more RQEs but holds +more open windows (`x / y`) and more closed ones, so it costs more ingest and +storage at the same latency. Hence: -- one RQE alone wants `y = g_i`; -- a set `A` of RQEs sharing a deployment wants the largest `y` dividing every - `g_i` in `A`, which is `gcd(A)`. +- for one RQE, `y = g_i` is strictly better than every finer slide that serves + it; +- for a set `A` of RQEs 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 RQEs share is the solver's choice, so every subset's gcd is a candidate. -Every other divisor of `x` is dominated by one of these. +Every other divisor of `x` is strictly worse than one of these. Example: `x = 60`, RQE `a` every 20 s, RQE `b` every 30 s. diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index fc8a849c..942ef93b 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -58,8 +58,9 @@ fn candidate_deployments( .collect::>(); let mut deployments = Vec::new(); for window_secs in windows { - // gcd(x, T) is the largest slide that serves an RQE. RQEs sharing a - // deployment need the gcd of theirs, and any subset might share. + // gcd(x, T) is the largest slide that serves an RQE. For RQEs sharing a + // deployment, the gcd of theirs is strictly better than any finer + // slide that serves them all. Any subset might share. let slides = subset_gcds( group .iter() From dc65cd186e4e7fb4043844138913d308b58075d5 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:19:14 -0400 Subject: [PATCH 08/18] docs: list the cost model's variables one per line Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 272f61e9..fed1de97 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -231,11 +231,18 @@ 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. -A deployment `D` holds `card(D.G)` instances per window, one per group. Let -`a_D = D.x / D.y`: each sample is inserted into `a_D` concurrently open -instances of its group. For RQE `i` on `D`, let `n_i = S_i / D.x` windows be -merged per query. Write `m`, `c_ins`, `c_mrg`, `c_qry` for the -configuration's measured per-instance memory and insert, merge and query CPU. +For deployment `D` serving RQE `i`: + +- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. +- `card(G)`: groups of `D`, so instances per window. +- `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`: RQE `i`'s lookback and interval. +- `n_i = S_i / x`: windows merged per query. +- `m`: memory per instance, measured. +- `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): From 654ea1426d9502449b466efa83c8fa5941d7cc1d Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:21:08 -0400 Subject: [PATCH 09/18] rqe-optimizer: merge memory holds both operands of a pairwise merge Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 4 ++-- rqe-optimizer/src/objectives.rs | 12 +++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index fed1de97..49b8985d 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -250,7 +250,7 @@ Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory | Phase | CPU | Memory | |---|---|---| | Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one merged instance per group) | +| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `2 × card(G) × m` (both operands of a pairwise merge, per group) | | Query, per RQE | `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) | @@ -282,7 +282,7 @@ no cheaper k-way merge. | Ingest memory | yes | yes | × `x/y` open | not modeled | | Storage memory | yes, sized for the longest `S` it serves | yes | × `(S−x)/y + 1` closed | not modeled | | Merge CPU | no, per RQE | yes | × `(S/x − 1)` folds | not modeled | -| Merge memory | no, per RQE | yes | × 1 merged instance | not modeled | +| Merge memory | no, per RQE | yes | × 2, the operands of a pairwise merge | not modeled | | Query CPU | no, per RQE | yes | — | one probe per group | | Query memory | no, per RQE | yes | — | 8 B, or 32 × 16 B for top-k | | Latency | per RQE | yes | `S/x − 1` merges | — | diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs index 79562e51..f2c1e5f1 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/objectives.rs @@ -106,14 +106,15 @@ pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCos } } -/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `card(G) · m`. +/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `2 · card(G) · m`, both +/// operands of a pairwise merge per group. pub(crate) fn merge(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { let groups = group_count(deployment, facts); let merges_per_group = merged_window_count(rqe, deployment) - 1.0; PhaseCost { cpu_secs_per_sec: groups * merges_per_group * deployment.config.merge_cpu_secs / rqe.interval_secs as f64, - memory_bytes: groups * deployment.config.mem_bytes_per_instance, + memory_bytes: 2.0 * groups * deployment.config.mem_bytes_per_instance, } } @@ -208,14 +209,14 @@ mod tests { assert_eq!(result.ingest.cpu_secs_per_sec, 28.0); // 7 × 2 × 2 assert_eq!(result.ingest.memory_bytes, 80.0); // 4 × 10 × 2 assert_eq!(result.merge.cpu_secs_per_sec, 24.0 / 30.0); // 4 × 2 × 3 / 30 - assert_eq!(result.merge.memory_bytes, 40.0); // 4 × 10 + assert_eq!(result.merge.memory_bytes, 80.0); // 2 × 4 × 10 assert_eq!(result.query.cpu_secs_per_sec, 20.0 / 30.0); // 4 × 5 / 30 assert_eq!(result.query.memory_bytes, 2048.0); // 4 × 32 × 16 assert_eq!(result.storage.cpu_secs_per_sec, 0.0); assert_eq!(result.storage.memory_bytes, 200.0); // 4 × 10 × 5 assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 + 2 × 3) assert!((result.cpu_secs_per_sec() - (28.0 + 44.0 / 30.0)).abs() < 1e-12); - assert_eq!(result.memory_bytes(), 80.0 + 40.0 + 2048.0 + 200.0); + assert_eq!(result.memory_bytes(), 80.0 + 80.0 + 2048.0 + 200.0); } #[test] @@ -235,6 +236,7 @@ mod tests { assert_eq!(result.storage.memory_bytes, 1200.0); // Ingest is paid once; merge once per RQE. assert_eq!(result.ingest.cpu_secs_per_sec, 2.0); - assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 10.0); + // Two RQEs × 2 operands × 2 groups × 10 bytes. + assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 2.0 * 10.0); } } From 8da91e7c66aba6b0c7179153eacdf38c9a5c63ff Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:26:18 -0400 Subject: [PATCH 10/18] rqe-optimizer: merge memory is one accumulator, none for direct queries Stored windows are live objects already counted in storage, so a merge adds only the accumulator per group. A query with L == x merges nothing. Candidate pruning now compares merge memory per served RQE, since it is no longer the same instance size for every RQE. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 8 ++-- rqe-optimizer/src/candidates.rs | 65 ++++++++++++++++++++++++-------- rqe-optimizer/src/objectives.rs | 26 +++++++++---- 3 files changed, 72 insertions(+), 27 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 49b8985d..75f0f871 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -162,8 +162,8 @@ explicit on the RQE; 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 -RQE it can and is no worse in instance memory, ingest CPU and memory, latency, -and stored memory for each such RQE. This is safe because any mapping using +RQE it can and is no worse in ingest CPU and memory, and in latency, merge +memory and stored memory for each such RQE. This is safe because any mapping using the removed candidate can substitute the remaining one without weakening a modeled objective. @@ -250,7 +250,7 @@ Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory | Phase | CPU | Memory | |---|---|---| | Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `2 × card(G) × m` (both operands of a pairwise merge, per group) | +| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group; the windows folded in are live in storage); 0 when `n_i = 1` | | Query, per RQE | `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) | @@ -282,7 +282,7 @@ no cheaper k-way merge. | Ingest memory | yes | yes | × `x/y` open | not modeled | | Storage memory | yes, sized for the longest `S` it serves | yes | × `(S−x)/y + 1` closed | not modeled | | Merge CPU | no, per RQE | yes | × `(S/x − 1)` folds | not modeled | -| Merge memory | no, per RQE | yes | × 2, the operands of a pairwise merge | not modeled | +| Merge memory | no, per RQE | yes | × 1 accumulator, 0 when `n_i = 1` | not modeled | | Query CPU | no, per RQE | yes | — | one probe per group | | Query memory | no, per RQE | yes | — | 8 B, or 32 × 16 B for top-k | | Latency | per RQE | yes | `S/x − 1` merges | — | diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 942ef93b..13457b04 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,5 +1,6 @@ //! Candidate generation and eligibility (§3). +use crate::objectives::merge_memory_per_group; use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds, WorkloadFacts}; use std::collections::{BTreeMap, BTreeSet}; @@ -125,9 +126,9 @@ pub fn build_all_candidates_unpruned( /// /// This comparison is deliberately local to a (capability, metric, grouping) /// group, where `card(G)`, arrival rate and query output size are common -/// multipliers. So it compares instance size (merge memory) and ingest CPU and -/// memory per group, then latency (merge and query CPU) and stored memory for -/// each RQE the dominated candidate can serve. +/// multipliers. So it compares ingest CPU and memory per group, then latency +/// (merge and query CPU), merge memory and stored memory for each RQE the +/// dominated candidate can serve. pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> Vec { let eligibility: Vec> = candidates .iter() @@ -179,8 +180,7 @@ fn candidate_dominates( return false; } - replacement.config.mem_bytes_per_instance <= original.config.mem_bytes_per_instance - && ingest_cpu(replacement) <= ingest_cpu(original) + ingest_cpu(replacement) <= ingest_cpu(original) && ingest_memory(replacement) <= ingest_memory(original) && original_coverage .iter() @@ -190,11 +190,12 @@ fn candidate_dominates( .iter() .enumerate() .all(|(rqe_index, &serves)| { + let rqe = &rqes[rqe_index]; !serves - || (query_latency(replacement, &rqes[rqe_index]) - <= query_latency(original, &rqes[rqe_index]) - && stored_memory(replacement, &rqes[rqe_index]) - <= stored_memory(original, &rqes[rqe_index])) + || (query_latency(replacement, rqe) <= query_latency(original, rqe) + && merge_memory_per_group(rqe, replacement) + <= merge_memory_per_group(rqe, original) + && stored_memory(replacement, rqe) <= stored_memory(original, rqe)) }) } @@ -205,8 +206,7 @@ fn strictly_better( original_coverage: &[bool], rqes: &[Rqe], ) -> bool { - replacement.config.mem_bytes_per_instance < original.config.mem_bytes_per_instance - || ingest_cpu(replacement) < ingest_cpu(original) + ingest_cpu(replacement) < ingest_cpu(original) || ingest_memory(replacement) < ingest_memory(original) || original_coverage .iter() @@ -216,11 +216,12 @@ fn strictly_better( .iter() .enumerate() .any(|(rqe_index, &serves)| { + let rqe = &rqes[rqe_index]; serves - && (query_latency(replacement, &rqes[rqe_index]) - < query_latency(original, &rqes[rqe_index]) - || stored_memory(replacement, &rqes[rqe_index]) - < stored_memory(original, &rqes[rqe_index])) + && (query_latency(replacement, rqe) < query_latency(original, rqe) + || merge_memory_per_group(rqe, replacement) + < merge_memory_per_group(rqe, original) + || stored_memory(replacement, rqe) < stored_memory(original, rqe)) }) } @@ -454,4 +455,38 @@ mod tests { assert_eq!(retained, vec![whole_window, panes]); } + + #[test] + fn retains_direct_query_candidate_that_never_merges() { + let r = rqe("r", 60, 60); + // x == L: no merge, so no merge memory. + let direct = Deployment { + capability: Capability::TopK, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + config: AtomicCostEntry { + mem_bytes_per_instance: 10.0, + ..cost() + }, + window_secs: 60, + slide_secs: 60, + }; + // Smaller and cheaper on every other cost, but merges two windows, + // holding a 4-byte accumulator per group. + let halves = Deployment { + config: AtomicCostEntry { + mem_bytes_per_instance: 4.0, + query_cpu_secs: 0.5, + merge_cpu_secs: 0.1, + ..cost() + }, + window_secs: 30, + slide_secs: 30, + ..direct.clone() + }; + + let retained = prune_dominated_candidates(&[r], vec![direct.clone(), halves.clone()]); + + assert_eq!(retained, vec![direct, halves]); + } } diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs index f2c1e5f1..b5911a4d 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/objectives.rs @@ -106,15 +106,25 @@ pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCos } } -/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `2 · card(G) · m`, both -/// operands of a pairwise merge per group. +/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `card(G) · m`, one +/// accumulator per group. The windows folded into it are live in storage. +/// A direct query (`L == x`) merges nothing and costs neither. pub(crate) fn merge(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { let groups = group_count(deployment, facts); let merges_per_group = merged_window_count(rqe, deployment) - 1.0; PhaseCost { cpu_secs_per_sec: groups * merges_per_group * deployment.config.merge_cpu_secs / rqe.interval_secs as f64, - memory_bytes: 2.0 * groups * deployment.config.mem_bytes_per_instance, + memory_bytes: groups * merge_memory_per_group(rqe, deployment), + } +} + +/// One accumulator if the query merges at all. +pub(crate) fn merge_memory_per_group(rqe: &Rqe, deployment: &Deployment) -> f64 { + if merged_window_count(rqe, deployment) > 1.0 { + deployment.config.mem_bytes_per_instance + } else { + 0.0 } } @@ -209,14 +219,14 @@ mod tests { assert_eq!(result.ingest.cpu_secs_per_sec, 28.0); // 7 × 2 × 2 assert_eq!(result.ingest.memory_bytes, 80.0); // 4 × 10 × 2 assert_eq!(result.merge.cpu_secs_per_sec, 24.0 / 30.0); // 4 × 2 × 3 / 30 - assert_eq!(result.merge.memory_bytes, 80.0); // 2 × 4 × 10 + assert_eq!(result.merge.memory_bytes, 40.0); // 4 × 10 assert_eq!(result.query.cpu_secs_per_sec, 20.0 / 30.0); // 4 × 5 / 30 assert_eq!(result.query.memory_bytes, 2048.0); // 4 × 32 × 16 assert_eq!(result.storage.cpu_secs_per_sec, 0.0); assert_eq!(result.storage.memory_bytes, 200.0); // 4 × 10 × 5 assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 + 2 × 3) assert!((result.cpu_secs_per_sec() - (28.0 + 44.0 / 30.0)).abs() < 1e-12); - assert_eq!(result.memory_bytes(), 80.0 + 80.0 + 2048.0 + 200.0); + assert_eq!(result.memory_bytes(), 80.0 + 40.0 + 2048.0 + 200.0); } #[test] @@ -224,7 +234,7 @@ mod tests { let deployment = deployment(10.0, 1.0, 1.0, 1.0, 60, 60); let result = score(&[rqe(60, 60)], &[deployment], &vec![0], &facts(1, 1)); assert_eq!(result.storage.memory_bytes, 10.0); - assert_eq!(result.merge.cpu_secs_per_sec, 0.0); + assert_eq!(result.merge, PhaseCost::default()); } #[test] @@ -236,7 +246,7 @@ mod tests { assert_eq!(result.storage.memory_bytes, 1200.0); // Ingest is paid once; merge once per RQE. assert_eq!(result.ingest.cpu_secs_per_sec, 2.0); - // Two RQEs × 2 operands × 2 groups × 10 bytes. - assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 2.0 * 10.0); + // Two RQEs × 2 groups × 10 bytes. + assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 10.0); } } From 4a2395a46da43589e3439f6a096995edbe4f62db Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 09:36:35 -0400 Subject: [PATCH 11/18] docs: add intuition for the two-step candidate construction Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 75f0f871..18754813 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -101,6 +101,13 @@ Candidates may be generated from individual RQEs, then deduplicated. This is only a way to construct the candidate set: when solving a workload, one selected deployment may serve multiple compatible RQEs. +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 RQEs. Pruning then attaches the +measured costs and drops a candidate when another serves all of its RQEs and +is no worse on every cost. + For each (capability, metric, G) group, generate candidates as follows: ```text From 87adc599987ef77875bb0e221bff881300abd2fa Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:06:25 -0400 Subject: [PATCH 12/18] rqe-optimizer: one dominance comparison in candidate pruning candidate_dominates and strictly_better walked the same costs twice. A single dominance() collects (replacement, original) cost pairs once and reports strictly better, equal or not dominating. Docs: define open and closed instances, fix the candidate pseudocode indentation, and reword card(G) and merge memory. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 19 ++-- rqe-optimizer/src/candidates.rs | 147 ++++++++++++++++--------------- rqe-optimizer/src/objectives.rs | 7 +- 3 files changed, 93 insertions(+), 80 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 18754813..70701cbe 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -61,6 +61,11 @@ For every label-value group, it creates an instance for every interval: [k × y, k × y + x) ``` +At time `t`, an instance is **open** while its interval has not ended +(`t < k × y + x`): it still receives samples. After that it is **closed**: it +never changes again and is kept only while some RQE's lookback still needs it. +A deployment has `x / y` open instances per group at any time. + Instances overlap when `x > y`. There is no subtract operation. To answer an RQE, the system selects and merges only non-overlapping instances, so items are never counted twice. @@ -113,11 +118,11 @@ 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: for each RQE i whose S_i is divisible by x: - g_i = gcd(x, T_i) # the largest slide that serves RQE i - slides = { gcd(A) : A a non-empty subset of {g_i} } - for each configuration serving the capability, - and each y in slides that is a multiple of the scrape interval: - add (capability, configuration, metric, G, x, y) + g_i = gcd(x, T_i) # the largest slide that serves RQE i + slides = { gcd(A) : A is a non-empty subset of {g_i} } + 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) ``` **Windows.** An RQE merges `S_i / x` whole windows, so `x` must divide `S_i`. @@ -241,7 +246,7 @@ window size, and query frequency. For deployment `D` serving RQE `i`: - `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. -- `card(G)`: groups of `D`, so instances per window. +- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window. - `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`: RQE `i`'s lookback and interval. @@ -257,7 +262,7 @@ Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory | Phase | CPU | Memory | |---|---|---| | Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group; the windows folded in are live in storage); 0 when `n_i = 1` | +| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | | Query, per RQE | `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) | diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 13457b04..4705ee18 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -139,90 +139,97 @@ pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> .iter() .enumerate() .filter_map(|(candidate_index, candidate)| { - let dominated = eligibility - .iter() - .enumerate() - .any(|(other_index, other_coverage)| { - other_index != candidate_index - && candidate_dominates( - &candidates[other_index], - other_coverage, - candidate, - &eligibility[candidate_index], - rqes, - ) - // Identical candidates dominate only in a stable direction, - // so a tie never removes both candidates. - && (strictly_better( - &candidates[other_index], - other_coverage, - candidate, - &eligibility[candidate_index], - rqes, - ) || other_index < candidate_index) - }); + let dominated = (0..candidates.len()).any(|other_index| { + if other_index == candidate_index { + return false; + } + match dominance( + &candidates[other_index], + &eligibility[other_index], + candidate, + &eligibility[candidate_index], + rqes, + ) { + Dominance::StrictlyBetter => true, + // The earlier of two identical candidates wins, so a tie + // never removes both. + Dominance::Equal => other_index < candidate_index, + Dominance::NotDominating => false, + } + }); (!dominated).then(|| candidate.clone()) }) .collect() } -fn candidate_dominates( +enum Dominance { + StrictlyBetter, + Equal, + NotDominating, +} + +/// Whether `replacement` can stand in for `original`: it serves every RQE +/// `original` serves and is no worse on any cost. +fn dominance( replacement: &Deployment, replacement_coverage: &[bool], original: &Deployment, original_coverage: &[bool], rqes: &[Rqe], -) -> bool { - if replacement.capability != original.capability - || replacement.metric != original.metric - || replacement.grouping_labels != original.grouping_labels - { - return false; +) -> Dominance { + let same_group = replacement.capability == original.capability + && replacement.metric == original.metric + && replacement.grouping_labels == original.grouping_labels; + let covers_original = original_coverage + .iter() + .zip(replacement_coverage) + .all(|(&original_serves, &replacement_serves)| !original_serves || replacement_serves); + if !same_group || !covers_original { + return Dominance::NotDominating; } - ingest_cpu(replacement) <= ingest_cpu(original) - && ingest_memory(replacement) <= ingest_memory(original) - && original_coverage - .iter() - .zip(replacement_coverage) - .all(|(&original_serves, &replacement_serves)| !original_serves || replacement_serves) - && original_coverage - .iter() - .enumerate() - .all(|(rqe_index, &serves)| { - let rqe = &rqes[rqe_index]; - !serves - || (query_latency(replacement, rqe) <= query_latency(original, rqe) - && merge_memory_per_group(rqe, replacement) - <= merge_memory_per_group(rqe, original) - && stored_memory(replacement, rqe) <= stored_memory(original, rqe)) - }) -} + // Each pair is (replacement's cost, original's cost). + let mut costs = vec![ + (ingest_cpu(replacement), ingest_cpu(original)), + (ingest_memory(replacement), ingest_memory(original)), + ]; + for (rqe, _) in rqes + .iter() + .zip(original_coverage) + .filter(|(_, &serves)| serves) + { + costs.push(( + query_latency(replacement, rqe), + query_latency(original, rqe), + )); + costs.push(( + merge_memory_per_group(rqe, replacement), + merge_memory_per_group(rqe, original), + )); + costs.push(( + stored_memory(replacement, rqe), + stored_memory(original, rqe), + )); + } -fn strictly_better( - replacement: &Deployment, - replacement_coverage: &[bool], - original: &Deployment, - original_coverage: &[bool], - rqes: &[Rqe], -) -> bool { - ingest_cpu(replacement) < ingest_cpu(original) - || ingest_memory(replacement) < ingest_memory(original) - || original_coverage - .iter() - .zip(replacement_coverage) - .any(|(&original_serves, &replacement_serves)| !original_serves && replacement_serves) - || original_coverage + let serves_more = original_coverage + .iter() + .zip(replacement_coverage) + .any(|(&original_serves, &replacement_serves)| !original_serves && replacement_serves); + if costs + .iter() + .any(|(replacement_cost, original_cost)| replacement_cost > original_cost) + { + Dominance::NotDominating + } else if serves_more + || costs .iter() - .enumerate() - .any(|(rqe_index, &serves)| { - let rqe = &rqes[rqe_index]; - serves - && (query_latency(replacement, rqe) < query_latency(original, rqe) - || merge_memory_per_group(rqe, replacement) - < merge_memory_per_group(rqe, original) - || stored_memory(replacement, rqe) < stored_memory(original, rqe)) - }) + .any(|(replacement_cost, original_cost)| replacement_cost < original_cost) + { + Dominance::StrictlyBetter + } else { + Dominance::Equal + } } fn open_window_count(deployment: &Deployment) -> f64 { diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs index b5911a4d..5cccbabb 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/objectives.rs @@ -74,7 +74,8 @@ impl Objectives { } } -/// `card(G)`: instances per window. +/// `card(G)`: cardinality of `G`, so the number of parallel accumulator +/// instances per window. fn group_count(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { facts[&deployment.metric].cardinality[&deployment.grouping_labels] as f64 } @@ -107,8 +108,8 @@ pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCos } /// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `card(G) · m`, one -/// accumulator per group. The windows folded into it are live in storage. -/// A direct query (`L == x`) merges nothing and costs neither. +/// accumulator per group. A direct query (`L == x`) merges nothing and costs +/// neither. pub(crate) fn merge(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { let groups = group_count(deployment, facts); let merges_per_group = merged_window_count(rqe, deployment) - 1.0; From 98ebb7fe0e3c085f6e7dba71312642c4fea7632e Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:08:26 -0400 Subject: [PATCH 13/18] docs: explain instance shape and size law in the cost model Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 53 ++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 70701cbe..306edaa2 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -271,11 +271,39 @@ Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence 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. -Exact multi-group accumulators are measured as one instance holding many -groups. The export divides their memory and merge cost by the measured group -count, so `card(G) ×` prices them correctly too. A family holding every group -in one fixed-size instance (HydraKLL) would need a per-family shape instead -(sketch-bench#142). +### Instance shape and size law + +Each exported cost row is measured on one instance, at whatever key count the +benchmark fed it (`measured_keys`). Turning that 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 with its keys. `Fixed` is set by the + configuration (e.g. CMS rows × columns); `PerKey` grows with every key. + +Memory per window is instances × instance size: + +| | Fixed | PerKey | +|---|---|---| +| **PerGroup** | `card(G) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap fixed at k = 32) | `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. + +The model uses one formula, `card(G) × m`, which is right for both cells in +use: + +- PerGroup + Fixed is that formula as is. +- Shared + PerKey reduces to it 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. + +The other two cells are deferred until a family needs them: Shared + Fixed +would be overpriced by `card(G)` (sketch-bench#142), and PerGroup + PerKey +needs the key labels `K`, the metric's labels minus `G`. Per-RQE latency is the serial CPU time of one query: @@ -299,18 +327,9 @@ no cheaper k-way merge. | Query memory | no, per RQE | yes | — | 8 B, or 32 × 16 B for top-k | | Latency | per RQE | yes | `S/x − 1` merges | — | -Keys inside an instance: - -- **Sketches** (CMS, CountSketch, KLL, DDSketch, HLL, UnivMon) keep one - fixed-size instance per group. The keys inside it, such as the endpoints a - per-service top-k counts, change neither memory nor CPU. The top-k heap is - fixed at the benchmark's k = 32. -- **Exact accumulators** keep one value per group, so keys are groups. The - export divides their measured memory and merge cost by the group count, so - `m` is per group. -- Nothing scales with keys below the group. Key labels `K` (the metric's - labels minus `G`) would matter only for a family whose size grows with keys - inside a group, such as an exact top-k map; none exists yet. +Keys inside an instance matter only through the size law above. 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. Not shared, though it may look shareable: From 464e17b1da6d8fa83586038973875da3c370cb44 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:16:07 -0400 Subject: [PATCH 14/18] docs: add a glossary, link the cost export, define keys Defines family, configuration, instance and the other terms the cost model uses, links scripts/export_rqe_optimizer_costs.sh, explains what a key is and why quantile sketches are treated as fixed size, and drops the per-cost breakdown table. Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 94 ++++++++++++++++++-------------- 1 file changed, 52 insertions(+), 42 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 306edaa2..5d3bea1a 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -6,13 +6,38 @@ Given a workload of repeating query expressions (RQEs), find sketch deployments that can serve it and report the trade-offs among query working memory, CPU, and per-RQE latency. +## Glossary + +- **RQE**: repeating query expression, evaluated every `T` over the last `S`. +- **Capability**: the statistic an RQE needs: sum/count, min, max, + rate/increase, quantile, cardinality or top-k. +- **Metric**: a named stream of samples whose series are told apart by labels. +- **Group**: one combination of values of an RQE's group-by labels `G`. There + are `card(G)` groups. +- **Family**: one sketch or accumulator implementation, such as `kll-percall`, + `cms-heap-topk-fastpath-vector2d` or `exact-sum`. Each capability lists the + families that serve it. +- **Configuration**: a family plus its parameters, such as KLL with `k = 200`. + One row of the cost table. +- **Cost table**: per configuration, measured memory per instance, CPU per + insert, merge and query, and accuracy. Exported by + [`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh). +- **Window**: the interval `[k × y, k × y + x)` an instance covers; `x` is the + window size and `y` the slide. +- **Instance**: one sketch or accumulator object holding one group's samples + (or all groups', for a shared family) over one window. Open or closed; see + [Window model](#window-model). +- **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. + ## Inputs Let `R = {r_1, ..., r_n}` be the RQE workload. Each RQE `r_i` provides: | Field | Meaning | |---|---| -| `cap_i` | Required capability: `freq`, `quantile`, `cardinality`, or `topk`. | +| `cap_i` | Required capability. | | `S_i` | Query-window size. This is the current `lookback` field. | | `T_i` | Query slide: how often the RQE runs. This is the current `interval` field. | | `metric_i` | Metric the RQE reads. | @@ -36,17 +61,18 @@ lambda(metric) = card(metric.labels) / scrape_interval samples/second `validate_facts` reports every missing or inconsistent fact up front. -sketch-bench supplies empirical measurements for each sketch configuration: +The cost table, exported by +[`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh) +from sketch-bench runs, gives for each configuration: -- memory per sketch instance; -- insert CPU per item; -- query CPU per estimate; +- memory per instance; +- CPU per insert; +- CPU per query of one instance; - CPU per pairwise merge; and - measured accuracy values. -Configurations are associated with the capabilities they can serve. The -implementation uses measured configuration variant names, because variants of -the same algorithm can have different costs. +Families are named by sketch-bench variant, not algorithm, because variants +of the same algorithm can have different costs. ## Window model @@ -273,14 +299,18 @@ top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. ### Instance shape and size law -Each exported cost row is measured on one instance, at whatever key count the -benchmark fed it (`measured_keys`). Turning that into a deployment's cost -needs two properties of the family: +Each row of the cost table (from +[`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh)) +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 with its keys. `Fixed` is set by the - configuration (e.g. CMS rows × columns); `PerKey` grows with every key. +- **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: @@ -292,6 +322,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, 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 them 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. + The model uses one formula, `card(G) × m`, which is right for both cells in use: @@ -303,7 +339,9 @@ use: The other two cells are deferred until a family needs them: Shared + Fixed would be overpriced by `card(G)` (sketch-bench#142), and PerGroup + PerKey -needs the key labels `K`, the metric's labels minus `G`. +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. Per-RQE latency is the serial CPU time of one query: @@ -314,34 +352,6 @@ latency_i = card(G) × (c_qry + (n_i − 1) × c_mrg) It is not a wall-clock SLA: it assumes no parallel execution across groups and no cheaper k-way merge. -### What each cost is counted per - -| Cost | Shared by RQEs on one deployment? | × groups `card(G)` | × windows | Per key inside an instance | -|---|---|---|---|---| -| Ingest CPU | yes, paid once per deployment | no, `lambda` already totals all groups | × `x/y` open | each sample is one insert, whatever the family | -| Ingest memory | yes | yes | × `x/y` open | not modeled | -| Storage memory | yes, sized for the longest `S` it serves | yes | × `(S−x)/y + 1` closed | not modeled | -| Merge CPU | no, per RQE | yes | × `(S/x − 1)` folds | not modeled | -| Merge memory | no, per RQE | yes | × 1 accumulator, 0 when `n_i = 1` | not modeled | -| Query CPU | no, per RQE | yes | — | one probe per group | -| Query memory | no, per RQE | yes | — | 8 B, or 32 × 16 B for top-k | -| Latency | per RQE | yes | `S/x − 1` merges | — | - -Keys inside an instance matter only through the size law above. 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. - -Not shared, though it may look shareable: - -- **The stream read.** Two deployments on the same metric each pay full - ingest. Only RQEs on the same deployment share it. -- **Merges and query results.** Two RQEs with the same lookback on one - deployment each pay their own merge and query. -- **Groupings.** A `{service, endpoint}` deployment does not serve - `by (service)`: `G` must match exactly, with no regrouping at query time. -- **Capabilities.** RQEs with different capabilities never share a - deployment, even on the same metric and `G`. - ## Procedure 1. Generate candidate deployments for each input RQE, then deduplicate them. From 3bde7c8d52fc4ab529f28bf46123b4a079030b04 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:17:29 -0400 Subject: [PATCH 15/18] docs: call RQEs repeating atomic query expressions (RAQEs) Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 106 +++++++++++++++---------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 5d3bea1a..18c40f90 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -1,18 +1,18 @@ -# RQE-to-sketch deployment mapping: v1 +# RAQE-to-sketch deployment mapping: v1 ## Purpose -Given a workload of repeating query expressions (RQEs), find sketch deployments +Given a workload of repeating atomic query expressions (RAQEs), find sketch deployments that can serve it and report the trade-offs among query working memory, CPU, -and per-RQE latency. +and per-RAQE latency. ## Glossary -- **RQE**: repeating query expression, evaluated every `T` over the last `S`. -- **Capability**: the statistic an RQE needs: sum/count, min, max, +- **RAQE**: repeating atomic query expression, evaluated every `T` over the last `S`. +- **Capability**: the statistic an RAQE needs: sum/count, min, max, rate/increase, quantile, cardinality or top-k. - **Metric**: a named stream of samples whose series are told apart by labels. -- **Group**: one combination of values of an RQE's group-by labels `G`. There +- **Group**: one combination of values of an RAQE's group-by labels `G`. There are `card(G)` groups. - **Family**: one sketch or accumulator implementation, such as `kll-percall`, `cms-heap-topk-fastpath-vector2d` or `exact-sum`. Each capability lists the @@ -33,14 +33,14 @@ and per-RQE latency. ## Inputs -Let `R = {r_1, ..., r_n}` be the RQE workload. Each RQE `r_i` provides: +Let `R = {r_1, ..., r_n}` be the RAQE workload. Each RAQE `r_i` provides: | Field | Meaning | |---|---| | `cap_i` | Required capability. | | `S_i` | Query-window size. This is the current `lookback` field. | -| `T_i` | Query slide: how often the RQE runs. This is the current `interval` field. | -| `metric_i` | Metric the RQE reads. | +| `T_i` | Query slide: how often the RAQE runs. This is the current `interval` field. | +| `metric_i` | Metric the RAQE reads. | | `G_i` | Group-by label set (`grouping_labels`). | | `accuracy_metric_i` | Accuracy measurement to check. | | `tol_i` | Accuracy threshold. | @@ -89,14 +89,14 @@ For every label-value group, it creates an instance for every interval: At time `t`, an instance is **open** while its interval has not ended (`t < k × y + x`): it still receives samples. After that it is **closed**: it -never changes again and is kept only while some RQE's lookback still needs it. +never changes again and is kept only while some RAQE's lookback still needs it. A deployment has `x / y` open instances per group at any time. Instances overlap when `x > y`. There is no subtract operation. To answer an -RQE, the system selects and merges only non-overlapping instances, so items +RAQE, the system selects and merges only non-overlapping instances, so items are never counted twice. -An RQE with query window `S` and query slide `T` can use a deployment when: +An RAQE with query window `S` and query slide `T` can use a deployment when: ```text x % y == 0 @@ -117,7 +117,7 @@ have produced other, overlapping instances between these starts. That is okay. T 3 minutes can use `x = 2 minutes` and `y = 1 minute`; each query merges five non-overlapping two-minute instances. -We assume all RQEs share a common time origin. Query phase offsets are not +We assume all RAQEs share a common time origin. Query phase offsets are not modeled. ## Candidate deployments @@ -128,50 +128,50 @@ A candidate deployment is: D = (capability, configuration, metric, G, x, y) ``` -Candidates may be generated from individual RQEs, then deduplicated. This is +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 RQEs. +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 RQEs. Pruning then attaches the -measured costs and drops a candidate when another serves all of its RQEs and +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: - for each RQE i whose S_i is divisible by x: - g_i = gcd(x, T_i) # the largest slide that serves RQE i + for each RAQE i whose S_i is divisible by x: + g_i = gcd(x, T_i) # the largest slide that serves RAQE i slides = { gcd(A) : A is a non-empty subset of {g_i} } 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) ``` -**Windows.** An RQE merges `S_i / x` whole windows, so `x` must divide `S_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 RQE `i` when it divides both `x` and `T_i`, -that is, when it divides `g_i`. A finer slide serves no more RQEs but holds +**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 RQE, `y = g_i` is strictly better than every finer slide that serves +- for one RAQE, `y = g_i` is strictly better than every finer slide that serves it; -- for a set `A` of RQEs sharing a deployment, `y = gcd(A)`, the largest slide +- 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 RQEs share is the solver's choice, so every subset's gcd is a candidate. +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`, RQE `a` every 20 s, RQE `b` every 30 s. +Example: `x = 60`, RAQE `a` every 20 s, RAQE `b` every 30 s. -| Served RQEs | `y` | Open windows `x / y` | +| Served RAQEs | `y` | Open windows `x / y` | |---|---|---| | `a` | gcd(60, 20) = 20 | 3 | | `b` | gcd(60, 30) = 30 | 2 | @@ -187,7 +187,7 @@ 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 RQE `r_i` is eligible for a candidate `D` when: +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`. @@ -196,34 +196,34 @@ An RQE `r_i` is eligible for a candidate `D` when: 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 RQE; it is never inferred from a metric name. A missing metric +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 -RQE it can and is no worse in ingest CPU and memory, and in latency, merge -memory and stored memory for each such RQE. This is safe because any mapping using +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 RQEs assigned to a +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 RQE `i` uses candidate deployment `D`; let `u_D` be 1 +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 RQE i +Σ_D z_{i,D} = 1 for every RAQE i z_{i,D} <= u_D for every eligible pair (i, D) ``` -Every RQE selects exactly one eligible deployment. Multiple RQEs may select +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 RQE. +results from several deployments to satisfy one RAQE. ### MILP formulation @@ -236,14 +236,14 @@ 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 RQE i +Σ_{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 -RQE selected it. It is not required for feasibility, but makes ingest cost +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. @@ -260,7 +260,7 @@ 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-RQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver +Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. ## Analytical cost model @@ -269,13 +269,13 @@ 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 RQE `i`: +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. - `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`: RQE `i`'s lookback and interval. +- `S_i`, `T_i`: RAQE `i`'s lookback and interval. - `n_i = S_i / x`: windows merged per query. - `m`: memory per instance, measured. - `c_ins`: CPU per insert, measured. @@ -288,8 +288,8 @@ Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory | Phase | CPU | Memory | |---|---|---| | Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | -| Query, per RQE | `card(G) × c_qry / T_i` | `card(G) ×` output bytes | +| 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 @@ -343,7 +343,7 @@ 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. -Per-RQE latency is the serial CPU time of one query: +Per-RAQE latency is the serial CPU time of one query: ```text latency_i = card(G) × (c_qry + (n_i − 1) × c_mrg) @@ -354,11 +354,11 @@ no cheaper k-way merge. ## Procedure -1. Generate candidate deployments for each input RQE, then deduplicate them. -2. Build the eligible candidate–RQE pairs. Reject pairs that fail capability, +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. -3. Enumerate feasible workload mappings. Every RQE must select one eligible - candidate; a single selected candidate may serve multiple RQEs. Small +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 through incremental Pareto filtering, retaining only the current frontier. 4. Score every complete mapping with the analytical cost model. @@ -378,15 +378,15 @@ each phase's CPU and memory, together with the selected deployment mapping. - **Accuracy after merging:** v1 uses the measured, single-instance accuracy of a configuration. Measure or model merged accuracy before relying on a selected mapping as truly accuracy-feasible. -- **Query-result sharing:** v1 charges every RQE its own query and merge CPU. - Revisit when RQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** the MILP takes optional per-RQE latency bounds; the +- **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:** the MILP takes optional per-RAQE latency bounds; the enumerator reports latency but does not reject a mapping for it. -- **Memory model:** query memory sums every RQE's merge and output memory, as +- **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. - **Bursts:** CPU is a mean over time, so plans are sized for average load. -- **Static planning:** no RQE churn, replanning, or migration cost. +- **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. - **Selection policy:** the enumerator reports the Pareto frontier; the MILP From a0ce454432086a5a4fe2b9ce3ff67981d751c17f Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:18:09 -0400 Subject: [PATCH 16/18] docs: flatten the candidate generation pseudocode Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 18c40f90..dbca0c98 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -143,14 +143,15 @@ 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: - for each RAQE i whose S_i is divisible by x: - g_i = gcd(x, T_i) # the largest slide that serves RAQE i - slides = { gcd(A) : A is a non-empty subset of {g_i} } + 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. From 94ea6ca0700217cbbf2895e6f41f1e07e3825576 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:38:54 -0400 Subject: [PATCH 17/18] docs: add phase to the glossary Co-Authored-By: Claude Opus 5.5 --- docs/rqe_sketch_deployment_v1.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index dbca0c98..5831c9f9 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -30,6 +30,11 @@ 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 [Analytical cost model](#analytical-cost-model). ## Inputs From c308abff5c5b05efe4bf0492073eb01e2bc1e8c9 Mon Sep 17 00:00:00 2001 From: Milind Srivastava Date: Tue, 6 Oct 2026 10:49:06 -0400 Subject: [PATCH 18/18] rqe-optimizer: rename objectives to analytical_cost_model, Objectives to PlanCost The module holds the per-phase cost formulas and score(); its output is a plan's cost, not an objective, and Objective already names what the MILP minimizes. In milp.rs, name the storage variables and cost closures for what they hold: deployment_storage_cost, storage_cost_for_rqe_and_deployment and merge_and_query_cost. Co-Authored-By: Claude Opus 5.5 --- rqe-optimizer/examples/small_problem.rs | 34 ++++++------ ...objectives.rs => analytical_cost_model.rs} | 8 +-- rqe-optimizer/src/autosketch.rs | 2 +- rqe-optimizer/src/candidates.rs | 2 +- rqe-optimizer/src/lib.rs | 6 +-- rqe-optimizer/src/milp.rs | 53 +++++++++---------- rqe-optimizer/src/pareto.rs | 40 +++++++------- 7 files changed, 72 insertions(+), 73 deletions(-) rename rqe-optimizer/src/{objectives.rs => analytical_cost_model.rs} (99%) diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 9fb5be5b..0bfec499 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -29,12 +29,12 @@ use std::collections::BTreeSet; use std::time::Instant; +use rqe_optimizer::analytical_cost_model::{score, PlanCost}; use rqe_optimizer::candidates::{ build_all_candidates, build_all_candidates_unpruned, eligible_deployments_for, }; use rqe_optimizer::enumerate::{brute_force, for_each_mapping, for_each_mapping_while, unservable}; use rqe_optimizer::milp::{minimize, MilpBounds, Objective}; -use rqe_optimizer::objectives::{score, Objectives}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; use rqe_optimizer::{ validate_facts, AccuracyDirection, AtomicCostTable, Capability, LabelSet, MetricFacts, Rqe, @@ -279,17 +279,17 @@ fn weight_flag(name: &str, default: f64) -> f64 { } } -fn print_objectives(label: &str, objectives: &Objectives) { +fn print_plan_cost(label: &str, plan_cost: &PlanCost) { println!( "{label}: cpu={:.3e} cpu-sec/sec, memory={:.1}MB", - objectives.cpu_secs_per_sec(), - objectives.memory_bytes() / 1e6, + plan_cost.cpu_secs_per_sec(), + plan_cost.memory_bytes() / 1e6, ); for (phase, cost) in [ - ("ingest", &objectives.ingest), - ("merge", &objectives.merge), - ("query", &objectives.query), - ("storage", &objectives.storage), + ("ingest", &plan_cost.ingest), + ("merge", &plan_cost.merge), + ("query", &plan_cost.query), + ("storage", &plan_cost.storage), ] { println!( " {phase:<7} cpu={:.3e} memory={:.1}MB", @@ -385,11 +385,11 @@ fn main() { .expect("small_problem MILP should be feasible"); println!( "MILP solution for {objective:?}: {:.3e}", - objective.value(&solution.objectives) + objective.value(&solution.plan_cost) ); - print_objectives(" totals", &solution.objectives); + print_plan_cost(" totals", &solution.plan_cost); print_mapping(1, &solution.mapping, &rqes, &deployments); - for (rqe, latency) in rqes.iter().zip(&solution.objectives.query_latency_secs) { + for (rqe, latency) in rqes.iter().zip(&solution.plan_cost.query_latency_secs) { println!(" {}: query_latency={latency:.3e} sec", rqe.id); } return; @@ -431,23 +431,23 @@ fn main() { let mappings = brute_force(&rqes, &deployments); println!("{} feasible full mappings", mappings.len()); - let objectives: Vec<_> = mappings + let plan_costs: Vec<_> = mappings .iter() .map(|m| score(&rqes, &deployments, m, &facts)) .collect(); - let front = pareto_front(&objectives); + let front = pareto_front(&plan_costs); println!("{} on the Pareto front\n", front.len()); let mut front = front; front.sort_unstable(); for &i in &front { - let obj = &objectives[i]; + let plan_cost = &plan_costs[i]; let distinct_deployments: BTreeSet = mappings[i].iter().copied().collect(); - print_objectives( + print_plan_cost( &format!("mapping {i}: {} deployments", distinct_deployments.len()), - obj, + plan_cost, ); - for (rqe, latency) in rqes.iter().zip(&obj.query_latency_secs) { + for (rqe, latency) in rqes.iter().zip(&plan_cost.query_latency_secs) { let rqe_id = &rqe.id; println!(" {rqe_id}: query_latency={latency:.3e} sec"); } diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/analytical_cost_model.rs similarity index 99% rename from rqe-optimizer/src/objectives.rs rename to rqe-optimizer/src/analytical_cost_model.rs index 5cccbabb..28161846 100644 --- a/rqe-optimizer/src/objectives.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -47,7 +47,7 @@ impl std::ops::AddAssign for PhaseCost { } #[derive(Debug, Clone)] -pub struct Objectives { +pub struct PlanCost { /// Paid once per active deployment. pub ingest: PhaseCost, /// Paid per RQE; memory as if every query runs at once. @@ -60,7 +60,7 @@ pub struct Objectives { pub query_latency_secs: Vec, } -impl Objectives { +impl PlanCost { pub fn cpu_secs_per_sec(&self) -> f64 { self.phases().map(|phase| phase.cpu_secs_per_sec).sum() } @@ -162,7 +162,7 @@ pub fn score( deployments: &[Deployment], mapping: &Mapping, facts: &WorkloadFacts, -) -> Objectives { +) -> PlanCost { assert_eq!( mapping.len(), rqes.len(), @@ -192,7 +192,7 @@ pub fn score( }) .collect(); - Objectives { + PlanCost { ingest: ingest_cost, merge: merge_cost, query: query_cost, diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index 8b98884d..74c0a464 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -321,8 +321,8 @@ impl Rng { #[cfg(test)] mod tests { use super::*; + use crate::analytical_cost_model::{score, PhaseCost}; use crate::candidates::is_eligible; - use crate::objectives::{score, PhaseCost}; use crate::test_support::{facts, METRIC}; use crate::{AccuracyDirection, Capability, LabelSet}; use std::collections::BTreeSet; diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 4705ee18..bf522f13 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,6 +1,6 @@ //! Candidate generation and eligibility (§3). -use crate::objectives::merge_memory_per_group; +use crate::analytical_cost_model::merge_memory_per_group; use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds, WorkloadFacts}; use std::collections::{BTreeMap, BTreeSet}; diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index f1f750b3..4fefad39 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -4,16 +4,16 @@ //! //! Three independent stages, so an ILP can replace [`enumerate`] alone: //! [`candidates`] builds 𝒟 and per-RQE eligibility (§3), [`enumerate`] -//! searches (§4), [`objectives`] scores (§5). +//! searches (§4), [`analytical_cost_model`] scores (§5). //! //! Every number the algorithm uses is caller-supplied, except the query -//! output size estimates in [`objectives`]. +//! output size estimates in [`analytical_cost_model`]. +pub mod analytical_cost_model; pub mod autosketch; pub mod candidates; pub mod enumerate; pub mod milp; -pub mod objectives; pub mod pareto; use std::collections::BTreeMap; diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index d462199a..d26abd06 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -3,8 +3,8 @@ //! The model is documented in `docs/rqe_sketch_deployment_v1.md`. It avoids //! enumerating the Cartesian product of eligible deployment choices. +use crate::analytical_cost_model::{self, score, PhaseCost, PlanCost, BYTES_PER_GIB}; use crate::candidates::eligible_deployments_for; -use crate::objectives::{self, score, Objectives, PhaseCost, BYTES_PER_GIB}; use crate::{Deployment, Mapping, Rqe, WorkloadFacts}; use good_lp::{ default_solver, variable, Expression, ProblemVariables, ResolutionError, Solution, SolverModel, @@ -32,10 +32,10 @@ impl Default for Objective { } impl Objective { - pub fn value(&self, objectives: &Objectives) -> f64 { + pub fn value(&self, plan_cost: &PlanCost) -> f64 { self.weigh(PhaseCost { - cpu_secs_per_sec: objectives.cpu_secs_per_sec(), - memory_bytes: objectives.memory_bytes(), + cpu_secs_per_sec: plan_cost.cpu_secs_per_sec(), + memory_bytes: plan_cost.memory_bytes(), }) } @@ -55,7 +55,7 @@ pub struct MilpBounds { #[derive(Debug, Clone)] pub struct MilpSolution { pub mapping: Mapping, - pub objectives: Objectives, + pub plan_cost: PlanCost, } /// Minimize `objective` subject to optional latency bounds. `facts` must pass @@ -99,7 +99,7 @@ pub fn minimize( }) .collect(); // Weighted storage cost per deployment: the max over the RQEs it serves. - let storage: Vec = deployments + let deployment_storage_cost: Vec = deployments .iter() .map(|_| variables.add(variable().min(0))) .collect(); @@ -108,16 +108,16 @@ pub fn minimize( // assignment, and storage once per deployment for its longest lookback. let ingest_cost: Vec = deployments .iter() - .map(|deployment| objective.weigh(objectives::ingest(deployment, facts))) + .map(|deployment| objective.weigh(analytical_cost_model::ingest(deployment, facts))) .collect(); - let assignment_cost = |rqe: &Rqe, deployment: &Deployment| { - objective.weigh(objectives::merge(rqe, deployment, facts)) - + objective.weigh(objectives::query(rqe, deployment, facts)) + let merge_and_query_cost = |rqe: &Rqe, deployment: &Deployment| { + objective.weigh(analytical_cost_model::merge(rqe, deployment, facts)) + + objective.weigh(analytical_cost_model::query(rqe, deployment, facts)) }; - let storage_cost = |rqe: &Rqe, deployment: &Deployment| { + let storage_cost_for_rqe_and_deployment = |rqe: &Rqe, deployment: &Deployment| { objective.weigh(PhaseCost { cpu_secs_per_sec: 0.0, - memory_bytes: objectives::storage_bytes(rqe, deployment, facts), + memory_bytes: analytical_cost_model::storage_bytes(rqe, deployment, facts), }) }; @@ -135,8 +135,8 @@ pub fn minimize( .map(|&deployment_index| { let deployment = &deployments[deployment_index]; ingest_cost[deployment_index] - + assignment_cost(rqe, deployment) - + storage_cost(rqe, deployment) + + merge_and_query_cost(rqe, deployment) + + storage_cost_for_rqe_and_deployment(rqe, deployment) }) .fold(f64::INFINITY, f64::min) }) @@ -147,14 +147,14 @@ pub fn minimize( 1.0 }; - let mut goal: Expression = storage.iter().sum(); + let mut goal: Expression = deployment_storage_cost.iter().sum(); for (&cost, &active_variable) in ingest_cost.iter().zip(&active) { goal.add_mul(cost / reference, active_variable); } for (rqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { goal.add_mul( - assignment_cost(&rqes[rqe_index], &deployments[deployment_index]) / reference, + merge_and_query_cost(&rqes[rqe_index], &deployments[deployment_index]) / reference, assignment, ); } @@ -170,16 +170,18 @@ pub fn minimize( let deployment = &deployments[deployment_index]; model.add_constraint((assignment - active[deployment_index]).leq(0)); // Zero when `w_mem` is 0; such a row can never bind. - let rqe_storage_cost = storage_cost(rqe, deployment) / reference; - if rqe_storage_cost > 0.0 { + let scaled_storage_cost = + storage_cost_for_rqe_and_deployment(rqe, deployment) / reference; + if scaled_storage_cost > 0.0 { model.add_constraint( - (rqe_storage_cost * assignment - storage[deployment_index]).leq(0), + (scaled_storage_cost * assignment - deployment_storage_cost[deployment_index]) + .leq(0), ); } // Each RQE takes exactly one deployment, so a per-RQE bound just // forbids the choices over it. Comparing in f64 here, not in the // solver, keeps µs latencies clear of its feasibility tolerance. - let latency = objectives::query_latency_secs(rqe, deployment, facts); + let latency = analytical_cost_model::query_latency_secs(rqe, deployment, facts); if bounds .max_query_latency_secs .get(rqe_index) @@ -214,11 +216,8 @@ pub fn minimize( .expect("MILP assigns exactly one deployment to every RQE") }) .collect(); - let objectives = score(rqes, deployments, &mapping, facts); - Ok(MilpSolution { - mapping, - objectives, - }) + let plan_cost = score(rqes, deployments, &mapping, facts); + Ok(MilpSolution { mapping, plan_cost }) } #[cfg(test)] @@ -253,7 +252,7 @@ mod tests { .expect("test workload is servable"); let milp = minimize(rqes, deployments, &facts, &MilpBounds::default(), objective) .expect("feasible MILP"); - let got = objective.value(&milp.objectives); + let got = objective.value(&milp.plan_cost); assert!( (got - best).abs() <= 1e-9 * best, "{objective:?}: {got} vs {best}" @@ -360,6 +359,6 @@ mod tests { ) .expect("feasible MILP"); assert_eq!(milp.mapping, vec![1]); - assert!(milp.objectives.query_latency_secs[0] <= 1e-7); + assert!(milp.plan_cost.query_latency_secs[0] <= 1e-7); } } diff --git a/rqe-optimizer/src/pareto.rs b/rqe-optimizer/src/pareto.rs index fa326791..66d9e0e1 100644 --- a/rqe-optimizer/src/pareto.rs +++ b/rqe-optimizer/src/pareto.rs @@ -1,6 +1,6 @@ //! Non-dominated filtering for `(CPU, memory, per-RQE latency)`. -use crate::{objectives::Objectives, Mapping}; +use crate::{analytical_cost_model::PlanCost, Mapping}; fn dominates(a: &[f64], b: &[f64]) -> bool { let mut strict = false; @@ -15,9 +15,9 @@ fn dominates(a: &[f64], b: &[f64]) -> bool { strict } -fn objective_vector(objectives: &Objectives) -> Vec { - let mut vector = vec![objectives.cpu_secs_per_sec(), objectives.memory_bytes()]; - vector.extend(&objectives.query_latency_secs); +fn pareto_vector(plan_cost: &PlanCost) -> Vec { + let mut vector = vec![plan_cost.cpu_secs_per_sec(), plan_cost.memory_bytes()]; + vector.extend(&plan_cost.query_latency_secs); vector } @@ -25,7 +25,7 @@ fn objective_vector(objectives: &Objectives) -> Vec { #[derive(Debug, Clone)] pub struct ParetoEntry { pub mapping: Mapping, - pub objectives: Objectives, + pub plan_cost: PlanCost, } /// Retains only non-dominated mappings while a streaming enumerator visits @@ -42,20 +42,20 @@ impl ParetoFront { /// Consider one scored mapping. Returns true when it remains on the /// frontier. Equal objective vectors are both retained. - pub fn consider(&mut self, mapping: &Mapping, objectives: Objectives) -> bool { - let candidate = objective_vector(&objectives); + pub fn consider(&mut self, mapping: &Mapping, plan_cost: PlanCost) -> bool { + let candidate = pareto_vector(&plan_cost); if self .entries .iter() - .any(|entry| dominates(&objective_vector(&entry.objectives), &candidate)) + .any(|entry| dominates(&pareto_vector(&entry.plan_cost), &candidate)) { return false; } self.entries - .retain(|entry| !dominates(&candidate, &objective_vector(&entry.objectives))); + .retain(|entry| !dominates(&candidate, &pareto_vector(&entry.plan_cost))); self.entries.push(ParetoEntry { mapping: mapping.clone(), - objectives, + plan_cost, }); true } @@ -65,24 +65,24 @@ impl ParetoFront { } } -pub fn pareto_front(objs: &[Objectives]) -> Vec { - let vectors: Vec> = objs.iter().map(objective_vector).collect(); - (0..objs.len()) - .filter(|&i| !(0..objs.len()).any(|j| j != i && dominates(&vectors[j], &vectors[i]))) +pub fn pareto_front(plan_costs: &[PlanCost]) -> Vec { + let vectors: Vec> = plan_costs.iter().map(pareto_vector).collect(); + (0..plan_costs.len()) + .filter(|&i| !(0..plan_costs.len()).any(|j| j != i && dominates(&vectors[j], &vectors[i]))) .collect() } #[cfg(test)] mod tests { use super::*; - use crate::objectives::PhaseCost; + use crate::analytical_cost_model::PhaseCost; - fn objectives(memory: f64, cpu: f64, latency: f64) -> Objectives { + fn plan_cost(memory: f64, cpu: f64, latency: f64) -> PlanCost { let phase = PhaseCost { cpu_secs_per_sec: cpu, memory_bytes: memory, }; - Objectives { + PlanCost { ingest: phase, merge: PhaseCost::default(), query: PhaseCost::default(), @@ -94,9 +94,9 @@ mod tests { #[test] fn incremental_front_discards_dominated_mappings() { let mut front = ParetoFront::new(); - assert!(front.consider(&vec![0], objectives(10.0, 10.0, 10.0))); - assert!(!front.consider(&vec![1], objectives(20.0, 20.0, 20.0))); - assert!(front.consider(&vec![2], objectives(5.0, 5.0, 5.0))); + assert!(front.consider(&vec![0], plan_cost(10.0, 10.0, 10.0))); + assert!(!front.consider(&vec![1], plan_cost(20.0, 20.0, 20.0))); + assert!(front.consider(&vec![2], plan_cost(5.0, 5.0, 5.0))); assert_eq!(front.entries().len(), 1); assert_eq!(front.entries()[0].mapping, vec![2]); }