From ad8658345a1e10ca3cb7e864ee97ddbfbd837f80 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 16:22:01 +0000 Subject: [PATCH 01/18] rqe-optimizer: batch latency SLA with provisioned vCPUs minimize_batch_sla bounds when an aligned batch of every RAQE finishes: the plan provisions V vCPUs shared by ingest (rho_ing) and the batch's merge and query work W, a fluid queue, so V >= rho_ing + W / SLA, and V >= the mean CPU. CPU is priced at V. A pair whose per-group work exceeds the SLA is forbidden. With a loose SLA the plan is minimize's. analytical_cost_model gains provisioned_vcpus and batch_makespan_ms to price any plan at an SLA. The model is in docs/rqe_sketch_deployment_v1.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 50 ++++- rqe-optimizer/src/analytical_cost_model.rs | 32 +++ rqe-optimizer/src/milp.rs | 231 ++++++++++++++++++++- 3 files changed, 301 insertions(+), 12 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 6f05b42b..28e556af 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -359,6 +359,44 @@ evaluates at once. The default weights are `(1, 0)`: CPU only. Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. +### Batch latency SLA (`milp::minimize_batch_sla`) + +A per-RAQE bound ignores that queries share the machine with ingest and with +each other. The batch SLA instead bounds when a whole batch finishes: every +RAQE fires at once (all intervals aligned, as at `t = 0`, the worst case), and +the plan provisions `V` vCPUs that ingest and the batch share. + +- Ingest is a steady load of `ρ_ing = Σ_D ingest_D.cpu × u_D` vCPUs. +- The batch is `W = Σ_(i,D)∈E latency_{i,D} × z_{i,D}` CPU-seconds of merge + and query work (`latency` below). Groups are independent, so the work + spreads over the `V − ρ_ing` vCPUs ingest leaves (a fluid queue). +- The batch finishes at `W / (V − ρ_ing)`, which must be at most the SLA `L`. + One group's merge and query can't be split, so a pair whose per-group work + `latency_{i,D} / card(G)` exceeds `L` is forbidden (`z_{i,D} = 0`). +- `V` also covers the mean load, `cpu = Σ_D ingest_D.cpu × u_D + + Σ_(i,D)∈E (merge + query)_{i,D}.cpu × z_{i,D}`. + +CPU is priced at the provisioned `V` instead of the mean, as a serverless +platform bills allocated vCPUs. With `V` continuous: + +```text +V ≥ cpu (mean load) +V ≥ ρ_ing + W / L (the batch finishes within L) + +minimize w_cpu × V + + w_mem × (Σ_D ingest_D.mem × u_D + + Σ_(i,D)∈E (merge + query)_{i,D}.mem × z_{i,D}) + + Σ_D stored_D +``` + +Both rows are linear in `u` and `z`, so the model stays a MILP. When the SLA +does not bind, `V = cpu` and the plan is `minimize`'s. A tighter SLA trades +ingest for faster queries, or buys vCPUs: it is always feasible as long as +every RAQE has a pair whose groups fit `L`. `analytical_cost_model` gives a +solved plan's `provisioned_vcpus` (`max(cpu, ρ_ing + W / L)`) and +`batch_makespan_ms` (`W / (V − ρ_ing)`), which also price a plan chosen by +another method (e.g. AutoSketch) at the same SLA. + ## Analytical cost model The analytical model combines the empirical per-operation Sketch Bench @@ -494,8 +532,9 @@ latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg summed over the sketch and its key tracker, if any. -It is not a wall-clock SLA: it assumes no parallel execution across groups and -no cheaper k-way merge. +On its own it is not a wall-clock SLA: it assumes no parallel execution across +groups and no cheaper k-way merge. The batch SLA above spreads the summed +`latency_i` of all RAQEs over the vCPUs ingest leaves. ## Procedure @@ -524,8 +563,11 @@ each phase's CPU and memory, together with the selected deployment mapping. largest shard count and N the study measured merge curves at (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds; the - enumerator reports latency but does not reject a mapping for it. +- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds, or one + batch SLA with provisioned vCPUs (`minimize_batch_sla`); the enumerator + reports latency but does not reject a mapping for it. The batch model is a + fluid queue: ingest is steady, groups split evenly across vCPUs, and + intervals align; staggered firing and scheduling overhead are not modeled. - **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. diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 2fb0a99c..0a1750ee 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -254,6 +254,38 @@ pub(crate) fn query_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &Wor .sum::() } +/// CPU time of one aligned batch, every RAQE evaluated once: `W = Σ_i +/// latency_i`, in CPU-seconds. +pub fn batch_work_secs(plan: &PlanCost) -> f64 { + plan.query_latency_ms.iter().sum::() / 1000.0 +} + +/// The vCPUs a plan provisions so that ingest and an aligned batch of every +/// RAQE share them and the batch finishes within `batch_sla_ms`: at least +/// the mean CPU, and `ρ_ing + W / SLA` (ingest holds `ρ_ing` vCPUs, the batch +/// runs on the rest). With no SLA, the mean CPU. +pub fn provisioned_vcpus(plan: &PlanCost, batch_sla_ms: Option) -> f64 { + let mean = plan.cpu_secs_per_sec(); + match batch_sla_ms { + Some(sla_ms) => { + mean.max(plan.ingest.cpu_secs_per_sec + batch_work_secs(plan) / (sla_ms / 1000.0)) + } + None => mean, + } +} + +/// When an aligned batch of every RAQE finishes on `vcpus`, in ms: its work +/// spread over the vCPUs ingest leaves, `W / (V − ρ_ing)`. +pub fn batch_makespan_ms(plan: &PlanCost, vcpus: f64) -> f64 { + 1000.0 * batch_work_secs(plan) / (vcpus - plan.ingest.cpu_secs_per_sec) +} + +/// The smallest unit of a query's work: one group's merge and query, in ms. +/// Groups run in parallel, so a batch SLA can't finish faster than this. +pub(crate) fn group_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + query_latency_ms(raqe, deployment, facts) / group_count(deployment, facts) +} + pub fn score( raqes: &[Raqe], deployments: &[Deployment], diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 605b791d..4fe7de35 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -39,10 +39,33 @@ impl Objective { }) } + /// The objective with CPU priced at the plan's provisioned vCPUs + /// ([`analytical_cost_model::provisioned_vcpus`]) instead of its mean. + pub fn value_provisioned(&self, plan_cost: &PlanCost, batch_sla_ms: Option) -> f64 { + self.weigh(PhaseCost { + cpu_secs_per_sec: analytical_cost_model::provisioned_vcpus(plan_cost, batch_sla_ms), + memory_bytes: plan_cost.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 } + + fn weigh_cpu(&self, cost: PhaseCost) -> f64 { + self.weigh(PhaseCost { + memory_bytes: 0.0, + ..cost + }) + } + + fn weigh_memory(&self, cost: PhaseCost) -> f64 { + self.weigh(PhaseCost { + cpu_secs_per_sec: 0.0, + ..cost + }) + } } /// The solved plan: the deployments to run and which one serves each RAQE. @@ -81,6 +104,40 @@ pub fn minimize( facts: &WorkloadFacts, objective: Objective, accuracy: &Accuracy, +) -> Result { + solve(raqes, deployments, facts, objective, accuracy, None) +} + +/// [`minimize`] under a batch latency SLA instead of per-RAQE bounds: every +/// RAQE fires at once, ingest and the batch share the plan's provisioned +/// vCPUs `V`, and the batch must finish within `batch_sla_ms`. CPU is priced +/// at `V` (see `docs/rqe_sketch_deployment_v1.md`, "Batch latency SLA"), +/// which equals the mean CPU when the SLA does not bind. +pub fn minimize_batch_sla( + raqes: &[Raqe], + deployments: &[Deployment], + facts: &WorkloadFacts, + objective: Objective, + accuracy: &Accuracy, + batch_sla_ms: f64, +) -> Result { + solve( + raqes, + deployments, + facts, + objective, + accuracy, + Some(batch_sla_ms), + ) +} + +fn solve( + raqes: &[Raqe], + deployments: &[Deployment], + facts: &WorkloadFacts, + objective: Objective, + accuracy: &Accuracy, + batch_sla_ms: Option, ) -> Result { let eligible: Vec> = raqes .iter() @@ -155,20 +212,62 @@ pub fn minimize( }; 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); + // Under a batch SLA, CPU is priced at the provisioned vCPUs, `cpu` (scaled + // by `w_cpu / reference`): at least the mean CPU, and at least ingest plus + // the batch's work over the SLA. Memory stays in the goal per phase. + let mut mean_cpu = Expression::from(0.0); + let mut batch_cpu = Expression::from(0.0); + let cpu = batch_sla_ms.map(|_| variables.add(variable().min(0))); + for (deployment_index, &active_variable) in active.iter().enumerate() { + let deployment = &deployments[deployment_index]; + if cpu.is_some() { + let ingest = analytical_cost_model::ingest(deployment, facts); + goal.add_mul(objective.weigh_memory(ingest) / reference, active_variable); + let ingest_cpu = objective.weigh_cpu(ingest) / reference; + mean_cpu.add_mul(ingest_cpu, active_variable); + batch_cpu.add_mul(ingest_cpu, active_variable); + } else { + goal.add_mul(ingest_cost[deployment_index] / reference, active_variable); + } } for (raqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { - goal.add_mul( - merge_and_query_cost(&raqes[raqe_index], &deployments[deployment_index]) - / reference, - assignment, - ); + let raqe = &raqes[raqe_index]; + let deployment = &deployments[deployment_index]; + match batch_sla_ms { + Some(sla_ms) => { + let mut merge_and_query = analytical_cost_model::merge(raqe, deployment, facts); + merge_and_query += analytical_cost_model::query(raqe, deployment, facts); + goal.add_mul( + objective.weigh_memory(merge_and_query) / reference, + assignment, + ); + mean_cpu.add_mul(objective.weigh_cpu(merge_and_query) / reference, assignment); + // The batch's work, CPU-sec, as vCPUs held for the SLA. + let work = PhaseCost { + cpu_secs_per_sec: analytical_cost_model::query_latency_ms( + raqe, deployment, facts, + ) / sla_ms, + memory_bytes: 0.0, + }; + batch_cpu.add_mul(objective.weigh_cpu(work) / reference, assignment); + } + None => goal.add_mul( + merge_and_query_cost(raqe, deployment) / reference, + assignment, + ), + } } } + if let Some(cpu) = cpu { + goal += cpu; + } let mut model = variables.minimise(goal).using(default_solver); + if let Some(cpu) = cpu { + model.add_constraint((mean_cpu - cpu).leq(0)); + model.add_constraint((batch_cpu - cpu).leq(0)); + } for (raqe_index, choices) in assignments.iter().enumerate() { let assignment_sum: Expression = choices.iter().map(|(_, variable)| *variable).sum(); model.add_constraint(assignment_sum.eq(1)); @@ -190,7 +289,12 @@ pub fn minimize( // forbids the choices over it. Comparing in f64 here, not in the // solver, keeps µs latencies clear of its feasibility tolerance. let latency_ms = analytical_cost_model::query_latency_ms(raqe, deployment, facts); - if raqe.latency_sla_ms.is_some_and(|limit| latency_ms > limit) { + // Under a batch SLA, one group's merge and query can't be split + // across vCPUs, so it alone must fit the SLA. + let group_latency_ms = analytical_cost_model::group_latency_ms(raqe, deployment, facts); + if raqe.latency_sla_ms.is_some_and(|limit| latency_ms > limit) + || batch_sla_ms.is_some_and(|limit| group_latency_ms > limit) + { model.add_constraint(Expression::from(assignment).leq(0)); } } @@ -394,6 +498,117 @@ mod tests { assert_eq!(solve(&[bounded]), vec![1]); } + /// Under a batch SLA, the MILP's plan, priced at its provisioned vCPUs, + /// is the best of every mapping whose groups each fit the SLA. + fn assert_batch_sla_matches_brute_force( + raqes: &[Raqe], + deployments: &[Deployment], + objective: Objective, + sla_ms: f64, + ) { + // 100 groups, so a batch's work spreads over vCPUs. + let facts = facts(100, 100); + let fits = |mapping: &Mapping| { + mapping.iter().zip(raqes).all(|(&d, raqe)| { + analytical_cost_model::group_latency_ms(raqe, &deployments[d], &facts) <= sla_ms + }) + }; + let best = brute_force(raqes, deployments, &facts, &table_accuracy) + .iter() + .filter(|mapping| fits(mapping)) + .map(|mapping| { + objective + .value_provisioned(&score(raqes, deployments, mapping, &facts), Some(sla_ms)) + }) + .min_by(f64::total_cmp) + .expect("test workload is servable within the SLA"); + let milp = minimize_batch_sla( + raqes, + deployments, + &facts, + objective, + &table_accuracy, + sla_ms, + ) + .expect("feasible MILP"); + let got = objective.value_provisioned(&milp.plan_cost, Some(sla_ms)); + assert!( + (got - best).abs() <= 1e-9 * best, + "{objective:?}, SLA {sla_ms} ms: {got} vs {best}" + ); + } + + #[test] + fn batch_sla_matches_brute_force_at_every_sla() { + let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; + // Cheap ingest with slow queries, or the reverse. + 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), + ]; + for objective in [weights(1.0, 0.0), weights(1.0, 4.0)] { + // Down to an SLA that rules out the slow-query deployment's groups. + for sla_ms in [1e12, 1e7, 1e6, 2e4] { + assert_batch_sla_matches_brute_force(&raqes, &deployments, objective, sla_ms); + } + } + } + + #[test] + fn a_loose_batch_sla_prices_the_mean_cpu() { + let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; + let deployments = vec![deployment(1.0, 20.0, 400.0), deployment(3.0, 10.0, 1.0)]; + let facts = facts(1, 1); + let free = minimize( + &raqes, + &deployments, + &facts, + Objective::default(), + &table_accuracy, + ) + .expect("feasible MILP"); + let loose = minimize_batch_sla( + &raqes, + &deployments, + &facts, + Objective::default(), + &table_accuracy, + 1e12, + ) + .expect("feasible MILP"); + assert_eq!(chosen(&loose, &deployments), chosen(&free, &deployments)); + assert_eq!( + analytical_cost_model::provisioned_vcpus(&loose.plan_cost, Some(1e12)), + loose.plan_cost.cpu_secs_per_sec() + ); + } + + #[test] + fn a_tight_batch_sla_provisions_for_the_batch_and_meets_it() { + let raqes = vec![raqe("r", 60_000)]; + // 100 groups at 100 samples/s. Ingest 100 vCPU and 300 s of query + // work, or ingest 120 and 100 s: 105 vs. 121.7 mean vCPUs. + let deployments = vec![deployment(1.0, 20.0, 3.0), deployment(1.2, 10.0, 1.0)]; + let facts = facts(100, 100); + let sla_ms = 3_000.0; + let milp = minimize_batch_sla( + &raqes, + &deployments, + &facts, + Objective::default(), + &table_accuracy, + sla_ms, + ) + .expect("feasible MILP"); + // Within 3 s: 120 + 100 s / 3 s = 153.3 vCPUs beats 100 + 300 / 3 = 200. + assert_eq!(chosen(&milp, &deployments), vec![1]); + let vcpus = analytical_cost_model::provisioned_vcpus(&milp.plan_cost, Some(sla_ms)); + assert!((vcpus - (120.0 + 100.0 / 3.0)).abs() < 1e-9, "{vcpus}"); + let makespan = analytical_cost_model::batch_makespan_ms(&milp.plan_cost, vcpus); + assert!((makespan - sla_ms).abs() < 1e-6, "{makespan}"); + } + #[test] fn matches_brute_force_with_shared_deployment_costs() { let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; From e8e024a56b533642552c577d1474b6fa6a020a09 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 18:30:03 +0000 Subject: [PATCH 02/18] docs: cost models 1 and 2, batch latency and query placement (design for review) Replaces the provisioned-V batch SLA write-up with the design under review: precompute and query jobs per RAQE firing, each on at most one core; an event-driven placement at a (CPU, memory) resource point gives batch latency; cost model 1 bills AUC, cost model 2 the peak; the MILP uses a linear surrogate and is verified by the placement. Four open questions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 138 ++++++++++++++++++++++--------- 1 file changed, 99 insertions(+), 39 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 28e556af..8990e734 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -359,43 +359,105 @@ evaluates at once. The default weights are `(1, 0)`: CPU only. Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. -### Batch latency SLA (`milp::minimize_batch_sla`) - -A per-RAQE bound ignores that queries share the machine with ingest and with -each other. The batch SLA instead bounds when a whole batch finishes: every -RAQE fires at once (all intervals aligned, as at `t = 0`, the worst case), and -the plan provisions `V` vCPUs that ingest and the batch share. - -- Ingest is a steady load of `ρ_ing = Σ_D ingest_D.cpu × u_D` vCPUs. -- The batch is `W = Σ_(i,D)∈E latency_{i,D} × z_{i,D}` CPU-seconds of merge - and query work (`latency` below). Groups are independent, so the work - spreads over the `V − ρ_ing` vCPUs ingest leaves (a fluid queue). -- The batch finishes at `W / (V − ρ_ing)`, which must be at most the SLA `L`. - One group's merge and query can't be split, so a pair whose per-group work - `latency_{i,D} / card(G)` exceeds `L` is forbidden (`z_{i,D} = 0`). -- `V` also covers the mean load, `cpu = Σ_D ingest_D.cpu × u_D + - Σ_(i,D)∈E (merge + query)_{i,D}.cpu × z_{i,D}`. - -CPU is priced at the provisioned `V` instead of the mean, as a serverless -platform bills allocated vCPUs. With `V` continuous: +### Cost models, batch latency and query placement (design, under review) + +Status: design for review (ProjectASAP/ASAPQuery#777). The code in +`milp::minimize_batch_sla` implements an earlier variant (CPU priced at a +provisioned `V`, one fluid batch) and is reworked to this design once it is +agreed. + +**Scope.** Evaluated on the synthetic mixed template set (spatial templates +every 1 s, temporal ones every 1 min, so the hyperperiod is `H = lcm(T_i) = +60 s`). Methods: ASAP (this MILP, with sharing), PerQuery (the same MILP +without sharing), AutoSketch-Adapted (fixed configs chosen by memory). Each is +evaluated under cost model 1 and cost model 2, each with no latency SLA and +with an SLA `L`. + +**Load over time.** + +- Background, continuous: ingest CPU `ρ_ing = Σ_D λ_D · (x/y) · c_ins`, and + memory `M_static = Σ_D` (open + closed windows). +- Each firing of RAQE `i` at `t = k · T_i` releases two jobs, each using at + most one core: + - precompute `P_i`: merge every group's windows, + `card(G) · (S/x − 1) · c_mrg` CPU-seconds (0 when `S = x`); + - query `Q_i`: query every group, `card(G) · c_qry`; it starts only after + `P_i` finishes. +- The chain `ℓ_i = P_i + Q_i` is one firing's single-core time, i.e. the + per-RAQE `latency_i` below. +- Memory: the `card(G)` merged accumulators are held from `P_i`'s start until + `Q_i` ends, plus `Q_i`'s output while it runs. +- A batch is all jobs released at one instant; the heaviest, `B0`, is at + `t = 0`, when every RAQE fires. A batch's latency is the time from its + release until its last `Q_i` finishes; the reported query latency is the + worst batch latency. + +**Placement algorithm, given a resource point (C vCPU, M GiB).** ```text -V ≥ cpu (mean load) -V ≥ ρ_ing + W / L (the batch finishes within L) +query_cores K = floor(C − ρ_ing) (K ≥ 1, and M ≥ M_static, else infeasible) +simulate 2 hyperperiods, event-driven: + on each release / completion: + ready = released P jobs + Q jobs whose P is done + order: release time, then Q before P, then longest-first (LPT) + while an idle core exists and the next ready job's memory fits: + start it (a P job reserves its accumulators until its Q finishes) +outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) +``` -minimize w_cpu × V - + w_mem × (Σ_D ingest_D.mem × u_D - + Σ_(i,D)∈E (merge + query)_{i,D}.mem × z_{i,D}) - + Σ_D stored_D +Two hyperperiods are simulated so that work carried over the wrap-around is +counted. + +**Cost models.** + +| | CPU term | Memory term | +|---|---|---| +| Cost model 1 (AUC) | `w1 · mean_t CPU(t) = w1 · (ρ_ing + Σ_i ℓ_i / T_i)`, independent of the schedule | `w2 · mean_t MEM(t)`, from the schedule | +| Cost model 2 (max) | `w1 · max_t CPU(t) = w1 · C` | `w2 · max_t MEM(t) = w2 · M` | + +Under cost model 2 the resource point `(C, M)` is decided by the MILP; under +cost model 1 it is an input (open question 1). + +**MILP: a linear surrogate, then verify with the scheduler.** + +```text +C ≥ ρ_ing + Σ (merge + query).cpu × z (stability, always) +M ≥ M_static + Σ_{i∈B0} card(G_i) · m_i × z_{i,D} (memory, conservative) +with SLA L: + z_{i,D} = 0 if ℓ_{i,D} > L (the chain fits) + Σ_{i∈B0} ℓ_{i,D} × z_{i,D} ≤ (C − ρ_ing) × L (capacity, necessary) ``` -Both rows are linear in `u` and `z`, so the model stays a MILP. When the SLA -does not bind, `V = cpu` and the plan is `minimize`'s. A tighter SLA trades -ingest for faster queries, or buys vCPUs: it is always feasible as long as -every RAQE has a pair whose groups fit `L`. `analytical_cost_model` gives a -solved plan's `provisioned_vcpus` (`max(cpu, ρ_ing + W / L)`) and -`batch_makespan_ms` (`W / (V − ρ_ing)`), which also price a plan chosen by -another method (e.g. AutoSketch) at the same SLA. +Graham's list-scheduling bound (`Σ ℓ / K + max ℓ`) gives the sufficient +margin: the solution is simulated, and if its worst batch exceeds `L`, the +capacity row's `L` becomes `L − max ℓ` and the MILP is solved again (at most +two solves). Without an SLA the SLA rows are dropped and the simulated latency +at the solution is reported. + +- Cost model 1 objective: `w1 · AUC(CPU) + w2 · AUC(mem)`, `(C, M)` fixed. +- Cost model 2 objective: `w1 · C + w2 · M`, `(C, M)` variables. +- PerQuery: the same MILP over single-RAQE candidates only. +- AutoSketch: fixed configs. Cost model 2: the smallest `(C, M)` at which the + simulation meets `L` (binary search). Cost model 1: its AUC cost, and its + simulated latency at the given `(C, M)`, or infeasible if it does not fit. + +**Outputs.** Per (method, cost model, SLA): cost; mean and peak CPU and +memory; the resource point; worst batch and per-RAQE latency; solve and +verify iterations; planning time. Figure: cost vs. worst batch latency, one +line per method, one panel per cost model and weight setting. + +**Open questions.** + +1. Cost model 1 with an SLA: capacity is free under AUC billing, so where + does the resource point come from? (a) a fixed `(C, M)` shared by all + methods (e.g. cost model 2's ASAP optimum at that SLA, or a sweep), or (b) + each method's own smallest `(C, M)` that meets `L`, reported next to its + AUC cost. +2. Early precompute: may `P_i` merge windows that closed before the release + ahead of time, or must it start at release (simpler, conservative)? +3. Integer cores under cost model 2: `C` continuous (fractional ingest plus + whole query cores), or an integer? +4. Scope: synthetic mixed set only, or also the Alibaba and Google traces? ## Analytical cost model @@ -533,8 +595,8 @@ latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg summed over the sketch and its key tracker, if any. On its own it is not a wall-clock SLA: it assumes no parallel execution across -groups and no cheaper k-way merge. The batch SLA above spreads the summed -`latency_i` of all RAQEs over the vCPUs ingest leaves. +groups and no cheaper k-way merge. Under the placement design above it is one +firing's precompute-then-query chain on one core. ## Procedure @@ -563,11 +625,9 @@ each phase's CPU and memory, together with the selected deployment mapping. largest shard count and N the study measured merge curves at (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds, or one - batch SLA with provisioned vCPUs (`minimize_batch_sla`); the enumerator - reports latency but does not reject a mapping for it. The batch model is a - fluid queue: ingest is steady, groups split evenly across vCPUs, and - intervals align; staggered firing and scheduling overhead are not modeled. +- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds; a batch + SLA with two cost models and query placement is under review (above). The + enumerator reports latency but does not reject a mapping for it. - **Memory model:** query memory sums every RAQE's merge and output memory, as if all queries run at once; real concurrency is not modeled. Query output size is an estimate. From 63c22abaf2c47e042f20e70cfc94b59ab2ba0682 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 18:43:18 +0000 Subject: [PATCH 03/18] docs: precompute is ingest; queries merge then estimate; fractional capacity Precompute is inserting samples into window instances (ingest), a steady background load; each firing's query job merges the query window's instances and estimates, at most one core. Capacity is fractional and shared as rates. States sketch-bench's measurement assumption (single threaded, CPU time = wall time). Two open questions remain. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 72 +++++++++++++++++--------------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 8990e734..982afcf9 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -375,33 +375,42 @@ with an SLA `L`. **Load over time.** -- Background, continuous: ingest CPU `ρ_ing = Σ_D λ_D · (x/y) · c_ins`, and - memory `M_static = Σ_D` (open + closed windows). -- Each firing of RAQE `i` at `t = k · T_i` releases two jobs, each using at - most one core: - - precompute `P_i`: merge every group's windows, - `card(G) · (S/x − 1) · c_mrg` CPU-seconds (0 when `S = x`); - - query `Q_i`: query every group, `card(G) · c_qry`; it starts only after - `P_i` finishes. -- The chain `ℓ_i = P_i + Q_i` is one firing's single-core time, i.e. the - per-RAQE `latency_i` below. -- Memory: the `card(G)` merged accumulators are held from `P_i`'s start until - `Q_i` ends, plus `Q_i`'s output while it runs. -- A batch is all jobs released at one instant; the heaviest, `B0`, is at - `t = 0`, when every RAQE fires. A batch's latency is the time from its +- Precompute is ingest: every sample is inserted into its open window + instances as it arrives, a steady background load of + `ρ_ing = Σ_D λ_D · (x/y) · c_ins` vCPUs (spread over groups, so it may use + more than one core). Memory `M_static = Σ_D` (open + closed windows). +- Each firing of RAQE `i` at `t = k · T_i` releases one query job `Q_i`: merge + the `S/x` window instances of each group for the query window, then + estimate. Its CPU work is `ℓ_i = card(G) · (c_qry + (S/x − 1) · c_mrg)`, + the per-RAQE `latency_i` below; merging is part of the query. +- `Q_i` needs the newest window, which closes at `t`, to be fully ingested. + Ingest keeps up whenever the plan is stable (below), so `Q_i` is ready at + `t`. +- `Q_i` holds its `card(G)` merge accumulators, and its output, while it runs. +- A batch is all query jobs released at one instant; the heaviest, `B0`, is + at `t = 0`, when every RAQE fires. A batch's latency is the time from its release until its last `Q_i` finishes; the reported query latency is the worst batch latency. -**Placement algorithm, given a resource point (C vCPU, M GiB).** +**Measurement assumptions (sketch-bench as is).** Every sketch operation is +single-threaded and compute-bound: sketch-bench's CPU time equals its wall +time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses +at most one core, and on a full core it takes its CPU time `ℓ_i`; the cost +table's `*_cpu_secs` are all the placement needs. + +**Placement algorithm, given a resource point (C vCPU, M GiB).** Capacity is +fractional; jobs share it as rates (a fluid, priority-ordered processor +sharing). ```text -query_cores K = floor(C − ρ_ing) (K ≥ 1, and M ≥ M_static, else infeasible) -simulate 2 hyperperiods, event-driven: - on each release / completion: - ready = released P jobs + Q jobs whose P is done - order: release time, then Q before P, then longest-first (LPT) - while an idle core exists and the next ready job's memory fits: - start it (a P job reserves its accumulators until its Q finishes) +capacity for queries K = C − ρ_ing (K > 0, and M ≥ M_static, else infeasible) +simulate 2 hyperperiods, event-driven (events: releases, completions): + ready = released query jobs not yet finished + order: release time (older batches first), then longest remaining work first + give rates in that order: job j gets a_j = min(1, K − rates already given), + as long as its accumulators fit in the free memory + a job runs at rate a_j: it finishes when its remaining work / a_j elapses + recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) ``` @@ -424,14 +433,15 @@ cost model 1 it is an input (open question 1). C ≥ ρ_ing + Σ (merge + query).cpu × z (stability, always) M ≥ M_static + Σ_{i∈B0} card(G_i) · m_i × z_{i,D} (memory, conservative) with SLA L: - z_{i,D} = 0 if ℓ_{i,D} > L (the chain fits) + z_{i,D} = 0 if ℓ_{i,D} > L (one query job fits) Σ_{i∈B0} ℓ_{i,D} × z_{i,D} ≤ (C − ρ_ing) × L (capacity, necessary) + (C − ρ_ing is fractional; under cost model 1, (C, M) is the given point) ``` -Graham's list-scheduling bound (`Σ ℓ / K + max ℓ`) gives the sufficient -margin: the solution is simulated, and if its worst batch exceeds `L`, the -capacity row's `L` becomes `L − max ℓ` and the MILP is solved again (at most -two solves). Without an SLA the SLA rows are dropped and the simulated latency +With jobs capped at one core, list scheduling finishes within +`Σ ℓ / K + max ℓ` (Graham), which gives the sufficient margin: the solution +is simulated, and if its worst batch exceeds `L`, the capacity row's `L` +becomes `L − max ℓ` and the MILP is solved again (at most two solves). Without an SLA the SLA rows are dropped and the simulated latency at the solution is reported. - Cost model 1 objective: `w1 · AUC(CPU) + w2 · AUC(mem)`, `(C, M)` fixed. @@ -453,11 +463,7 @@ line per method, one panel per cost model and weight setting. methods (e.g. cost model 2's ASAP optimum at that SLA, or a sweep), or (b) each method's own smallest `(C, M)` that meets `L`, reported next to its AUC cost. -2. Early precompute: may `P_i` merge windows that closed before the release - ahead of time, or must it start at release (simpler, conservative)? -3. Integer cores under cost model 2: `C` continuous (fractional ingest plus - whole query cores), or an integer? -4. Scope: synthetic mixed set only, or also the Alibaba and Google traces? +2. Scope: synthetic mixed set only, or also the Alibaba and Google traces? ## Analytical cost model @@ -596,7 +602,7 @@ summed over the sketch and its key tracker, if any. On its own it is not a wall-clock SLA: it assumes no parallel execution across groups and no cheaper k-way merge. Under the placement design above it is one -firing's precompute-then-query chain on one core. +firing's query job (merge, then estimate) on one core. ## Procedure From f3c343a1bcf2f5e4747b142ae581e0d0cf195093 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 18:59:43 +0000 Subject: [PATCH 04/18] docs: parallel ingest split by sample, compaction at window close, memory in three parts Ingest runs on ceil(rho_D) workers split by sample, each with its own open windows; a compaction job merges the partials at window close, on the query's critical path. Memory is ingest, storage and query, each counted once. Cost model 1 bills CPU and memory by use (elastic CPU, latency is the longest chain); cost model 2 provisions (C, M), billed at the peak, with the placement giving latency. The resource-point question is resolved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 134 ++++++++++++++++++------------- 1 file changed, 80 insertions(+), 54 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 982afcf9..7597ecc4 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -375,41 +375,78 @@ with an SLA `L`. **Load over time.** -- Precompute is ingest: every sample is inserted into its open window - instances as it arrives, a steady background load of - `ρ_ing = Σ_D λ_D · (x/y) · c_ins` vCPUs (spread over groups, so it may use - more than one core). Memory `M_static = Σ_D` (open + closed windows). +- Ingest is the precompute: every sample is inserted into its open window + instances as it arrives. Deployment `D`'s ingest is + `ρ_D = λ_D · (x/y) · c_ins` vCPUs. +- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers, at most one core each, split + by sample: each worker reads a share of the input (e.g. some Kafka + partitions or scrape targets) with no shuffle by group, so it keeps its own + open window instance of every group it sees. When a window closes (the + watermark passes its end), a compaction job merges the `k_D` partial + instances of each group into one stored instance: + `(k_D − 1) · card(G) · c_mrg` CPU-seconds, at most one core. With + `k_D = 1` there is no compaction. - Each firing of RAQE `i` at `t = k · T_i` releases one query job `Q_i`: merge - the `S/x` window instances of each group for the query window, then - estimate. Its CPU work is `ℓ_i = card(G) · (c_qry + (S/x − 1) · c_mrg)`, - the per-RAQE `latency_i` below; merging is part of the query. -- `Q_i` needs the newest window, which closes at `t`, to be fully ingested. - Ingest keeps up whenever the plan is stable (below), so `Q_i` is ready at - `t`. -- `Q_i` holds its `card(G)` merge accumulators, and its output, while it runs. + the `S/x` stored instances of each group for the query window, then + estimate, at most one core. Its CPU work is + `ℓ_i = card(G) · (c_qry + (S/x − 1) · c_mrg)`, the per-RAQE `latency_i` + below; merging is part of the query. +- `Q_i` reads the newest window, which closes at `t`, so it starts only after + that window's compaction finishes. - A batch is all query jobs released at one instant; the heaviest, `B0`, is at `t = 0`, when every RAQE fires. A batch's latency is the time from its release until its last `Q_i` finishes; the reported query latency is the worst batch latency. +**Memory, three parts, each counted once.** For deployment `D` with `m` bytes +per instance: + +| Part | What | Bytes | Held | +|---|---|---|---| +| Ingest | open windows, one copy per worker | `card(G) · m · (x/y) · k_D` | always | +| Storage | closed windows kept for lookbacks (compacted, one copy) | `card(G) · m · ((max S − x)/y + 1)` | always | +| Query | the merge accumulators `Q_i` creates (none for a direct query), and its output | `card(G) · m` + output | while `Q_i` runs | + +A window counts as ingest memory while open and as storage once compacted. +A query reads stored instances in place; only the accumulators its merge +creates are query memory. + **Measurement assumptions (sketch-bench as is).** Every sketch operation is single-threaded and compute-bound: sketch-bench's CPU time equals its wall time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses -at most one core, and on a full core it takes its CPU time `ℓ_i`; the cost -table's `*_cpu_secs` are all the placement needs. +at most one core, and on a full core it takes its CPU time; the cost table's +`*_cpu_secs` are all the model needs. + +**Cost model 1 (AUC: `w1 · AUC(CPU) + w2 · AUC(mem)`).** CPU is elastic and +billed by use, so every job starts when it is ready, on its own core: + +- `AUC(CPU) = Σ_D ρ_D + Σ_D compaction_D / y + Σ_i ℓ_i / T_i`, fixed by the + plan (compaction is the only addition, from parallel ingest). +- `AUC(mem) = Σ_D (ingest + storage)_D + Σ_i (query memory_i × duration_i) / T_i`. + Parallel ingest raises it through the `k_D` open copies. +- A batch's latency is its longest `compaction + Q_i` chain, so an SLA `L` + only forbids pairs with `(k_D − 1) · card(G) · c_mrg + ℓ_{i,D} > L` + (`z_{i,D} = 0`). No resource point is needed. + +**Cost model 2 (max: `w1 · max(CPU) + w2 · max(mem)`).** The plan provisions +a resource point `(C vCPU, M GiB)`, billed at its peak; ingest, compaction and +queries share it. The placement below gives the latency. **Placement algorithm, given a resource point (C vCPU, M GiB).** Capacity is -fractional; jobs share it as rates (a fluid, priority-ordered processor +fractional; jobs share it as rates (fluid, priority-ordered processor sharing). ```text -capacity for queries K = C − ρ_ing (K > 0, and M ≥ M_static, else infeasible) +capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0, and M covers + ingest + storage memory, else infeasible) simulate 2 hyperperiods, event-driven (events: releases, completions): - ready = released query jobs not yet finished - order: release time (older batches first), then longest remaining work first + ready = compaction jobs (released at window closes) + + query jobs whose newest window is compacted + order: release time (older first), then compaction before query + (it unblocks queries), then longest remaining work first give rates in that order: job j gets a_j = min(1, K − rates already given), - as long as its accumulators fit in the free memory - a job runs at rate a_j: it finishes when its remaining work / a_j elapses + as long as its memory fits in what ingest and storage leave + a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) ``` @@ -417,53 +454,42 @@ outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) Two hyperperiods are simulated so that work carried over the wrap-around is counted. -**Cost models.** - -| | CPU term | Memory term | -|---|---|---| -| Cost model 1 (AUC) | `w1 · mean_t CPU(t) = w1 · (ρ_ing + Σ_i ℓ_i / T_i)`, independent of the schedule | `w2 · mean_t MEM(t)`, from the schedule | -| Cost model 2 (max) | `w1 · max_t CPU(t) = w1 · C` | `w2 · max_t MEM(t) = w2 · M` | - -Under cost model 2 the resource point `(C, M)` is decided by the MILP; under -cost model 1 it is an input (open question 1). - -**MILP: a linear surrogate, then verify with the scheduler.** +**MILP: a linear surrogate, then verify with the placement.** `k_D` is fixed +by `D` (`⌈ρ_D⌉`), so its memory and compaction are constants per candidate. ```text -C ≥ ρ_ing + Σ (merge + query).cpu × z (stability, always) -M ≥ M_static + Σ_{i∈B0} card(G_i) · m_i × z_{i,D} (memory, conservative) -with SLA L: - z_{i,D} = 0 if ℓ_{i,D} > L (one query job fits) - Σ_{i∈B0} ℓ_{i,D} × z_{i,D} ≤ (C − ρ_ing) × L (capacity, necessary) - (C − ρ_ing is fractional; under cost model 1, (C, M) is the given point) +cost model 1: + minimize w1 · AUC(CPU) + w2 · AUC(mem) (linear in u_D, z_{i,D}) + with SLA L: z_{i,D} = 0 if (k_D − 1)·card(G)·c_mrg + ℓ_{i,D} > L + +cost model 2: + minimize w1 · C + w2 · M + C ≥ Σ_D ρ_D·u_D + Σ (compaction + query).cpu × z (stability) + M ≥ Σ_D (ingest + storage)_D·u_D + Σ_{i∈B0} card(G_i)·m_i × z_{i,D} (memory, conservative) + with SLA L: + z_{i,D} = 0 if (k_D − 1)·card(G)·c_mrg + ℓ_{i,D} > L (one chain fits) + Σ_{i∈B0} ℓ_{i,D} × z_{i,D} + Σ_D compaction_D·u_D ≤ (C − Σ_D ρ_D·u_D) × L (capacity, necessary) ``` -With jobs capped at one core, list scheduling finishes within -`Σ ℓ / K + max ℓ` (Graham), which gives the sufficient margin: the solution -is simulated, and if its worst batch exceeds `L`, the capacity row's `L` -becomes `L − max ℓ` and the MILP is solved again (at most two solves). Without an SLA the SLA rows are dropped and the simulated latency -at the solution is reported. +Under cost model 2, with jobs capped at one core, list scheduling finishes +within `Σ work / K + max chain` (Graham), which gives the sufficient margin: +the solution is simulated, and if its worst batch exceeds `L`, the capacity +row's `L` becomes `L − max chain` and the MILP is solved again (at most two +solves). Without an SLA the SLA rows are dropped and the latency is reported +(cost model 1: the longest chain; cost model 2: the placement at the +solution's `(C, M)`). -- Cost model 1 objective: `w1 · AUC(CPU) + w2 · AUC(mem)`, `(C, M)` fixed. -- Cost model 2 objective: `w1 · C + w2 · M`, `(C, M)` variables. - PerQuery: the same MILP over single-RAQE candidates only. -- AutoSketch: fixed configs. Cost model 2: the smallest `(C, M)` at which the - simulation meets `L` (binary search). Cost model 1: its AUC cost, and its - simulated latency at the given `(C, M)`, or infeasible if it does not fit. +- AutoSketch: fixed configs, chosen by memory. Cost model 1: its AUC cost and + longest chain. Cost model 2: the smallest `(C, M)` at which the placement + meets `L` (binary search on `C`, `M` at its peak need). **Outputs.** Per (method, cost model, SLA): cost; mean and peak CPU and memory; the resource point; worst batch and per-RAQE latency; solve and verify iterations; planning time. Figure: cost vs. worst batch latency, one line per method, one panel per cost model and weight setting. -**Open questions.** - -1. Cost model 1 with an SLA: capacity is free under AUC billing, so where - does the resource point come from? (a) a fixed `(C, M)` shared by all - methods (e.g. cost model 2's ASAP optimum at that SLA, or a sweep), or (b) - each method's own smallest `(C, M)` that meets `L`, reported next to its - AUC cost. -2. Scope: synthetic mixed set only, or also the Alibaba and Google traces? +**Decided.** Synthetic mixed set first; the Alibaba and Google traces later. ## Analytical cost model From 7e9fdd64f8f006c1de3a44fe5db5fa3a0ddf62bf Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:02:27 +0000 Subject: [PATCH 05/18] docs: the MILP for cost models 1 and 2; the placement sizes (C, M) Cost model 1 is exact and linear (elastic CPU: latency is the longest chain). Cost model 2's batch row is a surrogate that chooses the mapping; the placement then sizes C (smallest meeting the SLA) and M (its peak) for every method alike, replacing the re-solve loop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 80 +++++++++++++++++++------------- 1 file changed, 47 insertions(+), 33 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 7597ecc4..4c873906 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -361,10 +361,8 @@ never enumerates full mappings. ### Cost models, batch latency and query placement (design, under review) -Status: design for review (ProjectASAP/ASAPQuery#777). The code in -`milp::minimize_batch_sla` implements an earlier variant (CPU priced at a -provisioned `V`, one fluid batch) and is reworked to this design once it is -agreed. +Status: agreed design (ProjectASAP/ASAPQuery#777), being implemented in +`placement` (load, cost models, placement) and `milp::minimize_cost_model`. **Scope.** Evaluated on the synthetic mixed template set (spatial templates every 1 s, temporal ones every 1 min, so the hyperperiod is `H = lcm(T_i) = @@ -437,15 +435,15 @@ fractional; jobs share it as rates (fluid, priority-ordered processor sharing). ```text -capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0, and M covers - ingest + storage memory, else infeasible) +capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0 and the mean load + at most C, else infeasible) simulate 2 hyperperiods, event-driven (events: releases, completions): ready = compaction jobs (released at window closes) + query jobs whose newest window is compacted order: release time (older first), then compaction before query (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given), - as long as its memory fits in what ingest and storage leave + give rates in that order: job j gets a_j = min(1, K − rates already given) + (memory is not a limit here: `M` is set to the peak the placement reaches) a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) @@ -454,35 +452,51 @@ outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) Two hyperperiods are simulated so that work carried over the wrap-around is counted. -**MILP: a linear surrogate, then verify with the placement.** `k_D` is fixed -by `D` (`⌈ρ_D⌉`), so its memory and compaction are constants per candidate. +**MILP.** The variables are the existing `z_{i,D}` (RAQE `i` uses candidate +`D`), `u_D` (`D` is active) and `stored_D`; cost model 2 adds `C` and `M` +(continuous). Per candidate the model reads constants: ingest CPU `ρ_D`, +workers `k_D = ⌈ρ_D⌉`, ingest memory `I_D` (open windows × `k_D`), compaction +`c_D = (k_D − 1) · Σ instances · c_mrg` per closed window, every `y_D`; per +pair: the query job's work `ℓ_{i,D}`, its memory `q_{i,D}` (merge +accumulators and output) and storage `s_{i,D}`. + +Cost model 1 (by use; CPU elastic): + +```text +minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D I_D · u_D + Σ_D stored_D + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +s.t. the assignment rows above; stored_D ≥ s_{i,D} · z_{i,D} +with SLA L: z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) +``` + +Every term is linear, so this is exact: with elastic CPU a batch's latency is +its longest chain `c_D + ℓ_{i,D}`. + +Cost model 2 (provisioned `(C, M)`, billed at the peak): ```text -cost model 1: - minimize w1 · AUC(CPU) + w2 · AUC(mem) (linear in u_D, z_{i,D}) - with SLA L: z_{i,D} = 0 if (k_D − 1)·card(G)·c_mrg + ℓ_{i,D} > L - -cost model 2: - minimize w1 · C + w2 · M - C ≥ Σ_D ρ_D·u_D + Σ (compaction + query).cpu × z (stability) - M ≥ Σ_D (ingest + storage)_D·u_D + Σ_{i∈B0} card(G_i)·m_i × z_{i,D} (memory, conservative) - with SLA L: - z_{i,D} = 0 if (k_D − 1)·card(G)·c_mrg + ℓ_{i,D} > L (one chain fits) - Σ_{i∈B0} ℓ_{i,D} × z_{i,D} + Σ_D compaction_D·u_D ≤ (C − Σ_D ρ_D·u_D) × L (capacity, necessary) +minimize w1 · C + w2 · M +s.t. the assignment rows; stored_D ≥ s_{i,D} · z_{i,D} + C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) + M ≥ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} (every query at once) +with SLA L: + z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) + Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ≤ L · (C − Σ_D ρ_D · u_D) (the aligned batch fits) ``` -Under cost model 2, with jobs capped at one core, list scheduling finishes -within `Σ work / K + max chain` (Graham), which gives the sufficient margin: -the solution is simulated, and if its worst batch exceeds `L`, the capacity -row's `L` becomes `L − max chain` and the MILP is solved again (at most two -solves). Without an SLA the SLA rows are dropped and the latency is reported -(cost model 1: the longest chain; cost model 2: the placement at the -solution's `(C, M)`). - -- PerQuery: the same MILP over single-RAQE candidates only. -- AutoSketch: fixed configs, chosen by memory. Cost model 1: its AUC cost and - longest chain. Cost model 2: the smallest `(C, M)` at which the placement - meets `L` (binary search on `C`, `M` at its peak need). +The batch row is linear (`L` is a constant). It is a surrogate: it asks the +heaviest batch's work to fit the capacity ingest leaves, as if that work were +divisible. The MILP uses it to choose the mapping. The resource point is then +sized exactly by the placement, for every method alike: `C` is the smallest at +which the placement's worst batch meets `L` (binary search; with jobs capped at +one core, list scheduling ends within `Σ work / K + max chain`, so it exists +whenever every chain fits), and `M` is the placement's peak memory. Cost model +2's reported cost is `w1 · C + w2 · M` at that point. Without an SLA, `C` is +the mean load and the placement reports the latency it gives. + +- PerQuery: the same MILP over single-RAQE candidates only (no sharing). +- AutoSketch: fixed configs, chosen by memory; priced by the same functions + (cost model 1 by use; cost model 2 by the placement and binary search). **Outputs.** Per (method, cost model, SLA): cost; mean and peak CPU and memory; the resource point; worst batch and per-RAQE latency; solve and From 0b1fdef071d86517b081747d89f9212cc58eab59 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:11:41 +0000 Subject: [PATCH 06/18] rqe-optimizer: cost models 1 and 2 with query placement placement: a plan's load over time (ingest on ceil(rho) workers split by sample, compaction at window close, one query job per firing, each at most one core), cost model 1 (by use, elastic CPU, latency = longest chain) and cost model 2 (a provisioned (C, M) billed at the peak, sized by an event-driven placement: the smallest C meeting the SLA, M its peak). milp::minimize_cost_model: cost model 1 is exact and linear; cost model 2 uses a linear surrogate (batch work over the capacity ingest leaves, every query's memory at once), then corrects it with the placement's error on the chosen mapping and solves again, keeping the cheapest placed mapping. The earlier provisioned-V minimize_batch_sla is removed; minimize is unchanged. Tests: placement (one core per job, fractional capacity, shared batches, compaction before queries, backlog, both cost models); cost model 1 matches brute force with and without an SLA; cost model 2 meets the SLA and matches the brute-force placed optimum. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 32 +- rqe-optimizer/src/analytical_cost_model.rs | 42 +- rqe-optimizer/src/lib.rs | 1 + rqe-optimizer/src/milp.rs | 649 ++++++++++++++------- rqe-optimizer/src/placement.rs | 507 ++++++++++++++++ 5 files changed, 989 insertions(+), 242 deletions(-) create mode 100644 rqe-optimizer/src/placement.rs diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 4c873906..3a21ee99 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -361,7 +361,7 @@ never enumerates full mappings. ### Cost models, batch latency and query placement (design, under review) -Status: agreed design (ProjectASAP/ASAPQuery#777), being implemented in +Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in `placement` (load, cost models, placement) and `milp::minimize_cost_model`. **Scope.** Evaluated on the synthetic mixed template set (spatial templates @@ -484,15 +484,31 @@ with SLA L: Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ≤ L · (C − Σ_D ρ_D · u_D) (the aligned batch fits) ``` -The batch row is linear (`L` is a constant). It is a surrogate: it asks the -heaviest batch's work to fit the capacity ingest leaves, as if that work were -divisible. The MILP uses it to choose the mapping. The resource point is then -sized exactly by the placement, for every method alike: `C` is the smallest at +The batch row is linear (`L` is a constant). It is a surrogate: it treats the +heaviest batch's work as divisible, and the memory row holds every query at +once. So the MILP's `(C, M)` is not what the chosen mapping really needs. The +placement sizes it exactly, for every method alike: `C` is the smallest at which the placement's worst batch meets `L` (binary search; with jobs capped at one core, list scheduling ends within `Σ work / K + max chain`, so it exists -whenever every chain fits), and `M` is the placement's peak memory. Cost model -2's reported cost is `w1 · C + w2 · M` at that point. Without an SLA, `C` is -the mean load and the placement reports the latency it gives. +whenever every chain fits), and `M` is the placement's peak memory. Without an +SLA, `C` is the mean load and the placement reports the latency it gives. + +**Correction passes (cost model 2).** The MILP minimizes the surrogate peaks, +which may rank mappings differently from their placed peaks. So +`milp::minimize_cost_model` iterates: + +1. Solve the MILP; take its mapping and size its real `(C*, M*)` with the + placement. Cost `w1 · C* + w2 · M*`. +2. Measure the surrogate's error on that mapping: `δ_C = C* − Ĉ`, + `δ_M = M* − M̂`, where `Ĉ = max(mean load, ρ_ing + batch work / L)` and + `M̂ = ingest + storage + every query's memory` are the rows' values. +3. Add the errors back to the rows (`C ≥ ρ_ing + batch work / L + δ_C`, + `M ≥ … + δ_M`) and solve again. +4. Keep the mapping with the lowest placed cost; stop when a mapping repeats, + or after three corrections. + +Cost model 1 needs none of this: with elastic CPU every term is linear and +exact (CPU and memory by use, latency the longest chain). - PerQuery: the same MILP over single-RAQE candidates only (no sharing). - AutoSketch: fixed configs, chosen by memory; priced by the same functions diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 0a1750ee..22547616 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -254,36 +254,22 @@ pub(crate) fn query_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &Wor .sum::() } -/// CPU time of one aligned batch, every RAQE evaluated once: `W = Σ_i -/// latency_i`, in CPU-seconds. -pub fn batch_work_secs(plan: &PlanCost) -> f64 { - plan.query_latency_ms.iter().sum::() / 1000.0 +/// Parallel ingest workers of `deployment`, split by sample: `k = ⌈ρ⌉` for +/// its ingest CPU `ρ`, at least one, since sketch-bench's operations are +/// single-threaded (a worker uses at most one core). +pub fn ingest_workers(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + ingest(deployment, facts).cpu_secs_per_sec.ceil().max(1.0) } -/// The vCPUs a plan provisions so that ingest and an aligned batch of every -/// RAQE share them and the batch finishes within `batch_sla_ms`: at least -/// the mean CPU, and `ρ_ing + W / SLA` (ingest holds `ρ_ing` vCPUs, the batch -/// runs on the rest). With no SLA, the mean CPU. -pub fn provisioned_vcpus(plan: &PlanCost, batch_sla_ms: Option) -> f64 { - let mean = plan.cpu_secs_per_sec(); - match batch_sla_ms { - Some(sla_ms) => { - mean.max(plan.ingest.cpu_secs_per_sec + batch_work_secs(plan) / (sla_ms / 1000.0)) - } - None => mean, - } -} - -/// When an aligned batch of every RAQE finishes on `vcpus`, in ms: its work -/// spread over the vCPUs ingest leaves, `W / (V − ρ_ing)`. -pub fn batch_makespan_ms(plan: &PlanCost, vcpus: f64) -> f64 { - 1000.0 * batch_work_secs(plan) / (vcpus - plan.ingest.cpu_secs_per_sec) -} - -/// The smallest unit of a query's work: one group's merge and query, in ms. -/// Groups run in parallel, so a batch SLA can't finish faster than this. -pub(crate) fn group_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { - query_latency_ms(raqe, deployment, facts) / group_count(deployment, facts) +/// CPU-seconds to compact one closed window: merge the `k` workers' partial +/// instances of every group into one, `(k − 1) · Σ_parts instances · c_mrg`. +/// Zero with one worker. +pub fn compaction_secs(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let extra = ingest_workers(deployment, facts) - 1.0; + extra + * priced_parts(deployment, facts) + .map(|(config, instances, _)| instances * config.merge_cpu_secs) + .sum::() } pub fn score( diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index a7b82c19..115d7221 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -15,6 +15,7 @@ pub mod candidates; pub mod enumerate; pub mod milp; pub mod pareto; +pub mod placement; pub mod saturation; pub mod theory; diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 4fe7de35..bd9ed5fe 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -39,33 +39,10 @@ impl Objective { }) } - /// The objective with CPU priced at the plan's provisioned vCPUs - /// ([`analytical_cost_model::provisioned_vcpus`]) instead of its mean. - pub fn value_provisioned(&self, plan_cost: &PlanCost, batch_sla_ms: Option) -> f64 { - self.weigh(PhaseCost { - cpu_secs_per_sec: analytical_cost_model::provisioned_vcpus(plan_cost, batch_sla_ms), - memory_bytes: plan_cost.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 } - - fn weigh_cpu(&self, cost: PhaseCost) -> f64 { - self.weigh(PhaseCost { - memory_bytes: 0.0, - ..cost - }) - } - - fn weigh_memory(&self, cost: PhaseCost) -> f64 { - self.weigh(PhaseCost { - cpu_secs_per_sec: 0.0, - ..cost - }) - } } /// The solved plan: the deployments to run and which one serves each RAQE. @@ -104,40 +81,6 @@ pub fn minimize( facts: &WorkloadFacts, objective: Objective, accuracy: &Accuracy, -) -> Result { - solve(raqes, deployments, facts, objective, accuracy, None) -} - -/// [`minimize`] under a batch latency SLA instead of per-RAQE bounds: every -/// RAQE fires at once, ingest and the batch share the plan's provisioned -/// vCPUs `V`, and the batch must finish within `batch_sla_ms`. CPU is priced -/// at `V` (see `docs/rqe_sketch_deployment_v1.md`, "Batch latency SLA"), -/// which equals the mean CPU when the SLA does not bind. -pub fn minimize_batch_sla( - raqes: &[Raqe], - deployments: &[Deployment], - facts: &WorkloadFacts, - objective: Objective, - accuracy: &Accuracy, - batch_sla_ms: f64, -) -> Result { - solve( - raqes, - deployments, - facts, - objective, - accuracy, - Some(batch_sla_ms), - ) -} - -fn solve( - raqes: &[Raqe], - deployments: &[Deployment], - facts: &WorkloadFacts, - objective: Objective, - accuracy: &Accuracy, - batch_sla_ms: Option, ) -> Result { let eligible: Vec> = raqes .iter() @@ -212,62 +155,20 @@ fn solve( }; let mut goal: Expression = deployment_storage_cost.iter().sum(); - // Under a batch SLA, CPU is priced at the provisioned vCPUs, `cpu` (scaled - // by `w_cpu / reference`): at least the mean CPU, and at least ingest plus - // the batch's work over the SLA. Memory stays in the goal per phase. - let mut mean_cpu = Expression::from(0.0); - let mut batch_cpu = Expression::from(0.0); - let cpu = batch_sla_ms.map(|_| variables.add(variable().min(0))); - for (deployment_index, &active_variable) in active.iter().enumerate() { - let deployment = &deployments[deployment_index]; - if cpu.is_some() { - let ingest = analytical_cost_model::ingest(deployment, facts); - goal.add_mul(objective.weigh_memory(ingest) / reference, active_variable); - let ingest_cpu = objective.weigh_cpu(ingest) / reference; - mean_cpu.add_mul(ingest_cpu, active_variable); - batch_cpu.add_mul(ingest_cpu, active_variable); - } else { - goal.add_mul(ingest_cost[deployment_index] / reference, active_variable); - } + for (&cost, &active_variable) in ingest_cost.iter().zip(&active) { + goal.add_mul(cost / reference, active_variable); } for (raqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { - let raqe = &raqes[raqe_index]; - let deployment = &deployments[deployment_index]; - match batch_sla_ms { - Some(sla_ms) => { - let mut merge_and_query = analytical_cost_model::merge(raqe, deployment, facts); - merge_and_query += analytical_cost_model::query(raqe, deployment, facts); - goal.add_mul( - objective.weigh_memory(merge_and_query) / reference, - assignment, - ); - mean_cpu.add_mul(objective.weigh_cpu(merge_and_query) / reference, assignment); - // The batch's work, CPU-sec, as vCPUs held for the SLA. - let work = PhaseCost { - cpu_secs_per_sec: analytical_cost_model::query_latency_ms( - raqe, deployment, facts, - ) / sla_ms, - memory_bytes: 0.0, - }; - batch_cpu.add_mul(objective.weigh_cpu(work) / reference, assignment); - } - None => goal.add_mul( - merge_and_query_cost(raqe, deployment) / reference, - assignment, - ), - } + goal.add_mul( + merge_and_query_cost(&raqes[raqe_index], &deployments[deployment_index]) + / reference, + assignment, + ); } } - if let Some(cpu) = cpu { - goal += cpu; - } let mut model = variables.minimise(goal).using(default_solver); - if let Some(cpu) = cpu { - model.add_constraint((mean_cpu - cpu).leq(0)); - model.add_constraint((batch_cpu - cpu).leq(0)); - } for (raqe_index, choices) in assignments.iter().enumerate() { let assignment_sum: Expression = choices.iter().map(|(_, variable)| *variable).sum(); model.add_constraint(assignment_sum.eq(1)); @@ -289,12 +190,7 @@ fn solve( // forbids the choices over it. Comparing in f64 here, not in the // solver, keeps µs latencies clear of its feasibility tolerance. let latency_ms = analytical_cost_model::query_latency_ms(raqe, deployment, facts); - // Under a batch SLA, one group's merge and query can't be split - // across vCPUs, so it alone must fit the SLA. - let group_latency_ms = analytical_cost_model::group_latency_ms(raqe, deployment, facts); - if raqe.latency_sla_ms.is_some_and(|limit| latency_ms > limit) - || batch_sla_ms.is_some_and(|limit| group_latency_ms > limit) - { + if raqe.latency_sla_ms.is_some_and(|limit| latency_ms > limit) { model.add_constraint(Expression::from(assignment).leq(0)); } } @@ -331,6 +227,354 @@ fn solve( }) } +/// Which cost model [`minimize_cost_model`] minimizes +/// (`docs/rqe_sketch_deployment_v1.md`, "Cost models, batch latency and +/// query placement"). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CostModel { + /// `w_cpu · AUC(CPU) + w_mem · AUC(memory)`: billed by use, CPU elastic. + /// Exact and linear. + One, + /// `w_cpu · max(CPU) + w_mem · max(memory)`: a provisioned `(C, M)`, + /// billed at the peak. The MILP's batch row is a surrogate, corrected by + /// the placement (see [`minimize_cost_model`]). + Two, +} + +/// A [`minimize_cost_model`] solution, priced by its cost model. +#[derive(Debug, Clone)] +pub struct CostModelSolution { + pub milp: MilpSolution, + /// One candidate index per RAQE. + pub mapping: Mapping, + pub cost: crate::placement::ModelCost, + /// MILP solves (more than one only for cost model 2). + pub solves: usize, +} + +/// Correction passes for cost model 2, beyond the first solve. +const COST_MODEL_2_CORRECTIONS: usize = 3; + +/// Minimize `cost_model` with weights `w_cpu`, `w_mem` (per vCPU, per GiB), +/// optionally under a batch latency SLA `sla_ms`. +/// +/// Cost model 1 is solved exactly. Cost model 2's batch row +/// (`Σ ℓ + Σ compaction ≤ L · (C − ingest)`) treats the heaviest batch as +/// divisible, and its memory row holds every query at once; the placement +/// then sizes the chosen mapping's real `(C, M)`. The gap between the two is +/// added back to the rows (`C ≥ … + δ_C`, `M ≥ … + δ_M`) and the MILP solved +/// again, keeping the mapping whose placed cost is lowest, until a mapping +/// repeats or after [`COST_MODEL_2_CORRECTIONS`] passes. +#[allow(clippy::too_many_arguments)] +pub fn minimize_cost_model( + raqes: &[Raqe], + deployments: &[Deployment], + facts: &WorkloadFacts, + w_cpu: f64, + w_mem: f64, + cost_model: CostModel, + accuracy: &Accuracy, + sla_ms: Option, +) -> Result { + use crate::placement::{cost_model_1, cost_model_2, PlanLoad}; + let price = |mapping: &Mapping| { + let load = PlanLoad::new(raqes, deployments, mapping, facts); + match cost_model { + CostModel::One => Some(cost_model_1(&load, w_cpu, w_mem)), + CostModel::Two => cost_model_2(&load, w_cpu, w_mem, sla_ms), + } + }; + let mut corrections = (0.0, 0.0); + let mut best: Option = None; + let mut seen: Vec = Vec::new(); + for solve in 1..=1 + COST_MODEL_2_CORRECTIONS { + let (milp, mapping) = solve_cost_model( + raqes, + deployments, + facts, + w_cpu, + w_mem, + cost_model, + accuracy, + sla_ms, + corrections, + )?; + let cost = price(&mapping).ok_or(ResolutionError::Infeasible)?; + if cost_model == CostModel::One { + return Ok(CostModelSolution { + milp, + mapping, + cost, + solves: 1, + }); + } + let load = PlanLoad::new(raqes, deployments, &mapping, facts); + let (surrogate_cpu, surrogate_bytes) = surrogate_peaks(&load, sla_ms); + corrections = (cost.cpu - surrogate_cpu, cost.bytes - surrogate_bytes); + let repeated = seen.contains(&mapping); + seen.push(mapping.clone()); + if best.as_ref().is_none_or(|b| cost.value < b.cost.value) { + best = Some(CostModelSolution { + milp, + mapping, + cost, + solves: solve, + }); + } + if repeated { + break; + } + } + let mut best = best.expect("at least one solve"); + best.solves = seen.len(); + Ok(best) +} + +/// Cost model 2's surrogate `(C, M)` of a placed plan, the MILP's rows +/// without corrections: `C = max(mean load, ingest + batch work / L)`, and `M` +/// with every query's memory at once. +fn surrogate_peaks(load: &crate::placement::PlanLoad, sla_ms: Option) -> (f64, f64) { + let mean = load.auc_cpu(); + let cpu = match sla_ms { + Some(sla) => { + let batch: f64 = load.queries.iter().map(|q| q.work_secs).sum::() + + load + .deployments + .iter() + .map(|d| d.compaction_secs) + .sum::(); + mean.max(load.ingest_cpu() + batch / (sla / 1000.0)) + } + None => mean, + }; + let bytes = load.static_bytes() + load.queries.iter().map(|q| q.memory_bytes).sum::(); + (cpu, bytes) +} + +/// One MILP solve for [`minimize_cost_model`], with cost model 2's +/// corrections `(δ_C vCPU, δ_M bytes)`. +#[allow(clippy::too_many_arguments)] +fn solve_cost_model( + raqes: &[Raqe], + deployments: &[Deployment], + facts: &WorkloadFacts, + w_cpu: f64, + w_mem: f64, + cost_model: CostModel, + accuracy: &Accuracy, + sla_ms: Option, + (cpu_correction, bytes_correction): (f64, f64), +) -> Result<(MilpSolution, Mapping), ResolutionError> { + let secs = |ms: u64| ms as f64 / 1000.0; + // Per candidate: ingest vCPUs, compaction per window, its rate, ingest bytes. + let ingest_cpu: Vec = deployments + .iter() + .map(|d| analytical_cost_model::ingest(d, facts).cpu_secs_per_sec) + .collect(); + let compaction: Vec = deployments + .iter() + .map(|d| analytical_cost_model::compaction_secs(d, facts)) + .collect(); + let ingest_bytes: Vec = deployments + .iter() + .map(|d| { + analytical_cost_model::ingest(d, facts).memory_bytes + * analytical_cost_model::ingest_workers(d, facts) + }) + .collect(); + // Eligible pairs, less those whose chain exceeds the SLA. + let eligible: Vec> = raqes + .iter() + .map(|raqe| { + eligible_deployments_for(raqe, deployments, facts, accuracy) + .into_iter() + .filter(|&d| { + sla_ms.is_none_or(|sla| { + 1000.0 * compaction[d] + + analytical_cost_model::query_latency_ms(raqe, &deployments[d], facts) + <= sla + }) + }) + .collect() + }) + .collect(); + if eligible.iter().any(Vec::is_empty) { + return Err(ResolutionError::Infeasible); + } + // Per pair: query work (CPU-sec), its memory and the storage it needs. + let work = |i: usize, d: usize| { + analytical_cost_model::query_latency_ms(&raqes[i], &deployments[d], facts) / 1000.0 + }; + let query_bytes = |i: usize, d: usize| { + analytical_cost_model::merge(&raqes[i], &deployments[d], facts).memory_bytes + + analytical_cost_model::query(&raqes[i], &deployments[d], facts).memory_bytes + }; + let storage = |i: usize, d: usize| { + analytical_cost_model::storage_bytes(&raqes[i], &deployments[d], facts) + }; + + // Scale: the cost of each RAQE alone on its cheapest pair (cost model 1), + // so HiGHS sees magnitudes near 1. + let cpu_of = |i: usize, d: usize| { + ingest_cpu[d] + + compaction[d] / secs(deployments[d].slide_ms) + + work(i, d) / secs(raqes[i].interval_ms) + }; + let gib = |bytes: f64| bytes / BYTES_PER_GIB; + let reference: f64 = (0..raqes.len()) + .map(|i| { + eligible[i] + .iter() + .map(|&d| { + w_cpu * cpu_of(i, d) + + w_mem * gib(ingest_bytes[d] + storage(i, d) + query_bytes(i, d)) + }) + .fold(f64::INFINITY, f64::min) + }) + .sum(); + let reference = if reference.is_normal() { + reference + } else { + 1.0 + }; + let cpu_scale = (0..raqes.len()) + .map(|i| { + eligible[i] + .iter() + .map(|&d| cpu_of(i, d)) + .fold(f64::INFINITY, f64::min) + }) + .sum::() + .max(f64::MIN_POSITIVE); + let bytes_scale = (0..raqes.len()) + .map(|i| { + eligible[i] + .iter() + .map(|&d| ingest_bytes[d] + storage(i, d) + query_bytes(i, d)) + .fold(f64::INFINITY, f64::min) + }) + .sum::() + .max(1.0); + + let mut variables = ProblemVariables::new(); + let active: Vec = deployments + .iter() + .map(|_| variables.add(variable().binary())) + .collect(); + let assignments: Vec> = eligible + .iter() + .map(|choices| { + choices + .iter() + .map(|&d| (d, variables.add(variable().binary()))) + .collect() + }) + .collect(); + // Storage per deployment, in units of `bytes_scale`. + let stored: Vec = deployments + .iter() + .map(|_| variables.add(variable().min(0))) + .collect(); + // Cost model 2: C and M, in units of `cpu_scale` and `bytes_scale`. + let peaks = (cost_model == CostModel::Two).then(|| { + ( + variables.add(variable().min(0)), + variables.add(variable().min(0)), + ) + }); + + // CPU and memory terms, in scaled units. + let mut mean_cpu = Expression::from(0.0); + let mut batch_work = Expression::from(0.0); + let mut ingest = Expression::from(0.0); + let mut held_bytes: Expression = stored.iter().sum(); + let mut query_bytes_all = Expression::from(0.0); + let mut query_bytes_auc = Expression::from(0.0); + for (d, &u) in active.iter().enumerate() { + let deployment = &deployments[d]; + mean_cpu.add_mul( + (ingest_cpu[d] + compaction[d] / secs(deployment.slide_ms)) / cpu_scale, + u, + ); + ingest.add_mul(ingest_cpu[d] / cpu_scale, u); + batch_work.add_mul(compaction[d] / cpu_scale, u); + held_bytes.add_mul(ingest_bytes[d] / bytes_scale, u); + } + for (i, choices) in assignments.iter().enumerate() { + let interval = secs(raqes[i].interval_ms); + for &(d, z) in choices { + mean_cpu.add_mul(work(i, d) / interval / cpu_scale, z); + batch_work.add_mul(work(i, d) / cpu_scale, z); + query_bytes_all.add_mul(query_bytes(i, d) / bytes_scale, z); + query_bytes_auc.add_mul(query_bytes(i, d) * work(i, d) / interval / bytes_scale, z); + } + } + let cpu_weight = w_cpu * cpu_scale / reference; + let bytes_weight = w_mem * gib(bytes_scale) / reference; + let goal = match peaks { + None => { + cpu_weight * mean_cpu.clone() + bytes_weight * (held_bytes.clone() + query_bytes_auc) + } + Some((c, m)) => cpu_weight * c + bytes_weight * m, + }; + + let mut model = variables.minimise(goal).using(default_solver); + for (i, choices) in assignments.iter().enumerate() { + let sum: Expression = choices.iter().map(|&(_, z)| z).sum(); + model.add_constraint(sum.eq(1)); + for &(d, z) in choices { + model.add_constraint((z - active[d]).leq(0)); + let needed = storage(i, d) / bytes_scale; + if needed > 0.0 { + model.add_constraint((needed * z - stored[d]).leq(0)); + } + } + } + for (d, &u) in active.iter().enumerate() { + let used: Expression = assignments + .iter() + .flat_map(|choices| choices.iter()) + .filter(|(index, _)| *index == d) + .map(|&(_, z)| z) + .sum(); + model.add_constraint((u - used).leq(0)); + } + if let Some((c, m)) = peaks { + model.add_constraint((mean_cpu - c).leq(0)); + model.add_constraint( + (held_bytes + query_bytes_all + bytes_correction / bytes_scale - m).leq(0), + ); + if let Some(sla) = sla_ms { + // C ≥ ingest + (batch work) / L + δ_C. + let l = sla / 1000.0; + model.add_constraint( + (ingest + batch_work * (1.0 / l) + cpu_correction / cpu_scale - c).leq(0), + ); + } + } + + let solved = model.solve()?; + let mapping: Mapping = assignments + .iter() + .map(|choices| { + choices + .iter() + .find_map(|&(d, z)| (solved.value(z) > 0.5).then_some(d)) + .expect("the MILP assigns every RAQE one deployment") + }) + .collect(); + let plan_cost = score(raqes, deployments, &mapping, facts); + let (planned, planned_raqes) = plan(raqes, deployments, &mapping); + Ok(( + MilpSolution { + deployments: planned, + raqes: planned_raqes, + plan_cost, + }, + mapping, + )) +} + /// Keeps the deployments `mapping` uses, renumbered, with their instance /// counts. Every pair in `mapping` is eligible, so the counts exist. fn plan( @@ -498,115 +742,108 @@ mod tests { assert_eq!(solve(&[bounded]), vec![1]); } - /// Under a batch SLA, the MILP's plan, priced at its provisioned vCPUs, - /// is the best of every mapping whose groups each fit the SLA. - fn assert_batch_sla_matches_brute_force( + /// The cheapest mapping under `price` (None: unservable), by brute force. + fn brute_force_cost( raqes: &[Raqe], deployments: &[Deployment], - objective: Objective, - sla_ms: f64, - ) { - // 100 groups, so a batch's work spreads over vCPUs. - let facts = facts(100, 100); - let fits = |mapping: &Mapping| { - mapping.iter().zip(raqes).all(|(&d, raqe)| { - analytical_cost_model::group_latency_ms(raqe, &deployments[d], &facts) <= sla_ms - }) - }; - let best = brute_force(raqes, deployments, &facts, &table_accuracy) + facts: &WorkloadFacts, + price: impl Fn(&Mapping) -> Option, + ) -> f64 { + brute_force(raqes, deployments, facts, &table_accuracy) .iter() - .filter(|mapping| fits(mapping)) - .map(|mapping| { - objective - .value_provisioned(&score(raqes, deployments, mapping, &facts), Some(sla_ms)) - }) + .filter_map(price) .min_by(f64::total_cmp) - .expect("test workload is servable within the SLA"); - let milp = minimize_batch_sla( - raqes, - deployments, - &facts, - objective, - &table_accuracy, - sla_ms, - ) - .expect("feasible MILP"); - let got = objective.value_provisioned(&milp.plan_cost, Some(sla_ms)); - assert!( - (got - best).abs() <= 1e-9 * best, - "{objective:?}, SLA {sla_ms} ms: {got} vs {best}" - ); + .expect("servable") } - #[test] - fn batch_sla_matches_brute_force_at_every_sla() { + /// Two RAQEs, 100 groups, and candidates that trade ingest for queries. + fn cost_model_workload() -> (Vec, Vec, WorkloadFacts) { let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; - // Cheap ingest with slow queries, or the reverse. + // (memory, insert, merge, query, window, slide): cheap ingest with + // slow queries; costlier ingest with fast ones; a 10-minute window + // that answers `long` without merging but keeps 10 windows open. 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), + test_support::deployment(0.5 * BYTES_PER_GIB, 1e-3, 1e-4, 4e-3, 60_000, 60_000), + test_support::deployment(0.1 * BYTES_PER_GIB, 3e-3, 1e-5, 1e-5, 60_000, 60_000), + test_support::deployment(2.0 * BYTES_PER_GIB, 2e-4, 1e-5, 1e-5, 600_000, 60_000), ]; - for objective in [weights(1.0, 0.0), weights(1.0, 4.0)] { - // Down to an SLA that rules out the slow-query deployment's groups. - for sla_ms in [1e12, 1e7, 1e6, 2e4] { - assert_batch_sla_matches_brute_force(&raqes, &deployments, objective, sla_ms); - } - } + (raqes, deployments, facts(100, 100)) } #[test] - fn a_loose_batch_sla_prices_the_mean_cpu() { - let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; - let deployments = vec![deployment(1.0, 20.0, 400.0), deployment(3.0, 10.0, 1.0)]; - let facts = facts(1, 1); - let free = minimize( - &raqes, - &deployments, - &facts, - Objective::default(), - &table_accuracy, - ) - .expect("feasible MILP"); - let loose = minimize_batch_sla( - &raqes, - &deployments, - &facts, - Objective::default(), - &table_accuracy, - 1e12, - ) - .expect("feasible MILP"); - assert_eq!(chosen(&loose, &deployments), chosen(&free, &deployments)); - assert_eq!( - analytical_cost_model::provisioned_vcpus(&loose.plan_cost, Some(1e12)), - loose.plan_cost.cpu_secs_per_sec() - ); + fn cost_model_1_matches_brute_force_with_and_without_an_sla() { + use crate::placement::{cost_model_1, PlanLoad}; + let (raqes, deployments, facts) = cost_model_workload(); + for (w_cpu, w_mem) in [(1.0, 0.0), (1.0, 4.0)] { + for sla_ms in [None, Some(1e5), Some(300.0)] { + let price = |mapping: &Mapping| { + let cost = cost_model_1( + &PlanLoad::new(&raqes, &deployments, mapping, &facts), + w_cpu, + w_mem, + ); + sla_ms + .is_none_or(|l| cost.latency_ms <= l) + .then_some(cost.value) + }; + let best = brute_force_cost(&raqes, &deployments, &facts, price); + let got = minimize_cost_model( + &raqes, + &deployments, + &facts, + w_cpu, + w_mem, + CostModel::One, + &table_accuracy, + sla_ms, + ) + .expect("feasible"); + assert!( + (got.cost.value - best).abs() <= 1e-9 * best, + "({w_cpu}, {w_mem}), {sla_ms:?}: {} vs {best}", + got.cost.value + ); + assert!(sla_ms.is_none_or(|l| got.cost.latency_ms <= l)); + } + } } #[test] - fn a_tight_batch_sla_provisions_for_the_batch_and_meets_it() { - let raqes = vec![raqe("r", 60_000)]; - // 100 groups at 100 samples/s. Ingest 100 vCPU and 300 s of query - // work, or ingest 120 and 100 s: 105 vs. 121.7 mean vCPUs. - let deployments = vec![deployment(1.0, 20.0, 3.0), deployment(1.2, 10.0, 1.0)]; - let facts = facts(100, 100); - let sla_ms = 3_000.0; - let milp = minimize_batch_sla( - &raqes, - &deployments, - &facts, - Objective::default(), - &table_accuracy, - sla_ms, - ) - .expect("feasible MILP"); - // Within 3 s: 120 + 100 s / 3 s = 153.3 vCPUs beats 100 + 300 / 3 = 200. - assert_eq!(chosen(&milp, &deployments), vec![1]); - let vcpus = analytical_cost_model::provisioned_vcpus(&milp.plan_cost, Some(sla_ms)); - assert!((vcpus - (120.0 + 100.0 / 3.0)).abs() < 1e-9, "{vcpus}"); - let makespan = analytical_cost_model::batch_makespan_ms(&milp.plan_cost, vcpus); - assert!((makespan - sla_ms).abs() < 1e-6, "{makespan}"); + fn cost_model_2_meets_the_sla_and_corrections_find_the_best_mapping() { + use crate::placement::{cost_model_2, PlanLoad}; + let (raqes, deployments, facts) = cost_model_workload(); + for (w_cpu, w_mem) in [(1.0, 0.0), (1.0, 4.0)] { + for sla_ms in [None, Some(1e5), Some(2_000.0), Some(300.0)] { + let price = |mapping: &Mapping| { + cost_model_2( + &PlanLoad::new(&raqes, &deployments, mapping, &facts), + w_cpu, + w_mem, + sla_ms, + ) + .map(|cost| cost.value) + }; + let best = brute_force_cost(&raqes, &deployments, &facts, price); + let got = minimize_cost_model( + &raqes, + &deployments, + &facts, + w_cpu, + w_mem, + CostModel::Two, + &table_accuracy, + sla_ms, + ) + .expect("feasible"); + assert!(sla_ms.is_none_or(|l| got.cost.latency_ms <= l)); + assert!( + (got.cost.value - best).abs() <= 1e-3 * best, + "({w_cpu}, {w_mem}), {sla_ms:?}: {} vs {best} after {} solves", + got.cost.value, + got.solves + ); + } + } } #[test] diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs new file mode 100644 index 00000000..6697af74 --- /dev/null +++ b/rqe-optimizer/src/placement.rs @@ -0,0 +1,507 @@ +//! A plan's load over time, its cost under cost models 1 and 2, and the query +//! placement that gives its batch latency (`docs/rqe_sketch_deployment_v1.md`, +//! "Cost models, batch latency and query placement"). +//! +//! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. +//! Each closed window is compacted (the workers' partials merged into one), and +//! each RAQE firing runs one query job (merge, then estimate) once the newest +//! window is compacted. A job uses at most one core: sketch-bench's operations +//! are single-threaded, their CPU time equal to their wall time. + +use std::collections::BTreeMap; + +use crate::analytical_cost_model::{self, BYTES_PER_GIB}; +use crate::{Deployment, Mapping, Millis, Raqe, WorkloadFacts}; + +/// One active deployment's steady load. +#[derive(Debug, Clone)] +pub struct DeploymentLoad { + /// Ingest CPU, vCPUs. + pub ingest_cpu: f64, + /// Open windows on every worker, bytes. + pub ingest_bytes: f64, + /// Closed windows kept for the longest lookback served, bytes. + pub storage_bytes: f64, + /// CPU-seconds to compact one closed window (0 with one worker). + pub compaction_secs: f64, + /// Windows close every slide. + pub slide_ms: Millis, +} + +/// One RAQE's query job, run every interval. +#[derive(Debug, Clone)] +pub struct QueryLoad { + /// Index into [`PlanLoad::deployments`]. + pub deployment: usize, + pub interval_ms: Millis, + /// Merge then estimate, CPU-seconds (one core at most). + pub work_secs: f64, + /// Merge accumulators and output, held while the job runs. + pub memory_bytes: f64, +} + +/// A plan as load over time. +#[derive(Debug, Clone)] +pub struct PlanLoad { + pub deployments: Vec, + /// Index-aligned with the plan's RAQEs. + pub queries: Vec, +} + +impl PlanLoad { + /// The load of `mapping` (one candidate index per RAQE). + pub fn new( + raqes: &[Raqe], + candidates: &[Deployment], + mapping: &Mapping, + facts: &WorkloadFacts, + ) -> PlanLoad { + let mut index: BTreeMap = BTreeMap::new(); + let mut deployments: Vec = Vec::new(); + let mut queries = Vec::with_capacity(raqes.len()); + for (raqe, &candidate) in raqes.iter().zip(mapping) { + let deployment = &candidates[candidate]; + let at = *index.entry(candidate).or_insert_with(|| { + let ingest = analytical_cost_model::ingest(deployment, facts); + let workers = analytical_cost_model::ingest_workers(deployment, facts); + deployments.push(DeploymentLoad { + ingest_cpu: ingest.cpu_secs_per_sec, + ingest_bytes: ingest.memory_bytes * workers, + storage_bytes: 0.0, + compaction_secs: analytical_cost_model::compaction_secs(deployment, facts), + slide_ms: deployment.slide_ms, + }); + deployments.len() - 1 + }); + let storage = analytical_cost_model::storage_bytes(raqe, deployment, facts); + let load = &mut deployments[at]; + load.storage_bytes = load.storage_bytes.max(storage); + queries.push(QueryLoad { + deployment: at, + interval_ms: raqe.interval_ms, + work_secs: analytical_cost_model::query_latency_ms(raqe, deployment, facts) + / 1000.0, + memory_bytes: analytical_cost_model::merge(raqe, deployment, facts).memory_bytes + + analytical_cost_model::query(raqe, deployment, facts).memory_bytes, + }); + } + PlanLoad { + deployments, + queries, + } + } + + /// Steady ingest CPU, vCPUs. + pub fn ingest_cpu(&self) -> f64 { + self.deployments.iter().map(|d| d.ingest_cpu).sum() + } + + /// Ingest and storage memory, held at all times, bytes. + pub fn static_bytes(&self) -> f64 { + self.deployments + .iter() + .map(|d| d.ingest_bytes + d.storage_bytes) + .sum() + } + + /// Mean CPU, vCPUs: ingest, compaction and queries, by use. + pub fn auc_cpu(&self) -> f64 { + self.ingest_cpu() + + self + .deployments + .iter() + .map(|d| d.compaction_secs / secs(d.slide_ms)) + .sum::() + + self + .queries + .iter() + .map(|q| q.work_secs / secs(q.interval_ms)) + .sum::() + } + + /// Mean memory, bytes: ingest and storage always, and each query's memory + /// for its run on one core (`work_secs`) every interval. + pub fn auc_bytes(&self) -> f64 { + self.static_bytes() + + self + .queries + .iter() + .map(|q| q.memory_bytes * q.work_secs / secs(q.interval_ms)) + .sum::() + } + + /// One firing's chain on its own cores, seconds: the newest window's + /// compaction, then the query. + pub fn chain_secs(&self, raqe: usize) -> f64 { + let q = &self.queries[raqe]; + self.deployments[q.deployment].compaction_secs + q.work_secs + } + + /// The longest chain, ms: the batch latency when CPU is elastic (cost + /// model 1). + pub fn longest_chain_ms(&self) -> f64 { + 1000.0 + * (0..self.queries.len()) + .map(|i| self.chain_secs(i)) + .fold(0.0, f64::max) + } + + /// `lcm` of every interval and slide, ms. + pub fn hyperperiod_ms(&self) -> Millis { + self.queries + .iter() + .map(|q| q.interval_ms) + .chain(self.deployments.iter().map(|d| d.slide_ms)) + .fold(1, lcm) + } + + /// Place every job of two hyperperiods on `cpu` vCPUs shared with ingest + /// (fluid, priority-ordered processor sharing; module docs). `None` when + /// ingest alone does not fit or the mean load exceeds `cpu`. + pub fn place(&self, cpu: f64) -> Option { + place(self, cpu) + } +} + +/// The outcome of [`PlanLoad::place`]. +#[derive(Debug, Clone)] +pub struct Placement { + /// Over batches: release until the batch's last query finishes, ms. + pub worst_batch_ms: f64, + /// Index-aligned with the RAQEs: its worst firing, ms. + pub raqe_latency_ms: Vec, + /// Peak CPU (ingest plus running jobs), vCPUs. + pub peak_cpu: f64, + /// Peak memory (ingest, storage and running queries' memory), bytes. + pub peak_bytes: f64, +} + +/// Cost model 1 (AUC) and cost model 2 (max) of a plan, with the latency +/// that goes with each. +#[derive(Debug, Clone)] +pub struct ModelCost { + pub cpu: f64, + pub bytes: f64, + /// `w_cpu · cpu + w_mem · GiB`. + pub value: f64, + pub latency_ms: f64, +} + +/// Cost model 1: CPU and memory billed by use. CPU is elastic, so every job +/// starts when ready and the latency is the longest chain. +pub fn cost_model_1(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> ModelCost { + let (cpu, bytes) = (load.auc_cpu(), load.auc_bytes()); + ModelCost { + cpu, + bytes, + value: w_cpu * cpu + w_mem * bytes / BYTES_PER_GIB, + latency_ms: load.longest_chain_ms(), + } +} + +/// Cost model 2: CPU and memory billed at the peak of a provisioned +/// `(C, M)`. `C` is the smallest at which the placement's worst batch meets +/// `sla_ms` (the mean CPU with no SLA), `M` the placement's peak memory. +/// `None` when a chain alone exceeds the SLA. +pub fn cost_model_2( + load: &PlanLoad, + w_cpu: f64, + w_mem: f64, + sla_ms: Option, +) -> Option { + let floor = load.auc_cpu(); + let placed = |cpu: f64| load.place(cpu).expect("at or above the mean load"); + let (cpu, placement) = match sla_ms { + None => (floor, placed(floor)), + Some(sla) => { + if load.longest_chain_ms() > sla { + return None; + } + let meets = |cpu: f64| placed(cpu).worst_batch_ms <= sla; + let mut hi = floor.max(f64::MIN_POSITIVE); + while !meets(hi) { + hi *= 2.0; + } + let mut lo = floor; + if meets(lo) { + hi = lo; + } + while hi - lo > 1e-4 * hi { + let mid = 0.5 * (lo + hi); + if meets(mid) { + hi = mid; + } else { + lo = mid; + } + } + (hi, placed(hi)) + } + }; + let bytes = placement.peak_bytes; + Some(ModelCost { + cpu, + bytes, + value: w_cpu * cpu + w_mem * bytes / BYTES_PER_GIB, + latency_ms: placement.worst_batch_ms, + }) +} + +fn secs(ms: Millis) -> f64 { + ms as f64 / 1000.0 +} + +fn gcd(a: Millis, b: Millis) -> Millis { + if b == 0 { + a + } else { + gcd(b, a % b) + } +} + +fn lcm(a: Millis, b: Millis) -> Millis { + a / gcd(a, b) * b +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Kind { + /// Compaction runs before queries: it unblocks them. + Compaction, + Query, +} + +#[derive(Debug, Clone)] +struct Job { + release: f64, + kind: Kind, + /// Query: its RAQE; compaction: its deployment. + owner: usize, + remaining: f64, + memory: f64, + /// Index of the compaction job this query waits for. + after: Option, + done_at: Option, +} + +/// Work below this many CPU-seconds counts as done (float residue). +const EPSILON_SECS: f64 = 1e-15; + +fn place(load: &PlanLoad, cpu: f64) -> Option { + let capacity = cpu - load.ingest_cpu(); + if capacity <= 0.0 || load.auc_cpu() > cpu * (1.0 + 1e-12) { + return None; + } + let horizon = 2 * load.hyperperiod_ms(); + let mut jobs: Vec = Vec::new(); + // Compaction of the window closing at `t`, per deployment. + let mut compaction_at: BTreeMap<(usize, Millis), usize> = BTreeMap::new(); + for (d, deployment) in load.deployments.iter().enumerate() { + if deployment.compaction_secs <= 0.0 { + continue; + } + for t in (0..horizon).step_by(deployment.slide_ms as usize) { + compaction_at.insert((d, t), jobs.len()); + jobs.push(Job { + release: secs(t), + kind: Kind::Compaction, + owner: d, + remaining: deployment.compaction_secs, + memory: 0.0, + after: None, + done_at: None, + }); + } + } + for (i, query) in load.queries.iter().enumerate() { + for t in (0..horizon).step_by(query.interval_ms as usize) { + jobs.push(Job { + release: secs(t), + kind: Kind::Query, + owner: i, + remaining: query.work_secs, + memory: query.memory_bytes, + after: compaction_at.get(&(query.deployment, t)).copied(), + done_at: None, + }); + } + } + let mut releases: Vec = jobs.iter().map(|j| j.release).collect(); + releases.sort_by(f64::total_cmp); + releases.dedup(); + + let static_bytes = load.static_bytes(); + let (mut peak_cpu, mut peak_bytes) = (load.ingest_cpu(), static_bytes); + let mut now = 0.0; + let mut next_release = 0; + loop { + while next_release < releases.len() && releases[next_release] <= now { + next_release += 1; + } + let mut ready: Vec = (0..jobs.len()) + .filter(|&j| { + let job = &jobs[j]; + job.done_at.is_none() + && job.release <= now + && job.after.is_none_or(|c| jobs[c].done_at.is_some()) + }) + .collect(); + if ready.is_empty() && next_release == releases.len() { + break; + } + // Older first, compaction before queries, then longest first. + ready.sort_by(|&a, &b| { + let (a, b) = (&jobs[a], &jobs[b]); + a.release + .total_cmp(&b.release) + .then(a.kind.cmp(&b.kind)) + .then(b.remaining.total_cmp(&a.remaining)) + }); + let mut left = capacity; + let mut rates: Vec<(usize, f64)> = Vec::new(); + for &j in &ready { + if left <= 0.0 { + break; + } + let rate = left.min(1.0); + rates.push((j, rate)); + left -= rate; + } + let running_cpu: f64 = rates.iter().map(|&(_, r)| r).sum(); + let running_bytes: f64 = rates.iter().map(|&(j, _)| jobs[j].memory).sum(); + peak_cpu = peak_cpu.max(load.ingest_cpu() + running_cpu); + peak_bytes = peak_bytes.max(static_bytes + running_bytes); + let finish = rates + .iter() + .map(|&(j, r)| jobs[j].remaining / r) + .fold(f64::INFINITY, f64::min); + let release = releases.get(next_release).copied().unwrap_or(f64::INFINITY); + let step = finish.min(release - now); + for &(j, r) in &rates { + let job = &mut jobs[j]; + job.remaining -= r * step; + if job.remaining <= EPSILON_SECS.max(1e-12 * r * step) { + job.remaining = 0.0; + job.done_at = Some(now + step); + } + } + now += step; + } + + let mut batches: BTreeMap = BTreeMap::new(); + let mut raqe_latency_ms = vec![0.0f64; load.queries.len()]; + for job in jobs.iter().filter(|j| j.kind == Kind::Query) { + let latency_ms = 1000.0 * (job.done_at.expect("every job finishes") - job.release); + let batch = batches.entry(job.release.to_bits()).or_insert(0.0); + *batch = batch.max(latency_ms); + raqe_latency_ms[job.owner] = raqe_latency_ms[job.owner].max(latency_ms); + } + Some(Placement { + worst_batch_ms: batches.values().copied().fold(0.0, f64::max), + raqe_latency_ms, + peak_cpu, + peak_bytes, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn load(ingest_cpu: f64, compaction_secs: f64, queries: &[(Millis, f64)]) -> PlanLoad { + PlanLoad { + deployments: vec![DeploymentLoad { + ingest_cpu, + ingest_bytes: 10.0, + storage_bytes: 5.0, + compaction_secs, + slide_ms: 1_000, + }], + queries: queries + .iter() + .map(|&(interval_ms, work_secs)| QueryLoad { + deployment: 0, + interval_ms, + work_secs, + memory_bytes: 100.0, + }) + .collect(), + } + } + + #[test] + fn a_job_uses_at_most_one_core_and_slows_on_a_fraction() { + // Ingest 0.5 vCPU; one 0.1 s query every second. + let plan = load(0.5, 0.0, &[(1_000, 0.1)]); + let full = plan.place(1.5).unwrap(); + assert!( + (full.worst_batch_ms - 100.0).abs() < 1e-6, + "{}", + full.worst_batch_ms + ); + // More capacity doesn't help a one-core job. + assert!((plan.place(4.0).unwrap().worst_batch_ms - 100.0).abs() < 1e-6); + // 0.25 vCPU left for it: 0.4 s. + let quarter = plan.place(0.75).unwrap(); + assert!( + (quarter.worst_batch_ms - 400.0).abs() < 1e-6, + "{}", + quarter.worst_batch_ms + ); + assert!((quarter.peak_cpu - 0.75).abs() < 1e-9); + assert_eq!(quarter.peak_bytes, 15.0 + 100.0); + } + + #[test] + fn a_batch_shares_the_capacity_and_longest_runs_first() { + // Two queries of 0.3 s and 0.1 s every second on one free core: the + // batch ends at 0.4 s, the long one first (0.3 s). + let plan = load(0.0, 0.0, &[(1_000, 0.1), (1_000, 0.3)]); + let placed = plan.place(1.0).unwrap(); + assert!((placed.worst_batch_ms - 400.0).abs() < 1e-6); + assert!((placed.raqe_latency_ms[1] - 300.0).abs() < 1e-6); + // Two cores: each on its own. + assert!((plan.place(2.0).unwrap().worst_batch_ms - 300.0).abs() < 1e-6); + } + + #[test] + fn a_query_waits_for_the_newest_windows_compaction() { + // Compaction 0.2 s each second, then a 0.1 s query: 0.3 s. + let plan = load(0.0, 0.2, &[(1_000, 0.1)]); + assert!((plan.place(2.0).unwrap().worst_batch_ms - 300.0).abs() < 1e-6); + assert!((plan.longest_chain_ms() - 300.0).abs() < 1e-9); + } + + #[test] + fn the_aligned_batch_is_the_worst_and_backlog_carries_over() { + // Every second 0.5 s of work, every 2 s another 0.5 s, on one core: + // the aligned batch (t = 0, 2 s) takes 1 s; the other batches 0.5 s. + let plan = load(0.0, 0.0, &[(1_000, 0.5), (2_000, 0.5)]); + let placed = plan.place(1.0).unwrap(); + assert!( + (placed.worst_batch_ms - 1000.0).abs() < 1e-6, + "{}", + placed.worst_batch_ms + ); + // Below the mean load (0.75 vCPU) there is no placement. + assert!(plan.place(0.7).is_none()); + } + + #[test] + fn cost_models_bill_use_and_peak() { + let plan = load(0.5, 0.0, &[(1_000, 0.1)]); + let one = cost_model_1(&plan, 1.0, 0.0); + assert!((one.cpu - 0.6).abs() < 1e-12); + // Memory by use: 15 bytes always, 100 bytes for 0.1 s each second. + assert!((one.bytes - 25.0).abs() < 1e-12); + assert!((one.latency_ms - 100.0).abs() < 1e-9); + // Cost model 2 with no SLA: the mean CPU, and the queue it gives. + let two = cost_model_2(&plan, 1.0, 0.0, None).unwrap(); + assert!((two.cpu - 0.6).abs() < 1e-12); + assert!((two.latency_ms - 1000.0).abs() < 1e-6, "{}", two.latency_ms); + // A 200 ms SLA: the query needs 0.5 vCPU beside ingest, C = 1.0. + let tight = cost_model_2(&plan, 1.0, 0.0, Some(200.0)).unwrap(); + assert!((tight.cpu - 1.0).abs() < 1e-3, "{}", tight.cpu); + assert!(tight.latency_ms <= 200.0); + // Below the chain, infeasible. + assert!(cost_model_2(&plan, 1.0, 0.0, Some(50.0)).is_none()); + } +} From 2fa364077f1ae974ca4b09a3cf336e624630f9a7 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:12:44 +0000 Subject: [PATCH 07/18] docs: restructure the section as a design doc Title 'MILP with latency SLA constraints: cost models, query placement and batch latency'; in order: definitions, the two cost models, CPU and memory parts and how each is computed, batch latency vs. the SLA, the job placement algorithm, the MILP formulation, and the solution method (cost model 1 exact; cost model 2 surrogate, placement sizing and correction passes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 284 +++++++++++++++++-------------- 1 file changed, 157 insertions(+), 127 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 3a21ee99..aeaea0bb 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -359,167 +359,197 @@ evaluates at once. The default weights are `(1, 0)`: CPU only. Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. -### Cost models, batch latency and query placement (design, under review) +### MILP with latency SLA constraints: cost models, query placement and batch latency Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in -`placement` (load, cost models, placement) and `milp::minimize_cost_model`. - -**Scope.** Evaluated on the synthetic mixed template set (spatial templates -every 1 s, temporal ones every 1 min, so the hyperperiod is `H = lcm(T_i) = -60 s`). Methods: ASAP (this MILP, with sharing), PerQuery (the same MILP -without sharing), AutoSketch-Adapted (fixed configs chosen by memory). Each is -evaluated under cost model 1 and cost model 2, each with no latency SLA and -with an SLA `L`. - -**Load over time.** - -- Ingest is the precompute: every sample is inserted into its open window - instances as it arrives. Deployment `D`'s ingest is - `ρ_D = λ_D · (x/y) · c_ins` vCPUs. -- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers, at most one core each, split - by sample: each worker reads a share of the input (e.g. some Kafka - partitions or scrape targets) with no shuffle by group, so it keeps its own - open window instance of every group it sees. When a window closes (the - watermark passes its end), a compaction job merges the `k_D` partial - instances of each group into one stored instance: - `(k_D − 1) · card(G) · c_mrg` CPU-seconds, at most one core. With - `k_D = 1` there is no compaction. -- Each firing of RAQE `i` at `t = k · T_i` releases one query job `Q_i`: merge - the `S/x` stored instances of each group for the query window, then - estimate, at most one core. Its CPU work is - `ℓ_i = card(G) · (c_qry + (S/x − 1) · c_mrg)`, the per-RAQE `latency_i` - below; merging is part of the query. -- `Q_i` reads the newest window, which closes at `t`, so it starts only after - that window's compaction finishes. -- A batch is all query jobs released at one instant; the heaviest, `B0`, is - at `t = 0`, when every RAQE fires. A batch's latency is the time from its - release until its last `Q_i` finishes; the reported query latency is the - worst batch latency. - -**Memory, three parts, each counted once.** For deployment `D` with `m` bytes -per instance: +`rqe-optimizer/src/placement.rs` (load, cost models, placement) and +`milp::minimize_cost_model`. It extends the MILP above with two cost models +and a latency SLA on a whole batch of queries. Evaluated first on the +synthetic mixed template set; methods: ASAP (this MILP, with sharing), +PerQuery (the same MILP without sharing) and AutoSketch-Adapted (fixed +configs chosen by memory). -| Part | What | Bytes | Held | -|---|---|---|---| -| Ingest | open windows, one copy per worker | `card(G) · m · (x/y) · k_D` | always | -| Storage | closed windows kept for lookbacks (compacted, one copy) | `card(G) · m · ((max S − x)/y + 1)` | always | -| Query | the merge accumulators `Q_i` creates (none for a direct query), and its output | `card(G) · m` + output | while `Q_i` runs | - -A window counts as ingest memory while open and as storage once compacted. -A query reads stored instances in place; only the accumulators its merge -creates are query memory. +#### 1. Definitions -**Measurement assumptions (sketch-bench as is).** Every sketch operation is +| Symbol | Meaning | +|---|---| +| `D`, `i` | a candidate deployment; a RAQE | +| `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | +| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | +| `card(G)` | groups of `D`'s grouping (one instance per group per window; one for a sketch shared by all groups) | +| `λ_D` | samples/s arriving for `D`'s metric | +| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | +| `m` | measured bytes per instance | +| `n_{i,D} = S_i / x_D` | windows a query merges | +| `H = lcm(T_i, y_D)` | hyperperiod: the release pattern repeats every `H` | +| batch | all query jobs released at one instant; `B0` is the one at `t = 0`, where every RAQE fires | + +**Measurement assumption (sketch-bench as is).** Every sketch operation is single-threaded and compute-bound: sketch-bench's CPU time equals its wall time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses -at most one core, and on a full core it takes its CPU time; the cost table's +at most one core and, on a full core, takes its CPU time. The cost table's `*_cpu_secs` are all the model needs. -**Cost model 1 (AUC: `w1 · AUC(CPU) + w2 · AUC(mem)`).** CPU is elastic and -billed by use, so every job starts when it is ready, on its own core: +#### 2. Cost models + +- **Cost model 1 (by use):** `w1 · AUC(CPU) + w2 · AUC(memory)`, the mean + vCPUs and GiB over time. CPU is elastic: a job gets a core whenever it is + ready. +- **Cost model 2 (by peak):** `w1 · max(CPU) + w2 · max(memory)`. The plan + provisions a resource point `(C vCPU, M GiB)`, billed at that peak, and all + of its work shares it. -- `AUC(CPU) = Σ_D ρ_D + Σ_D compaction_D / y + Σ_i ℓ_i / T_i`, fixed by the - plan (compaction is the only addition, from parallel ingest). -- `AUC(mem) = Σ_D (ingest + storage)_D + Σ_i (query memory_i × duration_i) / T_i`. - Parallel ingest raises it through the `k_D` open copies. -- A batch's latency is its longest `compaction + Q_i` chain, so an SLA `L` - only forbids pairs with `(k_D − 1) · card(G) · c_mrg + ℓ_{i,D} > L` - (`z_{i,D} = 0`). No resource point is needed. +`w1`, `w2` are per vCPU and per GiB (CPU only: `(1, 0)`; Fargate prices). -**Cost model 2 (max: `w1 · max(CPU) + w2 · max(mem)`).** The plan provisions -a resource point `(C vCPU, M GiB)`, billed at its peak; ingest, compaction and -queries share it. The placement below gives the latency. +#### 3. CPU: parts and how each is computed + +| Part | When | CPU-seconds | Mean vCPUs | +|---|---|---|---| +| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | +| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts instances · c_mrg` | `c_D / y_D` | +| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · (c_qry + (n_{i,D} − 1) · c_mrg)` | `ℓ_{i,D} / T_i` | + +- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at + most one core), **split by sample**: each worker reads a share of the input + (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so + it keeps its own open window instance of every group it sees. +- When a window closes (the watermark passes its end), a **compaction** job + merges the `k_D` partial instances of each group into one stored instance. + With `k_D = 1` there is none. +- Each firing of RAQE `i` releases one **query job**: merge the `n_{i,D}` + stored instances of each group for the query window, then estimate. Merging + is part of the query. It reads the newest window, which closes at the firing + time, so it starts after that window's compaction. + +`AUC(CPU) = Σ_D (ρ_D + c_D / y_D) + Σ_i ℓ_{i,D} / T_i`. It is fixed by the +plan, whatever the schedule. + +#### 4. Memory: parts and how each is computed + +Each part is counted once: a window counts as ingest memory while open and as +storage once compacted, and a query reads stored instances in place. + +| Part | What | Bytes | Held | +|---|---|---|---| +| Ingest | open windows, one copy per worker | `I_D = card(G) · m · (x_D / y_D) · k_D` | always | +| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i card(G) · m · ((S_i − x_D) / y_D + 1)` | always | +| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = card(G) · m · [n_{i,D} > 1] + output` | while the query job runs | -**Placement algorithm, given a resource point (C vCPU, M GiB).** Capacity is -fractional; jobs share it as rates (fluid, priority-ordered processor +`AUC(memory) = Σ_D (I_D + stored_D) + Σ_i q_{i,D} · (run time) / T_i`. Under +cost model 1 a query job runs on its own core, so its run time is `ℓ_{i,D}`. +Under cost model 2 memory is the peak the placement reaches. + +#### 5. Batch latency and the SLA + +A batch's **latency** is the time from its release until its last query job +finishes, compaction included. The **query latency** of a plan is its worst +batch latency over the hyperperiod. A latency SLA `L` requires query latency +`≤ L`. + +- Cost model 1: CPU is elastic, so no job waits for a core. A batch's latency + is its longest **chain** `c_D + ℓ_{i,D}` (the newest window's compaction, + then the query), and the SLA requires `c_D + ℓ_{i,D} ≤ L` for every + assigned pair. +- Cost model 2: jobs share the provisioned capacity, so the latency comes from + the placement (§6). + +#### 6. Job placement algorithm (cost model 2) + +Given a resource point `(C, M)`, the placement finds when each job runs and +gives every batch's latency and the CPU and memory over time. Capacity is +fractional; running jobs share it as rates (fluid, priority-ordered processor sharing). ```text -capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0 and the mean load - at most C, else infeasible) +capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0 and the + mean load at most C, else infeasible) simulate 2 hyperperiods, event-driven (events: releases, completions): ready = compaction jobs (released at window closes) + query jobs whose newest window is compacted order: release time (older first), then compaction before query (it unblocks queries), then longest remaining work first give rates in that order: job j gets a_j = min(1, K − rates already given) - (memory is not a limit here: `M` is set to the peak the placement reaches) a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event -outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t), MEM(t) +outputs: per-RAQE and per-batch latency, worst batch latency, + CPU(t) = Σ ρ_D + Σ a_j, MEM(t) = Σ (I_D + stored_D) + Σ q of running jobs ``` Two hyperperiods are simulated so that work carried over the wrap-around is -counted. +counted. A job uses at most one core, so with `K ≥ 1` a batch on its own ends +within `Σ work / K + max chain` (Graham's list-scheduling bound). -**MILP.** The variables are the existing `z_{i,D}` (RAQE `i` uses candidate -`D`), `u_D` (`D` is active) and `stored_D`; cost model 2 adds `C` and `M` -(continuous). Per candidate the model reads constants: ingest CPU `ρ_D`, -workers `k_D = ⌈ρ_D⌉`, ingest memory `I_D` (open windows × `k_D`), compaction -`c_D = (k_D − 1) · Σ instances · c_mrg` per closed window, every `y_D`; per -pair: the query job's work `ℓ_{i,D}`, its memory `q_{i,D}` (merge -accumulators and output) and storage `s_{i,D}`. +#### 7. MILP formulation -Cost model 1 (by use; CPU elastic): +Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), +`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`; cost model 2 adds `C, M ≥ 0`. +Constants per candidate and pair are §3 and §4's. + +Common rows: ```text -minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D I_D · u_D + Σ_D stored_D + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] -s.t. the assignment rows above; stored_D ≥ s_{i,D} · z_{i,D} -with SLA L: z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) +Σ_D z_{i,D} = 1 for every RAQE i +z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E +stored_D ≥ card(G)·m·((S_i − x_D)/y_D + 1) · z_{i,D} +with SLA L: z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) ``` -Every term is linear, so this is exact: with elastic CPU a batch's latency is -its longest chain `c_D + ℓ_{i,D}`. +Cost model 1: + +```text +minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +``` -Cost model 2 (provisioned `(C, M)`, billed at the peak): +Cost model 2: ```text minimize w1 · C + w2 · M -s.t. the assignment rows; stored_D ≥ s_{i,D} · z_{i,D} - C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) - M ≥ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} (every query at once) +s.t. C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) + M ≥ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} + δ_M (memory) with SLA L: - z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) - Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ≤ L · (C − Σ_D ρ_D · u_D) (the aligned batch fits) + C ≥ Σ_D ρ_D · u_D + ( Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ) / L + δ_C (batch B0) ``` -The batch row is linear (`L` is a constant). It is a surrogate: it treats the -heaviest batch's work as divisible, and the memory row holds every query at -once. So the MILP's `(C, M)` is not what the chosen mapping really needs. The -placement sizes it exactly, for every method alike: `C` is the smallest at -which the placement's worst batch meets `L` (binary search; with jobs capped at -one core, list scheduling ends within `Σ work / K + max chain`, so it exists -whenever every chain fits), and `M` is the placement's peak memory. Without an -SLA, `C` is the mean load and the placement reports the latency it gives. - -**Correction passes (cost model 2).** The MILP minimizes the surrogate peaks, -which may rank mappings differently from their placed peaks. So -`milp::minimize_cost_model` iterates: - -1. Solve the MILP; take its mapping and size its real `(C*, M*)` with the - placement. Cost `w1 · C* + w2 · M*`. -2. Measure the surrogate's error on that mapping: `δ_C = C* − Ĉ`, - `δ_M = M* − M̂`, where `Ĉ = max(mean load, ρ_ing + batch work / L)` and - `M̂ = ingest + storage + every query's memory` are the rows' values. -3. Add the errors back to the rows (`C ≥ ρ_ing + batch work / L + δ_C`, - `M ≥ … + δ_M`) and solve again. -4. Keep the mapping with the lowest placed cost; stop when a mapping repeats, - or after three corrections. - -Cost model 1 needs none of this: with elastic CPU every term is linear and -exact (CPU and memory by use, latency the longest chain). - -- PerQuery: the same MILP over single-RAQE candidates only (no sharing). -- AutoSketch: fixed configs, chosen by memory; priced by the same functions - (cost model 1 by use; cost model 2 by the placement and binary search). - -**Outputs.** Per (method, cost model, SLA): cost; mean and peak CPU and -memory; the resource point; worst batch and per-RAQE latency; solve and -verify iterations; planning time. Figure: cost vs. worst batch latency, one -line per method, one panel per cost model and weight setting. - -**Decided.** Synthetic mixed set first; the Alibaba and Google traces later. +`δ_C = δ_M = 0` in the first solve (§8). Every row is linear: `L` is a +constant. + +#### 8. Solution method + +**Cost model 1** is solved exactly: with elastic CPU every term is linear, +and the SLA is a filter on pairs. + +**Cost model 2** cannot be solved exactly by this MILP: a peak depends on when +jobs run, which is a scheduling problem. A time-indexed MILP (a variable per +job per time slot) would be exact, but µs–ms jobs over a 60 s hyperperiod +make it far too large. So the MILP is a linear surrogate: its batch row treats +`B0`'s work as divisible over the capacity ingest leaves, and its memory row +holds every query at once. The plan is then sized and corrected with the +placement: + +1. **Solve** the MILP and take its mapping. +2. **Size** the mapping with the placement: `C*` is the smallest `C` at which + the worst batch meets `L` (binary search; it exists whenever every chain + fits); `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is + the mean load and the placement reports the latency it gives. The plan's + cost is `w1 · C* + w2 · M*`. +3. **Correct:** measure the surrogate's error on that mapping, + `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add + them to the rows and solve again. +4. **Keep** the mapping with the lowest placed cost; stop when a mapping + repeats, or after three corrections. + +**PerQuery** is the same MILP over single-RAQE candidates only (no sharing). +**AutoSketch** keeps its memory-chosen configs and is priced by the same +functions: cost model 1 by use (latency its longest chain); cost model 2 by +the placement and the binary search on `C`. + +#### 9. Outputs + +Per (method, cost model, SLA): cost; mean and peak CPU and memory; the +resource point; worst batch and per-RAQE latency; MILP solves; planning time. +Figure: cost vs. query latency, one line per method, one panel per cost model +and weight setting. ## Analytical cost model @@ -657,8 +687,8 @@ latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg summed over the sketch and its key tracker, if any. On its own it is not a wall-clock SLA: it assumes no parallel execution across -groups and no cheaper k-way merge. Under the placement design above it is one -firing's query job (merge, then estimate) on one core. +groups and no cheaper k-way merge. In the cost-model section above it is one +firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. ## Procedure @@ -687,8 +717,8 @@ each phase's CPU and memory, together with the selected deployment mapping. largest shard count and N the study measured merge curves at (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds; a batch - SLA with two cost models and query placement is under review (above). The +- **Latency SLAs:** `minimize` takes optional per-RAQE latency bounds; + `minimize_cost_model` takes a batch SLA under cost model 1 or 2 (above). The enumerator reports latency but does not reject a mapping for it. - **Memory model:** query memory sums every RAQE's merge and output memory, as if all queries run at once; real concurrency is not modeled. Query output From 2dae35a194870dd119a5c4e45ab743de449d3c9f Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:13:17 +0000 Subject: [PATCH 08/18] docs: plain-English explanation for every formula and the placement algorithm Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 83 +++++++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 1 deletion(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index aeaea0bb..214d88dc 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -424,6 +424,18 @@ at most one core and, on a full core, takes its CPU time. The cost table's `AUC(CPU) = Σ_D (ρ_D + c_D / y_D) + Σ_i ℓ_{i,D} / T_i`. It is fixed by the plan, whatever the schedule. +In words: + +- `ρ_D`: every second, `λ_D` samples arrive, and each is inserted into the + `x_D / y_D` windows still open, at `c_ins` each. +- `c_D`: closing a window merges, for every instance, the `k_D` workers' + partial copies into one, which takes `k_D − 1` merges. This happens once + per slide. +- `ℓ_{i,D}`: for each of the `card(G)` groups, a query merges its + `n_{i,D}` stored windows (`n − 1` merges), then answers once. This happens + once per interval. +- `AUC(CPU)` adds the three rates: work per second, in vCPUs. + #### 4. Memory: parts and how each is computed Each part is counted once: a window counts as ingest memory while open and as @@ -439,6 +451,17 @@ storage once compacted, and a query reads stored instances in place. cost model 1 a query job runs on its own core, so its run time is `ℓ_{i,D}`. Under cost model 2 memory is the peak the placement reaches. +In words: + +- `I_D`: every worker keeps one instance per group for each of the + `x_D / y_D` windows still open, and there are `k_D` workers. +- `stored_D`: closed windows are kept until the longest lookback that `D` + serves no longer needs them. That is `(S − x)/y + 1` windows per group. +- `q_{i,D}`: a merge builds one accumulator per group (a direct query, with + `n = 1`, reads the stored window and needs none), plus the answer. +- `AUC(memory)`: ingest and storage are held all the time. A query's memory + is held only while it runs, a fraction `run time / T_i` of the time. + #### 5. Batch latency and the SLA A batch's **latency** is the time from its release until its last query job @@ -475,6 +498,30 @@ outputs: per-RAQE and per-batch latency, worst batch latency, CPU(t) = Σ ρ_D + Σ a_j, MEM(t) = Σ (I_D + stored_D) + Σ q of running jobs ``` +In words: + +1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs off + the top; the rest, `K`, which may be a fraction, is shared by compaction + and query jobs. If the plan's mean load does not fit in `C`, there is no + placement. +2. **Release jobs.** Each window close releases a compaction job for its + deployment. Each firing releases a query job, which becomes ready only once + its deployment's newest window is compacted. +3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. + Within a batch, compaction runs before queries, because queries wait for + it. Then the longest remaining work runs first, so a long job doesn't end + up running alone at the end of the batch. +4. **Share capacity as rates.** In that order, each job gets up to one core + (a single-threaded job can't use more) from the capacity still free. The + last one served may get only a fraction and runs slower in proportion. +5. **Advance to the next event.** Time jumps to the next release or the + earliest finishing job, everyone's remaining work drops by rate × elapsed + time, and the rates are recomputed. +6. **Read off the results.** A query's latency is its finish minus its + release, and a batch's latency is that of its last query. The CPU in use + is ingest plus the rates; the memory is ingest, storage and the running + queries' memory. + Two hyperperiods are simulated so that work carried over the wrap-around is counted. A job uses at most one core, so with `K ≥ 1` a batch on its own ends within `Σ work / K + max chain` (Graham's list-scheduling bound). @@ -494,6 +541,17 @@ stored_D ≥ card(G)·m·((S_i − x_D)/y_D + 1) · z_{i,D} with SLA L: z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) ``` +In words: + +- Every RAQE is served by exactly one eligible deployment. +- A deployment is active if and only if some RAQE uses it, so its ingest is + paid once, however many RAQEs share it. +- A deployment stores enough closed windows for the longest lookback it + serves (a linearized max). +- Under an SLA, a pair whose own chain (the newest window's compaction, then + the query, each on a full core) is longer than `L` can never meet it, so it + is ruled out. + Cost model 1: ```text @@ -501,6 +559,12 @@ minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · + w2 · [ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] ``` +In words: the price of the mean vCPUs (ingest and compaction per active +deployment, plus each RAQE's query work per second), plus the price of the +mean memory (ingest and storage per active deployment, plus each query's +memory for the fraction of time it runs). With elastic CPU this is the cost +exactly, and the SLA is fully handled by the chain row above. + Cost model 2: ```text @@ -514,6 +578,19 @@ with SLA L: `δ_C = δ_M = 0` in the first solve (§8). Every row is linear: `L` is a constant. +In words: + +- The objective prices the provisioned peak, `C` vCPUs and `M` GiB. +- **Mean load:** the capacity must at least carry the average work, or a + backlog grows without bound. +- **Memory:** the capacity must hold ingest and storage, plus every query's + memory as if all ran at once (an upper bound on the peak). +- **Batch `B0`:** when every RAQE fires together, ingest keeps + `Σ ρ_D · u_D` vCPUs busy. The rest must finish the batch's queries and + compactions within `L`, so `C − ingest ≥ batch work / L`. This treats the + batch as divisible over the free capacity, which is a necessary condition. + §8 corrects it. + #### 8. Solution method **Cost model 1** is solved exactly: with elastic CPU every term is linear, @@ -535,7 +612,11 @@ placement: cost is `w1 · C* + w2 · M*`. 3. **Correct:** measure the surrogate's error on that mapping, `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add - them to the rows and solve again. + them to the rows and solve again. In words: the first solve may favor a + mapping whose real peak is higher than the rows said (jobs can't be split, + and queries wait for compaction), or penalize one whose real memory peak is + lower (not every query runs at once). Adding the observed gap lets the + next solve rank mappings closer to their placed cost. 4. **Keep** the mapping with the lowest placed cost; stop when a mapping repeats, or after three corrections. From 5a2ad5f9083e48dc59237b7f0eaf3d972c3291a4 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:18:17 +0000 Subject: [PATCH 09/18] docs, placement: one job placement for both cost models Cost model 1 is the placement with unlimited capacity (elastic CPU): every job starts when ready on its own core, so the latency is the longest chain and the closed form the MILP uses is exact; cost model 2 runs it with the provisioned C. A test checks the closed form against the placement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 28 +++++++++++++++++++--------- rqe-optimizer/src/placement.rs | 19 ++++++++++++++++--- 2 files changed, 35 insertions(+), 12 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 214d88dc..1029b19c 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -469,17 +469,21 @@ finishes, compaction included. The **query latency** of a plan is its worst batch latency over the hyperperiod. A latency SLA `L` requires query latency `≤ L`. -- Cost model 1: CPU is elastic, so no job waits for a core. A batch's latency - is its longest **chain** `c_D + ℓ_{i,D}` (the newest window's compaction, - then the query), and the SLA requires `c_D + ℓ_{i,D} ≤ L` for every - assigned pair. -- Cost model 2: jobs share the provisioned capacity, so the latency comes from - the placement (§6). +Both cost models get the latency from the same job placement (§6); they +differ only in the CPU capacity it is given: -#### 6. Job placement algorithm (cost model 2) +- Cost model 1: CPU is elastic, so the placement runs with unlimited capacity + and no job waits for a core. A batch's latency is then its longest + **chain** `c_D + ℓ_{i,D}` (the newest window's compaction, then the query), + and the SLA requires `c_D + ℓ_{i,D} ≤ L` for every assigned pair. +- Cost model 2: jobs share the provisioned capacity `C`, so they may queue, + and the latency is whatever the placement gives. -Given a resource point `(C, M)`, the placement finds when each job runs and -gives every batch's latency and the CPU and memory over time. Capacity is +#### 6. Job placement algorithm (both cost models) + +Given a CPU capacity, the placement finds when each job runs and gives every +batch's latency and the CPU and memory over time. Cost model 1 runs it with +unlimited capacity (elastic CPU); cost model 2 with the provisioned `C`. Capacity is fractional; running jobs share it as rates (fluid, priority-ordered processor sharing). @@ -526,6 +530,12 @@ Two hyperperiods are simulated so that work carried over the wrap-around is counted. A job uses at most one core, so with `K ≥ 1` a batch on its own ends within `Σ work / K + max chain` (Graham's list-scheduling bound). +With unlimited capacity (cost model 1) the placement has a closed form: every +job starts when ready on its own core, so a query runs for exactly +`ℓ_{i,D}`, a batch's latency is its longest chain, and the memory over time +averages to §4's `AUC(memory)`. That is why cost model 1's MILP below is +exact. + #### 7. MILP formulation Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs index 6697af74..54219c9c 100644 --- a/rqe-optimizer/src/placement.rs +++ b/rqe-optimizer/src/placement.rs @@ -1,6 +1,9 @@ //! A plan's load over time, its cost under cost models 1 and 2, and the query //! placement that gives its batch latency (`docs/rqe_sketch_deployment_v1.md`, -//! "Cost models, batch latency and query placement"). +//! "MILP with latency SLA constraints: cost models, query placement and batch +//! latency"). Both cost models use the placement: cost model 1 with unlimited +//! capacity, which has the closed form [`cost_model_1`] uses, and cost model 2 +//! with the provisioned `C`. //! //! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. //! Each closed window is compacted (the workers' partials merged into one), and @@ -187,8 +190,9 @@ pub struct ModelCost { pub latency_ms: f64, } -/// Cost model 1: CPU and memory billed by use. CPU is elastic, so every job -/// starts when ready and the latency is the longest chain. +/// Cost model 1: CPU and memory billed by use. CPU is elastic: the placement +/// with unlimited capacity, where every job starts when ready on its own core, +/// so the latency is the longest chain and each query runs for its work. pub fn cost_model_1(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> ModelCost { let (cpu, bytes) = (load.auc_cpu(), load.auc_bytes()); ModelCost { @@ -485,6 +489,15 @@ mod tests { assert!(plan.place(0.7).is_none()); } + #[test] + fn unlimited_capacity_gives_cost_model_1s_closed_form() { + // Compaction 0.2 s each second; queries of 0.1 s, 0.5 s and 0.3 s. + let plan = load(0.5, 0.2, &[(1_000, 0.1), (2_000, 0.5), (1_000, 0.3)]); + let placed = plan.place(1e9).unwrap(); + assert!((placed.worst_batch_ms - plan.longest_chain_ms()).abs() < 1e-6); + assert!((cost_model_1(&plan, 1.0, 0.0).latency_ms - placed.worst_batch_ms).abs() < 1e-6); + } + #[test] fn cost_models_bill_use_and_peak() { let plan = load(0.5, 0.0, &[(1_000, 0.1)]); From e9bd6d1de47924724a148720be479184ac1ceefd Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:19:17 +0000 Subject: [PATCH 10/18] docs, placement: a query is issued, not released Queries are issued at their firing time; compaction is triggered at a window close. The doc section and placement.rs use these terms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 22 +++++++++---------- rqe-optimizer/src/placement.rs | 37 ++++++++++++++++---------------- 2 files changed, 30 insertions(+), 29 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 1029b19c..8ca6bc56 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -381,8 +381,8 @@ configs chosen by memory). | `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | | `m` | measured bytes per instance | | `n_{i,D} = S_i / x_D` | windows a query merges | -| `H = lcm(T_i, y_D)` | hyperperiod: the release pattern repeats every `H` | -| batch | all query jobs released at one instant; `B0` is the one at `t = 0`, where every RAQE fires | +| `H = lcm(T_i, y_D)` | hyperperiod: the pattern of query issues and window closes repeats every `H` | +| batch | all query jobs issued at one instant; `B0` is the one at `t = 0`, where every RAQE fires | **Measurement assumption (sketch-bench as is).** Every sketch operation is single-threaded and compute-bound: sketch-bench's CPU time equals its wall @@ -416,7 +416,7 @@ at most one core and, on a full core, takes its CPU time. The cost table's - When a window closes (the watermark passes its end), a **compaction** job merges the `k_D` partial instances of each group into one stored instance. With `k_D = 1` there is none. -- Each firing of RAQE `i` releases one **query job**: merge the `n_{i,D}` +- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` stored instances of each group for the query window, then estimate. Merging is part of the query. It reads the newest window, which closes at the firing time, so it starts after that window's compaction. @@ -464,7 +464,7 @@ In words: #### 5. Batch latency and the SLA -A batch's **latency** is the time from its release until its last query job +A batch's **latency** is the time from its issue until its last query job finishes, compaction included. The **query latency** of a plan is its worst batch latency over the hyperperiod. A latency SLA `L` requires query latency `≤ L`. @@ -490,10 +490,10 @@ sharing). ```text capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0 and the mean load at most C, else infeasible) -simulate 2 hyperperiods, event-driven (events: releases, completions): - ready = compaction jobs (released at window closes) +simulate 2 hyperperiods, event-driven (events: query issues, window closes, completions): + ready = compaction jobs (triggered at window closes) + query jobs whose newest window is compacted - order: release time (older first), then compaction before query + order: issue / trigger time (older first), then compaction before query (it unblocks queries), then longest remaining work first give rates in that order: job j gets a_j = min(1, K − rates already given) a job at rate a_j finishes when its remaining work / a_j elapses @@ -508,8 +508,8 @@ In words: the top; the rest, `K`, which may be a fraction, is shared by compaction and query jobs. If the plan's mean load does not fit in `C`, there is no placement. -2. **Release jobs.** Each window close releases a compaction job for its - deployment. Each firing releases a query job, which becomes ready only once +2. **Issue jobs.** Each window close triggers a compaction job for its + deployment. Each firing issues a query job, which becomes ready only once its deployment's newest window is compacted. 3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. Within a batch, compaction runs before queries, because queries wait for @@ -518,11 +518,11 @@ In words: 4. **Share capacity as rates.** In that order, each job gets up to one core (a single-threaded job can't use more) from the capacity still free. The last one served may get only a fraction and runs slower in proportion. -5. **Advance to the next event.** Time jumps to the next release or the +5. **Advance to the next event.** Time jumps to the next query issue or window close, or the earliest finishing job, everyone's remaining work drops by rate × elapsed time, and the rates are recomputed. 6. **Read off the results.** A query's latency is its finish minus its - release, and a batch's latency is that of its last query. The CPU in use + issue, and a batch's latency is that of its last query. The CPU in use is ingest plus the rates; the memory is ingest, storage and the running queries' memory. diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs index 54219c9c..c3dd3d09 100644 --- a/rqe-optimizer/src/placement.rs +++ b/rqe-optimizer/src/placement.rs @@ -169,7 +169,7 @@ impl PlanLoad { /// The outcome of [`PlanLoad::place`]. #[derive(Debug, Clone)] pub struct Placement { - /// Over batches: release until the batch's last query finishes, ms. + /// Over batches: from the batch's issue until its last query finishes, ms. pub worst_batch_ms: f64, /// Index-aligned with the RAQEs: its worst firing, ms. pub raqe_latency_ms: Vec, @@ -275,7 +275,8 @@ enum Kind { #[derive(Debug, Clone)] struct Job { - release: f64, + /// When the job can start: a query's issue, or a compaction's window close. + issued: f64, kind: Kind, /// Query: its RAQE; compaction: its deployment. owner: usize, @@ -305,7 +306,7 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { for t in (0..horizon).step_by(deployment.slide_ms as usize) { compaction_at.insert((d, t), jobs.len()); jobs.push(Job { - release: secs(t), + issued: secs(t), kind: Kind::Compaction, owner: d, remaining: deployment.compaction_secs, @@ -318,7 +319,7 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { for (i, query) in load.queries.iter().enumerate() { for t in (0..horizon).step_by(query.interval_ms as usize) { jobs.push(Job { - release: secs(t), + issued: secs(t), kind: Kind::Query, owner: i, remaining: query.work_secs, @@ -328,34 +329,34 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { }); } } - let mut releases: Vec = jobs.iter().map(|j| j.release).collect(); - releases.sort_by(f64::total_cmp); - releases.dedup(); + let mut issues: Vec = jobs.iter().map(|j| j.issued).collect(); + issues.sort_by(f64::total_cmp); + issues.dedup(); let static_bytes = load.static_bytes(); let (mut peak_cpu, mut peak_bytes) = (load.ingest_cpu(), static_bytes); let mut now = 0.0; - let mut next_release = 0; + let mut next_issue = 0; loop { - while next_release < releases.len() && releases[next_release] <= now { - next_release += 1; + while next_issue < issues.len() && issues[next_issue] <= now { + next_issue += 1; } let mut ready: Vec = (0..jobs.len()) .filter(|&j| { let job = &jobs[j]; job.done_at.is_none() - && job.release <= now + && job.issued <= now && job.after.is_none_or(|c| jobs[c].done_at.is_some()) }) .collect(); - if ready.is_empty() && next_release == releases.len() { + if ready.is_empty() && next_issue == issues.len() { break; } // Older first, compaction before queries, then longest first. ready.sort_by(|&a, &b| { let (a, b) = (&jobs[a], &jobs[b]); - a.release - .total_cmp(&b.release) + a.issued + .total_cmp(&b.issued) .then(a.kind.cmp(&b.kind)) .then(b.remaining.total_cmp(&a.remaining)) }); @@ -377,8 +378,8 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { .iter() .map(|&(j, r)| jobs[j].remaining / r) .fold(f64::INFINITY, f64::min); - let release = releases.get(next_release).copied().unwrap_or(f64::INFINITY); - let step = finish.min(release - now); + let issue = issues.get(next_issue).copied().unwrap_or(f64::INFINITY); + let step = finish.min(issue - now); for &(j, r) in &rates { let job = &mut jobs[j]; job.remaining -= r * step; @@ -393,8 +394,8 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { let mut batches: BTreeMap = BTreeMap::new(); let mut raqe_latency_ms = vec![0.0f64; load.queries.len()]; for job in jobs.iter().filter(|j| j.kind == Kind::Query) { - let latency_ms = 1000.0 * (job.done_at.expect("every job finishes") - job.release); - let batch = batches.entry(job.release.to_bits()).or_insert(0.0); + let latency_ms = 1000.0 * (job.done_at.expect("every job finishes") - job.issued); + let batch = batches.entry(job.issued.to_bits()).or_insert(0.0); *batch = batch.max(latency_ms); raqe_latency_ms[job.owner] = raqe_latency_ms[job.owner].max(latency_ms); } From 97aaf6cdc25e39103adb6bd854a426872862ab51 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:27:34 +0000 Subject: [PATCH 11/18] docs: map cost models 1 and 2 to cloud billing; memory limit in the placement Cost model 2 matches containers billed by allocation and VMs (queueing for a core or for memory lowers the peaks); cost model 1 matches idealized fine-grained autoscaling, where queueing saves nothing and the cost-latency trade-off comes from the plan (precompute vs. query-time merging). The placement makes a job wait when its memory does not fit in M, and cost model 2's sizing searches (C, M) for the cheapest pair meeting L. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 57 ++++++++++++++++++++++++++++---- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 8ca6bc56..e3117f9d 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -401,6 +401,38 @@ at most one core and, on a full core, takes its CPU time. The cost table's `w1`, `w2` are per vCPU and per GiB (CPU only: `(1, 0)`; Fargate prices). +**How they map to cloud billing.** + +| Billing | Examples | Billed for | Cost model | +|---|---|---|---| +| Fixed-shape VMs | EC2, GCE instances | the instance shape (vCPU and memory bundled in fixed sizes) × run time, used or not | 2 (peak), but CPU and memory come in discrete bundles, not as two linear terms | +| Containers billed by allocation | AWS Fargate, GKE Autopilot, Azure Container Instances | the allocated vCPU and GB, priced separately, × run time (per second) | 2: `w1 · C + w2 · M`, separable and linear (our second weights are Fargate's prices) | +| Autoscaled containers and services | Cloud Run (request-based billing, CPU only while serving), Dataflow streaming, Flink on Kubernetes with an autoscaler | the allocation as it follows the load, × time | 1 (AUC), the closer the finer the scaling | +| Serverless functions | AWS Lambda, Cloud Functions | configured memory × run time (GB-seconds), CPU proportional to memory | per-job memory × time; not modeled | +| Managed analytics and streaming | Snowflake (warehouse size × run time), Managed Flink (KPU-hours, 1 vCPU + 4 GB each) | bundled resource units × time | 2 (provisioned), like the first two | + +Reserved instances, savings plans and spot change prices, not the billing +structure. + +Our ingest runs all the time and queries come in periodic bursts. + +- **Cost model 2** matches the first two rows and is how stream processing is + usually deployed: ingest and queries share long-running containers or VMs, + billed for what they are allocated. Both scheduling and the plan trade cost + for latency: making a job wait for a core or for memory lowers the peaks, so + a smaller `(C, M)` costs less at the price of latency. +- **Cost model 1** matches fine-grained autoscaling, idealized: capacity + follows the load at once. Queueing saves nothing here (a job holds its + memory only while it runs, so its memory × time is the same whenever it + runs, and CPU is billed by use), so every job runs as soon as it is ready. + The trade-off comes from the plan instead: a cheap plan keeps short windows + and merges many of them at query time (long queries), a fast one precomputes + more at ingest (more open windows, more CPU and memory). A tighter SLA rules + out the slow chains and forces the dearer plans. Real autoscalers add + trade-offs this idealization leaves out (scale-up and cold-start delay, + warm minimum instances billed while idle, billing granularity), so cost + model 1 is a lower bound for them. + #### 3. CPU: parts and how each is computed | Part | When | CPU-seconds | Mean vCPUs | @@ -495,7 +527,10 @@ simulate 2 hyperperiods, event-driven (events: query issues, window closes, comp + query jobs whose newest window is compacted order: issue / trigger time (older first), then compaction before query (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given) + give rates in that order: job j gets a_j = min(1, K − rates already given), + if it is already running or its memory fits in M − Σ (I_D + stored_D) + − the running jobs' memory; otherwise it waits (a running job holds its + memory until it finishes) a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, @@ -517,7 +552,12 @@ In words: up running alone at the end of the batch. 4. **Share capacity as rates.** In that order, each job gets up to one core (a single-threaded job can't use more) from the capacity still free. The - last one served may get only a fraction and runs slower in proportion. + last one served may get only a fraction and runs slower in proportion. A + job that is not yet running starts only if its memory fits in what ingest, + storage and the running jobs leave of `M`; otherwise it waits, so a smaller + `M` trades latency for a lower memory peak. Once started, a job keeps its + memory until it finishes. (Cost model 1 runs the placement with unlimited + capacity and memory.) 5. **Advance to the next event.** Time jumps to the next query issue or window close, or the earliest finishing job, everyone's remaining work drops by rate × elapsed time, and the rates are recomputed. @@ -615,11 +655,14 @@ holds every query at once. The plan is then sized and corrected with the placement: 1. **Solve** the MILP and take its mapping. -2. **Size** the mapping with the placement: `C*` is the smallest `C` at which - the worst batch meets `L` (binary search; it exists whenever every chain - fits); `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is - the mean load and the placement reports the latency it gives. The plan's - cost is `w1 · C* + w2 · M*`. +2. **Size** the mapping with the placement: search `(C, M)` for the cheapest + `w1 · C + w2 · M` at which the worst batch meets `L`. For each memory level + `M`, from the unconstrained peak down to ingest + storage + the largest + query (a fixed set of levels), binary-search the smallest `C` that meets + `L` with jobs waiting for memory above `M`; keep the cheapest pair + `(C*, M*)`. A smaller `M` makes jobs wait for memory, so it needs a larger + `C` to meet the same `L`. Without an SLA, `C*` is the mean load and `M*` + the smallest level, and the placement reports the latency they give. 3. **Correct:** measure the surrogate's error on that mapping, `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add them to the rows and solve again. In words: the first solve may favor a From dfb58bdf2769d26b7bb5430c239e122e340553a5 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:28:11 +0000 Subject: [PATCH 12/18] docs: memory does not limit the placement Billing charges the memory allocated; whether an application queues jobs to fit a smaller allocation is its own policy, not billing. So the placement has no memory limit and M is the peak it reaches at C*. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 33 +++++++++++++------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index e3117f9d..ad190232 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -419,8 +419,9 @@ Our ingest runs all the time and queries come in periodic bursts. - **Cost model 2** matches the first two rows and is how stream processing is usually deployed: ingest and queries share long-running containers or VMs, billed for what they are allocated. Both scheduling and the plan trade cost - for latency: making a job wait for a core or for memory lowers the peaks, so - a smaller `(C, M)` costs less at the price of latency. + for latency: with fewer cores, jobs wait for one, so a smaller `C` costs + less at the price of latency; and a plan that merges less at query time + needs less capacity for the same SLA. - **Cost model 1** matches fine-grained autoscaling, idealized: capacity follows the load at once. Queueing saves nothing here (a job holds its memory only while it runs, so its memory × time is the same whenever it @@ -527,10 +528,7 @@ simulate 2 hyperperiods, event-driven (events: query issues, window closes, comp + query jobs whose newest window is compacted order: issue / trigger time (older first), then compaction before query (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given), - if it is already running or its memory fits in M − Σ (I_D + stored_D) - − the running jobs' memory; otherwise it waits (a running job holds its - memory until it finishes) + give rates in that order: job j gets a_j = min(1, K − rates already given) a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, @@ -552,12 +550,10 @@ In words: up running alone at the end of the batch. 4. **Share capacity as rates.** In that order, each job gets up to one core (a single-threaded job can't use more) from the capacity still free. The - last one served may get only a fraction and runs slower in proportion. A - job that is not yet running starts only if its memory fits in what ingest, - storage and the running jobs leave of `M`; otherwise it waits, so a smaller - `M` trades latency for a lower memory peak. Once started, a job keeps its - memory until it finishes. (Cost model 1 runs the placement with unlimited - capacity and memory.) + last one served may get only a fraction and runs slower in proportion. + Memory does not limit the placement: billing charges the memory allocated, + and `M` is set to the peak the placement reaches. (Cost model 1 runs the + placement with unlimited capacity.) 5. **Advance to the next event.** Time jumps to the next query issue or window close, or the earliest finishing job, everyone's remaining work drops by rate × elapsed time, and the rates are recomputed. @@ -655,14 +651,11 @@ holds every query at once. The plan is then sized and corrected with the placement: 1. **Solve** the MILP and take its mapping. -2. **Size** the mapping with the placement: search `(C, M)` for the cheapest - `w1 · C + w2 · M` at which the worst batch meets `L`. For each memory level - `M`, from the unconstrained peak down to ingest + storage + the largest - query (a fixed set of levels), binary-search the smallest `C` that meets - `L` with jobs waiting for memory above `M`; keep the cheapest pair - `(C*, M*)`. A smaller `M` makes jobs wait for memory, so it needs a larger - `C` to meet the same `L`. Without an SLA, `C*` is the mean load and `M*` - the smallest level, and the placement reports the latency they give. +2. **Size** the mapping with the placement: `C*` is the smallest `C` at which + the worst batch meets `L` (binary search; it exists whenever every chain + fits); `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is + the mean load and the placement reports the latency it gives. The plan's + cost is `w1 · C* + w2 · M*`. 3. **Correct:** measure the surrogate's error on that mapping, `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add them to the rows and solve again. In words: the first solve may favor a From 741458fcca8d1445266133cd3d1d4ebed4ccf385 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:38:45 +0000 Subject: [PATCH 13/18] rqe-optimizer, docs: review fixes for cost models 1 and 2 - minimize_cost_model takes `allowed` candidates per RAQE, so PerQuery can rule out sharing: identical deployments as separate candidate copies each pay their own ingest (test). - One chain function (analytical_cost_model::chain_ms) and one SLA slack (meets_sla, 1e-9 relative) for the MILP's chain filter and the placement, so a chain equal to L is never feasible in one and not the other. - cost_model_2's doubling search stops after 64 steps. - The placement keeps a pending list of issued, unfinished jobs instead of scanning every job at each event. - A compaction holds the closed window's k partial copies while it runs: in AUC(memory), the placement's memory over time, and both MILPs' memory terms (test). - Docs: instances vs. groups in the formulas; the compaction memory row; per-RAQE latency bounds are not used; the search bounds; PerQuery via `allowed`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 97 ++++++++++++++-------- rqe-optimizer/src/analytical_cost_model.rs | 28 +++++++ rqe-optimizer/src/milp.rs | 94 +++++++++++++++++---- rqe-optimizer/src/placement.rs | 95 ++++++++++++++------- 4 files changed, 235 insertions(+), 79 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index ad190232..f56e1ed3 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -376,10 +376,11 @@ configs chosen by memory). | `D`, `i` | a candidate deployment; a RAQE | | `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | | `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | -| `card(G)` | groups of `D`'s grouping (one instance per group per window; one for a sketch shared by all groups) | +| `card(G)` | groups of `D`'s grouping | +| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | | `λ_D` | samples/s arriving for `D`'s metric | | `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | -| `m` | measured bytes per instance | +| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | | `n_{i,D} = S_i / x_D` | windows a query merges | | `H = lcm(T_i, y_D)` | hyperperiod: the pattern of query issues and window closes repeats every `H` | | batch | all query jobs issued at one instant; `B0` is the one at `t = 0`, where every RAQE fires | @@ -439,8 +440,8 @@ Our ingest runs all the time and queries come in periodic bursts. | Part | When | CPU-seconds | Mean vCPUs | |---|---|---|---| | Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | -| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts instances · c_mrg` | `c_D / y_D` | -| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · (c_qry + (n_{i,D} − 1) · c_mrg)` | `ℓ_{i,D} / T_i` | +| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | +| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | - Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at most one core), **split by sample**: each worker reads a share of the input @@ -464,9 +465,10 @@ In words: - `c_D`: closing a window merges, for every instance, the `k_D` workers' partial copies into one, which takes `k_D − 1` merges. This happens once per slide. -- `ℓ_{i,D}`: for each of the `card(G)` groups, a query merges its - `n_{i,D}` stored windows (`n − 1` merges), then answers once. This happens - once per interval. +- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows + (`n − 1` merges per instance), then answers once per group. This happens + once per interval. (A sketch shared by all groups merges one instance but + still answers every group.) - `AUC(CPU)` adds the three rates: work per second, in vCPUs. #### 4. Memory: parts and how each is computed @@ -476,13 +478,15 @@ storage once compacted, and a query reads stored instances in place. | Part | What | Bytes | Held | |---|---|---|---| -| Ingest | open windows, one copy per worker | `I_D = card(G) · m · (x_D / y_D) · k_D` | always | -| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i card(G) · m · ((S_i − x_D) / y_D + 1)` | always | -| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = card(G) · m · [n_{i,D} > 1] + output` | while the query job runs | +| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | +| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | +| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | +| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | -`AUC(memory) = Σ_D (I_D + stored_D) + Σ_i q_{i,D} · (run time) / T_i`. Under -cost model 1 a query job runs on its own core, so its run time is `ℓ_{i,D}`. -Under cost model 2 memory is the peak the placement reaches. +`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) ++ Σ_i q_{i,D} · (query run time) / T_i`. Under cost model 1 every job runs on +its own core, so a compaction runs for `c_D` and a query for `ℓ_{i,D}`. Under +cost model 2 memory is the peak the placement reaches. In words: @@ -490,17 +494,29 @@ In words: `x_D / y_D` windows still open, and there are `k_D` workers. - `stored_D`: closed windows are kept until the longest lookback that `D` serves no longer needs them. That is `(S − x)/y + 1` windows per group. -- `q_{i,D}`: a merge builds one accumulator per group (a direct query, with - `n = 1`, reads the stored window and needs none), plus the answer. -- `AUC(memory)`: ingest and storage are held all the time. A query's memory - is held only while it runs, a fraction `run time / T_i` of the time. +- Compaction: when a window closes, a new one opens, so ingest still holds + `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in + memory until the compaction has merged them. The merged copy takes the + storage slot that the oldest window frees at the same moment, so it is not + counted twice. +- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, + with `n = 1`, reads the stored window and needs none), plus the answer for + every group. +- `AUC(memory)`: ingest and storage are held all the time. A compaction's + and a query's memory are held only while they run, a fraction + `run time / y_D` or `run time / T_i` of the time. #### 5. Batch latency and the SLA A batch's **latency** is the time from its issue until its last query job finishes, compaction included. The **query latency** of a plan is its worst batch latency over the hyperperiod. A latency SLA `L` requires query latency -`≤ L`. +`≤ L`. The SLA is on the batch only: per-RAQE latency bounds +(`Raqe::latency_sla_ms`) are not used by these cost models. Latencies are +compared with `L` with a relative slack of `1e-9` +(`analytical_cost_model::meets_sla`), so float error in summing µs-scale work +can't turn a chain equal to `L` into a miss; every check (the MILP's chain +filter and the placement) uses the same `chain_ms` and the same slack. Both cost models get the latency from the same job placement (§6); they differ only in the CPU capacity it is given: @@ -532,7 +548,8 @@ simulate 2 hyperperiods, event-driven (events: query issues, window closes, comp a job at rate a_j finishes when its remaining work / a_j elapses recompute the rates at every event outputs: per-RAQE and per-batch latency, worst batch latency, - CPU(t) = Σ ρ_D + Σ a_j, MEM(t) = Σ (I_D + stored_D) + Σ q of running jobs + CPU(t) = Σ ρ_D + Σ a_j, + MEM(t) = Σ (I_D + stored_D) + memory of the running compactions and queries ``` In words: @@ -560,17 +577,21 @@ In words: 6. **Read off the results.** A query's latency is its finish minus its issue, and a batch's latency is that of its last query. The CPU in use is ingest plus the rates; the memory is ingest, storage and the running - queries' memory. + compactions' and queries' memory. Two hyperperiods are simulated so that work carried over the wrap-around is counted. A job uses at most one core, so with `K ≥ 1` a batch on its own ends within `Σ work / K + max chain` (Graham's list-scheduling bound). With unlimited capacity (cost model 1) the placement has a closed form: every -job starts when ready on its own core, so a query runs for exactly -`ℓ_{i,D}`, a batch's latency is its longest chain, and the memory over time -averages to §4's `AUC(memory)`. That is why cost model 1's MILP below is -exact. +job starts when ready on its own core, so a compaction runs for exactly `c_D` +and a query for exactly `ℓ_{i,D}`, a batch's latency is its longest chain, +and the memory over time averages to §4's `AUC(memory)`. That is why cost +model 1's MILP below is exact. + +The simulation keeps the issued, unfinished jobs in a pending list, so each +event looks only at the jobs in flight, not at every job of the two +hyperperiods. #### 7. MILP formulation @@ -602,13 +623,15 @@ Cost model 1: ```text minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] ``` In words: the price of the mean vCPUs (ingest and compaction per active deployment, plus each RAQE's query work per second), plus the price of the -mean memory (ingest and storage per active deployment, plus each query's -memory for the fraction of time it runs). With elastic CPU this is the cost +mean memory (ingest and storage per active deployment, each compaction's +partial copies for the fraction of time it runs, and each query's memory for +the fraction of time it runs). With elastic CPU this is the cost exactly, and the SLA is fully handled by the chain row above. Cost model 2: @@ -616,7 +639,7 @@ Cost model 2: ```text minimize w1 · C + w2 · M s.t. C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) - M ≥ Σ_D (I_D · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} + δ_M (memory) + M ≥ Σ_D ((I_D + k_D · w_D) · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} + δ_M (memory) with SLA L: C ≥ Σ_D ρ_D · u_D + ( Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ) / L + δ_C (batch B0) ``` @@ -629,8 +652,9 @@ In words: - The objective prices the provisioned peak, `C` vCPUs and `M` GiB. - **Mean load:** the capacity must at least carry the average work, or a backlog grows without bound. -- **Memory:** the capacity must hold ingest and storage, plus every query's - memory as if all ran at once (an upper bound on the peak). +- **Memory:** the capacity must hold ingest and storage, plus every + compaction's and every query's memory as if all ran at once (an upper bound + on the peak). - **Batch `B0`:** when every RAQE fires together, ingest keeps `Σ ρ_D · u_D` vCPUs busy. The rest must finish the batch's queries and compactions within `L`, so `C − ingest ≥ batch work / L`. This treats the @@ -652,8 +676,10 @@ placement: 1. **Solve** the MILP and take its mapping. 2. **Size** the mapping with the placement: `C*` is the smallest `C` at which - the worst batch meets `L` (binary search; it exists whenever every chain - fits); `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is + the worst batch meets `L` (doubling from the mean load, then binary search + to a 1e-4 relative gap; it exists whenever every chain fits, and the + doubling stops after 64 steps as a guard against float pathologies); + `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is the mean load and the placement reports the latency it gives. The plan's cost is `w1 · C* + w2 · M*`. 3. **Correct:** measure the surrogate's error on that mapping, @@ -666,7 +692,12 @@ placement: 4. **Keep** the mapping with the lowest placed cost; stop when a mapping repeats, or after three corrections. -**PerQuery** is the same MILP over single-RAQE candidates only (no sharing). +**PerQuery** is the same MILP with sharing ruled out. `minimize_cost_model` +takes `allowed`, the candidate indices each RAQE may use. PerQuery gives each +RAQE its own candidates, with a separate copy of any deployment that two +RAQEs could both use. Two RAQEs share a deployment only by choosing the same +candidate index (`u_D` is per index), so their copies stay apart and each +pays its own ingest. **AutoSketch** keeps its memory-chosen configs and is priced by the same functions: cost model 1 by use (latency its longest chain); cost model 2 by the placement and the binary search on `C`. diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 22547616..c9dc809c 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -272,6 +272,34 @@ pub fn compaction_secs(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { .sum::() } +/// Bytes a compaction holds while it runs: the closed window's `k` partial +/// copies, `k · Σ_parts instances · m` (one window's ingest memory per +/// worker, times `k`). The compacted result takes the storage slot the oldest +/// window frees, so it is not counted again. Zero with one worker. +pub fn compaction_bytes(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let workers = ingest_workers(deployment, facts); + if workers <= 1.0 { + return 0.0; + } + workers * ingest(deployment, facts).memory_bytes / open_window_count(deployment) +} + +/// One firing's chain on its own cores, ms: the newest window's compaction, +/// then the query (merge, then estimate). Under elastic CPU this is the +/// firing's latency; no placement can do better. +pub fn chain_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + 1000.0 * compaction_secs(deployment, facts) + query_latency_ms(raqe, deployment, facts) +} + +/// Slack for comparing a latency with an SLA: float error in summing µs-scale +/// work must not turn a chain equal to `L` into a miss. +pub const LATENCY_SLACK: f64 = 1e-9; + +/// Whether `latency_ms` meets `sla_ms`, with [`LATENCY_SLACK`]. +pub fn meets_sla(latency_ms: f64, sla_ms: f64) -> bool { + latency_ms <= sla_ms * (1.0 + LATENCY_SLACK) +} + pub fn score( raqes: &[Raqe], deployments: &[Deployment], diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index bd9ed5fe..d9d3024e 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -228,8 +228,8 @@ pub fn minimize( } /// Which cost model [`minimize_cost_model`] minimizes -/// (`docs/rqe_sketch_deployment_v1.md`, "Cost models, batch latency and -/// query placement"). +/// (`docs/rqe_sketch_deployment_v1.md`, "MILP with latency SLA constraints: +/// cost models, query placement and batch latency"). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CostModel { /// `w_cpu · AUC(CPU) + w_mem · AUC(memory)`: billed by use, CPU elastic. @@ -256,7 +256,14 @@ pub struct CostModelSolution { const COST_MODEL_2_CORRECTIONS: usize = 3; /// Minimize `cost_model` with weights `w_cpu`, `w_mem` (per vCPU, per GiB), -/// optionally under a batch latency SLA `sla_ms`. +/// optionally under a batch latency SLA `sla_ms`. Per-RAQE latency bounds +/// (`Raqe::latency_sla_ms`) are not used here: the SLA is on the batch. +/// +/// `allowed`, when given, lists for each RAQE the candidate indices it may +/// use, e.g. only its own candidates for PerQuery (no sharing). Two RAQEs +/// share a deployment only by choosing the same candidate index, so giving +/// each RAQE its own copies of identical deployments keeps them apart, each +/// paying its own ingest. /// /// Cost model 1 is solved exactly. Cost model 2's batch row /// (`Σ ℓ + Σ compaction ≤ L · (C − ingest)`) treats the heaviest batch as @@ -275,6 +282,7 @@ pub fn minimize_cost_model( cost_model: CostModel, accuracy: &Accuracy, sla_ms: Option, + allowed: Option<&[Vec]>, ) -> Result { use crate::placement::{cost_model_1, cost_model_2, PlanLoad}; let price = |mapping: &Mapping| { @@ -297,6 +305,7 @@ pub fn minimize_cost_model( cost_model, accuracy, sla_ms, + allowed, corrections, )?; let cost = price(&mapping).ok_or(ResolutionError::Infeasible)?; @@ -347,7 +356,13 @@ fn surrogate_peaks(load: &crate::placement::PlanLoad, sla_ms: Option) -> (f } None => mean, }; - let bytes = load.static_bytes() + load.queries.iter().map(|q| q.memory_bytes).sum::(); + let bytes = load.static_bytes() + + load + .deployments + .iter() + .map(|d| d.compaction_bytes) + .sum::() + + load.queries.iter().map(|q| q.memory_bytes).sum::(); (cpu, bytes) } @@ -363,6 +378,7 @@ fn solve_cost_model( cost_model: CostModel, accuracy: &Accuracy, sla_ms: Option, + allowed: Option<&[Vec]>, (cpu_correction, bytes_correction): (f64, f64), ) -> Result<(MilpSolution, Mapping), ResolutionError> { let secs = |ms: u64| ms as f64 / 1000.0; @@ -375,6 +391,10 @@ fn solve_cost_model( .iter() .map(|d| analytical_cost_model::compaction_secs(d, facts)) .collect(); + let compaction_bytes: Vec = deployments + .iter() + .map(|d| analytical_cost_model::compaction_bytes(d, facts)) + .collect(); let ingest_bytes: Vec = deployments .iter() .map(|d| { @@ -382,17 +402,20 @@ fn solve_cost_model( * analytical_cost_model::ingest_workers(d, facts) }) .collect(); - // Eligible pairs, less those whose chain exceeds the SLA. + // Eligible pairs (within `allowed`), less those whose chain exceeds the SLA. let eligible: Vec> = raqes .iter() - .map(|raqe| { + .enumerate() + .map(|(i, raqe)| { eligible_deployments_for(raqe, deployments, facts, accuracy) .into_iter() + .filter(|d| allowed.is_none_or(|allowed| allowed[i].contains(d))) .filter(|&d| { sla_ms.is_none_or(|sla| { - 1000.0 * compaction[d] - + analytical_cost_model::query_latency_ms(raqe, &deployments[d], facts) - <= sla + analytical_cost_model::meets_sla( + analytical_cost_model::chain_ms(raqe, &deployments[d], facts), + sla, + ) }) }) .collect() @@ -488,8 +511,10 @@ fn solve_cost_model( let mut batch_work = Expression::from(0.0); let mut ingest = Expression::from(0.0); let mut held_bytes: Expression = stored.iter().sum(); - let mut query_bytes_all = Expression::from(0.0); - let mut query_bytes_auc = Expression::from(0.0); + // Transient memory: every compaction and query at once (cost model 2's + // conservative peak), and by use (cost model 1). + let mut transient_bytes_all = Expression::from(0.0); + let mut transient_bytes_auc = Expression::from(0.0); for (d, &u) in active.iter().enumerate() { let deployment = &deployments[d]; mean_cpu.add_mul( @@ -499,21 +524,27 @@ fn solve_cost_model( ingest.add_mul(ingest_cpu[d] / cpu_scale, u); batch_work.add_mul(compaction[d] / cpu_scale, u); held_bytes.add_mul(ingest_bytes[d] / bytes_scale, u); + transient_bytes_all.add_mul(compaction_bytes[d] / bytes_scale, u); + transient_bytes_auc.add_mul( + compaction_bytes[d] * compaction[d] / secs(deployment.slide_ms) / bytes_scale, + u, + ); } for (i, choices) in assignments.iter().enumerate() { let interval = secs(raqes[i].interval_ms); for &(d, z) in choices { mean_cpu.add_mul(work(i, d) / interval / cpu_scale, z); batch_work.add_mul(work(i, d) / cpu_scale, z); - query_bytes_all.add_mul(query_bytes(i, d) / bytes_scale, z); - query_bytes_auc.add_mul(query_bytes(i, d) * work(i, d) / interval / bytes_scale, z); + transient_bytes_all.add_mul(query_bytes(i, d) / bytes_scale, z); + transient_bytes_auc.add_mul(query_bytes(i, d) * work(i, d) / interval / bytes_scale, z); } } let cpu_weight = w_cpu * cpu_scale / reference; let bytes_weight = w_mem * gib(bytes_scale) / reference; let goal = match peaks { None => { - cpu_weight * mean_cpu.clone() + bytes_weight * (held_bytes.clone() + query_bytes_auc) + cpu_weight * mean_cpu.clone() + + bytes_weight * (held_bytes.clone() + transient_bytes_auc) } Some((c, m)) => cpu_weight * c + bytes_weight * m, }; @@ -542,7 +573,7 @@ fn solve_cost_model( if let Some((c, m)) = peaks { model.add_constraint((mean_cpu - c).leq(0)); model.add_constraint( - (held_bytes + query_bytes_all + bytes_correction / bytes_scale - m).leq(0), + (held_bytes + transient_bytes_all + bytes_correction / bytes_scale - m).leq(0), ); if let Some(sla) = sla_ms { // C ≥ ingest + (batch work) / L + δ_C. @@ -796,6 +827,7 @@ mod tests { CostModel::One, &table_accuracy, sla_ms, + None, ) .expect("feasible"); assert!( @@ -833,6 +865,7 @@ mod tests { CostModel::Two, &table_accuracy, sla_ms, + None, ) .expect("feasible"); assert!(sla_ms.is_none_or(|l| got.cost.latency_ms <= l)); @@ -846,6 +879,37 @@ mod tests { } } + #[test] + fn allowed_candidates_keep_identical_deployments_apart() { + // Two RAQEs at one cadence, each with its own copy of one deployment. + let raqes = vec![raqe("a", 60_000), raqe("b", 60_000)]; + let one = test_support::deployment(BYTES_PER_GIB, 1e-3, 1e-5, 1e-5, 60_000, 60_000); + let deployments = vec![one.clone(), one]; + let facts = facts(100, 100); + let solve = |allowed: Option<&[Vec]>| { + minimize_cost_model( + &raqes, + &deployments, + &facts, + 1.0, + 0.0, + CostModel::One, + &table_accuracy, + None, + allowed, + ) + .expect("feasible") + }; + // Free to choose: both use one copy and ingest once. + let shared = solve(None); + assert_eq!(shared.mapping[0], shared.mapping[1]); + // Each on its own copy: two deployments, ingest paid twice. + let own = solve(Some(&[vec![0], vec![1]])); + assert_eq!(own.mapping, vec![0, 1]); + let ingest = analytical_cost_model::ingest(&deployments[0], &facts).cpu_secs_per_sec; + assert!((own.cost.cpu - shared.cost.cpu - ingest).abs() < 1e-12 * own.cost.cpu); + } + #[test] fn matches_brute_force_with_shared_deployment_costs() { let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs index c3dd3d09..881d804c 100644 --- a/rqe-optimizer/src/placement.rs +++ b/rqe-optimizer/src/placement.rs @@ -27,6 +27,9 @@ pub struct DeploymentLoad { pub storage_bytes: f64, /// CPU-seconds to compact one closed window (0 with one worker). pub compaction_secs: f64, + /// Bytes a compaction holds while it runs: the closed window's partial + /// copies (0 with one worker). + pub compaction_bytes: f64, /// Windows close every slide. pub slide_ms: Millis, } @@ -37,6 +40,9 @@ pub struct QueryLoad { /// Index into [`PlanLoad::deployments`]. pub deployment: usize, pub interval_ms: Millis, + /// Compaction of the newest window, then this job, on their own cores, ms + /// ([`analytical_cost_model::chain_ms`]). + pub chain_ms: f64, /// Merge then estimate, CPU-seconds (one core at most). pub work_secs: f64, /// Merge accumulators and output, held while the job runs. @@ -72,6 +78,7 @@ impl PlanLoad { ingest_bytes: ingest.memory_bytes * workers, storage_bytes: 0.0, compaction_secs: analytical_cost_model::compaction_secs(deployment, facts), + compaction_bytes: analytical_cost_model::compaction_bytes(deployment, facts), slide_ms: deployment.slide_ms, }); deployments.len() - 1 @@ -82,6 +89,7 @@ impl PlanLoad { queries.push(QueryLoad { deployment: at, interval_ms: raqe.interval_ms, + chain_ms: analytical_cost_model::chain_ms(raqe, deployment, facts), work_secs: analytical_cost_model::query_latency_ms(raqe, deployment, facts) / 1000.0, memory_bytes: analytical_cost_model::merge(raqe, deployment, facts).memory_bytes @@ -122,10 +130,16 @@ impl PlanLoad { .sum::() } - /// Mean memory, bytes: ingest and storage always, and each query's memory + /// Mean memory, bytes: ingest and storage always; each compaction's + /// partial copies for its run on one core every slide; each query's memory /// for its run on one core (`work_secs`) every interval. pub fn auc_bytes(&self) -> f64 { self.static_bytes() + + self + .deployments + .iter() + .map(|d| d.compaction_bytes * d.compaction_secs / secs(d.slide_ms)) + .sum::() + self .queries .iter() @@ -133,20 +147,10 @@ impl PlanLoad { .sum::() } - /// One firing's chain on its own cores, seconds: the newest window's - /// compaction, then the query. - pub fn chain_secs(&self, raqe: usize) -> f64 { - let q = &self.queries[raqe]; - self.deployments[q.deployment].compaction_secs + q.work_secs - } - /// The longest chain, ms: the batch latency when CPU is elastic (cost /// model 1). pub fn longest_chain_ms(&self) -> f64 { - 1000.0 - * (0..self.queries.len()) - .map(|i| self.chain_secs(i)) - .fold(0.0, f64::max) + self.queries.iter().map(|q| q.chain_ms).fold(0.0, f64::max) } /// `lcm` of every interval and slide, ms. @@ -206,7 +210,8 @@ pub fn cost_model_1(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> ModelCost { /// Cost model 2: CPU and memory billed at the peak of a provisioned /// `(C, M)`. `C` is the smallest at which the placement's worst batch meets /// `sla_ms` (the mean CPU with no SLA), `M` the placement's peak memory. -/// `None` when a chain alone exceeds the SLA. +/// `None` when a chain alone exceeds the SLA (or, failing float sanity, no +/// `C` up to `2^MAX_DOUBLINGS` times the mean load meets it). pub fn cost_model_2( load: &PlanLoad, w_cpu: f64, @@ -218,13 +223,19 @@ pub fn cost_model_2( let (cpu, placement) = match sla_ms { None => (floor, placed(floor)), Some(sla) => { - if load.longest_chain_ms() > sla { + if !analytical_cost_model::meets_sla(load.longest_chain_ms(), sla) { return None; } - let meets = |cpu: f64| placed(cpu).worst_batch_ms <= sla; + let meets = + |cpu: f64| analytical_cost_model::meets_sla(placed(cpu).worst_batch_ms, sla); let mut hi = floor.max(f64::MIN_POSITIVE); + let mut doublings = 0; while !meets(hi) { + if doublings == MAX_DOUBLINGS { + return None; + } hi *= 2.0; + doublings += 1; } let mut lo = floor; if meets(lo) { @@ -250,6 +261,11 @@ pub fn cost_model_2( }) } +/// Doublings of `C` above the mean load before cost model 2 gives up. With +/// every chain within the SLA a large enough `C` always meets it, so this only +/// stops a float pathology. +const MAX_DOUBLINGS: usize = 64; + fn secs(ms: Millis) -> f64 { ms as f64 / 1000.0 } @@ -310,7 +326,7 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { kind: Kind::Compaction, owner: d, remaining: deployment.compaction_secs, - memory: 0.0, + memory: deployment.compaction_bytes, after: None, done_at: None, }); @@ -329,27 +345,28 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { }); } } - let mut issues: Vec = jobs.iter().map(|j| j.issued).collect(); - issues.sort_by(f64::total_cmp); - issues.dedup(); + // Jobs by issue time; `pending` holds the issued, unfinished ones, so each + // event looks at the jobs in flight, not at every job. + let mut order: Vec = (0..jobs.len()).collect(); + order.sort_by(|&a, &b| jobs[a].issued.total_cmp(&jobs[b].issued)); + let mut next_job = 0; + let mut pending: Vec = Vec::new(); let static_bytes = load.static_bytes(); let (mut peak_cpu, mut peak_bytes) = (load.ingest_cpu(), static_bytes); let mut now = 0.0; - let mut next_issue = 0; loop { - while next_issue < issues.len() && issues[next_issue] <= now { - next_issue += 1; + while next_job < order.len() && jobs[order[next_job]].issued <= now { + pending.push(order[next_job]); + next_job += 1; } - let mut ready: Vec = (0..jobs.len()) - .filter(|&j| { - let job = &jobs[j]; - job.done_at.is_none() - && job.issued <= now - && job.after.is_none_or(|c| jobs[c].done_at.is_some()) - }) + pending.retain(|&j| jobs[j].done_at.is_none()); + let mut ready: Vec = pending + .iter() + .copied() + .filter(|&j| jobs[j].after.is_none_or(|c| jobs[c].done_at.is_some())) .collect(); - if ready.is_empty() && next_issue == issues.len() { + if pending.is_empty() && next_job == order.len() { break; } // Older first, compaction before queries, then longest first. @@ -378,7 +395,9 @@ fn place(load: &PlanLoad, cpu: f64) -> Option { .iter() .map(|&(j, r)| jobs[j].remaining / r) .fold(f64::INFINITY, f64::min); - let issue = issues.get(next_issue).copied().unwrap_or(f64::INFINITY); + let issue = order + .get(next_job) + .map_or(f64::INFINITY, |&j| jobs[j].issued); let step = finish.min(issue - now); for &(j, r) in &rates { let job = &mut jobs[j]; @@ -418,6 +437,7 @@ mod tests { ingest_bytes: 10.0, storage_bytes: 5.0, compaction_secs, + compaction_bytes: 0.0, slide_ms: 1_000, }], queries: queries @@ -425,6 +445,7 @@ mod tests { .map(|&(interval_ms, work_secs)| QueryLoad { deployment: 0, interval_ms, + chain_ms: 1000.0 * (compaction_secs + work_secs), work_secs, memory_bytes: 100.0, }) @@ -499,6 +520,18 @@ mod tests { assert!((cost_model_1(&plan, 1.0, 0.0).latency_ms - placed.worst_batch_ms).abs() < 1e-6); } + #[test] + fn a_compaction_holds_its_partial_copies_while_it_runs() { + // Compaction 0.2 s holding 50 bytes, then a 0.1 s query holding 100, + // each second, beside 15 bytes of ingest and storage. + let mut plan = load(0.0, 0.2, &[(1_000, 0.1)]); + plan.deployments[0].compaction_bytes = 50.0; + // They run one after the other: the peak is the query's. + assert_eq!(plan.place(2.0).unwrap().peak_bytes, 115.0); + // By use: 15 + 50 · 0.2 + 100 · 0.1 per second. + assert!((plan.auc_bytes() - 35.0).abs() < 1e-12); + } + #[test] fn cost_models_bill_use_and_peak() { let plan = load(0.5, 0.0, &[(1_000, 0.1)]); From 561d8b7e7ada8ee13e7005a39f5e8a4bf575295d Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:45:53 +0000 Subject: [PATCH 14/18] rqe-optimizer, docs: cost model 2 is evaluated with an SLA only Without an SLA, cost model 2's capacity is not pinned down (at the mean load, a placement that can't use every core keeps a growing backlog, so its latency depends on how long it is simulated). cost_model_2 takes the SLA, and minimize_cost_model asserts one for cost model 2. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 14 +++--- rqe-optimizer/src/milp.rs | 46 ++++++++++--------- rqe-optimizer/src/placement.rs | 79 ++++++++++++++------------------ 3 files changed, 65 insertions(+), 74 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index f56e1ed3..d18ab797 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -367,7 +367,9 @@ Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in and a latency SLA on a whole batch of queries. Evaluated first on the synthetic mixed template set; methods: ASAP (this MILP, with sharing), PerQuery (the same MILP without sharing) and AutoSketch-Adapted (fixed -configs chosen by memory). +configs chosen by memory). Cost model 1 is evaluated with and without a +latency SLA; cost model 2 with an SLA only (without one, its provisioned +capacity, and so its latency, is not pinned down). #### 1. Definitions @@ -525,8 +527,8 @@ differ only in the CPU capacity it is given: and no job waits for a core. A batch's latency is then its longest **chain** `c_D + ℓ_{i,D}` (the newest window's compaction, then the query), and the SLA requires `c_D + ℓ_{i,D} ≤ L` for every assigned pair. -- Cost model 2: jobs share the provisioned capacity `C`, so they may queue, - and the latency is whatever the placement gives. +- Cost model 2 (always with an SLA): jobs share the provisioned capacity `C`, + so they may queue, and the latency is whatever the placement gives. #### 6. Job placement algorithm (both cost models) @@ -640,7 +642,6 @@ Cost model 2: minimize w1 · C + w2 · M s.t. C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) M ≥ Σ_D ((I_D + k_D · w_D) · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} + δ_M (memory) -with SLA L: C ≥ Σ_D ρ_D · u_D + ( Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ) / L + δ_C (batch B0) ``` @@ -679,9 +680,8 @@ placement: the worst batch meets `L` (doubling from the mean load, then binary search to a 1e-4 relative gap; it exists whenever every chain fits, and the doubling stops after 64 steps as a guard against float pathologies); - `M*` is the placement's peak memory at `C*`. Without an SLA, `C*` is - the mean load and the placement reports the latency it gives. The plan's - cost is `w1 · C* + w2 · M*`. + `M*` is the placement's peak memory at `C*`. The plan's cost is + `w1 · C* + w2 · M*`. 3. **Correct:** measure the surrogate's error on that mapping, `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add them to the rows and solve again. In words: the first solve may favor a diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index d9d3024e..55980053 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -285,11 +285,16 @@ pub fn minimize_cost_model( allowed: Option<&[Vec]>, ) -> Result { use crate::placement::{cost_model_1, cost_model_2, PlanLoad}; + assert!( + cost_model == CostModel::One || sla_ms.is_some(), + "cost model 2 is evaluated with a latency SLA only" + ); let price = |mapping: &Mapping| { let load = PlanLoad::new(raqes, deployments, mapping, facts); - match cost_model { - CostModel::One => Some(cost_model_1(&load, w_cpu, w_mem)), - CostModel::Two => cost_model_2(&load, w_cpu, w_mem, sla_ms), + match (cost_model, sla_ms) { + (CostModel::One, _) => Some(cost_model_1(&load, w_cpu, w_mem)), + (CostModel::Two, Some(sla)) => cost_model_2(&load, w_cpu, w_mem, sla), + (CostModel::Two, None) => unreachable!("asserted above"), } }; let mut corrections = (0.0, 0.0); @@ -318,7 +323,8 @@ pub fn minimize_cost_model( }); } let load = PlanLoad::new(raqes, deployments, &mapping, facts); - let (surrogate_cpu, surrogate_bytes) = surrogate_peaks(&load, sla_ms); + let (surrogate_cpu, surrogate_bytes) = + surrogate_peaks(&load, sla_ms.expect("cost model 2 has an SLA")); corrections = (cost.cpu - surrogate_cpu, cost.bytes - surrogate_bytes); let repeated = seen.contains(&mapping); seen.push(mapping.clone()); @@ -342,20 +348,16 @@ pub fn minimize_cost_model( /// Cost model 2's surrogate `(C, M)` of a placed plan, the MILP's rows /// without corrections: `C = max(mean load, ingest + batch work / L)`, and `M` /// with every query's memory at once. -fn surrogate_peaks(load: &crate::placement::PlanLoad, sla_ms: Option) -> (f64, f64) { - let mean = load.auc_cpu(); - let cpu = match sla_ms { - Some(sla) => { - let batch: f64 = load.queries.iter().map(|q| q.work_secs).sum::() - + load - .deployments - .iter() - .map(|d| d.compaction_secs) - .sum::(); - mean.max(load.ingest_cpu() + batch / (sla / 1000.0)) - } - None => mean, - }; +fn surrogate_peaks(load: &crate::placement::PlanLoad, sla_ms: f64) -> (f64, f64) { + let batch: f64 = load.queries.iter().map(|q| q.work_secs).sum::() + + load + .deployments + .iter() + .map(|d| d.compaction_secs) + .sum::(); + let cpu = load + .auc_cpu() + .max(load.ingest_cpu() + batch / (sla_ms / 1000.0)); let bytes = load.static_bytes() + load .deployments @@ -845,7 +847,7 @@ mod tests { use crate::placement::{cost_model_2, PlanLoad}; let (raqes, deployments, facts) = cost_model_workload(); for (w_cpu, w_mem) in [(1.0, 0.0), (1.0, 4.0)] { - for sla_ms in [None, Some(1e5), Some(2_000.0), Some(300.0)] { + for sla_ms in [1e5, 2_000.0, 300.0] { let price = |mapping: &Mapping| { cost_model_2( &PlanLoad::new(&raqes, &deployments, mapping, &facts), @@ -864,14 +866,14 @@ mod tests { w_mem, CostModel::Two, &table_accuracy, - sla_ms, + Some(sla_ms), None, ) .expect("feasible"); - assert!(sla_ms.is_none_or(|l| got.cost.latency_ms <= l)); + assert!(got.cost.latency_ms <= sla_ms * (1.0 + 1e-9)); assert!( (got.cost.value - best).abs() <= 1e-3 * best, - "({w_cpu}, {w_mem}), {sla_ms:?}: {} vs {best} after {} solves", + "({w_cpu}, {w_mem}), {sla_ms}: {} vs {best} after {} solves", got.cost.value, got.solves ); diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs index 881d804c..50894b19 100644 --- a/rqe-optimizer/src/placement.rs +++ b/rqe-optimizer/src/placement.rs @@ -208,50 +208,40 @@ pub fn cost_model_1(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> ModelCost { } /// Cost model 2: CPU and memory billed at the peak of a provisioned -/// `(C, M)`. `C` is the smallest at which the placement's worst batch meets -/// `sla_ms` (the mean CPU with no SLA), `M` the placement's peak memory. +/// `(C, M)` under a latency SLA (cost model 2 is evaluated with an SLA only). +/// `C` is the smallest at which the placement's worst batch meets `sla_ms`, +/// `M` the placement's peak memory. /// `None` when a chain alone exceeds the SLA (or, failing float sanity, no /// `C` up to `2^MAX_DOUBLINGS` times the mean load meets it). -pub fn cost_model_2( - load: &PlanLoad, - w_cpu: f64, - w_mem: f64, - sla_ms: Option, -) -> Option { +pub fn cost_model_2(load: &PlanLoad, w_cpu: f64, w_mem: f64, sla_ms: f64) -> Option { let floor = load.auc_cpu(); let placed = |cpu: f64| load.place(cpu).expect("at or above the mean load"); - let (cpu, placement) = match sla_ms { - None => (floor, placed(floor)), - Some(sla) => { - if !analytical_cost_model::meets_sla(load.longest_chain_ms(), sla) { - return None; - } - let meets = - |cpu: f64| analytical_cost_model::meets_sla(placed(cpu).worst_batch_ms, sla); - let mut hi = floor.max(f64::MIN_POSITIVE); - let mut doublings = 0; - while !meets(hi) { - if doublings == MAX_DOUBLINGS { - return None; - } - hi *= 2.0; - doublings += 1; - } - let mut lo = floor; - if meets(lo) { - hi = lo; - } - while hi - lo > 1e-4 * hi { - let mid = 0.5 * (lo + hi); - if meets(mid) { - hi = mid; - } else { - lo = mid; - } - } - (hi, placed(hi)) + if !analytical_cost_model::meets_sla(load.longest_chain_ms(), sla_ms) { + return None; + } + let meets = |cpu: f64| analytical_cost_model::meets_sla(placed(cpu).worst_batch_ms, sla_ms); + let mut hi = floor.max(f64::MIN_POSITIVE); + let mut doublings = 0; + while !meets(hi) { + if doublings == MAX_DOUBLINGS { + return None; } - }; + hi *= 2.0; + doublings += 1; + } + let mut lo = floor; + if meets(lo) { + hi = lo; + } + while hi - lo > 1e-4 * hi { + let mid = 0.5 * (lo + hi); + if meets(mid) { + hi = mid; + } else { + lo = mid; + } + } + let (cpu, placement) = (hi, placed(hi)); let bytes = placement.peak_bytes; Some(ModelCost { cpu, @@ -540,15 +530,14 @@ mod tests { // Memory by use: 15 bytes always, 100 bytes for 0.1 s each second. assert!((one.bytes - 25.0).abs() < 1e-12); assert!((one.latency_ms - 100.0).abs() < 1e-9); - // Cost model 2 with no SLA: the mean CPU, and the queue it gives. - let two = cost_model_2(&plan, 1.0, 0.0, None).unwrap(); - assert!((two.cpu - 0.6).abs() < 1e-12); - assert!((two.latency_ms - 1000.0).abs() < 1e-6, "{}", two.latency_ms); + // Cost model 2 with a loose SLA: the mean CPU. + let loose = cost_model_2(&plan, 1.0, 0.0, 1e6).unwrap(); + assert!((loose.cpu - 0.6).abs() < 1e-12); // A 200 ms SLA: the query needs 0.5 vCPU beside ingest, C = 1.0. - let tight = cost_model_2(&plan, 1.0, 0.0, Some(200.0)).unwrap(); + let tight = cost_model_2(&plan, 1.0, 0.0, 200.0).unwrap(); assert!((tight.cpu - 1.0).abs() < 1e-3, "{}", tight.cpu); assert!(tight.latency_ms <= 200.0); // Below the chain, infeasible. - assert!(cost_model_2(&plan, 1.0, 0.0, Some(50.0)).is_none()); + assert!(cost_model_2(&plan, 1.0, 0.0, 50.0).is_none()); } } From ca113e2438c69a363af0ba9e774240793d0dd632 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 19:53:35 +0000 Subject: [PATCH 15/18] rqe-optimizer, docs: cost by use only, latency reported, not constrained The paper's message is lower cost and lower latency, so the MILP drops the peak-billed cost model and every latency constraint: - usage.rs (replacing placement.rs): a plan's resource use (ingest on ceil(rho) workers split by sample, compaction at window close, one query job per firing), its cost w_cpu * AUC(CPU) + w_mem * AUC(memory), and its latency, the longest chain (CPU is elastic). - milp::minimize_usage_cost (replacing minimize_cost_model): exact and linear, with `allowed` candidates per RAQE for PerQuery. Cost model 2, the placement, the SLA rows, the correction passes and meets_sla are removed; minimize is unchanged. - Docs: "Cost by use and batch latency": definitions, the cost model, CPU and memory parts, batch latency (reported), the MILP, and how it is solved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 304 +++--------- rqe-optimizer/src/analytical_cost_model.rs | 13 +- rqe-optimizer/src/lib.rs | 2 +- rqe-optimizer/src/milp.rs | 412 +++------------- rqe-optimizer/src/placement.rs | 543 --------------------- rqe-optimizer/src/usage.rs | 226 +++++++++ 6 files changed, 376 insertions(+), 1124 deletions(-) delete mode 100644 rqe-optimizer/src/placement.rs create mode 100644 rqe-optimizer/src/usage.rs diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index d18ab797..7d904a36 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -359,17 +359,16 @@ evaluates at once. The default weights are `(1, 0)`: CPU only. Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. -### MILP with latency SLA constraints: cost models, query placement and batch latency +### Cost by use and batch latency Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in -`rqe-optimizer/src/placement.rs` (load, cost models, placement) and -`milp::minimize_cost_model`. It extends the MILP above with two cost models -and a latency SLA on a whole batch of queries. Evaluated first on the -synthetic mixed template set; methods: ASAP (this MILP, with sharing), -PerQuery (the same MILP without sharing) and AutoSketch-Adapted (fixed -configs chosen by memory). Cost model 1 is evaluated with and without a -latency SLA; cost model 2 with an SLA only (without one, its provisioned -capacity, and so its latency, is not pinned down). +`rqe-optimizer/src/usage.rs` (resource use, cost, latency) and +`milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by +use. It has no latency constraint: the evaluation's message is lower cost and +lower latency, so latency is reported for every plan, not bounded. +Evaluated first on the synthetic mixed template set; methods: ASAP (this +MILP, with sharing), PerQuery (the same MILP without sharing) and +AutoSketch-Adapted (fixed configs chosen by memory). #### 1. Definitions @@ -384,8 +383,7 @@ capacity, and so its latency, is not pinned down). | `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | | `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | | `n_{i,D} = S_i / x_D` | windows a query merges | -| `H = lcm(T_i, y_D)` | hyperperiod: the pattern of query issues and window closes repeats every `H` | -| batch | all query jobs issued at one instant; `B0` is the one at `t = 0`, where every RAQE fires | +| batch | all query jobs issued at one instant | **Measurement assumption (sketch-bench as is).** Every sketch operation is single-threaded and compute-bound: sketch-bench's CPU time equals its wall @@ -393,49 +391,19 @@ time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses at most one core and, on a full core, takes its CPU time. The cost table's `*_cpu_secs` are all the model needs. -#### 2. Cost models +#### 2. Cost model -- **Cost model 1 (by use):** `w1 · AUC(CPU) + w2 · AUC(memory)`, the mean - vCPUs and GiB over time. CPU is elastic: a job gets a core whenever it is - ready. -- **Cost model 2 (by peak):** `w1 · max(CPU) + w2 · max(memory)`. The plan - provisions a resource point `(C vCPU, M GiB)`, billed at that peak, and all - of its work shares it. +`cost = w1 · AUC(CPU) + w2 · AUC(memory)`: the mean vCPUs and GiB over time, +priced per vCPU and per GiB (CPU only: `(1, 0)`; Fargate's prices). CPU is +elastic: a job gets a core whenever it is ready. -`w1`, `w2` are per vCPU and per GiB (CPU only: `(1, 0)`; Fargate prices). - -**How they map to cloud billing.** - -| Billing | Examples | Billed for | Cost model | -|---|---|---|---| -| Fixed-shape VMs | EC2, GCE instances | the instance shape (vCPU and memory bundled in fixed sizes) × run time, used or not | 2 (peak), but CPU and memory come in discrete bundles, not as two linear terms | -| Containers billed by allocation | AWS Fargate, GKE Autopilot, Azure Container Instances | the allocated vCPU and GB, priced separately, × run time (per second) | 2: `w1 · C + w2 · M`, separable and linear (our second weights are Fargate's prices) | -| Autoscaled containers and services | Cloud Run (request-based billing, CPU only while serving), Dataflow streaming, Flink on Kubernetes with an autoscaler | the allocation as it follows the load, × time | 1 (AUC), the closer the finer the scaling | -| Serverless functions | AWS Lambda, Cloud Functions | configured memory × run time (GB-seconds), CPU proportional to memory | per-job memory × time; not modeled | -| Managed analytics and streaming | Snowflake (warehouse size × run time), Managed Flink (KPU-hours, 1 vCPU + 4 GB each) | bundled resource units × time | 2 (provisioned), like the first two | - -Reserved instances, savings plans and spot change prices, not the billing -structure. - -Our ingest runs all the time and queries come in periodic bursts. - -- **Cost model 2** matches the first two rows and is how stream processing is - usually deployed: ingest and queries share long-running containers or VMs, - billed for what they are allocated. Both scheduling and the plan trade cost - for latency: with fewer cores, jobs wait for one, so a smaller `C` costs - less at the price of latency; and a plan that merges less at query time - needs less capacity for the same SLA. -- **Cost model 1** matches fine-grained autoscaling, idealized: capacity - follows the load at once. Queueing saves nothing here (a job holds its - memory only while it runs, so its memory × time is the same whenever it - runs, and CPU is billed by use), so every job runs as soon as it is ready. - The trade-off comes from the plan instead: a cheap plan keeps short windows - and merges many of them at query time (long queries), a fast one precomputes - more at ingest (more open windows, more CPU and memory). A tighter SLA rules - out the slow chains and forces the dearer plans. Real autoscalers add - trade-offs this idealization leaves out (scale-up and cold-start delay, - warm minimum instances billed while idle, billing granularity), so cost - model 1 is a lower bound for them. +This is billing by use, as on fine-grained autoscaling platforms (Cloud Run +with request-based billing, Dataflow streaming, Flink on Kubernetes with an +autoscaler), idealized: capacity follows the load at once. Billing for +provisioned capacity (VMs, or containers billed by allocation such as +Fargate) is not modeled. Since a job holds its memory only while it runs, its +memory × time is the same whenever it runs, and queueing a job would save +nothing. #### 3. CPU: parts and how each is computed @@ -486,9 +454,8 @@ storage once compacted, and a query reads stored instances in place. | Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | `AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) -+ Σ_i q_{i,D} · (query run time) / T_i`. Under cost model 1 every job runs on -its own core, so a compaction runs for `c_D` and a query for `ℓ_{i,D}`. Under -cost model 2 memory is the peak the placement reaches. ++ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its +own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. In words: @@ -508,206 +475,73 @@ In words: and a query's memory are held only while they run, a fraction `run time / y_D` or `run time / T_i` of the time. -#### 5. Batch latency and the SLA +#### 5. Batch latency A batch's **latency** is the time from its issue until its last query job -finishes, compaction included. The **query latency** of a plan is its worst -batch latency over the hyperperiod. A latency SLA `L` requires query latency -`≤ L`. The SLA is on the batch only: per-RAQE latency bounds -(`Raqe::latency_sla_ms`) are not used by these cost models. Latencies are -compared with `L` with a relative slack of `1e-9` -(`analytical_cost_model::meets_sla`), so float error in summing µs-scale work -can't turn a chain equal to `L` into a miss; every check (the MILP's chain -filter and the placement) uses the same `chain_ms` and the same slack. - -Both cost models get the latency from the same job placement (§6); they -differ only in the CPU capacity it is given: - -- Cost model 1: CPU is elastic, so the placement runs with unlimited capacity - and no job waits for a core. A batch's latency is then its longest - **chain** `c_D + ℓ_{i,D}` (the newest window's compaction, then the query), - and the SLA requires `c_D + ℓ_{i,D} ≤ L` for every assigned pair. -- Cost model 2 (always with an SLA): jobs share the provisioned capacity `C`, - so they may queue, and the latency is whatever the placement gives. - -#### 6. Job placement algorithm (both cost models) - -Given a CPU capacity, the placement finds when each job runs and gives every -batch's latency and the CPU and memory over time. Cost model 1 runs it with -unlimited capacity (elastic CPU); cost model 2 with the provisioned `C`. Capacity is -fractional; running jobs share it as rates (fluid, priority-ordered processor -sharing). +finishes, compaction included. A plan's **query latency** is its worst batch +latency. It is reported for every plan, not constrained. -```text -capacity for jobs K = C − Σ_D ρ_D (ingest is steady; K > 0 and the - mean load at most C, else infeasible) -simulate 2 hyperperiods, event-driven (events: query issues, window closes, completions): - ready = compaction jobs (triggered at window closes) - + query jobs whose newest window is compacted - order: issue / trigger time (older first), then compaction before query - (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given) - a job at rate a_j finishes when its remaining work / a_j elapses - recompute the rates at every event -outputs: per-RAQE and per-batch latency, worst batch latency, - CPU(t) = Σ ρ_D + Σ a_j, - MEM(t) = Σ (I_D + stored_D) + memory of the running compactions and queries -``` +CPU is elastic, so no job waits for a core, and a batch's latency is its +longest **chain**: the newest window's compaction, then the query, each on a +full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query +latency is the longest chain over its RAQEs. Per-RAQE latency bounds +(`Raqe::latency_sla_ms`) are not used. -In words: +In words: the trade-off between cost and latency comes from the plan. A cheap +plan keeps short windows and merges many of them at query time (long +chains); a faster one precomputes more at ingest (more open windows, more CPU +and memory). The MILP picks the cheapest plan; its latency is what that plan +gives. -1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs off - the top; the rest, `K`, which may be a fraction, is shared by compaction - and query jobs. If the plan's mean load does not fit in `C`, there is no - placement. -2. **Issue jobs.** Each window close triggers a compaction job for its - deployment. Each firing issues a query job, which becomes ready only once - its deployment's newest window is compacted. -3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. - Within a batch, compaction runs before queries, because queries wait for - it. Then the longest remaining work runs first, so a long job doesn't end - up running alone at the end of the batch. -4. **Share capacity as rates.** In that order, each job gets up to one core - (a single-threaded job can't use more) from the capacity still free. The - last one served may get only a fraction and runs slower in proportion. - Memory does not limit the placement: billing charges the memory allocated, - and `M` is set to the peak the placement reaches. (Cost model 1 runs the - placement with unlimited capacity.) -5. **Advance to the next event.** Time jumps to the next query issue or window close, or the - earliest finishing job, everyone's remaining work drops by rate × elapsed - time, and the rates are recomputed. -6. **Read off the results.** A query's latency is its finish minus its - issue, and a batch's latency is that of its last query. The CPU in use - is ingest plus the rates; the memory is ingest, storage and the running - compactions' and queries' memory. - -Two hyperperiods are simulated so that work carried over the wrap-around is -counted. A job uses at most one core, so with `K ≥ 1` a batch on its own ends -within `Σ work / K + max chain` (Graham's list-scheduling bound). - -With unlimited capacity (cost model 1) the placement has a closed form: every -job starts when ready on its own core, so a compaction runs for exactly `c_D` -and a query for exactly `ℓ_{i,D}`, a batch's latency is its longest chain, -and the memory over time averages to §4's `AUC(memory)`. That is why cost -model 1's MILP below is exact. - -The simulation keeps the issued, unfinished jobs in a pending list, so each -event looks only at the jobs in flight, not at every job of the two -hyperperiods. - -#### 7. MILP formulation +#### 6. MILP formulation Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), -`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`; cost model 2 adds `C, M ≥ 0`. -Constants per candidate and pair are §3 and §4's. - -Common rows: +`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and +pair are §3 and §4's. ```text -Σ_D z_{i,D} = 1 for every RAQE i -z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E -stored_D ≥ card(G)·m·((S_i − x_D)/y_D + 1) · z_{i,D} -with SLA L: z_{i,D} = 0 if c_D + ℓ_{i,D} > L (the chain fits) +minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +s.t. Σ_D z_{i,D} = 1 for every RAQE i + z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E + stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} ``` In words: +- The objective is the price of the mean vCPUs (ingest and compaction per + active deployment, plus each RAQE's query work per second), plus the price + of the mean memory (ingest and storage per active deployment, each + compaction's partial copies for the fraction of time it runs, and each + query's memory for the fraction of time it runs). - Every RAQE is served by exactly one eligible deployment. - A deployment is active if and only if some RAQE uses it, so its ingest is paid once, however many RAQEs share it. - A deployment stores enough closed windows for the longest lookback it serves (a linearized max). -- Under an SLA, a pair whose own chain (the newest window's compaction, then - the query, each on a full core) is longer than `L` can never meet it, so it - is ruled out. -Cost model 1: +#### 7. Solution method -```text -minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) - + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] -``` - -In words: the price of the mean vCPUs (ingest and compaction per active -deployment, plus each RAQE's query work per second), plus the price of the -mean memory (ingest and storage per active deployment, each compaction's -partial copies for the fraction of time it runs, and each query's memory for -the fraction of time it runs). With elastic CPU this is the cost -exactly, and the SLA is fully handled by the chain row above. +Every term is linear in `u` and `z`, so the MILP is solved exactly +(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair +so the solver sees magnitudes near 1). The solved plan's cost and latency are +then computed from its resource use (`usage::usage_cost`). -Cost model 2: +- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` + takes `allowed`, the candidate indices each RAQE may use. PerQuery gives + each RAQE its own candidates, with a separate copy of any deployment that + two RAQEs could both use. Two RAQEs share a deployment only by choosing the + same candidate index (`u_D` is per index), so their copies stay apart and + each pays its own ingest. +- **AutoSketch** keeps its memory-chosen configs and is priced by the same + function: its cost by use and its latency, the longest chain. -```text -minimize w1 · C + w2 · M -s.t. C ≥ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} (mean load) - M ≥ Σ_D ((I_D + k_D · w_D) · u_D + stored_D) + Σ_(i,D) q_{i,D} · z_{i,D} + δ_M (memory) - C ≥ Σ_D ρ_D · u_D + ( Σ_(i,D) ℓ_{i,D} · z_{i,D} + Σ_D c_D · u_D ) / L + δ_C (batch B0) -``` - -`δ_C = δ_M = 0` in the first solve (§8). Every row is linear: `L` is a -constant. - -In words: +#### 8. Outputs -- The objective prices the provisioned peak, `C` vCPUs and `M` GiB. -- **Mean load:** the capacity must at least carry the average work, or a - backlog grows without bound. -- **Memory:** the capacity must hold ingest and storage, plus every - compaction's and every query's memory as if all ran at once (an upper bound - on the peak). -- **Batch `B0`:** when every RAQE fires together, ingest keeps - `Σ ρ_D · u_D` vCPUs busy. The rest must finish the batch's queries and - compactions within `L`, so `C − ingest ≥ batch work / L`. This treats the - batch as divisible over the free capacity, which is a necessary condition. - §8 corrects it. - -#### 8. Solution method - -**Cost model 1** is solved exactly: with elastic CPU every term is linear, -and the SLA is a filter on pairs. - -**Cost model 2** cannot be solved exactly by this MILP: a peak depends on when -jobs run, which is a scheduling problem. A time-indexed MILP (a variable per -job per time slot) would be exact, but µs–ms jobs over a 60 s hyperperiod -make it far too large. So the MILP is a linear surrogate: its batch row treats -`B0`'s work as divisible over the capacity ingest leaves, and its memory row -holds every query at once. The plan is then sized and corrected with the -placement: - -1. **Solve** the MILP and take its mapping. -2. **Size** the mapping with the placement: `C*` is the smallest `C` at which - the worst batch meets `L` (doubling from the mean load, then binary search - to a 1e-4 relative gap; it exists whenever every chain fits, and the - doubling stops after 64 steps as a guard against float pathologies); - `M*` is the placement's peak memory at `C*`. The plan's cost is - `w1 · C* + w2 · M*`. -3. **Correct:** measure the surrogate's error on that mapping, - `δ_C = C* − Ĉ` and `δ_M = M* − M̂` (`Ĉ`, `M̂`: the rows' values for it), add - them to the rows and solve again. In words: the first solve may favor a - mapping whose real peak is higher than the rows said (jobs can't be split, - and queries wait for compaction), or penalize one whose real memory peak is - lower (not every query runs at once). Adding the observed gap lets the - next solve rank mappings closer to their placed cost. -4. **Keep** the mapping with the lowest placed cost; stop when a mapping - repeats, or after three corrections. - -**PerQuery** is the same MILP with sharing ruled out. `minimize_cost_model` -takes `allowed`, the candidate indices each RAQE may use. PerQuery gives each -RAQE its own candidates, with a separate copy of any deployment that two -RAQEs could both use. Two RAQEs share a deployment only by choosing the same -candidate index (`u_D` is per index), so their copies stay apart and each -pays its own ingest. -**AutoSketch** keeps its memory-chosen configs and is priced by the same -functions: cost model 1 by use (latency its longest chain); cost model 2 by -the placement and the binary search on `C`. - -#### 9. Outputs - -Per (method, cost model, SLA): cost; mean and peak CPU and memory; the -resource point; worst batch and per-RAQE latency; MILP solves; planning time. -Figure: cost vs. query latency, one line per method, one panel per cost model -and weight setting. +Per (method, weight setting): cost; mean CPU and memory, by part; query +latency and per-RAQE latency; planning time. Figure: cost and latency per +method, for each workload. ## Analytical cost model @@ -845,8 +679,8 @@ latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg summed over the sketch and its key tracker, if any. On its own it is not a wall-clock SLA: it assumes no parallel execution across -groups and no cheaper k-way merge. In the cost-model section above it is one -firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. +groups and no cheaper k-way merge. In "Cost by use and batch latency" above it +is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. ## Procedure @@ -876,7 +710,7 @@ each phase's CPU and memory, together with the selected deployment mapping. - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. - **Latency SLAs:** `minimize` takes optional per-RAQE latency bounds; - `minimize_cost_model` takes a batch SLA under cost model 1 or 2 (above). The + `minimize_usage_cost` has none and reports the batch latency (above). The enumerator reports latency but does not reject a mapping for it. - **Memory model:** query memory sums every RAQE's merge and output memory, as if all queries run at once; real concurrency is not modeled. Query output diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index c9dc809c..56a2b0d9 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -285,21 +285,12 @@ pub fn compaction_bytes(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { } /// One firing's chain on its own cores, ms: the newest window's compaction, -/// then the query (merge, then estimate). Under elastic CPU this is the -/// firing's latency; no placement can do better. +/// then the query (merge, then estimate). With elastic CPU this is the +/// firing's latency. pub fn chain_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { 1000.0 * compaction_secs(deployment, facts) + query_latency_ms(raqe, deployment, facts) } -/// Slack for comparing a latency with an SLA: float error in summing µs-scale -/// work must not turn a chain equal to `L` into a miss. -pub const LATENCY_SLACK: f64 = 1e-9; - -/// Whether `latency_ms` meets `sla_ms`, with [`LATENCY_SLACK`]. -pub fn meets_sla(latency_ms: f64, sla_ms: f64) -> bool { - latency_ms <= sla_ms * (1.0 + LATENCY_SLACK) -} - pub fn score( raqes: &[Raqe], deployments: &[Deployment], diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 115d7221..44429a81 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -15,9 +15,9 @@ pub mod candidates; pub mod enumerate; pub mod milp; pub mod pareto; -pub mod placement; pub mod saturation; pub mod theory; +pub mod usage; use std::collections::BTreeMap; use std::collections::BTreeSet; diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 55980053..59799917 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -227,168 +227,51 @@ pub fn minimize( }) } -/// Which cost model [`minimize_cost_model`] minimizes -/// (`docs/rqe_sketch_deployment_v1.md`, "MILP with latency SLA constraints: -/// cost models, query placement and batch latency"). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CostModel { - /// `w_cpu · AUC(CPU) + w_mem · AUC(memory)`: billed by use, CPU elastic. - /// Exact and linear. - One, - /// `w_cpu · max(CPU) + w_mem · max(memory)`: a provisioned `(C, M)`, - /// billed at the peak. The MILP's batch row is a surrogate, corrected by - /// the placement (see [`minimize_cost_model`]). - Two, -} - -/// A [`minimize_cost_model`] solution, priced by its cost model. +/// A [`minimize_usage_cost`] solution, with its cost billed by use and its +/// latency. #[derive(Debug, Clone)] -pub struct CostModelSolution { +pub struct UsageSolution { pub milp: MilpSolution, /// One candidate index per RAQE. pub mapping: Mapping, - pub cost: crate::placement::ModelCost, - /// MILP solves (more than one only for cost model 2). - pub solves: usize, + pub cost: crate::usage::UsageCost, } -/// Correction passes for cost model 2, beyond the first solve. -const COST_MODEL_2_CORRECTIONS: usize = 3; - -/// Minimize `cost_model` with weights `w_cpu`, `w_mem` (per vCPU, per GiB), -/// optionally under a batch latency SLA `sla_ms`. Per-RAQE latency bounds -/// (`Raqe::latency_sla_ms`) are not used here: the SLA is on the batch. +/// Minimize the cost billed by use, `w_cpu · AUC(CPU) + w_mem · AUC(memory)` +/// (per vCPU, per GiB; `docs/rqe_sketch_deployment_v1.md`, "Cost by use and +/// batch latency"). No latency constraint: the latency is reported, not +/// bounded, and per-RAQE latency bounds (`Raqe::latency_sla_ms`) are not +/// used. Every term is linear, so this is exact. /// /// `allowed`, when given, lists for each RAQE the candidate indices it may /// use, e.g. only its own candidates for PerQuery (no sharing). Two RAQEs /// share a deployment only by choosing the same candidate index, so giving /// each RAQE its own copies of identical deployments keeps them apart, each /// paying its own ingest. -/// -/// Cost model 1 is solved exactly. Cost model 2's batch row -/// (`Σ ℓ + Σ compaction ≤ L · (C − ingest)`) treats the heaviest batch as -/// divisible, and its memory row holds every query at once; the placement -/// then sizes the chosen mapping's real `(C, M)`. The gap between the two is -/// added back to the rows (`C ≥ … + δ_C`, `M ≥ … + δ_M`) and the MILP solved -/// again, keeping the mapping whose placed cost is lowest, until a mapping -/// repeats or after [`COST_MODEL_2_CORRECTIONS`] passes. -#[allow(clippy::too_many_arguments)] -pub fn minimize_cost_model( - raqes: &[Raqe], - deployments: &[Deployment], - facts: &WorkloadFacts, - w_cpu: f64, - w_mem: f64, - cost_model: CostModel, - accuracy: &Accuracy, - sla_ms: Option, - allowed: Option<&[Vec]>, -) -> Result { - use crate::placement::{cost_model_1, cost_model_2, PlanLoad}; - assert!( - cost_model == CostModel::One || sla_ms.is_some(), - "cost model 2 is evaluated with a latency SLA only" - ); - let price = |mapping: &Mapping| { - let load = PlanLoad::new(raqes, deployments, mapping, facts); - match (cost_model, sla_ms) { - (CostModel::One, _) => Some(cost_model_1(&load, w_cpu, w_mem)), - (CostModel::Two, Some(sla)) => cost_model_2(&load, w_cpu, w_mem, sla), - (CostModel::Two, None) => unreachable!("asserted above"), - } - }; - let mut corrections = (0.0, 0.0); - let mut best: Option = None; - let mut seen: Vec = Vec::new(); - for solve in 1..=1 + COST_MODEL_2_CORRECTIONS { - let (milp, mapping) = solve_cost_model( - raqes, - deployments, - facts, - w_cpu, - w_mem, - cost_model, - accuracy, - sla_ms, - allowed, - corrections, - )?; - let cost = price(&mapping).ok_or(ResolutionError::Infeasible)?; - if cost_model == CostModel::One { - return Ok(CostModelSolution { - milp, - mapping, - cost, - solves: 1, - }); - } - let load = PlanLoad::new(raqes, deployments, &mapping, facts); - let (surrogate_cpu, surrogate_bytes) = - surrogate_peaks(&load, sla_ms.expect("cost model 2 has an SLA")); - corrections = (cost.cpu - surrogate_cpu, cost.bytes - surrogate_bytes); - let repeated = seen.contains(&mapping); - seen.push(mapping.clone()); - if best.as_ref().is_none_or(|b| cost.value < b.cost.value) { - best = Some(CostModelSolution { - milp, - mapping, - cost, - solves: solve, - }); - } - if repeated { - break; - } - } - let mut best = best.expect("at least one solve"); - best.solves = seen.len(); - Ok(best) -} - -/// Cost model 2's surrogate `(C, M)` of a placed plan, the MILP's rows -/// without corrections: `C = max(mean load, ingest + batch work / L)`, and `M` -/// with every query's memory at once. -fn surrogate_peaks(load: &crate::placement::PlanLoad, sla_ms: f64) -> (f64, f64) { - let batch: f64 = load.queries.iter().map(|q| q.work_secs).sum::() - + load - .deployments - .iter() - .map(|d| d.compaction_secs) - .sum::(); - let cpu = load - .auc_cpu() - .max(load.ingest_cpu() + batch / (sla_ms / 1000.0)); - let bytes = load.static_bytes() - + load - .deployments - .iter() - .map(|d| d.compaction_bytes) - .sum::() - + load.queries.iter().map(|q| q.memory_bytes).sum::(); - (cpu, bytes) -} - -/// One MILP solve for [`minimize_cost_model`], with cost model 2's -/// corrections `(δ_C vCPU, δ_M bytes)`. -#[allow(clippy::too_many_arguments)] -fn solve_cost_model( +pub fn minimize_usage_cost( raqes: &[Raqe], deployments: &[Deployment], facts: &WorkloadFacts, w_cpu: f64, w_mem: f64, - cost_model: CostModel, accuracy: &Accuracy, - sla_ms: Option, allowed: Option<&[Vec]>, - (cpu_correction, bytes_correction): (f64, f64), -) -> Result<(MilpSolution, Mapping), ResolutionError> { +) -> Result { let secs = |ms: u64| ms as f64 / 1000.0; - // Per candidate: ingest vCPUs, compaction per window, its rate, ingest bytes. + let gib = |bytes: f64| bytes / BYTES_PER_GIB; + // Per candidate: ingest vCPUs and bytes (every worker's open windows), + // compaction CPU-seconds per window and the bytes it holds. let ingest_cpu: Vec = deployments .iter() .map(|d| analytical_cost_model::ingest(d, facts).cpu_secs_per_sec) .collect(); + let ingest_bytes: Vec = deployments + .iter() + .map(|d| { + analytical_cost_model::ingest(d, facts).memory_bytes + * analytical_cost_model::ingest_workers(d, facts) + }) + .collect(); let compaction: Vec = deployments .iter() .map(|d| analytical_cost_model::compaction_secs(d, facts)) @@ -397,14 +280,6 @@ fn solve_cost_model( .iter() .map(|d| analytical_cost_model::compaction_bytes(d, facts)) .collect(); - let ingest_bytes: Vec = deployments - .iter() - .map(|d| { - analytical_cost_model::ingest(d, facts).memory_bytes - * analytical_cost_model::ingest_workers(d, facts) - }) - .collect(); - // Eligible pairs (within `allowed`), less those whose chain exceeds the SLA. let eligible: Vec> = raqes .iter() .enumerate() @@ -412,14 +287,6 @@ fn solve_cost_model( eligible_deployments_for(raqe, deployments, facts, accuracy) .into_iter() .filter(|d| allowed.is_none_or(|allowed| allowed[i].contains(d))) - .filter(|&d| { - sla_ms.is_none_or(|sla| { - analytical_cost_model::meets_sla( - analytical_cost_model::chain_ms(raqe, &deployments[d], facts), - sla, - ) - }) - }) .collect() }) .collect(); @@ -437,23 +304,24 @@ fn solve_cost_model( let storage = |i: usize, d: usize| { analytical_cost_model::storage_bytes(&raqes[i], &deployments[d], facts) }; - - // Scale: the cost of each RAQE alone on its cheapest pair (cost model 1), - // so HiGHS sees magnitudes near 1. - let cpu_of = |i: usize, d: usize| { - ingest_cpu[d] - + compaction[d] / secs(deployments[d].slide_ms) - + work(i, d) / secs(raqes[i].interval_ms) + // Per-deployment and per-pair costs, priced. + let deployment_cost = |d: usize| { + let slide = secs(deployments[d].slide_ms); + w_cpu * (ingest_cpu[d] + compaction[d] / slide) + + w_mem * gib(ingest_bytes[d] + compaction_bytes[d] * compaction[d] / slide) }; - let gib = |bytes: f64| bytes / BYTES_PER_GIB; + let pair_cost = |i: usize, d: usize| { + let interval = secs(raqes[i].interval_ms); + w_cpu * work(i, d) / interval + w_mem * gib(query_bytes(i, d) * work(i, d) / interval) + }; + + // Scale: each RAQE alone on its cheapest pair, so HiGHS sees magnitudes + // near 1. let reference: f64 = (0..raqes.len()) .map(|i| { eligible[i] .iter() - .map(|&d| { - w_cpu * cpu_of(i, d) - + w_mem * gib(ingest_bytes[d] + storage(i, d) + query_bytes(i, d)) - }) + .map(|&d| deployment_cost(d) + pair_cost(i, d) + w_mem * gib(storage(i, d))) .fold(f64::INFINITY, f64::min) }) .sum(); @@ -462,24 +330,6 @@ fn solve_cost_model( } else { 1.0 }; - let cpu_scale = (0..raqes.len()) - .map(|i| { - eligible[i] - .iter() - .map(|&d| cpu_of(i, d)) - .fold(f64::INFINITY, f64::min) - }) - .sum::() - .max(f64::MIN_POSITIVE); - let bytes_scale = (0..raqes.len()) - .map(|i| { - eligible[i] - .iter() - .map(|&d| ingest_bytes[d] + storage(i, d) + query_bytes(i, d)) - .fold(f64::INFINITY, f64::min) - }) - .sum::() - .max(1.0); let mut variables = ProblemVariables::new(); let active: Vec = deployments @@ -495,61 +345,21 @@ fn solve_cost_model( .collect() }) .collect(); - // Storage per deployment, in units of `bytes_scale`. + // Priced storage per deployment, scaled: the max over the RAQEs it serves. let stored: Vec = deployments .iter() .map(|_| variables.add(variable().min(0))) .collect(); - // Cost model 2: C and M, in units of `cpu_scale` and `bytes_scale`. - let peaks = (cost_model == CostModel::Two).then(|| { - ( - variables.add(variable().min(0)), - variables.add(variable().min(0)), - ) - }); - - // CPU and memory terms, in scaled units. - let mut mean_cpu = Expression::from(0.0); - let mut batch_work = Expression::from(0.0); - let mut ingest = Expression::from(0.0); - let mut held_bytes: Expression = stored.iter().sum(); - // Transient memory: every compaction and query at once (cost model 2's - // conservative peak), and by use (cost model 1). - let mut transient_bytes_all = Expression::from(0.0); - let mut transient_bytes_auc = Expression::from(0.0); + + let mut goal: Expression = stored.iter().sum(); for (d, &u) in active.iter().enumerate() { - let deployment = &deployments[d]; - mean_cpu.add_mul( - (ingest_cpu[d] + compaction[d] / secs(deployment.slide_ms)) / cpu_scale, - u, - ); - ingest.add_mul(ingest_cpu[d] / cpu_scale, u); - batch_work.add_mul(compaction[d] / cpu_scale, u); - held_bytes.add_mul(ingest_bytes[d] / bytes_scale, u); - transient_bytes_all.add_mul(compaction_bytes[d] / bytes_scale, u); - transient_bytes_auc.add_mul( - compaction_bytes[d] * compaction[d] / secs(deployment.slide_ms) / bytes_scale, - u, - ); + goal.add_mul(deployment_cost(d) / reference, u); } for (i, choices) in assignments.iter().enumerate() { - let interval = secs(raqes[i].interval_ms); for &(d, z) in choices { - mean_cpu.add_mul(work(i, d) / interval / cpu_scale, z); - batch_work.add_mul(work(i, d) / cpu_scale, z); - transient_bytes_all.add_mul(query_bytes(i, d) / bytes_scale, z); - transient_bytes_auc.add_mul(query_bytes(i, d) * work(i, d) / interval / bytes_scale, z); + goal.add_mul(pair_cost(i, d) / reference, z); } } - let cpu_weight = w_cpu * cpu_scale / reference; - let bytes_weight = w_mem * gib(bytes_scale) / reference; - let goal = match peaks { - None => { - cpu_weight * mean_cpu.clone() - + bytes_weight * (held_bytes.clone() + transient_bytes_auc) - } - Some((c, m)) => cpu_weight * c + bytes_weight * m, - }; let mut model = variables.minimise(goal).using(default_solver); for (i, choices) in assignments.iter().enumerate() { @@ -557,7 +367,7 @@ fn solve_cost_model( model.add_constraint(sum.eq(1)); for &(d, z) in choices { model.add_constraint((z - active[d]).leq(0)); - let needed = storage(i, d) / bytes_scale; + let needed = w_mem * gib(storage(i, d)) / reference; if needed > 0.0 { model.add_constraint((needed * z - stored[d]).leq(0)); } @@ -572,19 +382,6 @@ fn solve_cost_model( .sum(); model.add_constraint((u - used).leq(0)); } - if let Some((c, m)) = peaks { - model.add_constraint((mean_cpu - c).leq(0)); - model.add_constraint( - (held_bytes + transient_bytes_all + bytes_correction / bytes_scale - m).leq(0), - ); - if let Some(sla) = sla_ms { - // C ≥ ingest + (batch work) / L + δ_C. - let l = sla / 1000.0; - model.add_constraint( - (ingest + batch_work * (1.0 / l) + cpu_correction / cpu_scale - c).leq(0), - ); - } - } let solved = model.solve()?; let mapping: Mapping = assignments @@ -596,16 +393,22 @@ fn solve_cost_model( .expect("the MILP assigns every RAQE one deployment") }) .collect(); + let cost = crate::usage::usage_cost( + &crate::usage::PlanLoad::new(raqes, deployments, &mapping, facts), + w_cpu, + w_mem, + ); let plan_cost = score(raqes, deployments, &mapping, facts); let (planned, planned_raqes) = plan(raqes, deployments, &mapping); - Ok(( - MilpSolution { + Ok(UsageSolution { + milp: MilpSolution { deployments: planned, raqes: planned_raqes, plan_cost, }, mapping, - )) + cost, + }) } /// Keeps the deployments `mapping` uses, renumbered, with their instance @@ -775,22 +578,8 @@ mod tests { assert_eq!(solve(&[bounded]), vec![1]); } - /// The cheapest mapping under `price` (None: unservable), by brute force. - fn brute_force_cost( - raqes: &[Raqe], - deployments: &[Deployment], - facts: &WorkloadFacts, - price: impl Fn(&Mapping) -> Option, - ) -> f64 { - brute_force(raqes, deployments, facts, &table_accuracy) - .iter() - .filter_map(price) - .min_by(f64::total_cmp) - .expect("servable") - } - /// Two RAQEs, 100 groups, and candidates that trade ingest for queries. - fn cost_model_workload() -> (Vec, Vec, WorkloadFacts) { + fn usage_workload() -> (Vec, Vec, WorkloadFacts) { let raqes = vec![raqe("frequent", 60_000), raqe("long", 600_000)]; // (memory, insert, merge, query, window, slide): cheap ingest with // slow queries; costlier ingest with fast ones; a 10-minute window @@ -804,80 +593,37 @@ mod tests { } #[test] - fn cost_model_1_matches_brute_force_with_and_without_an_sla() { - use crate::placement::{cost_model_1, PlanLoad}; - let (raqes, deployments, facts) = cost_model_workload(); - for (w_cpu, w_mem) in [(1.0, 0.0), (1.0, 4.0)] { - for sla_ms in [None, Some(1e5), Some(300.0)] { - let price = |mapping: &Mapping| { - let cost = cost_model_1( - &PlanLoad::new(&raqes, &deployments, mapping, &facts), - w_cpu, - w_mem, - ); - sla_ms - .is_none_or(|l| cost.latency_ms <= l) - .then_some(cost.value) - }; - let best = brute_force_cost(&raqes, &deployments, &facts, price); - let got = minimize_cost_model( - &raqes, - &deployments, - &facts, - w_cpu, - w_mem, - CostModel::One, - &table_accuracy, - sla_ms, - None, - ) - .expect("feasible"); - assert!( - (got.cost.value - best).abs() <= 1e-9 * best, - "({w_cpu}, {w_mem}), {sla_ms:?}: {} vs {best}", - got.cost.value - ); - assert!(sla_ms.is_none_or(|l| got.cost.latency_ms <= l)); - } - } - } - - #[test] - fn cost_model_2_meets_the_sla_and_corrections_find_the_best_mapping() { - use crate::placement::{cost_model_2, PlanLoad}; - let (raqes, deployments, facts) = cost_model_workload(); - for (w_cpu, w_mem) in [(1.0, 0.0), (1.0, 4.0)] { - for sla_ms in [1e5, 2_000.0, 300.0] { - let price = |mapping: &Mapping| { - cost_model_2( + fn usage_cost_matches_brute_force() { + use crate::usage::{usage_cost, PlanLoad}; + let (raqes, deployments, facts) = usage_workload(); + for (w_cpu, w_mem) in [(1.0, 0.0), (0.0, 1.0), (1.0, 4.0)] { + let best = brute_force(&raqes, &deployments, &facts, &table_accuracy) + .iter() + .map(|mapping| { + usage_cost( &PlanLoad::new(&raqes, &deployments, mapping, &facts), w_cpu, w_mem, - sla_ms, ) - .map(|cost| cost.value) - }; - let best = brute_force_cost(&raqes, &deployments, &facts, price); - let got = minimize_cost_model( - &raqes, - &deployments, - &facts, - w_cpu, - w_mem, - CostModel::Two, - &table_accuracy, - Some(sla_ms), - None, - ) - .expect("feasible"); - assert!(got.cost.latency_ms <= sla_ms * (1.0 + 1e-9)); - assert!( - (got.cost.value - best).abs() <= 1e-3 * best, - "({w_cpu}, {w_mem}), {sla_ms}: {} vs {best} after {} solves", - got.cost.value, - got.solves - ); - } + .value + }) + .min_by(f64::total_cmp) + .expect("servable"); + let got = minimize_usage_cost( + &raqes, + &deployments, + &facts, + w_cpu, + w_mem, + &table_accuracy, + None, + ) + .expect("feasible"); + assert!( + (got.cost.value - best).abs() <= 1e-9 * best, + "({w_cpu}, {w_mem}): {} vs {best}", + got.cost.value + ); } } @@ -889,15 +635,13 @@ mod tests { let deployments = vec![one.clone(), one]; let facts = facts(100, 100); let solve = |allowed: Option<&[Vec]>| { - minimize_cost_model( + minimize_usage_cost( &raqes, &deployments, &facts, 1.0, 0.0, - CostModel::One, &table_accuracy, - None, allowed, ) .expect("feasible") diff --git a/rqe-optimizer/src/placement.rs b/rqe-optimizer/src/placement.rs deleted file mode 100644 index 50894b19..00000000 --- a/rqe-optimizer/src/placement.rs +++ /dev/null @@ -1,543 +0,0 @@ -//! A plan's load over time, its cost under cost models 1 and 2, and the query -//! placement that gives its batch latency (`docs/rqe_sketch_deployment_v1.md`, -//! "MILP with latency SLA constraints: cost models, query placement and batch -//! latency"). Both cost models use the placement: cost model 1 with unlimited -//! capacity, which has the closed form [`cost_model_1`] uses, and cost model 2 -//! with the provisioned `C`. -//! -//! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. -//! Each closed window is compacted (the workers' partials merged into one), and -//! each RAQE firing runs one query job (merge, then estimate) once the newest -//! window is compacted. A job uses at most one core: sketch-bench's operations -//! are single-threaded, their CPU time equal to their wall time. - -use std::collections::BTreeMap; - -use crate::analytical_cost_model::{self, BYTES_PER_GIB}; -use crate::{Deployment, Mapping, Millis, Raqe, WorkloadFacts}; - -/// One active deployment's steady load. -#[derive(Debug, Clone)] -pub struct DeploymentLoad { - /// Ingest CPU, vCPUs. - pub ingest_cpu: f64, - /// Open windows on every worker, bytes. - pub ingest_bytes: f64, - /// Closed windows kept for the longest lookback served, bytes. - pub storage_bytes: f64, - /// CPU-seconds to compact one closed window (0 with one worker). - pub compaction_secs: f64, - /// Bytes a compaction holds while it runs: the closed window's partial - /// copies (0 with one worker). - pub compaction_bytes: f64, - /// Windows close every slide. - pub slide_ms: Millis, -} - -/// One RAQE's query job, run every interval. -#[derive(Debug, Clone)] -pub struct QueryLoad { - /// Index into [`PlanLoad::deployments`]. - pub deployment: usize, - pub interval_ms: Millis, - /// Compaction of the newest window, then this job, on their own cores, ms - /// ([`analytical_cost_model::chain_ms`]). - pub chain_ms: f64, - /// Merge then estimate, CPU-seconds (one core at most). - pub work_secs: f64, - /// Merge accumulators and output, held while the job runs. - pub memory_bytes: f64, -} - -/// A plan as load over time. -#[derive(Debug, Clone)] -pub struct PlanLoad { - pub deployments: Vec, - /// Index-aligned with the plan's RAQEs. - pub queries: Vec, -} - -impl PlanLoad { - /// The load of `mapping` (one candidate index per RAQE). - pub fn new( - raqes: &[Raqe], - candidates: &[Deployment], - mapping: &Mapping, - facts: &WorkloadFacts, - ) -> PlanLoad { - let mut index: BTreeMap = BTreeMap::new(); - let mut deployments: Vec = Vec::new(); - let mut queries = Vec::with_capacity(raqes.len()); - for (raqe, &candidate) in raqes.iter().zip(mapping) { - let deployment = &candidates[candidate]; - let at = *index.entry(candidate).or_insert_with(|| { - let ingest = analytical_cost_model::ingest(deployment, facts); - let workers = analytical_cost_model::ingest_workers(deployment, facts); - deployments.push(DeploymentLoad { - ingest_cpu: ingest.cpu_secs_per_sec, - ingest_bytes: ingest.memory_bytes * workers, - storage_bytes: 0.0, - compaction_secs: analytical_cost_model::compaction_secs(deployment, facts), - compaction_bytes: analytical_cost_model::compaction_bytes(deployment, facts), - slide_ms: deployment.slide_ms, - }); - deployments.len() - 1 - }); - let storage = analytical_cost_model::storage_bytes(raqe, deployment, facts); - let load = &mut deployments[at]; - load.storage_bytes = load.storage_bytes.max(storage); - queries.push(QueryLoad { - deployment: at, - interval_ms: raqe.interval_ms, - chain_ms: analytical_cost_model::chain_ms(raqe, deployment, facts), - work_secs: analytical_cost_model::query_latency_ms(raqe, deployment, facts) - / 1000.0, - memory_bytes: analytical_cost_model::merge(raqe, deployment, facts).memory_bytes - + analytical_cost_model::query(raqe, deployment, facts).memory_bytes, - }); - } - PlanLoad { - deployments, - queries, - } - } - - /// Steady ingest CPU, vCPUs. - pub fn ingest_cpu(&self) -> f64 { - self.deployments.iter().map(|d| d.ingest_cpu).sum() - } - - /// Ingest and storage memory, held at all times, bytes. - pub fn static_bytes(&self) -> f64 { - self.deployments - .iter() - .map(|d| d.ingest_bytes + d.storage_bytes) - .sum() - } - - /// Mean CPU, vCPUs: ingest, compaction and queries, by use. - pub fn auc_cpu(&self) -> f64 { - self.ingest_cpu() - + self - .deployments - .iter() - .map(|d| d.compaction_secs / secs(d.slide_ms)) - .sum::() - + self - .queries - .iter() - .map(|q| q.work_secs / secs(q.interval_ms)) - .sum::() - } - - /// Mean memory, bytes: ingest and storage always; each compaction's - /// partial copies for its run on one core every slide; each query's memory - /// for its run on one core (`work_secs`) every interval. - pub fn auc_bytes(&self) -> f64 { - self.static_bytes() - + self - .deployments - .iter() - .map(|d| d.compaction_bytes * d.compaction_secs / secs(d.slide_ms)) - .sum::() - + self - .queries - .iter() - .map(|q| q.memory_bytes * q.work_secs / secs(q.interval_ms)) - .sum::() - } - - /// The longest chain, ms: the batch latency when CPU is elastic (cost - /// model 1). - pub fn longest_chain_ms(&self) -> f64 { - self.queries.iter().map(|q| q.chain_ms).fold(0.0, f64::max) - } - - /// `lcm` of every interval and slide, ms. - pub fn hyperperiod_ms(&self) -> Millis { - self.queries - .iter() - .map(|q| q.interval_ms) - .chain(self.deployments.iter().map(|d| d.slide_ms)) - .fold(1, lcm) - } - - /// Place every job of two hyperperiods on `cpu` vCPUs shared with ingest - /// (fluid, priority-ordered processor sharing; module docs). `None` when - /// ingest alone does not fit or the mean load exceeds `cpu`. - pub fn place(&self, cpu: f64) -> Option { - place(self, cpu) - } -} - -/// The outcome of [`PlanLoad::place`]. -#[derive(Debug, Clone)] -pub struct Placement { - /// Over batches: from the batch's issue until its last query finishes, ms. - pub worst_batch_ms: f64, - /// Index-aligned with the RAQEs: its worst firing, ms. - pub raqe_latency_ms: Vec, - /// Peak CPU (ingest plus running jobs), vCPUs. - pub peak_cpu: f64, - /// Peak memory (ingest, storage and running queries' memory), bytes. - pub peak_bytes: f64, -} - -/// Cost model 1 (AUC) and cost model 2 (max) of a plan, with the latency -/// that goes with each. -#[derive(Debug, Clone)] -pub struct ModelCost { - pub cpu: f64, - pub bytes: f64, - /// `w_cpu · cpu + w_mem · GiB`. - pub value: f64, - pub latency_ms: f64, -} - -/// Cost model 1: CPU and memory billed by use. CPU is elastic: the placement -/// with unlimited capacity, where every job starts when ready on its own core, -/// so the latency is the longest chain and each query runs for its work. -pub fn cost_model_1(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> ModelCost { - let (cpu, bytes) = (load.auc_cpu(), load.auc_bytes()); - ModelCost { - cpu, - bytes, - value: w_cpu * cpu + w_mem * bytes / BYTES_PER_GIB, - latency_ms: load.longest_chain_ms(), - } -} - -/// Cost model 2: CPU and memory billed at the peak of a provisioned -/// `(C, M)` under a latency SLA (cost model 2 is evaluated with an SLA only). -/// `C` is the smallest at which the placement's worst batch meets `sla_ms`, -/// `M` the placement's peak memory. -/// `None` when a chain alone exceeds the SLA (or, failing float sanity, no -/// `C` up to `2^MAX_DOUBLINGS` times the mean load meets it). -pub fn cost_model_2(load: &PlanLoad, w_cpu: f64, w_mem: f64, sla_ms: f64) -> Option { - let floor = load.auc_cpu(); - let placed = |cpu: f64| load.place(cpu).expect("at or above the mean load"); - if !analytical_cost_model::meets_sla(load.longest_chain_ms(), sla_ms) { - return None; - } - let meets = |cpu: f64| analytical_cost_model::meets_sla(placed(cpu).worst_batch_ms, sla_ms); - let mut hi = floor.max(f64::MIN_POSITIVE); - let mut doublings = 0; - while !meets(hi) { - if doublings == MAX_DOUBLINGS { - return None; - } - hi *= 2.0; - doublings += 1; - } - let mut lo = floor; - if meets(lo) { - hi = lo; - } - while hi - lo > 1e-4 * hi { - let mid = 0.5 * (lo + hi); - if meets(mid) { - hi = mid; - } else { - lo = mid; - } - } - let (cpu, placement) = (hi, placed(hi)); - let bytes = placement.peak_bytes; - Some(ModelCost { - cpu, - bytes, - value: w_cpu * cpu + w_mem * bytes / BYTES_PER_GIB, - latency_ms: placement.worst_batch_ms, - }) -} - -/// Doublings of `C` above the mean load before cost model 2 gives up. With -/// every chain within the SLA a large enough `C` always meets it, so this only -/// stops a float pathology. -const MAX_DOUBLINGS: usize = 64; - -fn secs(ms: Millis) -> f64 { - ms as f64 / 1000.0 -} - -fn gcd(a: Millis, b: Millis) -> Millis { - if b == 0 { - a - } else { - gcd(b, a % b) - } -} - -fn lcm(a: Millis, b: Millis) -> Millis { - a / gcd(a, b) * b -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum Kind { - /// Compaction runs before queries: it unblocks them. - Compaction, - Query, -} - -#[derive(Debug, Clone)] -struct Job { - /// When the job can start: a query's issue, or a compaction's window close. - issued: f64, - kind: Kind, - /// Query: its RAQE; compaction: its deployment. - owner: usize, - remaining: f64, - memory: f64, - /// Index of the compaction job this query waits for. - after: Option, - done_at: Option, -} - -/// Work below this many CPU-seconds counts as done (float residue). -const EPSILON_SECS: f64 = 1e-15; - -fn place(load: &PlanLoad, cpu: f64) -> Option { - let capacity = cpu - load.ingest_cpu(); - if capacity <= 0.0 || load.auc_cpu() > cpu * (1.0 + 1e-12) { - return None; - } - let horizon = 2 * load.hyperperiod_ms(); - let mut jobs: Vec = Vec::new(); - // Compaction of the window closing at `t`, per deployment. - let mut compaction_at: BTreeMap<(usize, Millis), usize> = BTreeMap::new(); - for (d, deployment) in load.deployments.iter().enumerate() { - if deployment.compaction_secs <= 0.0 { - continue; - } - for t in (0..horizon).step_by(deployment.slide_ms as usize) { - compaction_at.insert((d, t), jobs.len()); - jobs.push(Job { - issued: secs(t), - kind: Kind::Compaction, - owner: d, - remaining: deployment.compaction_secs, - memory: deployment.compaction_bytes, - after: None, - done_at: None, - }); - } - } - for (i, query) in load.queries.iter().enumerate() { - for t in (0..horizon).step_by(query.interval_ms as usize) { - jobs.push(Job { - issued: secs(t), - kind: Kind::Query, - owner: i, - remaining: query.work_secs, - memory: query.memory_bytes, - after: compaction_at.get(&(query.deployment, t)).copied(), - done_at: None, - }); - } - } - // Jobs by issue time; `pending` holds the issued, unfinished ones, so each - // event looks at the jobs in flight, not at every job. - let mut order: Vec = (0..jobs.len()).collect(); - order.sort_by(|&a, &b| jobs[a].issued.total_cmp(&jobs[b].issued)); - let mut next_job = 0; - let mut pending: Vec = Vec::new(); - - let static_bytes = load.static_bytes(); - let (mut peak_cpu, mut peak_bytes) = (load.ingest_cpu(), static_bytes); - let mut now = 0.0; - loop { - while next_job < order.len() && jobs[order[next_job]].issued <= now { - pending.push(order[next_job]); - next_job += 1; - } - pending.retain(|&j| jobs[j].done_at.is_none()); - let mut ready: Vec = pending - .iter() - .copied() - .filter(|&j| jobs[j].after.is_none_or(|c| jobs[c].done_at.is_some())) - .collect(); - if pending.is_empty() && next_job == order.len() { - break; - } - // Older first, compaction before queries, then longest first. - ready.sort_by(|&a, &b| { - let (a, b) = (&jobs[a], &jobs[b]); - a.issued - .total_cmp(&b.issued) - .then(a.kind.cmp(&b.kind)) - .then(b.remaining.total_cmp(&a.remaining)) - }); - let mut left = capacity; - let mut rates: Vec<(usize, f64)> = Vec::new(); - for &j in &ready { - if left <= 0.0 { - break; - } - let rate = left.min(1.0); - rates.push((j, rate)); - left -= rate; - } - let running_cpu: f64 = rates.iter().map(|&(_, r)| r).sum(); - let running_bytes: f64 = rates.iter().map(|&(j, _)| jobs[j].memory).sum(); - peak_cpu = peak_cpu.max(load.ingest_cpu() + running_cpu); - peak_bytes = peak_bytes.max(static_bytes + running_bytes); - let finish = rates - .iter() - .map(|&(j, r)| jobs[j].remaining / r) - .fold(f64::INFINITY, f64::min); - let issue = order - .get(next_job) - .map_or(f64::INFINITY, |&j| jobs[j].issued); - let step = finish.min(issue - now); - for &(j, r) in &rates { - let job = &mut jobs[j]; - job.remaining -= r * step; - if job.remaining <= EPSILON_SECS.max(1e-12 * r * step) { - job.remaining = 0.0; - job.done_at = Some(now + step); - } - } - now += step; - } - - let mut batches: BTreeMap = BTreeMap::new(); - let mut raqe_latency_ms = vec![0.0f64; load.queries.len()]; - for job in jobs.iter().filter(|j| j.kind == Kind::Query) { - let latency_ms = 1000.0 * (job.done_at.expect("every job finishes") - job.issued); - let batch = batches.entry(job.issued.to_bits()).or_insert(0.0); - *batch = batch.max(latency_ms); - raqe_latency_ms[job.owner] = raqe_latency_ms[job.owner].max(latency_ms); - } - Some(Placement { - worst_batch_ms: batches.values().copied().fold(0.0, f64::max), - raqe_latency_ms, - peak_cpu, - peak_bytes, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn load(ingest_cpu: f64, compaction_secs: f64, queries: &[(Millis, f64)]) -> PlanLoad { - PlanLoad { - deployments: vec![DeploymentLoad { - ingest_cpu, - ingest_bytes: 10.0, - storage_bytes: 5.0, - compaction_secs, - compaction_bytes: 0.0, - slide_ms: 1_000, - }], - queries: queries - .iter() - .map(|&(interval_ms, work_secs)| QueryLoad { - deployment: 0, - interval_ms, - chain_ms: 1000.0 * (compaction_secs + work_secs), - work_secs, - memory_bytes: 100.0, - }) - .collect(), - } - } - - #[test] - fn a_job_uses_at_most_one_core_and_slows_on_a_fraction() { - // Ingest 0.5 vCPU; one 0.1 s query every second. - let plan = load(0.5, 0.0, &[(1_000, 0.1)]); - let full = plan.place(1.5).unwrap(); - assert!( - (full.worst_batch_ms - 100.0).abs() < 1e-6, - "{}", - full.worst_batch_ms - ); - // More capacity doesn't help a one-core job. - assert!((plan.place(4.0).unwrap().worst_batch_ms - 100.0).abs() < 1e-6); - // 0.25 vCPU left for it: 0.4 s. - let quarter = plan.place(0.75).unwrap(); - assert!( - (quarter.worst_batch_ms - 400.0).abs() < 1e-6, - "{}", - quarter.worst_batch_ms - ); - assert!((quarter.peak_cpu - 0.75).abs() < 1e-9); - assert_eq!(quarter.peak_bytes, 15.0 + 100.0); - } - - #[test] - fn a_batch_shares_the_capacity_and_longest_runs_first() { - // Two queries of 0.3 s and 0.1 s every second on one free core: the - // batch ends at 0.4 s, the long one first (0.3 s). - let plan = load(0.0, 0.0, &[(1_000, 0.1), (1_000, 0.3)]); - let placed = plan.place(1.0).unwrap(); - assert!((placed.worst_batch_ms - 400.0).abs() < 1e-6); - assert!((placed.raqe_latency_ms[1] - 300.0).abs() < 1e-6); - // Two cores: each on its own. - assert!((plan.place(2.0).unwrap().worst_batch_ms - 300.0).abs() < 1e-6); - } - - #[test] - fn a_query_waits_for_the_newest_windows_compaction() { - // Compaction 0.2 s each second, then a 0.1 s query: 0.3 s. - let plan = load(0.0, 0.2, &[(1_000, 0.1)]); - assert!((plan.place(2.0).unwrap().worst_batch_ms - 300.0).abs() < 1e-6); - assert!((plan.longest_chain_ms() - 300.0).abs() < 1e-9); - } - - #[test] - fn the_aligned_batch_is_the_worst_and_backlog_carries_over() { - // Every second 0.5 s of work, every 2 s another 0.5 s, on one core: - // the aligned batch (t = 0, 2 s) takes 1 s; the other batches 0.5 s. - let plan = load(0.0, 0.0, &[(1_000, 0.5), (2_000, 0.5)]); - let placed = plan.place(1.0).unwrap(); - assert!( - (placed.worst_batch_ms - 1000.0).abs() < 1e-6, - "{}", - placed.worst_batch_ms - ); - // Below the mean load (0.75 vCPU) there is no placement. - assert!(plan.place(0.7).is_none()); - } - - #[test] - fn unlimited_capacity_gives_cost_model_1s_closed_form() { - // Compaction 0.2 s each second; queries of 0.1 s, 0.5 s and 0.3 s. - let plan = load(0.5, 0.2, &[(1_000, 0.1), (2_000, 0.5), (1_000, 0.3)]); - let placed = plan.place(1e9).unwrap(); - assert!((placed.worst_batch_ms - plan.longest_chain_ms()).abs() < 1e-6); - assert!((cost_model_1(&plan, 1.0, 0.0).latency_ms - placed.worst_batch_ms).abs() < 1e-6); - } - - #[test] - fn a_compaction_holds_its_partial_copies_while_it_runs() { - // Compaction 0.2 s holding 50 bytes, then a 0.1 s query holding 100, - // each second, beside 15 bytes of ingest and storage. - let mut plan = load(0.0, 0.2, &[(1_000, 0.1)]); - plan.deployments[0].compaction_bytes = 50.0; - // They run one after the other: the peak is the query's. - assert_eq!(plan.place(2.0).unwrap().peak_bytes, 115.0); - // By use: 15 + 50 · 0.2 + 100 · 0.1 per second. - assert!((plan.auc_bytes() - 35.0).abs() < 1e-12); - } - - #[test] - fn cost_models_bill_use_and_peak() { - let plan = load(0.5, 0.0, &[(1_000, 0.1)]); - let one = cost_model_1(&plan, 1.0, 0.0); - assert!((one.cpu - 0.6).abs() < 1e-12); - // Memory by use: 15 bytes always, 100 bytes for 0.1 s each second. - assert!((one.bytes - 25.0).abs() < 1e-12); - assert!((one.latency_ms - 100.0).abs() < 1e-9); - // Cost model 2 with a loose SLA: the mean CPU. - let loose = cost_model_2(&plan, 1.0, 0.0, 1e6).unwrap(); - assert!((loose.cpu - 0.6).abs() < 1e-12); - // A 200 ms SLA: the query needs 0.5 vCPU beside ingest, C = 1.0. - let tight = cost_model_2(&plan, 1.0, 0.0, 200.0).unwrap(); - assert!((tight.cpu - 1.0).abs() < 1e-3, "{}", tight.cpu); - assert!(tight.latency_ms <= 200.0); - // Below the chain, infeasible. - assert!(cost_model_2(&plan, 1.0, 0.0, 50.0).is_none()); - } -} diff --git a/rqe-optimizer/src/usage.rs b/rqe-optimizer/src/usage.rs new file mode 100644 index 00000000..649c7b21 --- /dev/null +++ b/rqe-optimizer/src/usage.rs @@ -0,0 +1,226 @@ +//! A plan's resource use over time, its cost billed by use, and its batch +//! latency (`docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +//! latency"). +//! +//! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. +//! Each closed window is compacted (the workers' partials merged into one), +//! and each RAQE firing runs one query job (merge, then estimate) once the +//! newest window is compacted. A job uses at most one core: sketch-bench's +//! operations are single-threaded, their CPU time equal to their wall time. +//! CPU is elastic, so every job starts when it is ready. + +use std::collections::BTreeMap; + +use crate::analytical_cost_model::{self, BYTES_PER_GIB}; +use crate::{Deployment, Mapping, Millis, Raqe, WorkloadFacts}; + +/// One active deployment's steady load. +#[derive(Debug, Clone)] +pub struct DeploymentLoad { + /// Ingest CPU, vCPUs. + pub ingest_cpu: f64, + /// Open windows on every worker, bytes. + pub ingest_bytes: f64, + /// Closed windows kept for the longest lookback served, bytes. + pub storage_bytes: f64, + /// CPU-seconds to compact one closed window (0 with one worker). + pub compaction_secs: f64, + /// Bytes a compaction holds while it runs: the closed window's partial + /// copies (0 with one worker). + pub compaction_bytes: f64, + /// Windows close every slide. + pub slide_ms: Millis, +} + +/// One RAQE's query job, run every interval. +#[derive(Debug, Clone)] +pub struct QueryLoad { + /// Index into [`PlanLoad::deployments`]. + pub deployment: usize, + pub interval_ms: Millis, + /// Compaction of the newest window, then this job, on their own cores, ms + /// ([`analytical_cost_model::chain_ms`]). + pub chain_ms: f64, + /// Merge then estimate, CPU-seconds (one core at most). + pub work_secs: f64, + /// Merge accumulators and output, held while the job runs. + pub memory_bytes: f64, +} + +/// A plan as load over time. +#[derive(Debug, Clone)] +pub struct PlanLoad { + pub deployments: Vec, + /// Index-aligned with the plan's RAQEs. + pub queries: Vec, +} + +impl PlanLoad { + /// The load of `mapping` (one candidate index per RAQE). + pub fn new( + raqes: &[Raqe], + candidates: &[Deployment], + mapping: &Mapping, + facts: &WorkloadFacts, + ) -> PlanLoad { + let mut index: BTreeMap = BTreeMap::new(); + let mut deployments: Vec = Vec::new(); + let mut queries = Vec::with_capacity(raqes.len()); + for (raqe, &candidate) in raqes.iter().zip(mapping) { + let deployment = &candidates[candidate]; + let at = *index.entry(candidate).or_insert_with(|| { + let ingest = analytical_cost_model::ingest(deployment, facts); + let workers = analytical_cost_model::ingest_workers(deployment, facts); + deployments.push(DeploymentLoad { + ingest_cpu: ingest.cpu_secs_per_sec, + ingest_bytes: ingest.memory_bytes * workers, + storage_bytes: 0.0, + compaction_secs: analytical_cost_model::compaction_secs(deployment, facts), + compaction_bytes: analytical_cost_model::compaction_bytes(deployment, facts), + slide_ms: deployment.slide_ms, + }); + deployments.len() - 1 + }); + let storage = analytical_cost_model::storage_bytes(raqe, deployment, facts); + let load = &mut deployments[at]; + load.storage_bytes = load.storage_bytes.max(storage); + queries.push(QueryLoad { + deployment: at, + interval_ms: raqe.interval_ms, + chain_ms: analytical_cost_model::chain_ms(raqe, deployment, facts), + work_secs: analytical_cost_model::query_latency_ms(raqe, deployment, facts) + / 1000.0, + memory_bytes: analytical_cost_model::merge(raqe, deployment, facts).memory_bytes + + analytical_cost_model::query(raqe, deployment, facts).memory_bytes, + }); + } + PlanLoad { + deployments, + queries, + } + } + + /// Steady ingest CPU, vCPUs. + pub fn ingest_cpu(&self) -> f64 { + self.deployments.iter().map(|d| d.ingest_cpu).sum() + } + + /// Ingest and storage memory, held at all times, bytes. + pub fn static_bytes(&self) -> f64 { + self.deployments + .iter() + .map(|d| d.ingest_bytes + d.storage_bytes) + .sum() + } + + /// Mean CPU, vCPUs: ingest, compaction and queries, by use. + pub fn auc_cpu(&self) -> f64 { + self.ingest_cpu() + + self + .deployments + .iter() + .map(|d| d.compaction_secs / secs(d.slide_ms)) + .sum::() + + self + .queries + .iter() + .map(|q| q.work_secs / secs(q.interval_ms)) + .sum::() + } + + /// Mean memory, bytes: ingest and storage always; each compaction's + /// partial copies for its run on one core every slide; each query's memory + /// for its run on one core (`work_secs`) every interval. + pub fn auc_bytes(&self) -> f64 { + self.static_bytes() + + self + .deployments + .iter() + .map(|d| d.compaction_bytes * d.compaction_secs / secs(d.slide_ms)) + .sum::() + + self + .queries + .iter() + .map(|q| q.memory_bytes * q.work_secs / secs(q.interval_ms)) + .sum::() + } + + /// The longest chain, ms: the worst batch latency, since CPU is elastic. + pub fn longest_chain_ms(&self) -> f64 { + self.queries.iter().map(|q| q.chain_ms).fold(0.0, f64::max) + } +} + +/// A plan's cost billed by use, and its query latency. +#[derive(Debug, Clone)] +pub struct UsageCost { + /// Mean vCPUs. + pub cpu: f64, + /// Mean bytes. + pub bytes: f64, + /// `w_cpu · cpu + w_mem · GiB`. + pub value: f64, + /// Worst batch latency, ms: the longest chain, since CPU is elastic. + pub latency_ms: f64, +} + +/// `w_cpu · AUC(CPU) + w_mem · AUC(memory)` of `load`, and its latency. +pub fn usage_cost(load: &PlanLoad, w_cpu: f64, w_mem: f64) -> UsageCost { + let (cpu, bytes) = (load.auc_cpu(), load.auc_bytes()); + UsageCost { + cpu, + bytes, + value: w_cpu * cpu + w_mem * bytes / BYTES_PER_GIB, + latency_ms: load.longest_chain_ms(), + } +} + +fn secs(ms: Millis) -> f64 { + ms as f64 / 1000.0 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn load(ingest_cpu: f64, compaction_secs: f64, queries: &[(Millis, f64)]) -> PlanLoad { + PlanLoad { + deployments: vec![DeploymentLoad { + ingest_cpu, + ingest_bytes: 10.0, + storage_bytes: 5.0, + compaction_secs, + compaction_bytes: 50.0, + slide_ms: 1_000, + }], + queries: queries + .iter() + .map(|&(interval_ms, work_secs)| QueryLoad { + deployment: 0, + interval_ms, + chain_ms: 1000.0 * (compaction_secs + work_secs), + work_secs, + memory_bytes: 100.0, + }) + .collect(), + } + } + + #[test] + fn cpu_and_memory_are_billed_by_use() { + // Ingest 0.5 vCPU; compaction 0.2 s holding 50 bytes each second; a + // 0.1 s query holding 100 bytes each second; 15 bytes always. + let plan = load(0.5, 0.2, &[(1_000, 0.1)]); + let cost = usage_cost(&plan, 1.0, 0.0); + assert!((cost.cpu - 0.8).abs() < 1e-12); + assert!((cost.bytes - (15.0 + 50.0 * 0.2 + 100.0 * 0.1)).abs() < 1e-12); + assert_eq!(cost.value, cost.cpu); + } + + #[test] + fn the_latency_is_the_longest_chain() { + // Compaction 0.2 s before every query; queries of 0.1 s and 0.5 s. + let plan = load(0.0, 0.2, &[(1_000, 0.1), (2_000, 0.5)]); + assert!((usage_cost(&plan, 1.0, 0.0).latency_ms - 700.0).abs() < 1e-9); + } +} From adbb5bd2ec5e8105e5cb61e59959e9cdd9d253d9 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 20:06:06 +0000 Subject: [PATCH 16/18] rqe-optimizer, docs: an optional latency bound to trace the cost-latency frontier minimize_usage_cost takes latency_bound_ms: pairs whose chain exceeds it are ruled out, so the plan is the cheapest at least that fast (exact, since CPU is elastic). Sweeping it traces each method's Pareto frontier; it is not an SLA. Test: matches brute force under four bounds, and looser bounds never cost more. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 38 ++++++++++++++------ rqe-optimizer/src/milp.rs | 62 ++++++++++++++++++++++++++++++-- 2 files changed, 87 insertions(+), 13 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 7d904a36..fc79a0fc 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -364,8 +364,10 @@ never enumerates full mappings. Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in `rqe-optimizer/src/usage.rs` (resource use, cost, latency) and `milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by -use. It has no latency constraint: the evaluation's message is lower cost and -lower latency, so latency is reported for every plan, not bounded. +use, and the plan's latency is reported. The evaluation's message is lower +cost and lower latency, so instead of an SLA to meet or violate, an optional +latency bound traces each method's cost–latency Pareto frontier: the +cheapest plan whose latency is at most `L`, for a sweep of `L`. Evaluated first on the synthetic mixed template set; methods: ASAP (this MILP, with sharing), PerQuery (the same MILP without sharing) and AutoSketch-Adapted (fixed configs chosen by memory). @@ -479,7 +481,8 @@ In words: A batch's **latency** is the time from its issue until its last query job finishes, compaction included. A plan's **query latency** is its worst batch -latency. It is reported for every plan, not constrained. +latency. It is reported for every plan; a latency bound (§6) only traces the +frontier. CPU is elastic, so no job waits for a core, and a batch's latency is its longest **chain**: the newest window's compaction, then the query, each on a @@ -490,8 +493,8 @@ latency is the longest chain over its RAQEs. Per-RAQE latency bounds In words: the trade-off between cost and latency comes from the plan. A cheap plan keeps short windows and merges many of them at query time (long chains); a faster one precomputes more at ingest (more open windows, more CPU -and memory). The MILP picks the cheapest plan; its latency is what that plan -gives. +and memory). With no bound the MILP picks the cheapest plan, whatever its +latency; a bound `L` asks for the cheapest plan at least that fast. #### 6. MILP formulation @@ -506,6 +509,8 @@ minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · s.t. Σ_D z_{i,D} = 1 for every RAQE i z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} +with a latency bound L (optional): + z_{i,D} = 0 if c_D + ℓ_{i,D} > L ``` In words: @@ -520,10 +525,16 @@ In words: paid once, however many RAQEs share it. - A deployment stores enough closed windows for the longest lookback it serves (a linearized max). +- With a bound `L`, a pair whose chain (the newest window's compaction, then + the query, each on a full core) is longer than `L` is ruled out. Since CPU + is elastic, the plan's latency is then at most `L`, exactly. Chains are + compared with `L` with a relative slack of `1e-9`, so float error can't rule + out a chain equal to `L`. #### 7. Solution method -Every term is linear in `u` and `z`, so the MILP is solved exactly +Every term is linear in `u` and `z`, with or without a bound, so the MILP is +solved exactly (`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair so the solver sees magnitudes near 1). The solved plan's cost and latency are then computed from its resource use (`usage::usage_cost`). @@ -535,13 +546,20 @@ then computed from its resource use (`usage::usage_cost`). same candidate index (`u_D` is per index), so their copies stay apart and each pays its own ingest. - **AutoSketch** keeps its memory-chosen configs and is priced by the same - function: its cost by use and its latency, the longest chain. + function: its cost by use and its latency, the longest chain. It ignores + latency, so it is one point, not a frontier. +- **Frontier:** ASAP and PerQuery are solved for a sweep of bounds `L`, from + the smallest feasible one (the largest, over RAQEs, of each RAQE's fastest + chain) up to no bound. Each solve gives a (latency, cost) point; together + they are the method's frontier. In particular, `L` = AutoSketch's latency + gives each method's cost at no more than AutoSketch's latency. #### 8. Outputs -Per (method, weight setting): cost; mean CPU and memory, by part; query -latency and per-RAQE latency; planning time. Figure: cost and latency per -method, for each workload. +Per (method, weight setting, bound): cost; mean CPU and memory, by part; +query latency and per-RAQE latency; planning time. Figure: each method's +cost–latency frontier for each workload (ASAP and PerQuery as lines, +AutoSketch as a point). ## Analytical cost model diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 59799917..99cb9b52 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -227,6 +227,10 @@ pub fn minimize( }) } +/// Relative slack when comparing a chain with a latency bound, so float error +/// in summing µs-scale work can't rule out a chain equal to the bound. +const LATENCY_SLACK: f64 = 1e-9; + /// A [`minimize_usage_cost`] solution, with its cost billed by use and its /// latency. #[derive(Debug, Clone)] @@ -239,15 +243,19 @@ pub struct UsageSolution { /// Minimize the cost billed by use, `w_cpu · AUC(CPU) + w_mem · AUC(memory)` /// (per vCPU, per GiB; `docs/rqe_sketch_deployment_v1.md`, "Cost by use and -/// batch latency"). No latency constraint: the latency is reported, not -/// bounded, and per-RAQE latency bounds (`Raqe::latency_sla_ms`) are not -/// used. Every term is linear, so this is exact. +/// batch latency"). The latency is reported. `latency_bound_ms`, when given, +/// rules out every pair whose chain (`analytical_cost_model::chain_ms`) +/// exceeds it, so sweeping it traces the cost–latency Pareto frontier; it is +/// not an SLA to meet or violate. Per-RAQE latency bounds +/// (`Raqe::latency_sla_ms`) are not used. Every term is linear, so this is +/// exact. /// /// `allowed`, when given, lists for each RAQE the candidate indices it may /// use, e.g. only its own candidates for PerQuery (no sharing). Two RAQEs /// share a deployment only by choosing the same candidate index, so giving /// each RAQE its own copies of identical deployments keeps them apart, each /// paying its own ingest. +#[allow(clippy::too_many_arguments)] pub fn minimize_usage_cost( raqes: &[Raqe], deployments: &[Deployment], @@ -256,6 +264,7 @@ pub fn minimize_usage_cost( w_mem: f64, accuracy: &Accuracy, allowed: Option<&[Vec]>, + latency_bound_ms: Option, ) -> Result { let secs = |ms: u64| ms as f64 / 1000.0; let gib = |bytes: f64| bytes / BYTES_PER_GIB; @@ -287,6 +296,12 @@ pub fn minimize_usage_cost( eligible_deployments_for(raqe, deployments, facts, accuracy) .into_iter() .filter(|d| allowed.is_none_or(|allowed| allowed[i].contains(d))) + .filter(|&d| { + latency_bound_ms.is_none_or(|bound| { + analytical_cost_model::chain_ms(raqe, &deployments[d], facts) + <= bound * (1.0 + LATENCY_SLACK) + }) + }) .collect() }) .collect(); @@ -617,6 +632,7 @@ mod tests { w_mem, &table_accuracy, None, + None, ) .expect("feasible"); assert!( @@ -627,6 +643,45 @@ mod tests { } } + #[test] + fn a_latency_bound_gives_the_cheapest_plan_that_fast_by_brute_force() { + use crate::usage::{usage_cost, PlanLoad}; + let (raqes, deployments, facts) = usage_workload(); + let price = |mapping: &Mapping| { + usage_cost( + &PlanLoad::new(&raqes, &deployments, mapping, &facts), + 1.0, + 0.0, + ) + }; + let mut previous = (0.0, f64::INFINITY); + // Looser bounds never cost more and never give a faster plan. + for bound in [300.0, 1e3, 1e4, 1e6] { + let best = brute_force(&raqes, &deployments, &facts, &table_accuracy) + .iter() + .map(price) + .filter(|cost| cost.latency_ms <= bound) + .map(|cost| cost.value) + .min_by(f64::total_cmp) + .expect("servable within the bound"); + let got = minimize_usage_cost( + &raqes, + &deployments, + &facts, + 1.0, + 0.0, + &table_accuracy, + None, + Some(bound), + ) + .expect("feasible"); + assert!((got.cost.value - best).abs() <= 1e-9 * best, "{bound}"); + assert!(got.cost.latency_ms <= bound); + assert!(got.cost.value <= previous.1 * (1.0 + 1e-12)); + previous = (got.cost.latency_ms, got.cost.value); + } + } + #[test] fn allowed_candidates_keep_identical_deployments_apart() { // Two RAQEs at one cadence, each with its own copy of one deployment. @@ -643,6 +698,7 @@ mod tests { 0.0, &table_accuracy, allowed, + None, ) .expect("feasible") }; From 9de571ce6cb2224aaa19b585592df77fd3508582 Mon Sep 17 00:00:00 2001 From: zz_y Date: Thu, 8 Oct 2026 20:17:18 +0000 Subject: [PATCH 17/18] docs: two versions (no SLA; batch latency SLA) and the job placement algorithm Version 1 minimizes cost by use and reports latency, with an optional bound that traces the frontier; version 2 requires the batch latency, from the job placement, to be at most an SLA. The placement algorithm is back: with elastic CPU it has the closed form (longest chain) the code uses, which keeps both versions exact. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 108 +++++++++++++++++++++++-------- 1 file changed, 81 insertions(+), 27 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index fc79a0fc..6bcc62be 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -364,10 +364,13 @@ never enumerates full mappings. Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in `rqe-optimizer/src/usage.rs` (resource use, cost, latency) and `milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by -use, and the plan's latency is reported. The evaluation's message is lower -cost and lower latency, so instead of an SLA to meet or violate, an optional -latency bound traces each method's cost–latency Pareto frontier: the -cheapest plan whose latency is at most `L`, for a sweep of `L`. +use, in two versions: + +- **Version 1, no latency constraint:** the cheapest plan; its latency is + reported. Sweeping an optional latency bound traces each method's + cost–latency Pareto frontier. +- **Version 2, a batch latency SLA:** the cheapest plan whose batch latency, + from the job placement (§6), is at most the SLA `L`, for a grid of SLAs. Evaluated first on the synthetic mixed template set; methods: ASAP (this MILP, with sharing), PerQuery (the same MILP without sharing) and AutoSketch-Adapted (fixed configs chosen by memory). @@ -477,18 +480,18 @@ In words: and a query's memory are held only while they run, a fraction `run time / y_D` or `run time / T_i` of the time. -#### 5. Batch latency +#### 5. Batch latency and the SLA A batch's **latency** is the time from its issue until its last query job finishes, compaction included. A plan's **query latency** is its worst batch -latency. It is reported for every plan; a latency bound (§6) only traces the -frontier. +latency, given by the job placement (§6). Version 1 reports it; version 2 +requires it to be at most the SLA `L`. Per-RAQE latency bounds +(`Raqe::latency_sla_ms`) are not used. CPU is elastic, so no job waits for a core, and a batch's latency is its longest **chain**: the newest window's compaction, then the query, each on a full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query -latency is the longest chain over its RAQEs. Per-RAQE latency bounds -(`Raqe::latency_sla_ms`) are not used. +latency is the longest chain over its RAQEs. In words: the trade-off between cost and latency comes from the plan. A cheap plan keeps short windows and merges many of them at query time (long @@ -496,7 +499,53 @@ chains); a faster one precomputes more at ingest (more open windows, more CPU and memory). With no bound the MILP picks the cheapest plan, whatever its latency; a bound `L` asks for the cheapest plan at least that fast. -#### 6. MILP formulation +#### 6. Job placement algorithm + +The job placement decides when each job runs on the available CPU, and so +gives every batch's latency. It is defined for any CPU capacity; billing by +use makes CPU elastic, so it runs with unlimited capacity. + +```text +capacity for jobs K = C − Σ_D ρ_D (C = ∞ when CPU is elastic) +event-driven, over the hyperperiod H = lcm(T_i, y_D), twice +(events: query issues, window closes, completions): + ready = compaction jobs (triggered at window closes) + + query jobs whose newest window is compacted + order: issue / trigger time (older first), then compaction before query + (it unblocks queries), then longest remaining work first + give rates in that order: job j gets a_j = min(1, K − rates already given) + a job at rate a_j finishes when its remaining work / a_j elapses + recompute the rates at every event +outputs: per-RAQE and per-batch latency, worst batch latency +``` + +In words: + +1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs; the + rest, `K`, is shared by compaction and query jobs. +2. **Issue jobs.** Each window close triggers a compaction job for its + deployment. Each firing issues a query job, which becomes ready only once + its deployment's newest window is compacted. +3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. + Within a batch, compaction runs before queries, because queries wait for + it. Then the longest remaining work runs first, so a long job doesn't end + up running alone at the end of the batch. +4. **Share capacity as rates.** In that order, each job gets up to one core + (a single-threaded job can't use more) from the capacity still free. The + last one served may get only a fraction and runs slower in proportion. +5. **Advance to the next event.** Time jumps to the next query issue, window + close or completion; remaining work drops by rate × elapsed time, and the + rates are recomputed. +6. **Read off the results.** A query's latency is its finish minus its + issue, and a batch's latency is that of its last query. + +With elastic CPU (`K = ∞`) every job starts as soon as it is ready on its own +core, so the placement has a closed form: a compaction runs for `c_D`, a +query for `ℓ_{i,D}`, and a batch's latency is its longest chain +`c_D + ℓ_{i,D}`. The code uses this closed form (`usage::usage_cost`), and +it is what makes both MILP versions exact. + +#### 7. MILP formulation Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), `u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and @@ -509,7 +558,7 @@ minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · s.t. Σ_D z_{i,D} = 1 for every RAQE i z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} -with a latency bound L (optional): +version 2, a batch latency SLA L (or version 1's frontier bound L): z_{i,D} = 0 if c_D + ℓ_{i,D} > L ``` @@ -525,13 +574,14 @@ In words: paid once, however many RAQEs share it. - A deployment stores enough closed windows for the longest lookback it serves (a linearized max). -- With a bound `L`, a pair whose chain (the newest window's compaction, then - the query, each on a full core) is longer than `L` is ruled out. Since CPU - is elastic, the plan's latency is then at most `L`, exactly. Chains are +- Version 2 (and version 1's frontier bound): a pair whose chain (the newest + window's compaction, then the query, each on a full core) is longer than + `L` is ruled out. By the placement's closed form, the plan's batch latency + is then at most `L`, exactly: the SLA is met. Chains are compared with `L` with a relative slack of `1e-9`, so float error can't rule out a chain equal to `L`. -#### 7. Solution method +#### 8. Solution method Every term is linear in `u` and `z`, with or without a bound, so the MILP is solved exactly @@ -548,18 +598,22 @@ then computed from its resource use (`usage::usage_cost`). - **AutoSketch** keeps its memory-chosen configs and is priced by the same function: its cost by use and its latency, the longest chain. It ignores latency, so it is one point, not a frontier. -- **Frontier:** ASAP and PerQuery are solved for a sweep of bounds `L`, from - the smallest feasible one (the largest, over RAQEs, of each RAQE's fastest - chain) up to no bound. Each solve gives a (latency, cost) point; together - they are the method's frontier. In particular, `L` = AutoSketch's latency - gives each method's cost at no more than AutoSketch's latency. - -#### 8. Outputs - -Per (method, weight setting, bound): cost; mean CPU and memory, by part; -query latency and per-RAQE latency; planning time. Figure: each method's -cost–latency frontier for each workload (ASAP and PerQuery as lines, -AutoSketch as a point). +- **Version 1:** ASAP and PerQuery are solved with no bound (the cheapest + plan), and for a sweep of bounds `L` from the smallest feasible one (the + largest, over RAQEs, of each RAQE's fastest chain) up to the unbounded + plan's latency. Each solve gives a (latency, cost) point; together they are + the method's frontier. `L` = AutoSketch's latency gives each method's cost + at no more than AutoSketch's latency. +- **Version 2:** ASAP and PerQuery are solved at each SLA of a fixed grid; + an SLA below the smallest feasible bound has no plan. AutoSketch ignores + the SLA; its latency either meets it or not. + +#### 9. Outputs + +Per (method, weight setting, bound or SLA): cost; mean CPU and memory, by +part; query latency and per-RAQE latency; planning time. Figures: version 1, +each method's cost–latency frontier for each workload (ASAP and PerQuery as +lines, AutoSketch as a point); version 2, each method's cost at each SLA. ## Analytical cost model From 5aa3932add3a61152c1040329ab42ca1cc5dbae9 Mon Sep 17 00:00:00 2001 From: zz_y Date: Fri, 9 Oct 2026 17:24:44 +0000 Subject: [PATCH 18/18] docs: answer #188's review on the CPU means Every mean vCPU is an average rate over the same period (whole hyperperiods), so the parts add; ingest is already a rate (lambda_D = series / scrape interval), and only compaction and queries are divided by their period. AUC(CPU) is written as three sums to make that plain. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- docs/rqe_sketch_deployment_v1.md | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 6bcc62be..8f8c83a7 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -384,7 +384,7 @@ AutoSketch-Adapted (fixed configs chosen by memory). | `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | | `card(G)` | groups of `D`'s grouping | | `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | -| `λ_D` | samples/s arriving for `D`'s metric | +| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | | `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | | `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | | `n_{i,D} = S_i / x_D` | windows a query merges | @@ -412,6 +412,12 @@ nothing. #### 3. CPU: parts and how each is computed +Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, +over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, +over which every job pattern repeats exactly. A part with `w` CPU-seconds per +event every `P` seconds runs `H / P` times per hyperperiod, so its mean is +`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. + | Part | When | CPU-seconds | Mean vCPUs | |---|---|---|---| | Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | @@ -430,13 +436,16 @@ nothing. is part of the query. It reads the newest window, which closes at the firing time, so it starts after that window's compaction. -`AUC(CPU) = Σ_D (ρ_D + c_D / y_D) + Σ_i ℓ_{i,D} / T_i`. It is fixed by the -plan, whatever the schedule. +`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already +a rate; only compaction (per window close, every `y_D`) and queries (per +firing, every `T_i`) are divided by their period. It is fixed by the plan, +whatever the schedule. In words: -- `ρ_D`: every second, `λ_D` samples arrive, and each is inserted into the - `x_D / y_D` windows still open, at `c_ins` each. +- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already + inside `λ_D`), and each is inserted into the `x_D / y_D` windows still + open, at `c_ins` CPU-seconds each: CPU-seconds per second. - `c_D`: closing a window merges, for every instance, the `k_D` workers' partial copies into one, which takes `k_D − 1` merges. This happens once per slide.