diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 6f05b42b..8f8c83a7 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -359,6 +359,271 @@ evaluates at once. The default weights are `(1, 0)`: CPU only. Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver never enumerates full mappings. +### Cost by use and batch latency + +Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in +`rqe-optimizer/src/usage.rs` (resource use, cost, latency) and +`milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by +use, in two versions: + +- **Version 1, no latency constraint:** the cheapest plan; its latency is + reported. Sweeping an optional latency bound traces each method's + cost–latency Pareto frontier. +- **Version 2, a batch latency SLA:** the cheapest plan whose batch latency, + from the job placement (§6), is at most the SLA `L`, for a grid of SLAs. +Evaluated first on the synthetic mixed template set; methods: ASAP (this +MILP, with sharing), PerQuery (the same MILP without sharing) and +AutoSketch-Adapted (fixed configs chosen by memory). + +#### 1. Definitions + +| Symbol | Meaning | +|---|---| +| `D`, `i` | a candidate deployment; a RAQE | +| `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | +| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | +| `card(G)` | groups of `D`'s grouping | +| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | +| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | +| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | +| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | +| `n_{i,D} = S_i / x_D` | windows a query merges | +| batch | all query jobs issued at one instant | + +**Measurement assumption (sketch-bench as is).** Every sketch operation is +single-threaded and compute-bound: sketch-bench's CPU time equals its wall +time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses +at most one core and, on a full core, takes its CPU time. The cost table's +`*_cpu_secs` are all the model needs. + +#### 2. Cost model + +`cost = w1 · AUC(CPU) + w2 · AUC(memory)`: the mean vCPUs and GiB over time, +priced per vCPU and per GiB (CPU only: `(1, 0)`; Fargate's prices). CPU is +elastic: a job gets a core whenever it is ready. + +This is billing by use, as on fine-grained autoscaling platforms (Cloud Run +with request-based billing, Dataflow streaming, Flink on Kubernetes with an +autoscaler), idealized: capacity follows the load at once. Billing for +provisioned capacity (VMs, or containers billed by allocation such as +Fargate) is not modeled. Since a job holds its memory only while it runs, its +memory × time is the same whenever it runs, and queueing a job would save +nothing. + +#### 3. CPU: parts and how each is computed + +Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, +over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, +over which every job pattern repeats exactly. A part with `w` CPU-seconds per +event every `P` seconds runs `H / P` times per hyperperiod, so its mean is +`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. + +| Part | When | CPU-seconds | Mean vCPUs | +|---|---|---|---| +| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | +| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | +| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | + +- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at + most one core), **split by sample**: each worker reads a share of the input + (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so + it keeps its own open window instance of every group it sees. +- When a window closes (the watermark passes its end), a **compaction** job + merges the `k_D` partial instances of each group into one stored instance. + With `k_D = 1` there is none. +- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` + stored instances of each group for the query window, then estimate. Merging + is part of the query. It reads the newest window, which closes at the firing + time, so it starts after that window's compaction. + +`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already +a rate; only compaction (per window close, every `y_D`) and queries (per +firing, every `T_i`) are divided by their period. It is fixed by the plan, +whatever the schedule. + +In words: + +- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already + inside `λ_D`), and each is inserted into the `x_D / y_D` windows still + open, at `c_ins` CPU-seconds each: CPU-seconds per second. +- `c_D`: closing a window merges, for every instance, the `k_D` workers' + partial copies into one, which takes `k_D − 1` merges. This happens once + per slide. +- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows + (`n − 1` merges per instance), then answers once per group. This happens + once per interval. (A sketch shared by all groups merges one instance but + still answers every group.) +- `AUC(CPU)` adds the three rates: work per second, in vCPUs. + +#### 4. Memory: parts and how each is computed + +Each part is counted once: a window counts as ingest memory while open and as +storage once compacted, and a query reads stored instances in place. + +| Part | What | Bytes | Held | +|---|---|---|---| +| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | +| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | +| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | +| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | + +`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) ++ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its +own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. + +In words: + +- `I_D`: every worker keeps one instance per group for each of the + `x_D / y_D` windows still open, and there are `k_D` workers. +- `stored_D`: closed windows are kept until the longest lookback that `D` + serves no longer needs them. That is `(S − x)/y + 1` windows per group. +- Compaction: when a window closes, a new one opens, so ingest still holds + `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in + memory until the compaction has merged them. The merged copy takes the + storage slot that the oldest window frees at the same moment, so it is not + counted twice. +- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, + with `n = 1`, reads the stored window and needs none), plus the answer for + every group. +- `AUC(memory)`: ingest and storage are held all the time. A compaction's + and a query's memory are held only while they run, a fraction + `run time / y_D` or `run time / T_i` of the time. + +#### 5. Batch latency and the SLA + +A batch's **latency** is the time from its issue until its last query job +finishes, compaction included. A plan's **query latency** is its worst batch +latency, given by the job placement (§6). Version 1 reports it; version 2 +requires it to be at most the SLA `L`. Per-RAQE latency bounds +(`Raqe::latency_sla_ms`) are not used. + +CPU is elastic, so no job waits for a core, and a batch's latency is its +longest **chain**: the newest window's compaction, then the query, each on a +full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query +latency is the longest chain over its RAQEs. + +In words: the trade-off between cost and latency comes from the plan. A cheap +plan keeps short windows and merges many of them at query time (long +chains); a faster one precomputes more at ingest (more open windows, more CPU +and memory). With no bound the MILP picks the cheapest plan, whatever its +latency; a bound `L` asks for the cheapest plan at least that fast. + +#### 6. Job placement algorithm + +The job placement decides when each job runs on the available CPU, and so +gives every batch's latency. It is defined for any CPU capacity; billing by +use makes CPU elastic, so it runs with unlimited capacity. + +```text +capacity for jobs K = C − Σ_D ρ_D (C = ∞ when CPU is elastic) +event-driven, over the hyperperiod H = lcm(T_i, y_D), twice +(events: query issues, window closes, completions): + ready = compaction jobs (triggered at window closes) + + query jobs whose newest window is compacted + order: issue / trigger time (older first), then compaction before query + (it unblocks queries), then longest remaining work first + give rates in that order: job j gets a_j = min(1, K − rates already given) + a job at rate a_j finishes when its remaining work / a_j elapses + recompute the rates at every event +outputs: per-RAQE and per-batch latency, worst batch latency +``` + +In words: + +1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs; the + rest, `K`, is shared by compaction and query jobs. +2. **Issue jobs.** Each window close triggers a compaction job for its + deployment. Each firing issues a query job, which becomes ready only once + its deployment's newest window is compacted. +3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. + Within a batch, compaction runs before queries, because queries wait for + it. Then the longest remaining work runs first, so a long job doesn't end + up running alone at the end of the batch. +4. **Share capacity as rates.** In that order, each job gets up to one core + (a single-threaded job can't use more) from the capacity still free. The + last one served may get only a fraction and runs slower in proportion. +5. **Advance to the next event.** Time jumps to the next query issue, window + close or completion; remaining work drops by rate × elapsed time, and the + rates are recomputed. +6. **Read off the results.** A query's latency is its finish minus its + issue, and a batch's latency is that of its last query. + +With elastic CPU (`K = ∞`) every job starts as soon as it is ready on its own +core, so the placement has a closed form: a compaction runs for `c_D`, a +query for `ℓ_{i,D}`, and a batch's latency is its longest chain +`c_D + ℓ_{i,D}`. The code uses this closed form (`usage::usage_cost`), and +it is what makes both MILP versions exact. + +#### 7. MILP formulation + +Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), +`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and +pair are §3 and §4's. + +```text +minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] + + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +s.t. Σ_D z_{i,D} = 1 for every RAQE i + z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E + stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} +version 2, a batch latency SLA L (or version 1's frontier bound L): + z_{i,D} = 0 if c_D + ℓ_{i,D} > L +``` + +In words: + +- The objective is the price of the mean vCPUs (ingest and compaction per + active deployment, plus each RAQE's query work per second), plus the price + of the mean memory (ingest and storage per active deployment, each + compaction's partial copies for the fraction of time it runs, and each + query's memory for the fraction of time it runs). +- Every RAQE is served by exactly one eligible deployment. +- A deployment is active if and only if some RAQE uses it, so its ingest is + paid once, however many RAQEs share it. +- A deployment stores enough closed windows for the longest lookback it + serves (a linearized max). +- Version 2 (and version 1's frontier bound): a pair whose chain (the newest + window's compaction, then the query, each on a full core) is longer than + `L` is ruled out. By the placement's closed form, the plan's batch latency + is then at most `L`, exactly: the SLA is met. Chains are + compared with `L` with a relative slack of `1e-9`, so float error can't rule + out a chain equal to `L`. + +#### 8. Solution method + +Every term is linear in `u` and `z`, with or without a bound, so the MILP is +solved exactly +(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair +so the solver sees magnitudes near 1). The solved plan's cost and latency are +then computed from its resource use (`usage::usage_cost`). + +- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` + takes `allowed`, the candidate indices each RAQE may use. PerQuery gives + each RAQE its own candidates, with a separate copy of any deployment that + two RAQEs could both use. Two RAQEs share a deployment only by choosing the + same candidate index (`u_D` is per index), so their copies stay apart and + each pays its own ingest. +- **AutoSketch** keeps its memory-chosen configs and is priced by the same + function: its cost by use and its latency, the longest chain. It ignores + latency, so it is one point, not a frontier. +- **Version 1:** ASAP and PerQuery are solved with no bound (the cheapest + plan), and for a sweep of bounds `L` from the smallest feasible one (the + largest, over RAQEs, of each RAQE's fastest chain) up to the unbounded + plan's latency. Each solve gives a (latency, cost) point; together they are + the method's frontier. `L` = AutoSketch's latency gives each method's cost + at no more than AutoSketch's latency. +- **Version 2:** ASAP and PerQuery are solved at each SLA of a fixed grid; + an SLA below the smallest feasible bound has no plan. AutoSketch ignores + the SLA; its latency either meets it or not. + +#### 9. Outputs + +Per (method, weight setting, bound or SLA): cost; mean CPU and memory, by +part; query latency and per-RAQE latency; planning time. Figures: version 1, +each method's cost–latency frontier for each workload (ASAP and PerQuery as +lines, AutoSketch as a point); version 2, each method's cost at each SLA. + ## Analytical cost model The analytical model combines the empirical per-operation Sketch Bench @@ -494,8 +759,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. In "Cost by use and batch latency" above it +is one firing's query job `ℓ_{i,D}` (merge, then estimate) on one core. ## Procedure @@ -524,7 +790,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; the +- **Latency SLAs:** `minimize` takes optional per-RAQE latency bounds; + `minimize_usage_cost` has none and reports the batch latency (above). The enumerator reports latency but does not reject a mapping for it. - **Memory model:** query memory sums every RAQE's merge and output memory, as if all queries run at once; real concurrency is not modeled. Query output diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 2fb0a99c..56a2b0d9 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -254,6 +254,43 @@ pub(crate) fn query_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &Wor .sum::() } +/// 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) +} + +/// 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::() +} + +/// 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). 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) +} + pub fn score( raqes: &[Raqe], deployments: &[Deployment], diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index a7b82c19..44429a81 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -17,6 +17,7 @@ pub mod milp; pub mod pareto; 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 605b791d..99cb9b52 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -227,6 +227,205 @@ 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)] +pub struct UsageSolution { + pub milp: MilpSolution, + /// One candidate index per RAQE. + pub mapping: Mapping, + pub cost: crate::usage::UsageCost, +} + +/// 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"). 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], + facts: &WorkloadFacts, + w_cpu: f64, + 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; + // 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)) + .collect(); + let compaction_bytes: Vec = deployments + .iter() + .map(|d| analytical_cost_model::compaction_bytes(d, facts)) + .collect(); + let eligible: Vec> = raqes + .iter() + .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| { + latency_bound_ms.is_none_or(|bound| { + analytical_cost_model::chain_ms(raqe, &deployments[d], facts) + <= bound * (1.0 + LATENCY_SLACK) + }) + }) + .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) + }; + // 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 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| deployment_cost(d) + pair_cost(i, d) + w_mem * gib(storage(i, d))) + .fold(f64::INFINITY, f64::min) + }) + .sum(); + let reference = if reference.is_normal() { + reference + } else { + 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(); + // Priced storage per deployment, scaled: the max over the RAQEs it serves. + let stored: Vec = deployments + .iter() + .map(|_| variables.add(variable().min(0))) + .collect(); + + let mut goal: Expression = stored.iter().sum(); + for (d, &u) in active.iter().enumerate() { + goal.add_mul(deployment_cost(d) / reference, u); + } + for (i, choices) in assignments.iter().enumerate() { + for &(d, z) in choices { + goal.add_mul(pair_cost(i, d) / reference, z); + } + } + + 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 = w_mem * gib(storage(i, d)) / reference; + 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)); + } + + 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 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(UsageSolution { + milp: MilpSolution { + deployments: planned, + raqes: planned_raqes, + plan_cost, + }, + mapping, + cost, + }) +} + /// Keeps the deployments `mapping` uses, renumbered, with their instance /// counts. Every pair in `mapping` is eligible, so the counts exist. fn plan( @@ -394,6 +593,125 @@ mod tests { assert_eq!(solve(&[bounded]), vec![1]); } + /// Two RAQEs, 100 groups, and candidates that trade ingest for queries. + 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 + // that answers `long` without merging but keeps 10 windows open. + let deployments = vec![ + 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), + ]; + (raqes, deployments, facts(100, 100)) + } + + #[test] + 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, + ) + .value + }) + .min_by(f64::total_cmp) + .expect("servable"); + let got = minimize_usage_cost( + &raqes, + &deployments, + &facts, + w_cpu, + w_mem, + &table_accuracy, + None, + None, + ) + .expect("feasible"); + assert!( + (got.cost.value - best).abs() <= 1e-9 * best, + "({w_cpu}, {w_mem}): {} vs {best}", + got.cost.value + ); + } + } + + #[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. + 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_usage_cost( + &raqes, + &deployments, + &facts, + 1.0, + 0.0, + &table_accuracy, + allowed, + None, + ) + .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/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); + } +}