diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index abeb8e76..302f123f 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -10,14 +10,16 @@ implemented, what is next, and what is intentionally deferred. - Workload facts are per metric: full label set, scrape interval, and cardinality per label set. The arrival rate is derived from them, and `validate_facts` reports bad facts up front. -- Eligibility enforces capability, metric, spatial filter, grouping, alignment, and the RQE's +- Eligibility enforces capability, metric, spatial filter, grouping (equal, + or a subset for a family that merges across groups: a roll-up), alignment, and the RQE's measured accuracy, by each family's own metric, against the RAQE's SLA. - Candidate generation uses legal windows and subset gcds of query intervals, keeping only multiples of the scrape interval. A deployment may serve multiple compatible RQEs. -- Candidate dominance safely removes a deployment only when another covers all - of its RQEs with no worse instance memory, ingest CPU and memory, per-RQE - latency, or stored memory. +- Candidate dominance safely removes a deployment only when another at the + same grouping covers all of its RQEs with no worse ingest CPU and memory, + compaction (per window and per slide), per-RQE query-job CPU, query memory + (merge and output), or stored memory. - The analytical model scores four phases, each with CPU and memory: ingest (open windows), merge, query, and storage (closed windows, `(S − x)/y + 1` for the longest lookback), plus per-RQE latency. @@ -53,12 +55,12 @@ implemented, what is next, and what is intentionally deferred. ## Explicitly deferred - Query-result sharing across RQEs. -- Real query concurrency; memory assumes every query runs at once. +- Real query concurrency in the snapshot objective, whose memory assumes every + query runs at once (cost by use holds query memory only while it runs). - Bursty load; CPU is a mean over time. -- A per-family instance shape for families holding every group in one - fixed-size instance (HydraKLL, sketch-bench#142). -- Top-k `k` other than the benchmark's 32, and key labels `K`. +- Admitting Hydra. +- Key labels `K` (PerGroup + PerKey sizes). - RQE churn, replanning, and migration cost. -- Precomputed rollups; v1 merges selected base instances at query time. +- Temporal pre-merging; v1 merges selected base instances at query time. - A policy for choosing one mapping from the reported Pareto frontier. - Additional capabilities beyond frequency, quantile, cardinality, and top-k. diff --git a/docs/rqe_optimizer_candidates.md b/docs/rqe_optimizer_candidates.md new file mode 100644 index 00000000..fd0d9cee --- /dev/null +++ b/docs/rqe_optimizer_candidates.md @@ -0,0 +1,241 @@ +# RQE optimizer: candidate generation and mapping + +This document is the canonical design for candidate construction, eligibility +(accuracy included), finer-to-coarser roll-ups and dominance pruning. What a +candidate costs, and the MILP that maps RAQEs to candidates, are in +[Cost models](rqe_optimizer_cost_model.md). + +## Candidate deployments + +A candidate deployment is: + +```text +D = (capability, configuration, metric, G, x, y) +``` + +Candidates may be generated from individual RAQEs, then deduplicated. This is +only a way to construct the candidate set: when solving a workload, one +selected deployment may serve multiple compatible RAQEs. + +Intuition: candidates are built in two steps, and each drops only candidates +that another candidate beats, so the best plan is never lost. Generation uses +no measurements. It keeps every legal window and configuration, and drops only +slides that a coarser slide beats for the same RAQEs. Pruning then attaches the +measured costs and drops a candidate when another serves all of its RAQEs and +is no worse on every cost. + +Deployments exist only at groupings some RAQE asks for. For each (capability, +metric, spatial filter, grouping `G`), let `R(G)` be the RAQEs a deployment at +`G` may serve: those grouped exactly by `G` for a family that does not merge +across groups, and those grouped by any subset of `G` (roll-ups included) for +a family that does (`mergeable_across_groups`). A coarse RAQE so contributes +its lookback and interval to the fine deployment's windows and slides. Top-k +doesn't roll up, so its heaps come from exact-grouping RAQEs only. Then: + +```text +for each RAQE set R(G), and each window x that divides some S_i in it and is a multiple of the scrape interval: + g = { g_i = gcd(x, T_i) : RAQE i with S_i divisible by x } + slides = { gcd(A) : A is a non-empty subset of g } + for each y in slides that is a multiple of the scrape interval: + for each configuration that serves the capability: + add (capability, configuration, metric, G, x, y) +``` + +`g_i = gcd(x, T_i)` is the largest slide that serves RAQE `i`. + +**Windows.** An RAQE merges `S_i / x` whole windows, so `x` must divide `S_i`. +Windows and slides finer than the scrape interval would only split one +scrape's samples. + +**Slides.** A slide `y` serves RAQE `i` when it divides both `x` and `T_i`, +that is, when it divides `g_i`. A finer slide serves no more RAQEs but holds +more open windows (`x / y`) and more closed ones, so it costs more ingest and +storage at the same latency. Hence: + +- for one RAQE, `y = g_i` is strictly better than every finer slide that serves + it; +- for a set `A` of RAQEs sharing a deployment, `y = gcd(A)`, the largest slide + dividing every `g_i` in `A`, is strictly better than every finer slide that + serves them all. + +Which RAQEs share is the solver's choice, so every subset's gcd is a candidate. +Every other divisor of `x` is strictly worse than one of these. + +Example: `x = 60`, RAQE `a` every 20 s, RAQE `b` every 30 s. + +| Served RAQEs | `y` | Open windows `x / y` | +|---|---|---| +| `a` | gcd(60, 20) = 20 | 3 | +| `b` | gcd(60, 30) = 30 | 2 | +| `a` and `b` | gcd(20, 30) = 10 | 6 | + +The slides are `{10, 20, 30}`. `y = 5` would also serve both, but holds 12 open +windows instead of 6. With a 15 s scrape interval only `y = 30` remains: no +multiple of 15 divides both 20 and 30, so `a` and `b` cannot share at +`x = 60`. + +The subset gcds take one pass, without listing subsets: keep the gcds found so +far, and for each new `g` add `g` and `gcd(found, g)` for every `found`. For +`{20, 30}`: `{20}`, then `{20, 30, 10}`. One pass suffices because +`gcd(A ∪ {g}) = gcd(gcd(A), g)`. + +An RAQE `r_i` is eligible for a candidate `D` when: + +1. `cap_i = D.capability`, `metric_i = D.metric`, the same spatial filter, + and `G_i = D.G`, or `G_i ⊂ D.G` when `D`'s family has + `mergeable_across_groups` (a roll-up; see below). A coarse deployment never + serves a finer RAQE. +2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. +3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family + (`family_properties`, which also gives the direction), clears `tol_i`. + +Exact accumulators take that accuracy from the cost table; they merge without +loss, so the window size doesn't matter. Sketches take it +from the saturation study's error-vs-N curves (`SaturationCurves`, #156), +read at the number of items one answered group receives over the RAQE's +whole lookback: series per `G_i` group times scrapes per lookback. On a +roll-up the answered group is the RAQE's coarse one. + +- The curve is the configuration's at the metric's fitted `data_shape` for + the RAQE's grouping `G_i` (zipf θ and keys `K`, or tail index `a` for + quantiles). Between grid + points, the worst bracketing point; outside the grid, or with no fit, no + accuracy. +- Between checkpoints, the worse neighbour. Below the first checkpoint, no + accuracy. Past the last, the plateau if the point saturated, else none. +- The curve's `error_metric` must be the family's metric; `SaturationCurves::load` + refuses a curve for another metric as a stale study. +- For sketches that merge exactly, the window size doesn't matter: a merged + answer reads the curve at the lookback's item count, like a single sketch. + KLL and univmon-cardinality merge lossily (#131; UnivMon rebuilds its + heavy-hitter heaps from the union of the merged heaps): an answer merged from `n = S_i / D.x` windows, + times the average fan-out `⌈card(D.G) / card(G_i)⌉` on a roll-up, reads + the study's merge curve (`saturation_merge_curve.csv`, the sketch merged + from `n` shards of the same items) at the lookback's item count. Between + measured shard counts, the worse. Past the largest measured count, or past + a merge curve's last N, the curves say nothing, so the answer takes the + guarantee below, no better than the largest count's last measurement; the + study should measure the merge counts a workload needs + (`--merge-shards-list`) so the guarantee isn't what decides (#158); + univmon-cardinality has no guarantee, so past its curves it has no + accuracy. `SaturationCurves::load` refuses a study with no merge curves + for a lossy non-heap candidate sketch (KLL, univmon-cardinality, + univmon-topk). The fan-out is the average; the largest group's is + #189. +- A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap + top-k (CMS-heap, CountSketch-heap) keeps a heap of `n · k` in a deployment + answering from `n = S_i / D.x` merged windows (`n = 1` gives `k`). + Candidates carry one heap per distinct `n · k` among the RAQEs on a window, + and a RAQE is eligible only where the heap holds its `n · k`. Such a merged answer reads as one sketch: the + plain curve, then the guarantee fallback. It assumes the merged heaps still + hold the true top `k`; it is not a guarantee. So heap top-k needs no merge + curves. Costs come from the cost table's rows at heaps 32, 128, 512 and + 2048 (`heap=`), linear in the heap between them and past them. Curves are + measured per `k` (`topk_k=` in the config; 10, 32 and 100 by default) at a + heap of `k`, and larger heaps read the same curve. A RAQE reads the curve + at its `k`, else at the next larger measured `k` (harder); past every + measured `k`, only the guarantee at its `k`. Its query outputs `k` + entries per group. +- Where the study measured nothing for a bracketing point at or above its + first N (past an unsaturated curve, past the measured merge counts or N, + or with no merge curve), the accuracy falls back to the algorithm's + guarantee at 95% confidence (`rqe_optimizer::theory`; two-sided for + rank and relative errors, one-sided for CMS overestimates). It is never + better than the worst last measurement of the curves it extends. The fallbacks are: + - KLL: rank error `2.296 / k^0.9723` (DataSketches' 99% value), scaled + to 95% two-sided; + - DDSketch: relative value error `α` (unbounded store); + - HLL: `1.96 · 1.04 / sqrt(2^lg_k)`; + - CMS-heap top-k, unmerged: the share of the top `k` Zipf(θ, K) keys kept + ranked for every key at once. With Markov per row, independent rows, + and a union bound over the `K − k` other keys, key `i` fails with + probability at most `(cols · (p_i − p_{k+1}))^−rows`. Keys are counted + from the most frequent while the summed failure stays within 5%. It + assumes the heap ranks keys by their final CMS estimates. + + A sketch with no published bound, a merged top-k answer, a point below + the first N, or a shape outside the grid stays unknown. + `accuracy_with_source` reports which points used a bound. + +The cost table's sketch accuracies are not read, but they are one point on +each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto +`a`) is a grid point's key. `SaturationCurves::check_cost_table` reports every +row whose `accuracy_metric` is not its family's or not its curve's +`error_metric`, whose configuration is not in the grid, or whose accuracy +disagrees with the curve at `measured_at` (beyond 3 seed standard errors plus +5%). The study adds the cost table's shape to the grid as a full row and +column (θ = 1.1 at every K, K = 1e4 at every θ), so every sketch row has a +grid point and the grid stays a full cross. `SaturationCurves::load` +refuses curves whose Zipf grid isn't a full cross of its θ and K values and +names the missing points: a hole would leave every shape around it without +accuracy (for example, curves from `--points-from` or a narrowed `--resume`). A row without a grid point (a study run +with `--no-cost-shape`) is reported as unchecked. `small_problem` refuses to plan +when any row disagrees. + +For lower-is-better metrics, passing means `measured <= tol_i`. For +higher-is-better metrics, passing means `measured >= tol_i`. Direction is +explicit on the RAQE; it is never inferred from a metric name. A missing metric +does not pass. + +Before mapping, prune a candidate only if another candidate with the same +capability, metric, spatial filter and grouping can serve every RAQE it can, +and is no worse in ingest CPU and memory, in compaction (CPU-seconds per +window, and CPU and byte-seconds per second), and, for each RAQE it serves, +in query-job CPU (`ℓ`), query memory (merge accumulators and output) and +stored memory. Every cost in both objectives, and every chain (compaction, then +query), is monotone in these, so any mapping using the removed candidate can +substitute the remaining one without raising cost or latency. + +Closed instances must be stored long enough to answer the RAQEs assigned to a +deployment. Retention is not a candidate parameter: a deployment stores the +history needed by the largest assigned query window, costed as the storage +phase ([Cost models](rqe_optimizer_cost_model.md), §3). + +## Workload mapping + +Every RAQE selects exactly one eligible candidate; several RAQEs may select +the same one and so share its ingest. A query may merge several instances +of its candidate, but v1 never combines results from several deployments to +answer one RAQE. The MILP over the eligible pairs, its objective and its +latency bound are in [Cost models](rqe_optimizer_cost_model.md) (§7 for cost +by use; the snapshot objective changes only its coefficients). The solver +never enumerates full mappings. + +## Fine-to-coarse group roll-ups + +A deployment grouped by `G_d` can answer a RAQE grouped by `G_r ⊂ G_d` when +its family merges across groups (`mergeable_across_groups`): at query time, +the fine instances of each coarse group are merged into one, then answered. +This is a **roll-up**. Families that do: exact sum/min/max, HLL, +univmon-cardinality, KLL and DDSketch. These don't, and serve only +`G_r = G_d`: + +- **Rate/increase** (`exact-increase`). A coarse increase is the sum of its + series' increases, `Σ_s increase_s`, so it is not the increase of the + summed counter: a reset in one series is hidden by the others' growth. + The accumulator tracks one counter, and its merge joins two pieces of it + in time (a drop at the seam is a reset), so merging two groups' counters + is wrong: A going 100 → 110 and B going 5 → 8 over the same minute merge + to 10, not 13. A roll-up would need per-series state and a sum of values, + not this merge. (ASAPQuery keys `MultipleIncrease` per series: it plans + only bare `rate`/`increase`, which keep every label.) +- **Top-k** (CMS-heap, CountSketch-heap, univmon-topk). A coarse group's top + `k` can hold keys that are in none of its fine groups' heaps. +- **Hydra**. It inserts every label subset of its schema, so a coarse + grouping inside the schema is answered directly from the grid, never by + merging fine groups; it is not a candidate today. + +- **Cost**: ingest, compaction and storage stay at `G_d`; the query job merges + `I_d · n − I_r` times and answers `card(G_r)` groups + ([Cost models](rqe_optimizer_cost_model.md), §3). A direct roll-up + (`n = 1`) still merges `card(G_d) − card(G_r)` instances. +- **Accuracy**: read at `G_r`: its `data_shape`, and its items per group over + the lookback. KLL's and univmon-cardinality's merge curves are read at + `⌈card(G_d)/card(G_r)⌉ · n` merged instances, the average fan-out, an estimate rather than a + worst-group bound (uneven fan-out is #189). +- **Facts**: `validate_facts` requires `card(X) ≤ card(Y)` for every pair + `X ⊂ Y` among the label sets a plan can use (every RAQE grouping on the + metric, and its full label set), so a merge count is never negative. + Label sets no RAQE groups by are not checked. +- **Plan output**: a RAQE rolls up exactly when its grouping differs from its + deployment's. diff --git a/docs/rqe_optimizer_cost_model.md b/docs/rqe_optimizer_cost_model.md new file mode 100644 index 00000000..02b4f162 --- /dev/null +++ b/docs/rqe_optimizer_cost_model.md @@ -0,0 +1,431 @@ +# RQE optimizer: cost models + +This document is the one home for what a candidate costs (§3's table), the +canonical cost-by-use model with its MILP, and the still-supported +snapshot-AUC objective. Candidates and eligibility are in +[Candidate generation and eligibility](rqe_optimizer_candidates.md). + +## Model status and relationship + +- **Cost by use and batch latency** is the canonical model for the current + ASAP-versus-AutoSketch evaluation. It accounts for ingest workers, + window-close compaction, transient memory over its holding time, elastic CPU, + and a batch-latency bound. +- **Resource primitives and the snapshot-AUC objective** remain supported for + the original generic optimizer. They define the measured per-operation and + per-instance inputs used everywhere, then use the older snapshot accounting: + query memory is summed as if concurrent, there is no worker fan-out or + compaction, and latency is serial query work. It is not the evaluation's + billing model. +- **Hydra** is future work, not a candidate today. + +The two implemented objectives share the same resource primitives and §3's +table; they differ in how they account for them over time, and in latency +(a batch's longest chain vs. each RAQE's serial query time). + +## 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` | +| `a_D = x_D / y_D` | open windows; each sample is inserted into `a_D` instances | +| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | +| `G_d`, `G_r` | `D`'s grouping; RAQE `i`'s grouping, equal to `G_d` or, for a family that merges across groups, a subset of it (a **roll-up**) | +| `card(G)` | groups of grouping `G` | +| part | the sketch, plus a key tracker if the family needs one; every cost below is summed over parts | +| `I_d` | a part's instances per window: `card(G_d)`, or 1 for a sketch shared by all groups | +| `I_r` | the states a query of `i` ends with: `card(G_r)`, or 1 for a sketch shared by all groups | +| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | +| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | +| `m` | measured bytes per instance; `w_D = Σ_parts I_d · m`, one window of all instances | +| `n_{i,D} = S_i / x_D` | windows a query merges | +| `k_D = ⌈ρ_D⌉` | ingest workers (at least one), from ingest CPU `ρ_D` (§3) | +| batch | all query jobs issued at one instant | + +**Measurement assumption (sketch-bench as is).** Every sketch operation is +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. Cost of each phase: CPU and memory + +This is the one cost table: every phase, with its CPU and its memory. Each +cell is per part; a phase's cost is the sum over parts. + +| Phase | When | CPU-seconds per event | Mean vCPUs | Memory (bytes) | Held | +|---|---|---|---|---|---| +| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · a_D · c_ins` | `ingest_D = I_d · m · a_D · k_D` (open windows, one copy per worker) | always | +| Compaction | at each window close | `c_D = (k_D − 1) · I_d · c_mrg` | `c_D / y_D` | `k_D · I_d · m` (the closed window's partial copies; 0 when `k_D = 1`) | while it runs: `c_D` | +| Query job of RAQE `i` (merge, then estimate) | at each firing | `ℓ_{i,D} = card(G_r) · c_qry + (I_d · n_{i,D} − I_r) · c_mrg` | `ℓ_{i,D} / T_i` | `q_{i,D} = I_r · m(S_i) · [merges > 0] + card(G_r) · output bytes` | while it runs: `ℓ_{i,D}` | +| Storage | always | — | 0 | `stored_D = max_i I_d · m · ((S_i − x_D) / y_D + 1)` (closed windows, one compacted copy) | always | + +- **No roll-up** (`G_r = G_d`, so `I_r = I_d`): the query merges + `I_d · (n − 1)` times, and a direct query (`n = 1`) merges nothing and + holds no accumulator. +- **Roll-up** (`G_r ⊂ G_d`): a query reads `I_d · n` states and ends with + `I_r`, and each merge folds two into one, so it merges `I_d · n − I_r` + times, even when direct. Ingest, compaction and storage stay at `G_d`; + the query's accumulators, answers and output are at `G_r`. +- `m(S_i)` is an accumulator holding the lookback of one `G_r` group (it + differs from `m` only for DDSketch on a metric with a value range, which is + sized from the values it holds). +- Ingest runs on `k_D` parallel workers (each uses at most one core), + **split by sample**: each worker reads a share of the input (e.g. some + Kafka partitions or scrape targets) with no shuffle by group, so it keeps + its own open window instance of every group it sees. +- When a window closes (the watermark passes its end), a **compaction** job + merges the `k_D` partial instances of each group into one stored instance. + With `k_D = 1` there is none. The merged copy takes the storage slot that + the oldest window frees at the same moment, so it is not counted twice. +- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` + stored instances of each group for the query window, then estimate. + Merging is part of the query. It reads the newest window, which closes at + the firing time, so it starts after that window's compaction. It reads + stored instances in place. +- Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence + `(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. +- Query output is estimated at 8 bytes per group, or `k` × 16 bytes per group + for top-k (`k` the deployment's answered top-k, 32 by default, with 64-bit + key hashes); it is not measured. A top-k sketch's `c_qry` is measured at + `k = 32` and scaled by `k / 32`. +- `k_D = ⌈ρ_D⌉` takes the deployment's whole ingest CPU, summed over its + parts (sketch and key tracker). + +In words: + +- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already + inside `λ_D`), and each is inserted into the `a_D` windows still open, at + `c_ins` CPU-seconds each: CPU-seconds per second. +- `c_D`: closing a window merges, for every instance, the `k_D` workers' + partial copies into one, which takes `k_D − 1` merges. This happens once + per slide. +- `ℓ_{i,D}`: a query merges the stored windows it reads down to one state per + answered group, then answers once per `G_r` group. This happens once per + interval. (A sketch shared by all groups merges one instance but still + answers every group.) +- `ingest_D`: every worker keeps one instance per group for each of the `a_D` + windows still open, and there are `k_D` workers. +- `stored_D`: closed windows are kept until the longest lookback that `D` + serves no longer needs them. +- `q_{i,D}`: a merge builds one accumulator per answered group, plus the + answer for every group. + +#### 4. AUC(CPU) and AUC(memory) + +Every "mean vCPUs" is a long-run average rate, CPU-seconds per second, over +the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, over +which every job pattern repeats exactly. A part with `w` CPU-seconds per +event every `P` seconds runs `H / P` times per hyperperiod, so its mean is +`(H / P) · w / H = w / P`; ingest is already a rate. So the columns add. + +```text +AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i +AUC(memory) = Σ_D (ingest_D + stored_D + k_D · w_D · c_D / y_D) + + Σ_i q_{i,D} · ℓ_{i,D} / T_i +``` + +CPU is elastic, so every job runs on its own core: a compaction runs for +`c_D` and a query for `ℓ_{i,D}`. Both AUCs are fixed by the plan, whatever +the schedule. + +In words: `AUC(CPU)` adds the three rates, work per second in vCPUs; ingest +is already a rate, and only compaction (per window close, every `y_D`) and +queries (per firing, every `T_i`) are divided by their period. +`AUC(memory)` holds ingest and storage all the time, and a compaction's and +a query's memory only while they run, a fraction `run time / y_D` or +`run time / T_i` of the time. + +#### 5. Batch latency and the SLA + +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 ((ingest_D + k_D · w_D · c_D / y_D) · u_D + stored_D) + + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] +s.t. Σ_D z_{i,D} = 1 for every RAQE i + z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E + 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 divided by the sum, over RAQEs, of +each RAQE's cheapest pair on its own, so the solver sees magnitudes near 1). The solved plan's cost and latency are +then computed from its resource use (`usage::usage_cost`). + +- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` + 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. + +## Resource primitives and the snapshot-AUC objective + +The measured per-operation primitives (`m`, `c_ins`, `c_mrg`, `c_qry`, from +the cost table) and how they scale with a deployment (instance shape and size +law, below) are shared by both objectives; the one cost table is §3's. + +`m` is measured per instance, except for DDSketch on a metric with a +`value_range`: `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` +bytes, one bucket count per `gamma`-power in the range, capped by the values +one instance holds (`λ · x / card(G_d)` for a window, `λ · S / card(G_r)` for +a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. +The range is the metric's, so `m` is an upper bound for a group whose own +values span less. + +**Snapshot-AUC objective** (`milp::minimize`, `analytical_cost_model::score`; +still supported). It prices §3's table with older accounting: + +- one ingest worker (`k_D = 1`), so no compaction; +- each RAQE's merge and query memory (`q_{i,D}`) held all the time, as if + every query ran at once, instead of for `ℓ_{i,D} / T_i` of the time; +- a RAQE's latency is its query job's serial CPU time `ℓ_{i,D}`, with no + compaction before it, checked against the RAQE's own + `latency_sla_ms` (no batch latency). + +Its CPU (`ρ_D`, `ℓ_{i,D} / T_i`) and its ingest and storage memory are §3's +with `k_D = 1`, roll-ups included. + +### Instance shape and size law + +Each row of the cost table (from +[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py)) +is measured on one instance, at whatever key count the benchmark fed it +(`measured_keys`). A key is one distinct entry an instance stores exactly, +such as one group's running sum in an exact accumulator. Turning a row into a +deployment's cost needs two properties of the family: + +- **Shape**: instances per window. `PerGroup` keeps one per group, so + `card(G_d)`; `Shared` keeps one for all groups. +- **Law**: how one instance's size grows. `Fixed` is set by the configuration + (e.g. CMS rows × columns); `PerKey` stores one entry per key, so it grows + linearly with keys. + +Memory per window is instances × instance size: + +| | Fixed | PerKey | +|---|---|---| +| **PerGroup** | `card(G_d) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G_d) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | +| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G_d) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | + +The same factor scales merge and query CPU. Insert CPU is per sample and does +not scale. + +Quantile sketches have no keys. KLL's `m` is Fixed, and the same at every +item count, because `asap_sketchlib::KLL` allocates once at construction. +Since #192 the cost table's KLL rows report that allocation: item slots, +level index and merge buffer, 5536 B at `k = 50`. Cost tables measured +before it, including the committed `autosketch-vs-asap-inputs`, carry a +nominal `4 · k · sizeof(T)` instead (1600 B at `k = 50`; the allocation is +1.58× that at `k = 200`, 1.14× at `k = 800`), so they understate KLL +memory (#191). +DDSketch is sized from the metric's `value_range` when given (capped by +values per instance), else from the measured size. + +The model uses `I_d × m`, where `I_d` is instances per window: + +- PerGroup + Fixed: `I_d = card(G_d)`. +- Shared + PerKey reduces to `I_d = card(G_d)` because the export divides the + exact accumulators' memory and merge cost by `measured_keys` + (`groups_per_instance`), making `m` a per-group cost. Their query cost is + already per group. +- Shared + Fixed: `I_d = 1`. In code this is the family property + `one_fixed_size_sketch_for_all_groups`, true only for HydraKLL. It applies + to memory and merge; query stays `card(G_r) × c_qry`, one probe per answered group. + A fixed-size sketch degrades as groups grow, so it is eligible only when + `card(G_d)` is at most the `subpopulations` its row was measured at. This + models a sketch keyed by the joined `G` value alone; the current rows fan + out to every label subset (sketch-bench#165), and merging several windows + is not yet measured (sketch-bench#166). + +PerGroup + PerKey is deferred until a family needs it: it needs the key labels +`K`, the metric's labels minus `G`. So for every family in use, nothing scales +with keys below the group: a per-service top-k CMS costs the same however +many endpoints it counts. + +Side by side, what each family puts into §3's table (every phase then +follows from it): + +| | KLL (per group) | exact-sum (per-group normalized) | HydraKLL (shared, fixed) | +|---|---|---|---| +| `m`, `c_mrg` in the row | one group's | whole ÷ groups | whole sketch | +| `I_d` (instances per window) | `card(G_d)` | `card(G_d)` | 1 | +| `I_r` (states a query ends with) | `card(G_r)` | `card(G_r)` | 1 | +| probes per query (`c_qry`) | `card(G_r)` | `card(G_r)` | `card(G_r)` | +| key tracker part | none | none | DeltaSet, `I_d = card(G_d)` | +| rolls up (`G_r ⊂ G_d`) | yes | yes | no | + +HydraKLL has `FamilyProperties` but is in no capability's family list, so it +is never a candidate. + +### Family properties and key tracker + +Each family has properties, hardcoded by variant in `family_properties` +(an unknown variant panics rather than getting a default): + +- `mergeable_across_windows`: a family without it only serves `S_i = x`. + Every family in use merges. +- `mergeable_across_groups`: it can serve a RAQE at a subset grouping (a + roll-up, [candidates](rqe_optimizer_candidates.md#fine-to-coarse-group-roll-ups)). + True for exact sum/min/max, HLL, univmon-cardinality, KLL and DDSketch. +- `one_fixed_size_sketch_for_all_groups`: the Shared + Fixed cell above. +- `needs_delta_set_key_tracker`: the sketch can't list its groups, so a + DeltaSet (`exact-delta-set`) records each window's keys for the query to + probe. True for HydraKLL. A candidate needing one carries the DeltaSet row + and is dropped if the cost table has none; a deployment without its tracker + is never eligible. The cost table may hold at most one DeltaSet row. + +The tracker is priced as an exact accumulator on the same `x`, `y` and `G`, +in every phase: ingest, merge (union of the `n_i` windows' key sets), query +(enumerate keys) and storage. Its `m` is per key, so it adds `card(G_d) × m_ds` +per window. The AutoSketch baseline skips shared fixed-size families for now +(sketch-bench#159). + +A query job's serial CPU time, `ℓ_{i,D}` (§3), summed over the sketch and +its key tracker, is a RAQE's latency in the snapshot-AUC objective and the +query half of its chain in cost by use. On its own it is not a wall-clock +SLA: it assumes no parallel execution across groups and no cheaper k-way +merge. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index 8f8c83a7..767f0858 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -31,11 +31,16 @@ and per-RAQE latency. - **Deployment**: a configuration run over one metric, grouped by `G`, with window `x` and slide `y`. A **candidate** is a deployment the optimizer may choose. -- **Phase**: one of the four kinds of work a deployment does, each costed in - CPU and memory: **ingest** (inserting samples into open instances), - **merge** (folding a query's windows into an accumulator), **query** - (reading the merged result) and **storage** (keeping closed instances, no - CPU). See [Analytical cost model](#analytical-cost-model). +- **Phase**: one of the kinds of work a deployment does, each costed in CPU + and memory: **ingest** (inserting samples into open instances), + **compaction** (merging the ingest workers' copies of a closed window), + the **query job** (merging a query's windows, and on a roll-up its fine + groups, then reading the result) and **storage** (keeping closed + instances, no CPU). The snapshot objective and `PlanCost` report the query + job as two phases, **merge** and **query**, and have no compaction. See + [Cost models](rqe_optimizer_cost_model.md). +- **Roll-up**: a deployment grouped by `G_d` serving a RAQE grouped by a + subset `G_r`, by merging each coarse group's fine instances at query time. ## Inputs @@ -77,7 +82,7 @@ The cost table, measured by - CPU per pairwise merge; - the comparator's accuracy scores, and `accuracy_metric`, the one that is the row's accuracy (only exact accumulators read it; see - [eligibility](#candidate-deployments)); and + [eligibility](rqe_optimizer_candidates.md#candidate-deployments)); and - `measured_at`, the data it was measured on. The study measures every configuration once, serially, at one data shape: @@ -139,635 +144,24 @@ non-overlapping two-minute instances. We assume all RAQEs share a common time origin. Query phase offsets are not modeled. -## Candidate deployments +## Planning design -A candidate deployment is: +The optimizer has two companion design documents: -```text -D = (capability, configuration, metric, G, x, y) -``` - -Candidates may be generated from individual RAQEs, then deduplicated. This is -only a way to construct the candidate set: when solving a workload, one -selected deployment may serve multiple compatible RAQEs. - -Intuition: candidates are built in two steps, and each drops only candidates -that another candidate beats, so the best plan is never lost. Generation uses -no measurements. It keeps every legal window and configuration, and drops only -slides that a coarser slide beats for the same RAQEs. Pruning then attaches the -measured costs and drops a candidate when another serves all of its RAQEs and -is no worse on every cost. - -For each (capability, metric, G) group, generate candidates as follows: - -```text -for each window x that divides some S_i and is a multiple of the scrape interval: - g = { g_i = gcd(x, T_i) : RAQE i with S_i divisible by x } - slides = { gcd(A) : A is a non-empty subset of g } - for each y in slides that is a multiple of the scrape interval: - for each configuration that serves the capability: - add (capability, configuration, metric, G, x, y) -``` - -`g_i = gcd(x, T_i)` is the largest slide that serves RAQE `i`. - -**Windows.** An RAQE merges `S_i / x` whole windows, so `x` must divide `S_i`. -Windows and slides finer than the scrape interval would only split one -scrape's samples. - -**Slides.** A slide `y` serves RAQE `i` when it divides both `x` and `T_i`, -that is, when it divides `g_i`. A finer slide serves no more RAQEs but holds -more open windows (`x / y`) and more closed ones, so it costs more ingest and -storage at the same latency. Hence: - -- for one RAQE, `y = g_i` is strictly better than every finer slide that serves - it; -- for a set `A` of RAQEs sharing a deployment, `y = gcd(A)`, the largest slide - dividing every `g_i` in `A`, is strictly better than every finer slide that - serves them all. - -Which RAQEs share is the solver's choice, so every subset's gcd is a candidate. -Every other divisor of `x` is strictly worse than one of these. - -Example: `x = 60`, RAQE `a` every 20 s, RAQE `b` every 30 s. - -| Served RAQEs | `y` | Open windows `x / y` | -|---|---|---| -| `a` | gcd(60, 20) = 20 | 3 | -| `b` | gcd(60, 30) = 30 | 2 | -| `a` and `b` | gcd(20, 30) = 10 | 6 | - -The slides are `{10, 20, 30}`. `y = 5` would also serve both, but holds 12 open -windows instead of 6. With a 15 s scrape interval only `y = 30` remains: no -multiple of 15 divides both 20 and 30, so `a` and `b` cannot share at -`x = 60`. - -The subset gcds take one pass, without listing subsets: keep the gcds found so -far, and for each new `g` add `g` and `gcd(found, g)` for every `found`. For -`{20, 30}`: `{20}`, then `{20, 30, 10}`. One pass suffices because -`gcd(A ∪ {g}) = gcd(gcd(A), g)`. - -An RAQE `r_i` is eligible for a candidate `D` when: - -1. `cap_i = D.capability`, `metric_i = D.metric` and `G_i = D.G`. -2. `D.x % D.y = 0`, `S_i % D.x = 0`, and `T_i % D.y = 0`. -3. The accuracy of `D` for `r_i`, in the accuracy metric of `D`'s family - (`family_properties`, which also gives the direction), clears `tol_i`. - -Exact accumulators take that accuracy from the cost table; they merge without -loss, so the window size doesn't matter. Sketches take it -from the saturation study's error-vs-N curves (`SaturationCurves`, #156), -read at the number of items one group receives over the RAQE's whole -lookback: series per group times scrapes per lookback. - -- The curve is the configuration's at the metric's fitted `data_shape` for - `G` (zipf θ and keys `K`, or tail index `a` for quantiles). Between grid - points, the worst bracketing point; outside the grid, or with no fit, no - accuracy. -- Between checkpoints, the worse neighbour. Below the first checkpoint, no - accuracy. Past the last, the plateau if the point saturated, else none. -- The curve's `error_metric` must be the family's metric; `SaturationCurves::load` - refuses a curve for another metric as a stale study. -- For sketches that merge exactly, the window size doesn't matter: a merged - answer reads the curve at the lookback's item count, like a single sketch. - KLL and top-k merge lossily (#131): an answer merged from `m = S_i / D.x` - windows reads the study's merge curve (`saturation_merge_curve.csv`, the - sketch merged from `m` shards of the same items) at the lookback's item - count. Between measured shard counts, the worse. Past the largest - measured count, or without a merge curve, a merged KLL or top-k answer has - no accuracy: the study must measure the merge counts a workload needs - (`--merge-shards-list`) up to the N it reads at: past the merge curve's - last N, the merged answer has no accuracy either (#158). - `SaturationCurves::load` refuses a study with no merge curves for a - candidate KLL sketch. -- A top-k RAQE asks for its own `k` (`Raqe::topk_k`, default 32). Heap - top-k (CMS-heap, CountSketch-heap) keeps a heap of `m · k` in a deployment - answering from `m = S_i / D.x` merged windows (`m = 1` gives `k`). - Candidates carry one heap per distinct `m · k` among the RAQEs on a window, - and a RAQE is eligible only where the heap holds its `m · k`. Such a merged answer reads as one sketch: the - plain curve, then the guarantee fallback. It assumes the merged heaps still - hold the true top `k`; it is not a guarantee. So heap top-k needs no merge - curves. Costs come from the cost table's rows at heaps 32, 128, 512 and - 2048 (`heap=`), linear in the heap between them and past them. Curves are - measured per `k` (`topk_k=` in the config; 10, 32 and 100 by default) at a - heap of `k`, and larger heaps read the same curve. A RAQE reads the curve - at its `k`, else at the next larger measured `k` (harder); past every - measured `k`, only the guarantee at its `k`. Its query outputs `k` - entries per group. -- Where the study measured nothing for a bracketing point at or above its - first N (past an unsaturated curve, past the measured merge counts or N, - or with no merge curve), the accuracy falls back to the algorithm's - guarantee at 95% confidence (`rqe_optimizer::theory`; two-sided for - rank and relative errors, one-sided for CMS overestimates). It is never - better than the worst last measurement of the curves it extends. The fallbacks are: - - KLL: rank error `2.296 / k^0.9723` (DataSketches' 99% value), scaled - to 95% two-sided; - - DDSketch: relative value error `α` (unbounded store); - - HLL: `1.96 · 1.04 / sqrt(2^lg_k)`; - - CMS-heap top-k, unmerged: the share of the top `k` Zipf(θ, K) keys kept - ranked for every key at once. With Markov per row, independent rows, - and a union bound over the `K − k` other keys, key `i` fails with - probability at most `(cols · (p_i − p_{k+1}))^−rows`. Keys are counted - from the most frequent while the summed failure stays within 5%. It - assumes the heap ranks keys by their final CMS estimates. - - A sketch with no published bound, a merged top-k answer, a point below - the first N, or a shape outside the grid stays unknown. - `accuracy_with_source` reports which points used a bound. - -The cost table's sketch accuracies are not read, but they are one point on -each curve: a row's `measured_at` (items, Zipf θ and population, or Pareto -`a`) is a grid point's key. `SaturationCurves::check_cost_table` reports every -row whose `accuracy_metric` is not its family's or not its curve's -`error_metric`, whose configuration is not in the grid, or whose accuracy -disagrees with the curve at `measured_at` (beyond 3 seed standard errors plus -5%). The study adds the cost table's shape to the grid as a full row and -column (θ = 1.1 at every K, K = 1e4 at every θ), so every sketch row has a -grid point and the grid stays a full cross. `SaturationCurves::load` -refuses curves whose Zipf grid isn't a full cross of its θ and K values and -names the missing points: a hole would leave every shape around it without -accuracy (for example, curves from `--points-from` or a narrowed `--resume`). A row without a grid point (a study run -with `--no-cost-shape`) is reported as unchecked. `small_problem` refuses to plan -when any row disagrees. - -For lower-is-better metrics, passing means `measured <= tol_i`. For -higher-is-better metrics, passing means `measured >= tol_i`. Direction is -explicit on the RAQE; it is never inferred from a metric name. A missing metric -does not pass. - -Before mapping, prune a candidate only if another candidate can serve every -RAQE it can and is no worse in ingest CPU and memory, and in latency, merge -memory and stored memory for each such RAQE. This is safe because any mapping using -the removed candidate can substitute the remaining one without weakening a -modeled objective. - -Closed instances must be stored long enough to answer the RAQEs assigned to a -deployment. Retention is not a candidate parameter: a deployment stores the -history needed by the largest assigned query window, costed as the storage -phase (below). - -## Workload mapping - -Let `z_{i,D}` be 1 when RAQE `i` uses candidate deployment `D`; let `u_D` be 1 -when deployment `D` is active. - -```text -Σ_D z_{i,D} = 1 for every RAQE i -z_{i,D} <= u_D for every eligible pair (i, D) -``` - -Every RAQE selects exactly one eligible deployment. Multiple RAQEs may select -the same deployment and therefore share its ingest work. A query may merge -multiple instances from its selected deployment, but v1 does not combine -results from several deployments to satisfy one RAQE. - -### MILP formulation - -Let `E` be the eligible `(i, D)` pairs. The solver has one binary `z_{i,D}` -for each pair in `E`, one binary `u_D` for each candidate, and a continuous -`stored_D` for each candidate's closed-window storage. - -```text -z_{i,D} ∈ {0, 1} for (i, D) ∈ E -u_D ∈ {0, 1} for D ∈ candidates -stored_D ≥ 0 - -Σ_{D: (i,D) ∈ E} z_{i,D} = 1 for every RAQE i -z_{i,D} ≤ u_D for (i, D) ∈ E -u_D ≤ Σ_{i: (i,D) ∈ E} z_{i,D} for every candidate D -stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E -``` - -The `u_D ≤ Σ z` constraint prevents a deployment from becoming active when no -RAQE selected it. It is not required for feasibility, but makes ingest cost -unambiguous. `stored_D` is a linearized max: a deployment stores enough for -the longest lookback it serves. - -The only objective, `Objective::AUCCost { w_cpu, w_mem }`, weighs each phase -cost (below) as `w(c) = w_cpu × c.cpu + w_mem × c.memory_GiB`: - -```text -minimize Σ_D w(ingest_D) × u_D - + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} - + Σ_D stored_D -``` - -CPU is the area under the CPU curve (mean CPU-sec/sec), so plans are sized -for the mean load, not for bursts. Memory sums every phase, as if every query -evaluates at once. The default weights are `(1, 0)`: CPU only. - -Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver -never enumerates full mappings. - -### Cost by use and batch latency - -Status: agreed design (ProjectASAP/ASAPQuery#777), implemented in -`rqe-optimizer/src/usage.rs` (resource use, cost, latency) and -`milp::minimize_usage_cost`. The MILP minimizes the cost of a plan billed by -use, in two versions: - -- **Version 1, no latency constraint:** the cheapest plan; its latency is - reported. Sweeping an optional latency bound traces each method's - cost–latency Pareto frontier. -- **Version 2, a batch latency SLA:** the cheapest plan whose batch latency, - from the job placement (§6), is at most the SLA `L`, for a grid of SLAs. -Evaluated first on the synthetic mixed template set; methods: ASAP (this -MILP, with sharing), PerQuery (the same MILP without sharing) and -AutoSketch-Adapted (fixed configs chosen by memory). - -#### 1. Definitions - -| Symbol | Meaning | -|---|---| -| `D`, `i` | a candidate deployment; a RAQE | -| `x_D`, `y_D` | `D`'s window and slide; a window closes every `y_D` | -| `S_i`, `T_i` | RAQE `i`'s lookback and interval; it fires at `t = k · T_i` | -| `card(G)` | groups of `D`'s grouping | -| `inst_D` | instances per window: `card(G)`, or 1 for a sketch shared by all groups, plus `card(G)` for a key tracker if the family needs one | -| `λ_D` | samples/s arriving for `D`'s metric: `card(series) / scrape interval`, already a rate | -| `c_ins`, `c_mrg`, `c_qry` | measured CPU-seconds per insert, per pairwise merge, per query of one instance | -| `m` | measured bytes per instance; `w_D = Σ_parts inst · m`, one window of all instances | -| `n_{i,D} = S_i / x_D` | windows a query merges | -| batch | all query jobs issued at one instant | - -**Measurement assumption (sketch-bench as is).** Every sketch operation is -single-threaded and compute-bound: sketch-bench's CPU time equals its wall -time (e.g. an insert phase of 62.65 ms CPU and 62.65 ms wall). So a job uses -at most one core and, on a full core, takes its CPU time. The cost table's -`*_cpu_secs` are all the model needs. - -#### 2. Cost model - -`cost = w1 · AUC(CPU) + w2 · AUC(memory)`: the mean vCPUs and GiB over time, -priced per vCPU and per GiB (CPU only: `(1, 0)`; Fargate's prices). CPU is -elastic: a job gets a core whenever it is ready. - -This is billing by use, as on fine-grained autoscaling platforms (Cloud Run -with request-based billing, Dataflow streaming, Flink on Kubernetes with an -autoscaler), idealized: capacity follows the load at once. Billing for -provisioned capacity (VMs, or containers billed by allocation such as -Fargate) is not modeled. Since a job holds its memory only while it runs, its -memory × time is the same whenever it runs, and queueing a job would save -nothing. - -#### 3. CPU: parts and how each is computed - -Every "mean vCPUs" below is a long-run average rate, CPU-seconds per second, -over the same period: a whole number of hyperperiods `H = lcm(T_i, y_D)`, -over which every job pattern repeats exactly. A part with `w` CPU-seconds per -event every `P` seconds runs `H / P` times per hyperperiod, so its mean is -`(H / P) · w / H = w / P`; ingest is already a rate. So the three columns add. - -| Part | When | CPU-seconds | Mean vCPUs | -|---|---|---|---| -| Ingest (the precompute) | continuously, as samples arrive | — | `ρ_D = λ_D · (x_D / y_D) · c_ins` | -| Compaction | at each window close | `c_D = (k_D − 1) · Σ_parts inst · c_mrg` | `c_D / y_D` | -| Query job of RAQE `i` | at each firing | `ℓ_{i,D} = card(G) · c_qry + Σ_parts inst · (n_{i,D} − 1) · c_mrg` | `ℓ_{i,D} / T_i` | - -- Ingest runs on `k_D = ⌈ρ_D⌉` parallel workers (at least one; each uses at - most one core), **split by sample**: each worker reads a share of the input - (e.g. some Kafka partitions or scrape targets) with no shuffle by group, so - it keeps its own open window instance of every group it sees. -- When a window closes (the watermark passes its end), a **compaction** job - merges the `k_D` partial instances of each group into one stored instance. - With `k_D = 1` there is none. -- Each firing of RAQE `i` issues one **query job**: merge the `n_{i,D}` - stored instances of each group for the query window, then estimate. Merging - is part of the query. It reads the newest window, which closes at the firing - time, so it starts after that window's compaction. - -`AUC(CPU) = Σ_D ρ_D + Σ_D c_D / y_D + Σ_i ℓ_{i,D} / T_i`: ingest is already -a rate; only compaction (per window close, every `y_D`) and queries (per -firing, every `T_i`) are divided by their period. It is fixed by the plan, -whatever the schedule. - -In words: - -- `ρ_D`: every second, `λ_D` samples arrive (the scrape interval is already - inside `λ_D`), and each is inserted into the `x_D / y_D` windows still - open, at `c_ins` CPU-seconds each: CPU-seconds per second. -- `c_D`: closing a window merges, for every instance, the `k_D` workers' - partial copies into one, which takes `k_D − 1` merges. This happens once - per slide. -- `ℓ_{i,D}`: a query merges each instance's `n_{i,D}` stored windows - (`n − 1` merges per instance), then answers once per group. This happens - once per interval. (A sketch shared by all groups merges one instance but - still answers every group.) -- `AUC(CPU)` adds the three rates: work per second, in vCPUs. - -#### 4. Memory: parts and how each is computed - -Each part is counted once: a window counts as ingest memory while open and as -storage once compacted, and a query reads stored instances in place. - -| Part | What | Bytes | Held | -|---|---|---|---| -| Ingest | open windows, one copy per worker | `I_D = w_D · (x_D / y_D) · k_D` | always | -| Storage | closed windows for the longest lookback served (one compacted copy) | `stored_D = max_i w_D · ((S_i − x_D) / y_D + 1)` | always | -| Compaction | the closed window's `k_D` partial copies, until merged | `k_D · w_D` (0 when `k_D = 1`) | while the compaction job runs | -| Query | the accumulators the merge creates (none when `n = 1`) and the output | `q_{i,D} = w_D · [n_{i,D} > 1] + card(G) · output bytes` | while the query job runs | - -`AUC(memory) = Σ_D (I_D + stored_D + k_D · w_D · (compaction run time) / y_D) -+ Σ_i q_{i,D} · (query run time) / T_i`. CPU is elastic, so every job runs on its -own core: a compaction runs for `c_D` and a query for `ℓ_{i,D}`. - -In words: - -- `I_D`: every worker keeps one instance per group for each of the - `x_D / y_D` windows still open, and there are `k_D` workers. -- `stored_D`: closed windows are kept until the longest lookback that `D` - serves no longer needs them. That is `(S − x)/y + 1` windows per group. -- Compaction: when a window closes, a new one opens, so ingest still holds - `x_D / y_D` open windows. The closed window's `k_D` partial copies stay in - memory until the compaction has merged them. The merged copy takes the - storage slot that the oldest window frees at the same moment, so it is not - counted twice. -- `q_{i,D}`: a merge builds one accumulator per instance (a direct query, - with `n = 1`, reads the stored window and needs none), plus the answer for - every group. -- `AUC(memory)`: ingest and storage are held all the time. A compaction's - and a query's memory are held only while they run, a fraction - `run time / y_D` or `run time / T_i` of the time. - -#### 5. Batch latency and the SLA - -A batch's **latency** is the time from its issue until its last query job -finishes, compaction included. A plan's **query latency** is its worst batch -latency, given by the job placement (§6). Version 1 reports it; version 2 -requires it to be at most the SLA `L`. Per-RAQE latency bounds -(`Raqe::latency_sla_ms`) are not used. - -CPU is elastic, so no job waits for a core, and a batch's latency is its -longest **chain**: the newest window's compaction, then the query, each on a -full core, `c_D + ℓ_{i,D}` (`analytical_cost_model::chain_ms`). A plan's query -latency is the longest chain over its RAQEs. - -In words: the trade-off between cost and latency comes from the plan. A cheap -plan keeps short windows and merges many of them at query time (long -chains); a faster one precomputes more at ingest (more open windows, more CPU -and memory). With no bound the MILP picks the cheapest plan, whatever its -latency; a bound `L` asks for the cheapest plan at least that fast. - -#### 6. Job placement algorithm - -The job placement decides when each job runs on the available CPU, and so -gives every batch's latency. It is defined for any CPU capacity; billing by -use makes CPU elastic, so it runs with unlimited capacity. - -```text -capacity for jobs K = C − Σ_D ρ_D (C = ∞ when CPU is elastic) -event-driven, over the hyperperiod H = lcm(T_i, y_D), twice -(events: query issues, window closes, completions): - ready = compaction jobs (triggered at window closes) - + query jobs whose newest window is compacted - order: issue / trigger time (older first), then compaction before query - (it unblocks queries), then longest remaining work first - give rates in that order: job j gets a_j = min(1, K − rates already given) - a job at rate a_j finishes when its remaining work / a_j elapses - recompute the rates at every event -outputs: per-RAQE and per-batch latency, worst batch latency -``` - -In words: - -1. **Reserve ingest.** Ingest runs all the time and takes `Σ ρ_D` vCPUs; the - rest, `K`, is shared by compaction and query jobs. -2. **Issue jobs.** Each window close triggers a compaction job for its - deployment. Each firing issues a query job, which becomes ready only once - its deployment's newest window is compacted. -3. **Prioritize.** Ready jobs run oldest batch first, so no batch starves. - Within a batch, compaction runs before queries, because queries wait for - it. Then the longest remaining work runs first, so a long job doesn't end - up running alone at the end of the batch. -4. **Share capacity as rates.** In that order, each job gets up to one core - (a single-threaded job can't use more) from the capacity still free. The - last one served may get only a fraction and runs slower in proportion. -5. **Advance to the next event.** Time jumps to the next query issue, window - close or completion; remaining work drops by rate × elapsed time, and the - rates are recomputed. -6. **Read off the results.** A query's latency is its finish minus its - issue, and a batch's latency is that of its last query. - -With elastic CPU (`K = ∞`) every job starts as soon as it is ready on its own -core, so the placement has a closed form: a compaction runs for `c_D`, a -query for `ℓ_{i,D}`, and a batch's latency is its longest chain -`c_D + ℓ_{i,D}`. The code uses this closed form (`usage::usage_cost`), and -it is what makes both MILP versions exact. - -#### 7. MILP formulation - -Variables: `z_{i,D} ∈ {0,1}` (RAQE `i` uses `D`, for eligible pairs `E`), -`u_D ∈ {0,1}` (`D` is active), `stored_D ≥ 0`. Constants per candidate and -pair are §3 and §4's. - -```text -minimize w1 · [ Σ_D (ρ_D + c_D / y_D) · u_D + Σ_(i,D) (ℓ_{i,D} / T_i) · z_{i,D} ] - + w2 · [ Σ_D ((I_D + k_D · w_D · c_D / y_D) · u_D + stored_D) - + Σ_(i,D) (q_{i,D} · ℓ_{i,D} / T_i) · z_{i,D} ] -s.t. Σ_D z_{i,D} = 1 for every RAQE i - z_{i,D} ≤ u_D ≤ Σ_i z_{i,D} for (i, D) ∈ E - stored_D ≥ w_D · ((S_i − x_D) / y_D + 1) · z_{i,D} -version 2, a batch latency SLA L (or version 1's frontier bound L): - z_{i,D} = 0 if c_D + ℓ_{i,D} > L -``` - -In words: - -- The objective is the price of the mean vCPUs (ingest and compaction per - active deployment, plus each RAQE's query work per second), plus the price - of the mean memory (ingest and storage per active deployment, each - compaction's partial copies for the fraction of time it runs, and each - query's memory for the fraction of time it runs). -- Every RAQE is served by exactly one eligible deployment. -- A deployment is active if and only if some RAQE uses it, so its ingest is - paid once, however many RAQEs share it. -- A deployment stores enough closed windows for the longest lookback it - serves (a linearized max). -- Version 2 (and version 1's frontier bound): a pair whose chain (the newest - window's compaction, then the query, each on a full core) is longer than - `L` is ruled out. By the placement's closed form, the plan's batch latency - is then at most `L`, exactly: the SLA is met. Chains are - compared with `L` with a relative slack of `1e-9`, so float error can't rule - out a chain equal to `L`. - -#### 8. Solution method - -Every term is linear in `u` and `z`, with or without a bound, so the MILP is -solved exactly -(`milp::minimize_usage_cost`; costs are scaled by each RAQE's cheapest pair -so the solver sees magnitudes near 1). The solved plan's cost and latency are -then computed from its resource use (`usage::usage_cost`). - -- **PerQuery** is the same MILP with sharing ruled out. `minimize_usage_cost` - takes `allowed`, the candidate indices each RAQE may use. PerQuery gives - each RAQE its own candidates, with a separate copy of any deployment that - two RAQEs could both use. Two RAQEs share a deployment only by choosing the - same candidate index (`u_D` is per index), so their copies stay apart and - each pays its own ingest. -- **AutoSketch** keeps its memory-chosen configs and is priced by the same - function: its cost by use and its latency, the longest chain. It ignores - latency, so it is one point, not a frontier. -- **Version 1:** ASAP and PerQuery are solved with no bound (the cheapest - plan), and for a sweep of bounds `L` from the smallest feasible one (the - largest, over RAQEs, of each RAQE's fastest chain) up to the unbounded - plan's latency. Each solve gives a (latency, cost) point; together they are - the method's frontier. `L` = AutoSketch's latency gives each method's cost - at no more than AutoSketch's latency. -- **Version 2:** ASAP and PerQuery are solved at each SLA of a fixed grid; - an SLA below the smallest feasible bound has no plan. AutoSketch ignores - the SLA; its latency either meets it or not. - -#### 9. Outputs - -Per (method, weight setting, bound or SLA): cost; mean CPU and memory, by -part; query latency and per-RAQE latency; planning time. Figures: version 1, -each method's cost–latency frontier for each workload (ASAP and PerQuery as -lines, AutoSketch as a point); version 2, each method's cost at each SLA. - -## Analytical cost model - -The analytical model combines the empirical per-operation Sketch Bench -measurements with workload properties such as group cardinality, arrival rate, -window size, and query frequency. - -For deployment `D` serving RAQE `i`: - -- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. -- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window (one for a shared fixed-size sketch; see below). -- `x`, `y`: `D`'s window and slide. -- `a_D = x / y`: open windows; each sample is inserted into `a_D` instances of its group. -- `S_i`, `T_i`: RAQE `i`'s lookback and interval. -- `n_i = S_i / x`: windows merged per query. -- `m`: memory per instance, measured. For DDSketch on a metric with a - `value_range`, `m = (floor(ln(hi / lo) / ln((1 + alpha) / (1 - alpha))) + 1) × 8` - bytes instead: one bucket count per `gamma`-power in the range, capped by - the values one instance sees (`λ · x / card(G)` for a window, `λ · L / card(G)` - for a query's merge accumulator), as sketch-bench's `dd_footprint` counts them. The range is the metric's, so `m` is an upper - bound for a group whose own values span less. -- `c_ins`: CPU per insert, measured. -- `c_mrg`: CPU per pairwise merge, measured. -- `c_qry`: CPU per query of one instance, measured. - -Costs split into four phases, each with CPU (mean CPU-sec/sec) and memory -(bytes): - -| Phase | CPU | Memory | -|---|---|---| -| Ingest, per active `D` | `lambda × a_D × c_ins` | `card(G) × m × a_D` (open windows) | -| Merge, per RAQE | `card(G) × (n_i − 1) × c_mrg / T_i` | `card(G) × m` (one accumulator per group); 0 when `n_i = 1` | -| Query, per RAQE | `card(G) × c_qry / T_i` | `card(G) ×` output bytes | -| Storage, per active `D` | 0 | `card(G) × m × ((max_i S_i − x) / y + 1)` (closed windows) | - -Closed windows wholly inside a lookback start in `[t − S, t − x]`, hence -`(S − x) / y + 1` of them; storage takes the longest lookback `D` serves. -Query output is estimated at 8 bytes per group, or 32 × 16 bytes per group for -top-k (sketch-bench's heap size, with 64-bit key hashes); it is not measured. - -### Instance shape and size law - -Each row of the cost table (from -[`scripts/study_saturation.py --phase optimizer-cost`](../scripts/study_saturation.py)) -is measured on one instance, at whatever key count the benchmark fed it -(`measured_keys`). A key is one distinct entry an instance stores exactly, -such as one group's running sum in an exact accumulator. Turning a row into a -deployment's cost needs two properties of the family: - -- **Shape**: instances per window. `PerGroup` keeps one per group, so - `card(G)`; `Shared` keeps one for all groups. -- **Law**: how one instance's size grows. `Fixed` is set by the configuration - (e.g. CMS rows × columns); `PerKey` stores one entry per key, so it grows - linearly with keys. - -Memory per window is instances × instance size: - -| | Fixed | PerKey | -|---|---|---| -| **PerGroup** | `card(G) × m`: CMS, CountSketch, KLL, DDSketch, HLL, UnivMon, top-k (heap `m · k`) | `card(G) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | -| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | - -The same factor scales merge and query CPU. Insert CPU is per sample and does -not scale. - -Quantile sketches have no keys, but are not strictly fixed either: KLL grows -slowly with the number of values inserted (about `k × log(n / k)`), and -DDSketch with the range of values. The model treats KLL as Fixed at the size -the export measured (1,000,000 values per instance), so it misstates instances -that see far fewer or far more values. DDSketch is sized from the metric's -`value_range` when given (capped by values per instance), else from the -measured size. - -The model uses `I × m`, where `I` is instances per window: - -- PerGroup + Fixed: `I = card(G)`. -- Shared + PerKey reduces to `I = card(G)` because the export divides the - exact accumulators' memory and merge cost by `measured_keys` - (`groups_per_instance`), making `m` a per-group cost. Their query cost is - already per group. -- Shared + Fixed: `I = 1`. In code this is the family property - `one_fixed_size_sketch_for_all_groups`, true only for HydraKLL. It applies - to memory and merge; query stays `card(G) × c_qry`, one probe per group. - A fixed-size sketch degrades as groups grow, so it is eligible only when - `card(G)` is at most the `subpopulations` its row was measured at. This - models a sketch keyed by the joined `G` value alone; the current rows fan - out to every label subset (sketch-bench#165), and merging several windows - is not yet measured (sketch-bench#166). - -PerGroup + PerKey is deferred until a family needs it: it needs the key labels -`K`, the metric's labels minus `G`. So for every family in use, nothing scales -with keys below the group: a per-service top-k CMS costs the same however -many endpoints it counts. - -Side by side, with `G = card(G)` and `C` closed windows: - -| | KLL (per group) | exact-sum (per-group normalized) | HydraKLL (shared, fixed) | -|---|---|---|---| -| `m`, `c_mrg` in the row | one group's | whole ÷ groups | whole sketch | -| Ingest CPU | `λ·a_D·c_ins` | `λ·a_D·c_ins` | `λ·a_D·c_ins` | -| Ingest memory | `G·m·a_D` | `G·m·a_D` | `m·a_D` | -| Merge CPU | `G·(n_i−1)·c_mrg/T_i` | same | `(n_i−1)·c_mrg/T_i` | -| Merge memory | `G·m` | same | `m` | -| Query CPU | `G·c_qry/T_i` | same | `G·c_qry/T_i` | -| Query memory | `G ×` output bytes | same | `G ×` output bytes | -| Storage memory | `G·m·C` | same | `m·C` | -| Latency | `G·(c_qry + (n_i−1)·c_mrg)` | same | `(n_i−1)·c_mrg + G·c_qry` | - -### Family properties and key tracker - -Each family has properties, hardcoded by variant in `family_properties` -(an unknown variant panics rather than getting a default): - -- `mergeable_across_windows`: a family without it only serves `S_i = x`. - Every family in use merges. -- `one_fixed_size_sketch_for_all_groups`: the Shared + Fixed cell above. -- `needs_delta_set_key_tracker`: the sketch can't list its groups, so a - DeltaSet (`exact-delta-set`) records each window's keys for the query to - probe. True for HydraKLL. A candidate needing one carries the DeltaSet row - and is dropped if the cost table has none; a deployment without its tracker - is never eligible. The cost table may hold at most one DeltaSet row. - -The tracker is priced as an exact accumulator on the same `x`, `y` and `G`, -in every phase: ingest, merge (union of the `n_i` windows' key sets), query -(enumerate keys) and storage. Its `m` is per key, so it adds `card(G) × m_ds` -per window. The AutoSketch baseline skips shared fixed-size families for now -(sketch-bench#159). - -Per-RAQE latency is the serial CPU time of one query: - -```text -latency_i = card(G) × c_qry + I × (n_i − 1) × c_mrg -``` - -summed over the sketch and its key tracker, if any. +- [Candidate generation and eligibility](rqe_optimizer_candidates.md): + candidate construction, eligibility (accuracy included), finer-to-coarser + roll-ups and dominance pruning. +- [Cost models](rqe_optimizer_cost_model.md): the one cost table, the + canonical cost-by-use and batch-latency model with its MILP, and the + supported snapshot-AUC objective. -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 1. Generate candidate deployments for each input RAQE, then deduplicate them. 2. Build the eligible candidate–RAQE pairs. Reject pairs that fail capability, - metric, grouping, window alignment, or empirical accuracy. + metric, grouping (equal, or a subset for a roll-up), window alignment, or + accuracy. 3. Enumerate feasible workload mappings. Every RAQE must select one eligible candidate; a single selected candidate may serve multiple RAQEs. Small instances may retain every mapping eagerly; larger ones stream mappings @@ -781,25 +175,30 @@ The Pareto vector is: (CPU, memory, {latency_i}) ``` -CPU and memory are the sums over the four phases. The report also includes +CPU and memory are the sums over the snapshot objective's phases (ingest, merge, query, storage). The report also includes each phase's CPU and memory, together with the selected deployment mapping. ## v1 scope and TODOs -- **Accuracy after merging:** KLL and top-k are planned only up to the - largest shard count and N the study measured merge curves at (#158). +- **Accuracy after merging:** KLL and univmon-cardinality read their merge + curves up to the largest shard count and N the study measured; past them, + KLL's guarantee, no better than the last measurement (univmon-cardinality + has none, so no accuracy). Roll-ups multiply the merge count by the + fan-out, so they reach the guarantee sooner. Heap top-k reads its plain + curve (#158). - **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. Revisit when RAQE semantics and execution timing identify safe reuse cases. - **Latency SLAs:** `minimize` takes optional per-RAQE latency bounds; - `minimize_usage_cost` has none and reports the batch latency (above). The - enumerator reports latency but does not reject a mapping for it. -- **Memory model:** query memory sums every RAQE's merge and output memory, as - if all queries run at once; real concurrency is not modeled. Query output - size is an estimate. + `minimize_usage_cost` takes an optional batch-latency bound and reports the + batch latency. The enumerator reports latency but does not reject a + mapping for it. +- **Memory model:** cost by use holds query memory only while a query runs; + the snapshot objective sums every RAQE's merge and output memory as if all + queries ran at once. Query output size is an estimate. - **Bursts:** CPU is a mean over time, so plans are sized for average load. - **Static planning:** no RAQE churn, replanning, or migration cost. -- **Rollups:** v1 does not precompute merged rollups. Queries merge their - selected base instances when they run. +- **Temporal pre-merging:** v1 does not precompute merged windows. Queries + merge their selected base instances when they run. - **Selection policy:** the enumerator reports the Pareto frontier; the MILP selects one point by the `w_cpu`/`w_mem` weights. @@ -809,7 +208,8 @@ each phase's CPU and memory, together with the selected deployment mapping. generation and pruning, eligibility checks, analytical objectives, and streaming Pareto filtering. The separation between candidate generation, enumeration, objectives, and Pareto filtering remains the intended boundary -for future solver work. +for future solver work. Hydra, a shared-subpopulation deployment rather than +a fine-state roll-up, is future work. Exporter bugs, benchmark-dataset choices, and historic run counts belong in `rqe_optimizer_TODO.md` or issue tracking, not in this problem statement. diff --git a/rqe-optimizer/examples/autosketch_vs_asap.rs b/rqe-optimizer/examples/autosketch_vs_asap.rs index d9479f45..027947b3 100644 --- a/rqe-optimizer/examples/autosketch_vs_asap.rs +++ b/rqe-optimizer/examples/autosketch_vs_asap.rs @@ -13,7 +13,7 @@ //! ``` //! //! Every plan is priced by use (`usage::usage_cost`, sketch-bench -//! `docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch latency"): +//! `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency"): //! `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, at each weight //! setting of #777 §4 (CPU only; Fargate's per-vCPU and per-GB prices). A //! batch's latency is its longest chain (the newest window's compaction, @@ -670,7 +670,7 @@ fn frontier_bounds(lo: f64, hi: f64, n: usize, extra: f64) -> Vec { } /// Every method's plan for `w`, priced by use at each weight setting, with -/// its latency (`docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +/// its latency (`docs/rqe_optimizer_cost_model.md`, "Cost by use and batch /// latency"): version 1 (no latency constraint; frontier) in `results`, /// version 2 (each SLA of `slas`) in `sla_results`. fn evaluate(w: &Workload, runs: usize, weights: &[(&str, f64, f64)], slas: &[f64]) -> Value { diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 2ea5f4fa..20cd2fea 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -205,6 +205,19 @@ fn raqes() -> Vec { latency_sla_ms: None, topk_k: None, }, + // Shares KLL with the per-endpoint p99s by rolling up. + Raqe { + id: "latency_p99_1h_by_service".to_string(), + capability: Capability::Quantile, + lookback_ms: 3_600_000, + interval_ms: 60_000, + metric: duration(), + spatial_filter: String::new(), + grouping_labels: s.clone(), + accuracy_sla: 0.05, + latency_sla_ms: None, + topk_k: None, + }, Raqe { id: "latency_p99_1d".to_string(), capability: Capability::Quantile, @@ -503,8 +516,17 @@ fn main() { .zip(&solution.raqes) .zip(&solution.plan_cost.query_latency_ms) { + let served_by = &solution.deployments[planned.deployment].deployment; + let roll_up = if served_by.grouping_labels == raqe.grouping_labels { + String::new() + } else { + format!( + " rolls up {:?} -> {:?}", + served_by.grouping_labels, raqe.grouping_labels + ) + }; println!( - " {} -> deployment {} merged_instances={} query_latency={latency:.3e} ms", + " {} -> deployment {} merged_instances={} query_latency={latency:.3e} ms{roll_up}", raqe.id, planned.deployment, planned.merged_instance_count, ); } diff --git a/rqe-optimizer/examples/workload_scenarios.rs b/rqe-optimizer/examples/workload_scenarios.rs index 8faa735e..09e0bcc4 100644 --- a/rqe-optimizer/examples/workload_scenarios.rs +++ b/rqe-optimizer/examples/workload_scenarios.rs @@ -4,10 +4,11 @@ //! one workload solved with the MILP and printed as the deployments it runs //! and the queries each one serves. //! -//! A deployment serves only queries with its own capability, metric and -//! grouping (`candidates::is_eligible`), so the mixed-grouping and -//! mixed-type sweeps cost the same as solving each part alone. They are -//! baselines for when the model shares across groupings. +//! A deployment serves only queries with its own capability and metric, and +//! its own grouping or, for a family that merges across groups, a subset of +//! it (a roll-up; `candidates::is_eligible`). So the mixed-type sweeps cost +//! the same as solving each part alone, while the mixed-grouping sweeps can +//! share one fine deployment across groupings. //! //! Run: //! `cargo run --release -p rqe-optimizer --example workload_scenarios -- diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md index 8b0d512c..3c6ca699 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic-sla/README.md @@ -1,7 +1,7 @@ # Synthetic mixed set: AutoSketch vs. ASAP under a batch latency SLA (version 2) Version 2 of the evaluation in ProjectASAP/ASAPQuery#777, with the cost model -of sketch-bench `docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +of sketch-bench `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency": - **Cost by use:** `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, for diff --git a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md index 280de391..462edace 100644 --- a/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md +++ b/rqe-optimizer/results/autosketch-vs-asap-synthetic/README.md @@ -7,7 +7,7 @@ template set per metric, 50 · m RQEs). One accuracy level, p95: 95% in each family's own metric (rank, relative value and relative error at most 0.05; top-k precision at least 0.95). -**Cost model: cost by use** (sketch-bench `docs/rqe_sketch_deployment_v1.md`, +**Cost model: cost by use** (sketch-bench `docs/rqe_optimizer_cost_model.md`, "Cost by use and batch latency", #188): `w_cpu · AUC(CPU) + w_mem · AUC(memory)`, CPU elastic, at two weight settings (CPU only, in vCPU; AWS Fargate's per-vCPU and per-GB prices, in $/hour). CPU covers ingest (on diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs index 56a2b0d9..9e8cd16e 100644 --- a/rqe-optimizer/src/analytical_cost_model.rs +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -1,4 +1,4 @@ -//! Analytical scoring built from measured per-operation costs (§5). +//! Analytical scoring built from measured per-operation costs (`docs/rqe_optimizer_cost_model.md`). //! //! Costs split into four phases, each with CPU and memory: //! - ingest: inserts into open windows, and their state; @@ -11,12 +11,17 @@ //! Measured costs are per instance. A deployment holds `card(G)` instances //! per window, or one if its family keeps [one fixed-size sketch for all //! groups](crate::FamilyProperties::one_fixed_size_sketch_for_all_groups). +//! A RAQE grouped by `G_r`, a subset of the deployment's `G_d`, is read by +//! merging each `G_r` group's instances into one (a roll-up), so merge and +//! query are priced at `G_r`, ingest and storage at `G_d`. //! Exact accumulators hold many groups in one instance, but the export //! divides their memory and merge cost by the group count, so `card(G) ×` //! prices them correctly too. A [key tracker](crate::Deployment::key_tracker) //! is priced like an exact accumulator on the same windows, in every phase. -use crate::{secs, AtomicCostEntry, Capability, Deployment, Mapping, Millis, Raqe, WorkloadFacts}; +use crate::{ + secs, AtomicCostEntry, Capability, Deployment, LabelSet, Mapping, Millis, Raqe, WorkloadFacts, +}; use std::collections::{BTreeMap, BTreeSet}; pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; @@ -73,9 +78,9 @@ impl PlanCost { } } -/// `card(G)`: cardinality of `G`, the number of groups. -fn group_count(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { - facts[&deployment.metric].cardinality[&deployment.grouping_labels] as f64 +/// `card(grouping)` on `deployment`'s metric: the number of groups. +fn group_count(deployment: &Deployment, grouping: &LabelSet, facts: &WorkloadFacts) -> f64 { + facts[&deployment.metric].cardinality[grouping] as f64 } /// The sketch and its key tracker, if any, each with its instances per @@ -98,7 +103,7 @@ fn priced_parts<'a>( "{}: key tracker present iff the family needs one, or the plan is mispriced", deployment.config.sketch ); - let groups = group_count(deployment, facts); + let groups = group_count(deployment, &deployment.grouping_labels, facts); let sketch_instances = if properties.one_fixed_size_sketch_for_all_groups { 1.0 } else { @@ -113,8 +118,8 @@ fn priced_parts<'a>( } /// `m`: memory of one `config` instance (`deployment`'s sketch or its key -/// tracker) holding `span_ms` of one group's samples: a -/// window `x`, or the lookback `L` for a query's merge accumulator. +/// tracker) holding `span_ms` of one `grouping` group's samples: a window `x` +/// of `G_d`, or the lookback `L` of `G_r` for a query's merge accumulator. /// DDSketch on a metric with a known value range holds one store (values are /// positive) of [`dd_bucket_count`] buckets, capped by the values it holds, /// `λ · span / card(G)`, as `dd_footprint` caps them by count. The range is the metric's, so this is @@ -124,14 +129,15 @@ pub(crate) fn instance_memory_bytes( config: &AtomicCostEntry, deployment: &Deployment, facts: &WorkloadFacts, + grouping: &LabelSet, span_ms: Millis, ) -> f64 { let metric = &facts[&deployment.metric]; let alpha = config.sketch_config["params"]["alpha"].as_f64(); match (config.sketch.as_str(), metric.value_range, alpha) { ("dd", Some((lo, hi)), Some(alpha)) => { - let values = - metric.arrival_rate_per_sec() * secs(span_ms) / group_count(deployment, facts); + let values = metric.arrival_rate_per_sec() * secs(span_ms) + / group_count(deployment, grouping, facts); dd_bucket_count(lo, hi, alpha).min(values.ceil().max(1.0)) * DD_BYTES_PER_BUCKET } _ => config.mem_bytes_per_instance, @@ -158,6 +164,36 @@ fn merged_window_count(raqe: &Raqe, deployment: &Deployment) -> f64 { .expect("only eligible pairs are costed") as f64 } +/// States one query of `raqe` ends with on `part`: one per `G_r` group, or +/// one for a sketch shared by all groups. +fn answered_instances( + raqe: &Raqe, + deployment: &Deployment, + facts: &WorkloadFacts, + part: Part, +) -> f64 { + if part == Part::Sketch && deployment.properties().one_fixed_size_sketch_for_all_groups { + 1.0 + } else { + group_count(deployment, &raqe.grouping_labels, facts) + } +} + +/// Merges one query of `raqe` does on `part`, which holds `sketch_instances` +/// per window. Each folds two states into one, so it is the states read, +/// `sketch_instances · L/x`, less the `answered_instances` left. Without a +/// roll-up, `card(G) · (L/x − 1)`. +fn merge_count( + raqe: &Raqe, + deployment: &Deployment, + facts: &WorkloadFacts, + sketch_instances: f64, + part: Part, +) -> f64 { + sketch_instances * merged_window_count(raqe, deployment) + - answered_instances(raqe, deployment, facts, part) +} + /// Per part: CPU `λ · (x/y) · c_ins`; memory `instances · m · (x/y)`. pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { let open_windows = open_window_count(deployment); @@ -167,28 +203,39 @@ pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCos cost += PhaseCost { cpu_secs_per_sec: arrival_rate * open_windows * config.insert_cpu_secs, memory_bytes: instances - * instance_memory_bytes(config, deployment, facts, deployment.window_ms) + * instance_memory_bytes( + config, + deployment, + facts, + &deployment.grouping_labels, + deployment.window_ms, + ) * open_windows, }; } cost } -/// Per part: CPU `instances · (L/x − 1) · c_mrg / T`; memory `instances · m`, -/// every merged accumulator held at once, each holding the whole lookback. A -/// direct query (`L == x`) merges nothing and costs neither. +/// Per part: CPU [`merge_count`]` · c_mrg / T`; memory `answered_instances · +/// m`, every merged accumulator held at once, each holding the whole lookback. +/// A direct query (`L == x`) without a roll-up merges nothing and costs neither. pub(crate) fn merge(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let merges_per_instance = merged_window_count(raqe, deployment) - 1.0; - if merges_per_instance == 0.0 { - return PhaseCost::default(); - } let mut cost = PhaseCost::default(); - for (config, instances, _) in priced_parts(deployment, facts) { + for (config, sketch_instances, part) in priced_parts(deployment, facts) { + let merges = merge_count(raqe, deployment, facts, sketch_instances, part); + if merges == 0.0 { + continue; + } cost += PhaseCost { - cpu_secs_per_sec: instances * merges_per_instance * config.merge_cpu_secs - / secs(raqe.interval_ms), - memory_bytes: instances - * instance_memory_bytes(config, deployment, facts, raqe.lookback_ms), + cpu_secs_per_sec: merges * config.merge_cpu_secs / secs(raqe.interval_ms), + memory_bytes: answered_instances(raqe, deployment, facts, part) + * instance_memory_bytes( + config, + deployment, + facts, + &raqe.grouping_labels, + raqe.lookback_ms, + ), }; } cost @@ -206,10 +253,10 @@ fn query_cpu_secs(raqe: &Raqe, config: &AtomicCostEntry, part: Part) -> f64 { } } -/// CPU `card(G) · Σ c_qry / T`, one probe per group of each part; memory -/// `card(G) ·` output bytes per group. +/// CPU `card(G_r) · Σ c_qry / T`, one probe per answered group of each part; +/// memory `card(G_r) ·` output bytes per group. pub(crate) fn query(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { - let groups = group_count(deployment, facts); + let groups = group_count(deployment, &raqe.grouping_labels, facts); let output_bytes_per_group = match raqe.capability { Capability::TopKByValue | Capability::TopKByCount => { crate::answered_k(&deployment.config) as f64 * OUTPUT_BYTES_PER_TOPK_ENTRY @@ -234,22 +281,28 @@ pub(crate) fn storage_bytes(raqe: &Raqe, deployment: &Deployment, facts: &Worklo priced_parts(deployment, facts) .map(|(config, instances, _)| { instances - * instance_memory_bytes(config, deployment, facts, deployment.window_ms) + * instance_memory_bytes( + config, + deployment, + facts, + &deployment.grouping_labels, + deployment.window_ms, + ) * closed_windows }) .sum() } /// Serial CPU time of one query, in ms, summed over parts: -/// `card(G) · c_qry + instances · (L/x − 1) · c_mrg`. +/// `card(G_r) · c_qry + `[`merge_count`]` · c_mrg`. pub(crate) fn query_latency_ms(raqe: &Raqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { - let groups = group_count(deployment, facts); - let merges_per_instance = merged_window_count(raqe, deployment) - 1.0; + let groups = group_count(deployment, &raqe.grouping_labels, facts); 1000.0 * priced_parts(deployment, facts) - .map(|(config, instances, part)| { + .map(|(config, sketch_instances, part)| { groups * query_cpu_secs(raqe, config, part) - + instances * merges_per_instance * config.merge_cpu_secs + + merge_count(raqe, deployment, facts, sketch_instances, part) + * config.merge_cpu_secs }) .sum::() } @@ -365,7 +418,7 @@ mod tests { let window = |d: &Deployment| d.window_ms; assert_eq!( - instance_memory_bytes(&dd.config, &dd, &ranged, window(&dd)), + instance_memory_bytes(&dd.config, &dd, &ranged, &dd.grouping_labels, window(&dd)), 80.0 ); // 10 buckets × 8 B assert_eq!(ingest(&dd, &ranged).memory_bytes, 80.0); @@ -390,12 +443,24 @@ mod tests { // No range, or not DDSketch: the measured size. assert_eq!( - instance_memory_bytes(&dd.config, &dd, &facts(1, 1), window(&dd)), + instance_memory_bytes( + &dd.config, + &dd, + &facts(1, 1), + &dd.grouping_labels, + window(&dd) + ), 1_000.0 ); let cms = deployment(1_000.0, 0.0, 0.0, 0.0, 60_000, 60_000); assert_eq!( - instance_memory_bytes(&cms.config, &cms, &ranged, window(&cms)), + instance_memory_bytes( + &cms.config, + &cms, + &ranged, + &cms.grouping_labels, + window(&cms) + ), 1_000.0 ); } @@ -515,4 +580,58 @@ mod tests { deployment.config.sketch = "hydra-kll".into(); ingest(&deployment, &facts(1, 1)); } + + /// p99 by service from KLL by (service, endpoint), every per-instance + /// cost 1: each query reads 50 fine states per window and leaves 5. + #[test] + fn a_roll_up_merges_every_fine_window_into_its_coarse_group() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + let hourly = quantile_by(&["service"], 3_600_000, 60_000); + let merges = 50.0 * 60.0 - 5.0; + assert_eq!( + merge(&hourly, &by_endpoint, &facts), + PhaseCost { + cpu_secs_per_sec: merges / 60.0, + memory_bytes: 5.0, + } + ); + assert_eq!( + query(&hourly, &by_endpoint, &facts).cpu_secs_per_sec, + 5.0 / 60.0 + ); + assert_eq!( + query_latency_ms(&hourly, &by_endpoint, &facts), + 1000.0 * (5.0 + merges) + ); + // A direct query still folds each service's 10 endpoints into one. + let direct = quantile_by(&["service"], 60_000, 60_000); + assert_eq!( + merge(&direct, &by_endpoint, &facts).cpu_secs_per_sec, + 45.0 / 60.0 + ); + } + + /// A roll-up's DDSketch accumulator holds a coarse group's values: 50 + /// samples/s over a 2 s lookback into 5 services is 20 values each, past + /// the 10-bucket range, so 80 B per service, not the 16 B two per-endpoint + /// values would need. + #[test] + fn a_dd_roll_up_sizes_its_accumulator_at_the_coarse_grouping() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let mut facts = service_endpoint_facts(); + facts + .get_mut(crate::test_support::METRIC) + .unwrap() + .value_range = Some((1.0, 1000.0)); + let mut by_endpoint = kll_by(&["service", "endpoint"], 1_000); + by_endpoint.config.sketch = "dd".into(); + by_endpoint.config.sketch_config = serde_json::json!({"params": {"alpha": 1.0 / 3.0}}); + let by_service = quantile_by(&["service"], 2_000, 2_000); + assert_eq!( + merge(&by_service, &by_endpoint, &facts).memory_bytes, + 5.0 * 80.0 + ); + } } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index 89d35fac..09afe4fa 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,4 +1,4 @@ -//! Candidate generation and eligibility (§3). +//! Candidate generation and eligibility (`docs/rqe_optimizer_candidates.md`). use crate::analytical_cost_model; use crate::{ @@ -60,8 +60,15 @@ fn measured_at_group_count(config: &AtomicCostEntry, groups: u64) -> bool { /// Windows and slides are multiples of the metric's scrape interval: anything /// finer only splits one scrape's samples. +/// +/// Deployments are grouped by `grouping` and built from the families whose +/// [`mergeable_across_groups`](crate::FamilyProperties::mergeable_across_groups) +/// equals `mergeable_across_groups`. Their windows, slides and heaps come from +/// `group`, the RAQEs they may serve. fn candidate_deployments( group: &[&Raqe], + grouping: &LabelSet, + mergeable_across_groups: bool, costs: &[AtomicCostEntry], metric_facts: &MetricFacts, allow_undeployable_families: bool, @@ -89,6 +96,8 @@ fn candidate_deployments( capability .candidate_families(allow_undeployable_families) .any(|family| family == c.sketch) + && crate::family_properties(&c.sketch).mergeable_across_groups + == mergeable_across_groups }) .collect(); let heap_rows = heap_rows_by_shape(&family_rows); @@ -152,7 +161,7 @@ fn candidate_deployments( capability, metric: group[0].metric.clone(), spatial_filter: group[0].spatial_filter.clone(), - grouping_labels: group[0].grouping_labels.clone(), + grouping_labels: grouping.clone(), config: config.clone(), window_ms, slide_ms, @@ -319,8 +328,34 @@ pub fn build_all_candidates_unpruned( } groups .iter() - .flat_map(|(&(_, metric, _, _), group)| { - candidate_deployments(group, costs, &facts[metric], allow_undeployable_families) + .flat_map(|(&(capability, metric, filter, grouping), exact_group)| { + // A family that rolls up may also serve RAQEs grouped by a subset, + // so its windows must suit theirs too. + let subset_group: Vec<&Raqe> = raqes + .iter() + .filter(|r| { + r.capability == capability + && r.metric == metric + && r.spatial_filter == filter + && r.grouping_labels.is_subset(grouping) + }) + .collect(); + [ + (exact_group.as_slice(), false), + (subset_group.as_slice(), true), + ] + .into_iter() + .flat_map(|(group, mergeable_across_groups)| { + candidate_deployments( + group, + grouping, + mergeable_across_groups, + costs, + &facts[metric], + allow_undeployable_families, + ) + }) + .collect::>() }) .collect() } @@ -329,10 +364,12 @@ pub fn build_all_candidates_unpruned( /// mapping without making any modeled objective worse. /// /// This comparison is local to a (capability, metric, spatial_filter, -/// grouping) group, where query output size is common. It compares ingest CPU -/// and memory, then latency (merge and query CPU), merge memory and stored -/// memory for each RAQE the dominated candidate can serve, all as the -/// analytical cost model prices them: a sketch shared by all groups and a +/// grouping) group. It compares ingest CPU and memory; compaction per window +/// (it starts every chain) and per second (CPU-seconds and byte-seconds per +/// slide, as cost by use bills it); then, for each RAQE the dominated +/// candidate can serve, the query job's CPU (merge and query, its latency), +/// its memory (merge accumulators and output) and stored memory. All are as +/// the analytical cost model prices them: a sketch shared by all groups and a /// sketch per group don't scale alike with `card(G)`. pub fn prune_dominated_candidates( raqes: &[Raqe], @@ -373,10 +410,12 @@ pub fn prune_dominated_candidates( /// One candidate's costs, computed once for every pairwise comparison. struct CandidateCosts { - /// Ingest CPU and memory. - ingest: [f64; 2], - /// Per RAQE: latency, merge memory and stored memory if the candidate - /// serves it, else `None`. + /// Per deployment: ingest CPU and memory; compaction CPU-seconds per + /// window (it starts every chain); and compaction CPU and byte-seconds + /// per second, as cost by use bills them every slide. + ingest: [f64; 5], + /// Per RAQE: latency, query memory (merge and output) and stored memory + /// if the candidate serves it, else `None`. per_raqe: Vec>, } @@ -388,20 +427,30 @@ impl CandidateCosts { accuracy: &Accuracy, ) -> Self { let ingest = analytical_cost_model::ingest(candidate, facts); + let compaction_secs = analytical_cost_model::compaction_secs(candidate, facts); + let slide_secs = crate::secs(candidate.slide_ms); let per_raqe = raqes .iter() .map(|raqe| { is_eligible(raqe, candidate, facts, accuracy).then(|| { [ analytical_cost_model::query_latency_ms(raqe, candidate, facts), - analytical_cost_model::merge(raqe, candidate, facts).memory_bytes, + analytical_cost_model::merge(raqe, candidate, facts).memory_bytes + + analytical_cost_model::query(raqe, candidate, facts).memory_bytes, analytical_cost_model::storage_bytes(raqe, candidate, facts), ] }) }) .collect(); Self { - ingest: [ingest.cpu_secs_per_sec, ingest.memory_bytes], + ingest: [ + ingest.cpu_secs_per_sec, + ingest.memory_bytes, + compaction_secs, + compaction_secs / slide_secs, + analytical_cost_model::compaction_bytes(candidate, facts) * compaction_secs + / slide_secs, + ], per_raqe, } } @@ -502,7 +551,9 @@ pub fn is_eligible(r: &Raqe, d: &Deployment, facts: &WorkloadFacts, accuracy: &A r.capability == d.capability && r.metric == d.metric && r.spatial_filter == d.spatial_filter - && r.grouping_labels == d.grouping_labels + && (r.grouping_labels == d.grouping_labels + || (properties.mergeable_across_groups + && r.grouping_labels.is_subset(&d.grouping_labels))) && d.window_ms != 0 && d.slide_ms != 0 && d.window_ms.is_multiple_of(d.slide_ms) @@ -888,6 +939,46 @@ mod tests { assert_eq!(retained, vec![coarse]); } + #[test] + fn prunes_the_candidate_with_larger_query_output() { + // Two heaps that differ only in the `k` they answer: the larger one + // outputs 100 entries per group, not 32, at the same CPU. + let r = raqe("r", 60_000, 60_000); + let answering = |k: u64| { + let mut d = crate::test_support::deployment(1.0, 1.0, 1.0, 0.0, 60_000, 60_000); + d.config.sketch_config = + serde_json::json!({"params": {"heap": 1u64 << 40, "topk_k": k}}); + d + }; + let retained = prune_dominated_candidates( + &[r], + &facts(1, 1), + vec![answering(100), answering(32)], + &table_accuracy, + ); + assert_eq!(retained, vec![answering(32)]); + } + + #[test] + fn retains_candidate_with_cheaper_compaction() { + // A direct RAQE never merges at query time, so merge CPU shows up only + // in compaction. `cheap_ingest` ingests on 2 workers (ρ = 2) and + // compacts for 100 s; `cheap_compaction` ingests on 3 (ρ = 3) and + // compacts for 2 s. Neither is no worse on every cost. + let r = raqe("r", 60_000, 60_000); + let cheap_ingest = crate::test_support::deployment(1.0, 1.0, 100.0, 1.0, 60_000, 60_000); + let cheap_compaction = crate::test_support::deployment(1.0, 1.5, 1.0, 1.0, 60_000, 60_000); + + let retained = prune_dominated_candidates( + &[r], + &facts(1, 2), + vec![cheap_ingest.clone(), cheap_compaction.clone()], + &table_accuracy, + ); + + assert_eq!(retained, vec![cheap_ingest, cheap_compaction]); + } + #[test] fn retains_candidate_with_lower_query_latency() { let r = raqe("r", 60_000, 60_000); @@ -1037,4 +1128,108 @@ mod tests { &table_accuracy, ); } + + #[test] + fn a_mergeable_deployment_serves_a_coarser_grouping_only() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let serves = |d: &Deployment, grouping: &[&str]| { + is_eligible( + &quantile_by(grouping, 60_000, 60_000), + d, + &facts, + &table_accuracy, + ) + }; + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + assert!(serves(&by_endpoint, &["service", "endpoint"])); + assert!(serves(&by_endpoint, &["service"])); + assert!(serves(&by_endpoint, &[])); + assert!(!serves(&by_endpoint, &["pod"])); + assert!(!serves( + &kll_by(&["service"], 60_000), + &["service", "endpoint"] + )); + } + + #[test] + fn a_rate_serves_only_its_own_grouping() { + use crate::test_support::{kll_by, quantile_by, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = kll_by(&["service", "endpoint"], 60_000); + let increase_by_endpoint = Deployment { + capability: Capability::RateOrIncrease, + config: AtomicCostEntry { + sketch: "exact-increase".into(), + accuracy_metric: metric_of("exact-increase"), + ..by_endpoint.config.clone() + }, + ..by_endpoint + }; + let rate_by = |grouping: &[&str]| Raqe { + capability: Capability::RateOrIncrease, + ..quantile_by(grouping, 60_000, 60_000) + }; + let serves = |r: &Raqe| is_eligible(r, &increase_by_endpoint, &facts, &table_accuracy); + assert!(serves(&rate_by(&["service", "endpoint"]))); + assert!(!serves(&rate_by(&["service"]))); + } + + #[test] + fn top_k_serves_only_its_own_grouping() { + use crate::test_support::{deployment, label_set, service_endpoint_facts}; + let facts = service_endpoint_facts(); + let by_endpoint = Deployment { + grouping_labels: label_set(&["service", "endpoint"]), + ..deployment(1.0, 1.0, 1.0, 1.0, 60_000, 60_000) + }; + let serves = |grouping: &[&str]| { + let r = Raqe { + grouping_labels: label_set(grouping), + ..raqe("r", 60_000, 60_000) + }; + is_eligible(&r, &by_endpoint, &facts, &table_accuracy) + }; + assert!(serves(&["service", "endpoint"])); + assert!(!serves(&["service"])); + } + + /// A 1 h fine RAQE alone never yields a 90 min window. Its 90 min coarse + /// sibling does, but only for the family that can serve both. + #[test] + fn fine_candidates_take_windows_from_coarser_raqes() { + use crate::test_support::{label_set, quantile_by, service_endpoint_facts}; + const HOUR: Millis = 3_600_000; + const NINETY_MINUTES: Millis = 5_400_000; + let fine = ["service", "endpoint"]; + let topk_by = |grouping: &[&str], lookback_ms| Raqe { + grouping_labels: label_set(grouping), + ..raqe("r", lookback_ms, lookback_ms) + }; + let raqes = [ + quantile_by(&fine, HOUR, HOUR), + quantile_by(&["service"], NINETY_MINUTES, NINETY_MINUTES), + topk_by(&fine, HOUR), + topk_by(&["service"], NINETY_MINUTES), + ]; + let kll = AtomicCostEntry { + sketch: "kll-percall".into(), + sketch_config: serde_json::json!({"params": {"k": 200}}), + accuracy_metric: metric_of("kll-percall"), + ..cost() + }; + let candidates = + build_all_candidates_unpruned(&raqes, &[kll, cost()], &service_endpoint_facts(), false); + let fine_windows = |sketch: &str| { + candidates + .iter() + .filter(|d| d.config.sketch == sketch && d.grouping_labels == label_set(&fine)) + .map(|d| d.window_ms) + .collect::>() + }; + assert!(fine_windows("kll-percall").contains(&NINETY_MINUTES)); + let topk_windows = fine_windows("cms-heap-topk-fastpath-vector2d"); + assert!(topk_windows.contains(&HOUR)); + assert!(!topk_windows.contains(&NINETY_MINUTES)); + } } diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 666cf5a1..8fe68f70 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -1,20 +1,20 @@ -//! Brute-force search over full mappings (§4, §7 step 2). +//! Brute-force search over full mappings. //! -//! A mapping is one deployment choice per RAQE (§4's only constraint is -//! `Σ_D x_{i,D} = 1`; `y_D` is derived). No RAQE is eligible outside its own -//! `(capability, metric, spatial_filter, grouping_labels)` group, so choices are independent and the search -//! space is exactly the cartesian product of the per-RAQE eligible lists -- -//! nothing to prune against. Sharing falls out when two choices land on the -//! same index. +//! A mapping is one deployment choice per RAQE (the MILP's only constraint is +//! `Σ_D z_{i,D} = 1`; `u_D` is derived). Choices are independent, so the +//! search space is exactly the cartesian product of the per-RAQE eligible +//! lists -- nothing to prune against. Sharing falls out when two choices land +//! on the same index, including a fine deployment chosen by a RAQE that rolls +//! up to a coarser grouping. //! //! An ILP would replace this module alone: `Mapping` already encodes -//! `x_{i,D}` and `y_D`. +//! `z_{i,D}` and `u_D`. use crate::{ candidates::eligible_deployments_for, Accuracy, Deployment, Mapping, Raqe, WorkloadFacts, }; -/// RAQEs nothing in `deployments` can serve (§3.4). Surfaced separately from +/// RAQEs nothing in `deployments` can serve. Surfaced separately from /// `brute_force`: an unservable RAQE is a modeling gap (tolerance too tight, /// no such config), not a normal empty result. pub fn unservable( diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 44429a81..e7868d5d 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -1,10 +1,11 @@ //! v1 brute-force solver for the RAQE -> sketch-deployment mapping problem. -//! `docs/rqe_sketch_deployment_v1.md` is the problem statement; doc comments -//! cite its section numbers. +//! `docs/rqe_sketch_deployment_v1.md` is the problem statement; +//! `rqe_optimizer_candidates.md` and `rqe_optimizer_cost_model.md` hold the +//! detailed planning design. //! //! Three independent stages, so an ILP can replace [`enumerate`] alone: -//! [`candidates`] builds 𝒟 and per-RAQE eligibility (§3), [`enumerate`] -//! searches (§4), [`analytical_cost_model`] scores (§5). +//! [`candidates`] builds 𝒟 and per-RAQE eligibility, [`enumerate`] searches, +//! and [`analytical_cost_model`] scores. //! //! Every number the algorithm uses is caller-supplied, except the query //! output size estimates in [`analytical_cost_model`]. @@ -32,10 +33,12 @@ pub(crate) fn secs(ms: Millis) -> f64 { ms as f64 / 1000.0 } -/// A group-by key, compared as a set (§3's `labels_i == labels_D` rule). +/// A group-by key, compared as a set: a deployment serves a RAQE with the +/// same one, or a subset of it when the family is +/// [`mergeable_across_groups`](FamilyProperties::mergeable_across_groups). pub type LabelSet = BTreeSet; -/// What an RAQE's statistic needs (§1). A variant becomes a candidate only +/// What an RAQE's statistic needs. A variant becomes a candidate only /// if it is in both `families()` and [`DEPLOYABLE_FAMILIES`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Capability { @@ -209,6 +212,10 @@ pub fn heap_capacity(config: &AtomicCostEntry) -> Option { pub struct FamilyProperties { /// Windows fold into one. A family without it only serves `L == x`. pub mergeable_across_windows: bool, + /// Groups' states fold into their parent group's: a deployment grouped by + /// `G` serves a RAQE grouped by any subset of `G` (a roll-up). Not top-k, + /// whose heaps drop items that are in the parent's top k but no child's. + pub mergeable_across_groups: bool, /// One sketch of fixed size holds every group: the design doc's Shared + /// Fixed cell. Memory, merge and storage don't scale with `card(G)`. /// Exact accumulators are Shared + PerKey and `false` here, because the @@ -232,6 +239,7 @@ pub fn family_properties(variant: &str) -> FamilyProperties { use AccuracyDirection::{HigherIsBetter, LowerIsBetter}; let one_sketch_per_group = |metric, direction| FamilyProperties { mergeable_across_windows: true, + mergeable_across_groups: true, one_fixed_size_sketch_for_all_groups: false, needs_delta_set_key_tracker: false, exact: false, @@ -243,7 +251,15 @@ pub fn family_properties(variant: &str) -> FamilyProperties { ..one_sketch_per_group("relative_error", LowerIsBetter) }; match variant { - "exact-sum" | "exact-min" | "exact-max" | "exact-increase" => exact, + "exact-sum" | "exact-min" | "exact-max" => exact, + // Not rolled up: its merge joins two pieces of one counter in time + // (the later start after a drop is a reset), so merging two groups' + // counters is wrong. A coarse increase is the sum of per-series + // increases, which needs per-series state and a sum, not this merge. + "exact-increase" => FamilyProperties { + mergeable_across_groups: false, + ..exact + }, KEY_TRACKER_FAMILY => FamilyProperties { accuracy: None, ..exact @@ -253,9 +269,13 @@ pub fn family_properties(variant: &str) -> FamilyProperties { "dd" => one_sketch_per_group("mean_relative_value_error", LowerIsBetter), "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" - | "univmon-topk" => one_sketch_per_group("precision_at_k", HigherIsBetter), + | "univmon-topk" => FamilyProperties { + mergeable_across_groups: false, + ..one_sketch_per_group("precision_at_k", HigherIsBetter) + }, "hydra-kll" => FamilyProperties { mergeable_across_windows: true, + mergeable_across_groups: false, one_fixed_size_sketch_for_all_groups: true, needs_delta_set_key_tracker: true, exact: false, @@ -275,6 +295,7 @@ pub struct MetricFacts { pub scrape_interval_ms: Millis, /// `card(X)`: distinct value combinations of each label set `X` in use. /// Must include `labels` itself, whose cardinality is the series count. + /// A label set never has more groups than any superset of it. pub cardinality: BTreeMap, /// `(lo, hi)`: smallest and largest positive sample value, if known. /// Sizes DDSketch; without it, DDSketch keeps the measured memory. @@ -365,13 +386,33 @@ pub fn validate_facts(raqes: &[Raqe], facts: &WorkloadFacts) -> Result<(), Vec false, }; } - if let (Some(&groups), Some(&series)) = - (cardinality.get(grouping), cardinality.get(all_labels)) - { - if groups > series { - problems.insert(format!( - "{metric}: {grouping:?} has {groups} groups but only {series} series" - )); + } + // Dropping labels never adds groups. A roll-up's merge count, + // `card(G_d) · L/x − card(G_r)`, relies on it, so it is checked between + // the label sets a plan can use: every RAQE grouping on the metric, and + // its full label set. A label set no RAQE groups by is never read. + let mut used: BTreeMap<&str, BTreeSet<&LabelSet>> = BTreeMap::new(); + for raqe in raqes { + if let Some(metric_facts) = facts.get(&raqe.metric) { + used.entry(&raqe.metric) + .or_insert_with(|| BTreeSet::from([&metric_facts.labels])) + .insert(&raqe.grouping_labels); + } + } + for (metric, label_sets) in &used { + let cardinality = &facts[*metric].cardinality; + for coarse in label_sets { + for fine in label_sets { + if let (Some(&coarse_groups), Some(&fine_groups)) = + (cardinality.get(*coarse), cardinality.get(*fine)) + { + if coarse.is_subset(fine) && coarse_groups > fine_groups { + problems.insert(format!( + "{metric}: {coarse:?} has {coarse_groups} groups but its superset \ + {fine:?} only {fine_groups}" + )); + } + } } } } @@ -397,7 +438,7 @@ pub enum AccuracyDirection { HigherIsBetter, } -/// One repeating query expression (§1). +/// One repeating query expression. #[derive(Debug, Clone)] pub struct Raqe { pub id: String, @@ -487,7 +528,7 @@ pub fn row_accuracy(config: &AtomicCostEntry) -> f64 { }) } -/// A candidate deployment (§3): one configuration, one grouped stream, and a +/// A candidate deployment (`docs/rqe_optimizer_candidates.md`): one configuration, one grouped stream, and a /// sliding sketch window. Retention is an execution/storage concern, not an /// optimizer candidate dimension. #[derive(Debug, Clone, PartialEq)] @@ -548,7 +589,7 @@ impl Deployment { /// A full mapping: one deployment index (into the `deployments` slice passed /// to `enumerate::brute_force`) per RAQE, aligned with the `raqes` slice's /// order. `z_{i,D} = 1 <=> mapping[i] == D`'s index; `u_D = 1 <=>` `D`'s -/// index appears anywhere in `mapping` (§4) -- `y` is never stored +/// index appears anywhere in `mapping` -- `y` is never stored /// separately, it's always derived from `mapping`. pub type Mapping = Vec; @@ -652,6 +693,51 @@ pub(crate) mod test_support { key_tracker: None, } } + + pub fn label_set(names: &[&str]) -> LabelSet { + names.iter().map(|name| name.to_string()).collect() + } + + /// 5 services × 10 endpoints, one series per endpoint, scraped every + /// second: the coarse and fine groupings of a roll-up. + pub fn service_endpoint_facts() -> WorkloadFacts { + let service = label_set(&["service"]); + let service_endpoint = label_set(&["service", "endpoint"]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: service_endpoint.clone(), + scrape_interval_ms: 1_000, + cardinality: BTreeMap::from([(service, 5), (service_endpoint, 50)]), + value_range: None, + data_shape: BTreeMap::new(), + }, + )]) + } + + /// A per-group KLL deployment by `grouping`, every per-instance cost 1. + pub fn kll_by(grouping: &[&str], window_ms: Millis) -> Deployment { + let base = deployment(1.0, 1.0, 1.0, 1.0, window_ms, window_ms); + Deployment { + capability: Capability::Quantile, + grouping_labels: label_set(grouping), + config: AtomicCostEntry { + sketch: "kll-percall".into(), + sketch_config: serde_json::json!({"params": {"k": 200}}), + accuracy_metric: metric_of("kll-percall"), + ..base.config + }, + ..base + } + } + + pub fn quantile_by(grouping: &[&str], lookback_ms: Millis, interval_ms: Millis) -> Raqe { + Raqe { + capability: Capability::Quantile, + grouping_labels: label_set(grouping), + ..raqe(lookback_ms, interval_ms) + } + } } #[cfg(test)] @@ -865,26 +951,73 @@ mod tests { ); } - #[test] - fn rejects_more_groups_than_series() { - let facts = WorkloadFacts::from([( + /// Facts where `(service)` has more groups than its superset + /// `(service, endpoint)`, and `(pod)` has none at all. + fn inconsistent_facts() -> WorkloadFacts { + WorkloadFacts::from([( METRIC.to_string(), MetricFacts { - labels: labels(&["service", "endpoint"]), + labels: labels(&["service", "endpoint", "pod"]), scrape_interval_ms: 15_000, cardinality: BTreeMap::from([ (labels(&["service"]), 60), (labels(&["service", "endpoint"]), 50), + (labels(&["pod"]), 0), + (labels(&["service", "endpoint", "pod"]), 30_000), ]), value_range: None, data_shape: BTreeMap::new(), }, - )]); + )]) + } + + /// Between two RAQE groupings, the subset may not have more groups. + #[test] + fn rejects_a_used_label_set_with_more_groups_than_a_used_superset() { + let grouped = |l: &[&str]| Raqe { + grouping_labels: labels(l), + ..raqe(60_000, 60_000) + }; + assert_eq!( + validate_facts( + &[grouped(&["service"]), grouped(&["service", "endpoint"])], + &inconsistent_facts() + ) + .unwrap_err(), + [format!( + "{METRIC}: {{\"service\"}} has 60 groups but its superset \ + {{\"endpoint\", \"service\"}} only 50" + )] + ); + } + + /// A RAQE grouping may not have more groups than the series. + #[test] + fn rejects_a_grouping_with_more_groups_than_series() { + let mut facts = inconsistent_facts(); + let cardinality = &mut facts.get_mut(METRIC).unwrap().cardinality; + cardinality.insert(labels(&["service", "endpoint", "pod"]), 40); + let r = Raqe { + grouping_labels: labels(&["service"]), + ..raqe(60_000, 60_000) + }; + assert_eq!( + validate_facts(&[r], &facts).unwrap_err(), + [format!( + "{METRIC}: {{\"service\"}} has 60 groups but its superset \ + {{\"endpoint\", \"pod\", \"service\"}} only 40" + )] + ); + } + + /// Label sets no RAQE groups by are never read, so inconsistencies there + /// don't reject the workload. + #[test] + fn ignores_label_sets_no_raqe_uses() { let r = Raqe { grouping_labels: labels(&["service"]), ..raqe(60_000, 60_000) }; - let problems = validate_facts(&[r], &facts).unwrap_err(); - assert!(problems[0].contains("60 groups but only 50 series")); + assert_eq!(validate_facts(&[r], &inconsistent_facts()), Ok(())); } } diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index 99cb9b52..165d654b 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -1,6 +1,7 @@ -//! MILP solver for one scalarized RAQE deployment optimization (§4). +//! MILP solver for one scalarized RAQE deployment optimization. //! -//! The model is documented in `docs/rqe_sketch_deployment_v1.md`. It avoids +//! Candidate construction is documented in `docs/rqe_optimizer_candidates.md` +//! and the cost model in `docs/rqe_optimizer_cost_model.md`. It avoids //! enumerating the Cartesian product of eligible deployment choices. use crate::analytical_cost_model::{self, score, PhaseCost, PlanCost, BYTES_PER_GIB}; @@ -68,6 +69,8 @@ pub struct PlannedRaqe { /// Index into [`MilpSolution::deployments`]. pub deployment: usize, /// `n = L/x` windows merged per query; 1 means Direct, more means Merge. + /// A roll-up (the RAQE's grouping differs from its deployment's) also + /// merges each coarse group's fine groups, even when `n = 1`. pub merged_instance_count: u64, } @@ -242,7 +245,7 @@ pub struct UsageSolution { } /// Minimize the cost billed by use, `w_cpu · AUC(CPU) + w_mem · AUC(memory)` -/// (per vCPU, per GiB; `docs/rqe_sketch_deployment_v1.md`, "Cost by use and +/// (per vCPU, per GiB; `docs/rqe_optimizer_cost_model.md`, "Cost by use and /// batch latency"). The latency is reported. `latency_bound_ms`, when given, /// rules out every pair whose chain (`analytical_cost_model::chain_ms`) /// exceeds it, so sweeping it traces the cost–latency Pareto frontier; it is diff --git a/rqe-optimizer/src/saturation.rs b/rqe-optimizer/src/saturation.rs index 81ebf849..bbf623ee 100644 --- a/rqe-optimizer/src/saturation.rs +++ b/rqe-optimizer/src/saturation.rs @@ -213,12 +213,16 @@ fn curve_error_at( } } -/// KLL and the heap top-k sketches lose accuracy when merged (#131): a -/// merged answer reads their merge curve. The other sketches merge exactly. +/// KLL, the heap top-k sketches and UnivMon lose accuracy when merged +/// (#131): a merged answer reads their merge curve. UnivMon's counters add +/// exactly, but each level's heavy-hitter heap is rebuilt from the union of +/// the two heaps, so a key heavy only in the union is lost. The other +/// sketches merge exactly. fn merges_lossily(sketch: &str) -> bool { matches!( sketch, "kll-percall" + | "univmon-cardinality" | "cms-heap-topk-fastpath-vector2d" | "countsketch-heap-topk-fastpath-vector2d" | "univmon-topk" @@ -362,8 +366,9 @@ impl SaturationCurves { // accuracy. let mut lossy: BTreeMap<&str, bool> = BTreeMap::new(); for (sketch, point) in points.values() { - // Heap top-k merges as one sketch when sized m · k, so only KLL - // needs the curves. + // Heap top-k merges as one sketch when sized m · k, so only the + // non-heap lossy sketches (KLL, univmon-cardinality, univmon-topk) + // need the curves. if is_candidate(sketch) && merges_lossily(sketch) && !has_heap(sketch) { *lossy.entry(sketch).or_default() |= !point.merged.is_empty(); } @@ -446,7 +451,9 @@ impl SaturationCurves { return table_accuracy(raqe, deployment).map(|v| (v, AccuracySource::Measured)); } let metric_facts = &facts[&deployment.metric]; - let grouping = &deployment.grouping_labels; + // The answered groups: the RAQE's, coarser than the deployment's on a + // roll-up, whose answer is the merged coarse group's. + let grouping = &raqe.grouping_labels; let shape = metric_facts.data_shape.get(grouping)?; let k = raqe.topk_k(); let base = with_topk_k(&config_params(&deployment.config)?, TOPK_K); @@ -464,7 +471,12 @@ impl SaturationCurves { let covered = items_per_group(metric_facts, grouping, raqe.lookback_ms); let (_, direction) = accuracy_key(&deployment.config.sketch); let merges = if merges_lossily(&deployment.config.sketch) { - let merges = deployment.query_instance_count(raqe.lookback_ms)?; + // A roll-up also merges each coarse group's children, the average + // `card(G_d) / card(G_r)` of them. + // ponytail: average fan-out; the largest group's is sketch-bench#189. + let fan_out = metric_facts.cardinality[&deployment.grouping_labels] + .div_ceil(metric_facts.cardinality[grouping]); + let merges = deployment.query_instance_count(raqe.lookback_ms)? * fan_out; // A heap of m · k merged from m windows reads as one sketch: the // merged heaps are taken to still hold the true top k. match ( @@ -821,6 +833,16 @@ mod tests { const TOPK: &str = "cms-heap-topk-fastpath-vector2d"; + /// UnivMon's heaps are rebuilt on merge, so its cardinality reads merge + /// curves like KLL; HLL's register max and DDSketch's bucket sums are + /// exact. + #[test] + fn univmon_cardinality_merges_lossily_hll_and_dd_do_not() { + assert!(merges_lossily("univmon-cardinality")); + assert!(!merges_lossily("hll")); + assert!(!merges_lossily("dd")); + } + /// Top-k rows=3 cols=1024 at θ ∈ {1.0, 1.2}, K ∈ {1e3, 1e5}. Precision /// falls with N; θ = 1.0 is worse, and K = 1e5 never saturates. Merged /// from 4 shards it loses 0.02 more, from 16 shards 0.1. @@ -984,6 +1006,45 @@ mod tests { assert_eq!(at(100_000), None); } + /// p99 by service from KLL by (service, endpoint) reads the coarse + /// group's shape and items, merged from its 10 endpoints. + #[test] + fn a_kll_roll_up_reads_the_merge_curve_at_fan_out_times_windows() { + use crate::test_support::{kll_by, label_set, quantile_by, service_endpoint_facts}; + let curve = |error: f64| vec![(1e3, error, 0.0), (1e4, error + 0.01, 0.0)]; + let kll = GridPoint { + params: parse_config("k=200"), + shape: MeasuredShape::Pareto { tail_index: 2.0 }, + error_metric: "mean_rank_err".into(), + n_sat: None, + curve: curve(0.01), + merged: BTreeMap::from([(4, curve(0.02)), (16, curve(0.05))]), + }; + let curves = SaturationCurves { + points_by_sketch: BTreeMap::from([("kll-percall".to_string(), vec![kll])]), + }; + let mut facts = service_endpoint_facts(); + let metric = facts.get_mut(METRIC).unwrap(); + // Only the coarse grouping's shape is on the grid. + metric + .data_shape + .insert(label_set(&["service"]), shape(1.0, 1.0)); + metric.data_shape.insert( + label_set(&["service", "endpoint"]), + DataShape { + tail_index: 9.0, + ..shape(1.0, 1.0) + }, + ); + // 10 series per service × 100 s = 1e3 items, in one window. + let by_service = quantile_by(&["service"], 100_000, 100_000); + let accuracy = + |grouping: &[&str]| curves.accuracy(&by_service, &kll_by(grouping, 100_000), &facts); + assert_eq!(accuracy(&["service"]), Some(0.01)); + // 10 merged endpoints sit between 4 and 16 shards: the worse, 16. + assert_eq!(accuracy(&["service", "endpoint"]), Some(0.05)); + } + /// A heap of m · k merged from m windows reads as one sketch: the plain /// curve, not the merge curve, and no merge curve is needed. #[test] diff --git a/rqe-optimizer/src/usage.rs b/rqe-optimizer/src/usage.rs index 649c7b21..349cd3b7 100644 --- a/rqe-optimizer/src/usage.rs +++ b/rqe-optimizer/src/usage.rs @@ -1,5 +1,5 @@ //! A plan's resource use over time, its cost billed by use, and its batch -//! latency (`docs/rqe_sketch_deployment_v1.md`, "Cost by use and batch +//! latency (`docs/rqe_optimizer_cost_model.md`, "Cost by use and batch //! latency"). //! //! Ingest is a steady load on `⌈ρ⌉` workers per deployment, split by sample. diff --git a/rqe-optimizer/tests/mixed_grouping.rs b/rqe-optimizer/tests/mixed_grouping.rs new file mode 100644 index 00000000..b33c564d --- /dev/null +++ b/rqe-optimizer/tests/mixed_grouping.rs @@ -0,0 +1,166 @@ +//! A workload asking the same question at two groupings, `(service, +//! endpoint)` and `(service)`, solved end to end. A family whose states merge +//! across groups serves both from one fine deployment; one whose don't keeps a +//! deployment per grouping (sketch-bench#187). + +use std::collections::BTreeMap; + +use aqpbm_core::MeasuredAt; +use rqe_optimizer::candidates::build_all_candidates; +use rqe_optimizer::milp::{minimize, MilpSolution, Objective}; +use rqe_optimizer::{ + accuracy_key, validate_facts, AccuracyDirection, AtomicCostEntry, Capability, Deployment, + LabelSet, MetricFacts, Raqe, WorkloadFacts, +}; + +const METRIC: &str = "http_request_duration_seconds"; +const HOUR_MS: u64 = 3_600_000; +const MINUTE_MS: u64 = 60_000; + +fn labels(names: &[&str]) -> LabelSet { + names.iter().map(|name| name.to_string()).collect() +} + +/// 5 services × 10 endpoints × 600 pods = 30,000 series, scraped every 15 s. +fn facts() -> WorkloadFacts { + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint", "pod"]), + scrape_interval_ms: 15_000, + cardinality: BTreeMap::from([ + (labels(&["service"]), 5), + (labels(&["service", "endpoint"]), 50), + (labels(&["service", "endpoint", "pod"]), 30_000), + ]), + value_range: None, + data_shape: BTreeMap::new(), + }, + )]) +} + +fn raqe(id: &str, capability: Capability, grouping: &[&str], accuracy_sla: f64) -> Raqe { + Raqe { + id: id.into(), + capability, + lookback_ms: HOUR_MS, + interval_ms: MINUTE_MS, + metric: METRIC.into(), + spatial_filter: String::new(), + grouping_labels: labels(grouping), + accuracy_sla, + latency_sla_ms: None, + topk_k: None, + } +} + +fn raqes() -> Vec { + vec![ + raqe( + "p99_by_endpoint", + Capability::Quantile, + &["service", "endpoint"], + 0.05, + ), + raqe("p99_by_service", Capability::Quantile, &["service"], 0.05), + raqe( + "top_by_endpoint", + Capability::TopKByValue, + &["service", "endpoint"], + 0.9, + ), + raqe("top_by_service", Capability::TopKByValue, &["service"], 0.9), + ] +} + +/// Ingest dominates merge and query, as it does in the measured table, so +/// sharing one deployment is cheaper than keeping two whenever it is allowed. +fn cost_row(sketch: &str, params: serde_json::Value) -> AtomicCostEntry { + let (accuracy_metric, _) = accuracy_key(sketch); + AtomicCostEntry { + sketch: sketch.into(), + sketch_config: serde_json::json!({ "params": params }), + mem_bytes_per_instance: 1_000.0, + insert_cpu_secs: 1e-6, + merge_cpu_secs: 1e-6, + query_cpu_secs: 1e-6, + query_accuracy: BTreeMap::from([(accuracy_metric.to_string(), 0.0)]), + accuracy_metric: accuracy_metric.into(), + measured_at: MeasuredAt { + items_per_instance: 1_000_000, + keys_per_instance: Some(10_000), + value_range: None, + merge_operand_items: None, + distribution: None, + }, + } +} + +fn cost_table() -> Vec { + vec![ + cost_row("kll-percall", serde_json::json!({ "k": 200 })), + // A heap large enough for any merge, so heap size never decides the plan. + cost_row( + "cms-heap-topk-fastpath-vector2d", + serde_json::json!({ "rows": 3, "cols": 1024, "heap": 1u64 << 40 }), + ), + ] +} + +/// Every candidate meets every SLA, so the plan is decided by eligibility and +/// cost alone. +fn perfect_accuracy(_: &Raqe, deployment: &Deployment) -> Option { + match accuracy_key(&deployment.config.sketch).1 { + AccuracyDirection::LowerIsBetter => Some(0.0), + AccuracyDirection::HigherIsBetter => Some(1.0), + } +} + +fn solve(raqes: &[Raqe]) -> MilpSolution { + let facts = facts(); + validate_facts(raqes, &facts).expect("valid workload facts"); + let candidates = build_all_candidates(raqes, &cost_table(), &facts, false, &perfect_accuracy); + minimize( + raqes, + &candidates, + &facts, + Objective::default(), + &perfect_accuracy, + ) + .expect("feasible plan") +} + +/// The planned deployment serving the RAQE named `id`. +fn deployment_serving<'a>(solution: &'a MilpSolution, raqes: &[Raqe], id: &str) -> &'a Deployment { + let index = raqes.iter().position(|raqe| raqe.id == id).unwrap(); + &solution.deployments[solution.raqes[index].deployment].deployment +} + +#[test] +fn a_fine_kll_deployment_serves_both_quantile_raqes() { + let raqes = raqes(); + let solution = solve(&raqes); + let by_endpoint = deployment_serving(&solution, &raqes, "p99_by_endpoint"); + let by_service = deployment_serving(&solution, &raqes, "p99_by_service"); + assert_eq!( + by_endpoint, by_service, + "one KLL deployment should serve both groupings" + ); + assert_eq!( + by_endpoint.grouping_labels, + labels(&["service", "endpoint"]) + ); +} + +#[test] +fn top_k_never_rolls_up() { + let raqes = raqes(); + let solution = solve(&raqes); + let by_endpoint = deployment_serving(&solution, &raqes, "top_by_endpoint"); + let by_service = deployment_serving(&solution, &raqes, "top_by_service"); + assert_eq!( + by_endpoint.grouping_labels, + labels(&["service", "endpoint"]) + ); + assert_eq!(by_service.grouping_labels, labels(&["service"])); +} diff --git a/scripts/plot_autosketch_vs_asap_sla.py b/scripts/plot_autosketch_vs_asap_sla.py index 2d2dc89b..103b1294 100644 --- a/scripts/plot_autosketch_vs_asap_sla.py +++ b/scripts/plot_autosketch_vs_asap_sla.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Plot version 2 (a batch latency SLA) of the AutoSketch vs. ASAP evaluation -(ProjectASAP/ASAPQuery#777; sketch-bench docs/rqe_sketch_deployment_v1.md, +(ProjectASAP/ASAPQuery#777; sketch-bench docs/rqe_optimizer_cost_model.md, "Cost by use and batch latency") from the `sla_results` of `autosketch_vs_asap synthetic` runs. diff --git a/scripts/plot_autosketch_vs_asap_synthetic.py b/scripts/plot_autosketch_vs_asap_synthetic.py index 6af54b4d..72849e2c 100644 --- a/scripts/plot_autosketch_vs_asap_synthetic.py +++ b/scripts/plot_autosketch_vs_asap_synthetic.py @@ -2,7 +2,7 @@ """Plot the synthetic AutoSketch vs. ASAP evaluation (ProjectASAP/ASAPQuery#777, section 7) from the JSON files of `autosketch_vs_asap synthetic`. -Every plan is priced by use (sketch-bench docs/rqe_sketch_deployment_v1.md, +Every plan is priced by use (sketch-bench docs/rqe_optimizer_cost_model.md, "Cost by use and batch latency"): w_cpu * AUC(CPU) + w_mem * AUC(memory), with CPU elastic, and its query latency (the longest chain) is reported. ASAP and PerQuery-CostAware are solved without a bound and for a sweep of latency