diff --git a/docs/rqe_optimizer_TODO.md b/docs/rqe_optimizer_TODO.md index 13f42e94..348ab3c1 100644 --- a/docs/rqe_optimizer_TODO.md +++ b/docs/rqe_optimizer_TODO.md @@ -5,18 +5,23 @@ implemented, what is next, and what is intentionally deferred. ## Done in v1 -- Sliding deployments use `(capability, configuration, labels, x, y)`, where - `x` is window size and `y` is slide. -- Eligibility enforces capability, labels, alignment, and the RQE's measured - `accuracy_metric` constraint. -- Candidate generation uses legal windows and subset gcds of query intervals. - A deployment may serve multiple compatible RQEs. +- Sliding deployments use `(capability, configuration, metric, G, x, y)`, + where `x` is window size and `y` is slide. +- Workload facts are per metric: full label set, scrape interval, and + cardinality per label set. The arrival rate is derived from them, and + `validate_facts` reports bad facts up front. +- Eligibility enforces capability, metric, grouping, alignment, and the RQE's + measured `accuracy_metric` constraint. +- Candidate generation uses legal windows and subset gcds of query intervals, + keeping only multiples of the scrape interval. A deployment may serve + multiple compatible RQEs. - Candidate dominance safely removes a deployment only when another covers all - of its RQEs with no worse query memory, ingest CPU, or per-RQE latency. -- The analytical model combines measured per-operation costs with label-set - cardinality and arrival rate to score ingest CPU, query CPU, merge CPU, - total CPU, query memory, and per-RQE latency. -- The Pareto vector is `(peak_query_memory, TCO_cpu, {latency_i})`. + of its RQEs with no worse instance memory, ingest CPU and memory, per-RQE + latency, or stored memory. +- The analytical model scores four phases, each with CPU and memory: ingest + (open windows), merge, query, and storage (closed windows, `(S − x)/y + 1` + for the longest lookback), plus per-RQE latency. +- The Pareto vector is `(CPU, memory, {latency_i})`. - Eager enumeration remains available for small inputs. Streaming enumeration retains only the incremental Pareto frontier. - `small_problem --candidates-only` reports generated and retained candidate @@ -25,30 +30,33 @@ implemented, what is next, and what is intentionally deferred. can print initial example mappings. - `scripts/export_rqe_optimizer_costs.sh` exports the 18-row measured cost table used by `small_problem`, without changing ASAPQuery's exporter. -- The MILP uses HiGHS to minimize TCO without enumerating mappings. It accepts - optional peak-memory and per-RQE latency bounds and returns a normal mapping. -- `small_problem --milp` accepts repeatable per-RQE latency limits and includes - 1-hour, 6-hour, and 1-day quantile RQEs to exercise those constraints. -- A regression test confirms the MILP matches exhaustive minimum-TCO search on - a tiny workload with shared deployment activation costs. -- Retained memory (`(x + max S) / y` instances per active deployment) is - scored, and `milp::minimize_cost` minimizes the hourly price on one EC2 - machine family in fractional instances. Prices are a committed snapshot from - `scripts/fetch_ec2_pricing.py`; `small_problem --milp --machine-family NAME` - uses it. +- The MILP uses HiGHS to minimize `Objective::AUCCost { w_cpu, w_mem }`, + `w_cpu × CPU + w_mem × memory GiB` (default `(1, 0)`), without enumerating + mappings. It accepts optional per-RQE latency bounds and returns a normal + mapping. +- `small_problem --milp` takes `--w-cpu`/`--w-mem` and repeatable per-RQE + latency limits, and includes 1-hour, 6-hour, and 1-day quantile RQEs to + exercise those constraints. +- Regression tests confirm the MILP matches exhaustive search on tiny + workloads with shared deployments, at several weightings. ## Next - Add a hard `--max-mappings` limit to streaming experiments. - Validate accuracy after merging `S / x` sketch instances. V1 currently uses single-instance measurements, which do not establish final query accuracy. -- Add repeated MILP solves for Pareto exploration across memory and latency - budgets, or through normalized weighted objectives. +- Add repeated MILP solves for Pareto exploration across latency budgets or + weights. +- Set `w_cpu`/`w_mem` from real prices. ## Explicitly deferred - Query-result sharing across RQEs. -- Merge buffers and concurrent-query memory. +- Real query concurrency; memory assumes every query runs at once. +- Bursty load; CPU is a mean over time. +- A per-family instance shape for families holding every group in one + fixed-size instance (HydraKLL, sketch-bench#142). +- Top-k `k` other than the benchmark's 32, and key labels `K`. - RQE churn, replanning, and migration cost. - Precomputed rollups; v1 merges selected base instances at query time. - A policy for choosing one mapping from the reported Pareto frontier. diff --git a/docs/rqe_sketch_deployment_v1.md b/docs/rqe_sketch_deployment_v1.md index cd1b8457..5831c9f9 100644 --- a/docs/rqe_sketch_deployment_v1.md +++ b/docs/rqe_sketch_deployment_v1.md @@ -1,48 +1,83 @@ -# RQE-to-sketch deployment mapping: v1 +# RAQE-to-sketch deployment mapping: v1 ## Purpose -Given a workload of repeating query expressions (RQEs), find sketch deployments +Given a workload of repeating atomic query expressions (RAQEs), find sketch deployments that can serve it and report the trade-offs among query working memory, CPU, -and per-RQE latency. - -v1 is static and small-scale. It enumerates feasible mappings rather than -calling an ILP solver, but states the problem in solver-friendly terms so that -enumeration can be replaced later. +and per-RAQE latency. + +## Glossary + +- **RAQE**: repeating atomic query expression, evaluated every `T` over the last `S`. +- **Capability**: the statistic an RAQE needs: sum/count, min, max, + rate/increase, quantile, cardinality or top-k. +- **Metric**: a named stream of samples whose series are told apart by labels. +- **Group**: one combination of values of an RAQE's group-by labels `G`. There + are `card(G)` groups. +- **Family**: one sketch or accumulator implementation, such as `kll-percall`, + `cms-heap-topk-fastpath-vector2d` or `exact-sum`. Each capability lists the + families that serve it. +- **Configuration**: a family plus its parameters, such as KLL with `k = 200`. + One row of the cost table. +- **Cost table**: per configuration, measured memory per instance, CPU per + insert, merge and query, and accuracy. Exported by + [`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh). +- **Window**: the interval `[k × y, k × y + x)` an instance covers; `x` is the + window size and `y` the slide. +- **Instance**: one sketch or accumulator object holding one group's samples + (or all groups', for a shared family) over one window. Open or closed; see + [Window model](#window-model). +- **Deployment**: a configuration run over one metric, grouped by `G`, with + window `x` and slide `y`. A **candidate** is a deployment the optimizer may + choose. +- **Phase**: one of the four kinds of work a deployment does, each costed in + CPU and memory: **ingest** (inserting samples into open instances), + **merge** (folding a query's windows into an accumulator), **query** + (reading the merged result) and **storage** (keeping closed instances, no + CPU). See [Analytical cost model](#analytical-cost-model). ## Inputs -Let `R = {r_1, ..., r_n}` be the RQE workload. Each RQE `r_i` provides: +Let `R = {r_1, ..., r_n}` be the RAQE workload. Each RAQE `r_i` provides: | Field | Meaning | |---|---| -| `cap_i` | Required capability: `freq`, `quantile`, `cardinality`, or `topk`. | +| `cap_i` | Required capability. | | `S_i` | Query-window size. This is the current `lookback` field. | -| `T_i` | Query slide: how often the RQE runs. This is the current `interval` field. | -| `labels_i` | Group-by label set. | +| `T_i` | Query slide: how often the RAQE runs. This is the current `interval` field. | +| `metric_i` | Metric the RAQE reads. | +| `G_i` | Group-by label set (`grouping_labels`). | | `accuracy_metric_i` | Accuracy measurement to check. | | `tol_i` | Accuracy threshold. | | `direction_i` | Whether lower or higher values are better. | -For each label set, the caller provides: +For each metric, the caller provides `MetricFacts`: + +- `labels`: every label the metric's series carry. +- `scrape_interval`: every series yields one sample per scrape. +- `card(X)`: distinct value combinations of each label set `X` in use, + including `labels` itself (the raw series count). -- `card(labels)`: number of distinct label-value groups. -- `lambda(labels)`: aggregate item arrival rate across those groups, in - items/second. +The arrival rate is derived as follows (not provided by the user): -These are inputs to the optimizer; estimating them is outside v1. +```text +lambda(metric) = card(metric.labels) / scrape_interval samples/second +``` -Sketch Bench supplies empirical measurements for each sketch configuration: +`validate_facts` reports every missing or inconsistent fact up front. -- memory per sketch instance; -- insert CPU per item; -- query CPU per estimate; +The cost table, exported by +[`scripts/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh) +from sketch-bench runs, gives for each configuration: + +- memory per instance; +- CPU per insert; +- CPU per query of one instance; - CPU per pairwise merge; and - measured accuracy values. -Configurations are associated with the capabilities they can serve. The -implementation uses measured configuration variant names, because variants of -the same algorithm can have different costs. +Families are named by sketch-bench variant, not algorithm, because variants +of the same algorithm can have different costs. ## Window model @@ -57,11 +92,16 @@ For every label-value group, it creates an instance for every interval: [k × y, k × y + x) ``` +At time `t`, an instance is **open** while its interval has not ended +(`t < k × y + x`): it still receives samples. After that it is **closed**: it +never changes again and is kept only while some RAQE's lookback still needs it. +A deployment has `x / y` open instances per group at any time. + Instances overlap when `x > y`. There is no subtract operation. To answer an -RQE, the system selects and merges only non-overlapping instances, so items +RAQE, the system selects and merges only non-overlapping instances, so items are never counted twice. -An RQE with query window `S` and query slide `T` can use a deployment when: +An RAQE with query window `S` and query slide `T` can use a deployment when: ```text x % y == 0 @@ -76,14 +116,13 @@ For a query ending at time `t`, use the instances: ``` They exactly cover the query window and do not overlap. The deployment may -have produced other, overlapping instances between these starts; this query -does not merge them. +have produced other, overlapping instances between these starts. That is okay. Those overlapping instances are not used for this query. `S % T == 0` is not required. For example, a 10-minute window running every 3 minutes can use `x = 2 minutes` and `y = 1 minute`; each query merges five non-overlapping two-minute instances. -v1 assumes all RQEs share a common time origin. Query phase offsets are not +We assume all RAQEs share a common time origin. Query phase offsets are not modeled. ## Candidate deployments @@ -91,118 +130,144 @@ modeled. A candidate deployment is: ```text -D = (capability, configuration, labels, x, y) +D = (capability, configuration, metric, G, x, y) ``` -Candidates may be generated from individual RQEs, then deduplicated. This is +Candidates may be generated from individual RAQEs, then deduplicated. This is only a way to construct the candidate set: when solving a workload, one -selected deployment may serve multiple compatible RQEs. +selected deployment may serve multiple compatible RAQEs. + +Intuition: candidates are built in two steps, and each drops only candidates +that another candidate beats, so the best plan is never lost. Generation uses +no measurements. It keeps every legal window and configuration, and drops only +slides that a coarser slide beats for the same 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/label-set group, generate candidates as follows: +For each (capability, metric, G) group, generate candidates as follows: ```text -for each x that divides S_i for at least one RQE i in the group: - let g_i = gcd(x, T_i) for every RQE i whose S_i is divisible by x - let slides = every gcd reachable from a non-empty subset of {g_i} - for each measured configuration that serves the group's capability: - for each y in slides: - add (capability, configuration, labels, x, y) +for each 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) ``` -For an RQE considered alone, its only useful slide for a fixed `x` is its -largest legal slide, `gcd(x, T_i)`. A smaller slide adds ingest fan-out without -improving that RQE's query cost or memory. A shared deployment may need a -smaller slide: for example, two RQEs with `gcd(x, T)` values of 20 and 30 need -`y = 10` to share. Subset gcds include that slide without enumerating every -divisor. Any still-finer slide is useful only if it aligns an additional RQE, -in which case it appears as another subset gcd. +`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 | -An RQE `r_i` is eligible for a candidate `D` when: +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`. -1. `cap_i = D.capability` and `labels_i = D.labels`. +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. `D.configuration` contains a measured value for `accuracy_metric_i` that clears `tol_i` in `direction_i`. For lower-is-better metrics, passing means `measured <= tol_i`. For higher-is-better metrics, passing means `measured >= tol_i`. Direction is -explicit on the RQE; it is never inferred from a metric name. A missing metric +explicit on the RAQE; it is never inferred from a metric name. A missing metric does not pass. Before mapping, prune a candidate only if another candidate can serve every -RQE it can and is no worse in query memory, ingest CPU, latency, and retained -memory for each such RQE. This is safe because any mapping using the removed candidate can -substitute the remaining one without weakening a modeled objective. +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. -Historical instances must be retained long enough to answer the RQEs assigned -to a deployment. Retention is not a candidate parameter: a deployment retains -the history needed by the largest assigned query window. Its memory is scored -as retained memory (below) and priced by `minimize_cost`. +Closed instances must be stored long enough to answer the RAQEs assigned to a +deployment. Retention is not a candidate parameter: a deployment stores the +history needed by the largest assigned query window, costed as the storage +phase (below). ## Workload mapping -Let `z_{i,D}` be 1 when RQE `i` uses candidate deployment `D`; let `u_D` be 1 +Let `z_{i,D}` be 1 when RAQE `i` uses candidate deployment `D`; let `u_D` be 1 when deployment `D` is active. ```text -Σ_D z_{i,D} = 1 for every RQE i +Σ_D z_{i,D} = 1 for every RAQE i z_{i,D} <= u_D for every eligible pair (i, D) ``` -Every RQE selects exactly one eligible deployment. Multiple RQEs may select +Every RAQE selects exactly one eligible deployment. Multiple RAQEs may select the same deployment and therefore share its ingest work. A query may merge multiple instances from its selected deployment, but v1 does not combine -results from several deployments to satisfy one RQE. +results from several deployments to satisfy one RAQE. ### MILP formulation Let `E` be the eligible `(i, D)` pairs. The solver has one binary `z_{i,D}` for each pair in `E`, one binary `u_D` for each candidate, and a continuous -variable `M` for peak query memory. It minimizes a chosen scalarization or -solves under supplied budgets. +`stored_D` for each candidate's closed-window storage. ```text -z_{i,D} ∈ {0, 1} for (i, D) ∈ E -u_D ∈ {0, 1} for D ∈ candidates -M ≥ 0 +z_{i,D} ∈ {0, 1} for (i, D) ∈ E +u_D ∈ {0, 1} for D ∈ candidates +stored_D ≥ 0 -Σ_{D: (i,D) ∈ E} z_{i,D} = 1 for every RQE i +Σ_{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 -M ≥ query_memory_{i,D} × z_{i,D} for (i, D) ∈ E +stored_D ≥ w(storage_{i,D}) × z_{i,D} for (i, D) ∈ E ``` -The final `u_D` constraint prevents a deployment from becoming active when no -RQE selected it. It is not required for feasibility, but makes ingest cost -unambiguous. - -All CPU and latency terms are constants for an eligible pair. The solver uses: - -```text -TCO_cpu = Σ_D ingest_cpu_D × u_D - + Σ_(i,D)∈E (query_cpu_{i,D} + merge_cpu_{i,D}) / T_i × z_{i,D} - -latency_i = Σ_{D: (i,D)∈E} latency_{i,D} × z_{i,D} -``` +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. -`minimize_cost` instead prices the plan on one EC2 machine family `f` (vCPUs -`vcpu_f`, memory `gib_f`, hourly price `price_f`) in fractional instances -`n_f`, with a continuous `R_D ≥ 0` for each candidate's retained GiB: +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 price_f × n_f -R_D ≥ retained_gib_{i,D} × z_{i,D} for (i, D) ∈ E -vcpu_f × n_f ≥ TCO_cpu -gib_f × n_f ≥ Σ_D R_D +minimize Σ_D w(ingest_D) × u_D + + Σ_(i,D)∈E (w(merge_{i,D}) + w(query_{i,D})) × z_{i,D} + + Σ_D stored_D ``` -Prices come from `rqe-optimizer/data/ec2-pricing-.json`, written by -`scripts/fetch_ec2_pricing.py`. Disk is not priced. +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. -One solve needs a scalar objective, such as minimum `TCO_cpu` subject to -`M ≤ memory_budget` and optional `latency_i ≤ latency_budget_i`. To sample the -Pareto frontier, repeat solves over memory and latency budgets, or use a -normalized weighted objective. The solver never enumerates full mappings. +Per-RAQE latency bounds forbid the pairs over them (`z_{i,D} = 0`). The solver +never enumerates full mappings. ## Analytical cost model @@ -210,77 +275,96 @@ The analytical model combines the empirical per-operation Sketch Bench measurements with workload properties such as group cardinality, arrival rate, window size, and query frequency. -For deployment `D`, let `a_D = D.x / D.y`. Each incoming item is inserted into -`a_D` concurrently active sketch instances per group. - -### Query working memory - -v1 models query working memory, not retained-storage footprint. For RQE `i`: +For deployment `D` serving RAQE `i`: + +- `lambda`: samples/sec arriving for `D`'s metric, `card(metric.labels) / scrape_interval`. +- `card(G)`: cardinality of `G`, so the number of parallel accumulator instances per window. +- `x`, `y`: `D`'s window and slide. +- `a_D = x / y`: open windows; each sample is inserted into `a_D` instances of its group. +- `S_i`, `T_i`: RAQE `i`'s lookback and interval. +- `n_i = S_i / x`: windows merged per query. +- `m`: memory per instance, measured. +- `c_ins`: CPU per insert, measured. +- `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/export_rqe_optimizer_costs.sh`](../scripts/export_rqe_optimizer_costs.sh)) +is measured on one instance, at whatever key count the benchmark fed it +(`measured_keys`). A key is one distinct entry an instance stores exactly, +such as one group's running sum in an exact accumulator. Turning a row into a +deployment's cost needs two properties of the family: + +- **Shape**: instances per window. `PerGroup` keeps one per group, so + `card(G)`; `Shared` keeps one for all groups. +- **Law**: how one instance's size grows. `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 fixed at k = 32) | `card(G) × m × keys_per_group / measured_keys`: none yet (e.g. an exact top-k map) | +| **Shared** | `m`: HydraKLL and other Hydra sketches | `m × card(G) / measured_keys`: exact sum, min, max, increase (one value per group, so keys = groups) | + +The same factor scales merge and query CPU. Insert CPU is per sample and does +not scale. + +Quantile sketches have no keys, but are not strictly fixed either: KLL grows +slowly with the number of values inserted (about `k × log(n / k)`), and +DDSketch with the range of values. The model treats them as Fixed at the size +the export measured (1,000,000 values per instance), so it misstates instances +that see far fewer or far more values. + +The model uses one formula, `card(G) × m`, which is right for both cells in +use: + +- PerGroup + Fixed is that formula as is. +- Shared + PerKey reduces to it because the export divides the exact + accumulators' memory and merge cost by `measured_keys` + (`groups_per_instance`), making `m` a per-group cost. Their query cost is + already per group. + +The other two cells are deferred until a family needs them: Shared + Fixed +would be overpriced by `card(G)` (sketch-bench#142), and PerGroup + PerKey +needs the key labels `K`, the metric's labels minus `G`. So for every family +in use, nothing scales with keys below the group: a per-service top-k CMS +costs the same however many endpoints it counts. + +Per-RAQE latency is the serial CPU time of one query: ```text -query_memory_i = card(labels_i) × mem_bytes(D(i).configuration) +latency_i = card(G) × (c_qry + (n_i − 1) × c_mrg) ``` -This assumes one instance per group is loaded and groups are processed -concurrently. It does not model merge buffers or concurrent queries. - -The mapping-level memory objective is the worst individual query: - -```text -peak_query_memory = max_i query_memory_i -``` - -### Retained memory - -A deployment holds `x / y` open instances plus the closed instances still -inside the longest lookback it serves: - -```text -retained_memory = Σ_{D: u_D=1} card(D.labels) × mem_bytes(D.configuration) - × (D.x + max_{i: D(i)=D} S_i) / D.y -``` - -### CPU - -Ingest CPU is paid once for every active deployment: - -```text -ingest_cpu = Σ_{D: u_D=1} - lambda(D.labels) × a_D × insert_cpu_secs(D.configuration) -``` - -For RQE `i`, let `n_i = S_i / D(i).x`. One query performs one final estimate -and `n_i - 1` pairwise merges for each group: - -```text -query_cpu_i = card(labels_i) × query_cpu_secs(D(i).configuration) -merge_cpu_i = card(labels_i) × (n_i - 1) × merge_cpu_secs(D(i).configuration) -latency_i = query_cpu_i + merge_cpu_i -``` - -`latency_i` is estimated serial CPU time for one query, not a wall-clock SLA. -It assumes no parallel execution across groups and no cheaper k-way merge. - -The repeating query load is: - -```text -query_cpu = Σ_i query_cpu_i / T_i -merge_cpu = Σ_i merge_cpu_i / T_i -``` - -Total steady-state CPU is: - -```text -TCO_cpu = ingest_cpu + merge_cpu + query_cpu -``` +It is not a wall-clock SLA: it assumes no parallel execution across groups and +no cheaper k-way merge. ## Procedure -1. Generate candidate deployments for each input RQE, then deduplicate them. -2. Build the eligible candidate–RQE pairs. Reject pairs that fail capability, - labels, window alignment, or empirical accuracy. -3. Enumerate feasible workload mappings. Every RQE must select one eligible - candidate; a single selected candidate may serve multiple RQEs. Small +1. Generate candidate deployments for each input RAQE, then deduplicate them. +2. Build the eligible candidate–RAQE pairs. Reject pairs that fail capability, + metric, grouping, window alignment, or empirical accuracy. +3. Enumerate feasible workload mappings. Every RAQE must select one eligible + candidate; a single selected candidate may serve multiple RAQEs. Small instances may retain every mapping eagerly; larger ones stream mappings through incremental Pareto filtering, retaining only the current frontier. 4. Score every complete mapping with the analytical cost model. @@ -289,28 +373,30 @@ TCO_cpu = ingest_cpu + merge_cpu + query_cpu The Pareto vector is: ```text -(peak_query_memory, TCO_cpu, {latency_i}) +(CPU, memory, {latency_i}) ``` -The report also includes `ingest_cpu`, `merge_cpu`, and `query_cpu` as the -breakdown of `TCO_cpu`, together with the selected deployment mapping. +CPU and memory are the sums over the four phases. The report also includes +each phase's CPU and memory, together with the selected deployment mapping. ## v1 scope and TODOs - **Accuracy after merging:** v1 uses the measured, single-instance accuracy of a configuration. Measure or model merged accuracy before relying on a selected mapping as truly accuracy-feasible. -- **Query-result sharing:** v1 charges every RQE its own query and merge CPU. - Revisit when RQE semantics and execution timing identify safe reuse cases. -- **Latency SLAs:** v1 reports per-RQE latency but does not reject a mapping - for exceeding a target. Add optional per-RQE maximum latency as a hard - constraint when workloads supply targets. -- **Memory model:** merge buffers and concurrent queries are not modeled. -- **Static planning:** no RQE churn, replanning, or migration cost. +- **Query-result sharing:** v1 charges every RAQE its own query and merge CPU. + Revisit when RAQE semantics and execution timing identify safe reuse cases. +- **Latency SLAs:** the MILP takes optional per-RAQE latency bounds; the + enumerator reports latency but does not reject a mapping for it. +- **Memory model:** query memory sums every RAQE's merge and output memory, as + if all queries run at once; real concurrency is not modeled. Query output + size is an estimate. +- **Bursts:** CPU is a mean over time, so plans are sized for average load. +- **Static planning:** no RAQE churn, replanning, or migration cost. - **Rollups:** v1 does not precompute merged rollups. Queries merge their selected base instances when they run. -- **Selection policy:** the optimizer reports the Pareto frontier; selecting a - single point through weights or budgets is deferred. +- **Selection policy:** the enumerator reports the Pareto frontier; the MILP + selects one point by the `w_cpu`/`w_mem` weights. ## Implementation status diff --git a/rqe-optimizer/data/ec2-pricing-2026-10-04.json b/rqe-optimizer/data/ec2-pricing-2026-10-04.json deleted file mode 100644 index 49741bbd..00000000 --- a/rqe-optimizer/data/ec2-pricing-2026-10-04.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "source": "https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/ec2/USD/current/ec2-ondemand-without-sec-sel/US%20East%20(N.%20Virginia)/Linux/index.json", - "region": "US East (N. Virginia)", - "operating_system": "Linux", - "pricing": "on-demand", - "publication_date": "2026-09-25T17:45:21Z", - "fetched": "2026-10-04", - "families": [ - { - "family": "compute_optimized", - "instance_type": "c7i.xlarge", - "vcpu": 4, - "memory_gib": 8.0, - "usd_per_hour": 0.1785, - "rate_code": "D8WVCVBE32N227KA.JRTCKXETXF.6YS6EN2CT7" - }, - { - "family": "general_purpose", - "instance_type": "m7i.xlarge", - "vcpu": 4, - "memory_gib": 16.0, - "usd_per_hour": 0.2016, - "rate_code": "W8MD4QK5G3J3QYWR.JRTCKXETXF.6YS6EN2CT7" - }, - { - "family": "memory_optimized", - "instance_type": "r7i.xlarge", - "vcpu": 4, - "memory_gib": 32.0, - "usd_per_hour": 0.2646, - "rate_code": "PRGSWU6294SJ3Z93.JRTCKXETXF.6YS6EN2CT7" - } - ] -} diff --git a/rqe-optimizer/examples/small_problem.rs b/rqe-optimizer/examples/small_problem.rs index 354c8967..0bfec499 100644 --- a/rqe-optimizer/examples/small_problem.rs +++ b/rqe-optimizer/examples/small_problem.rs @@ -9,9 +9,9 @@ //! no translation layer, since `rqe_optimizer::Deployment` embeds //! `AtomicCostEntry` directly. //! -//! Every other number this example uses (RQE definitions, label-set -//! cardinality/arrival-rate) lives in the two tables below (`label_sets`, -//! `rqes`) and nowhere else in this file. +//! Every other number this example uses (RQE definitions, metric labels, +//! cardinalities and scrape intervals) lives in the two tables below +//! (`facts`, `rqes`) and nowhere else in this file. //! //! Run: `scripts/export_rqe_optimizer_costs.sh` once. Do not run this example //! with no mode flag on a large workload: eager mode retains every feasible @@ -20,25 +20,25 @@ //! `--candidates-only` to inspect candidate pruning safely, without starting //! mapping enumeration. Streaming mode logs progress every one million //! mappings by default; pass `--progress-every N` to change that interval or -//! `--print-first N` to display example mappings. `--milp` solves the -//! minimum-TCO model without enumerating mappings. Repeat -//! `--latency-limit RQE_ID=SECONDS` to impose MILP latency bounds. Add -//! `--machine-family NAME` (`compute_optimized`, `general_purpose`, -//! `memory_optimized`) to minimize that EC2 family's hourly price instead. +//! `--print-first N` to display example mappings. `--milp` minimizes +//! `w_cpu · CPU + w_mem · memory GiB` without enumerating mappings; set the +//! weights with `--w-cpu X --w-mem Y` (default 1 and 0). Repeat +//! `--latency-limit RQE_ID=SECONDS` to impose MILP latency bounds. //! `--sample-mappings N` prints N feasible mappings and exits. use std::collections::BTreeSet; use std::time::Instant; +use rqe_optimizer::analytical_cost_model::{score, PlanCost}; use rqe_optimizer::candidates::{ build_all_candidates, build_all_candidates_unpruned, eligible_deployments_for, }; use rqe_optimizer::enumerate::{brute_force, for_each_mapping, for_each_mapping_while, unservable}; -use rqe_optimizer::milp::{minimize_cost, minimize_tco, MilpBounds}; -use rqe_optimizer::objectives::{score, MachineFamily}; +use rqe_optimizer::milp::{minimize, MilpBounds, Objective}; use rqe_optimizer::pareto::{pareto_front, ParetoFront}; use rqe_optimizer::{ - AccuracyDirection, AtomicCostTable, Capability, LabelSet, LabelSetInfo, LabelSetTable, Rqe, + validate_facts, AccuracyDirection, AtomicCostTable, Capability, LabelSet, MetricFacts, Rqe, + WorkloadFacts, }; /// Accuracy metric keys the real comparators actually report (checked @@ -57,22 +57,9 @@ const CARDINALITY_ERR: &str = "relative_error"; const TOPK_PRECISION: &str = "precision_at_k"; const COST_TABLE_PATH: &str = "out/rqe_atomic_costs.json"; -const EC2_PRICING: &str = include_str!("../data/ec2-pricing-2026-10-04.json"); -fn machine_family() -> Option { - let args: Vec<_> = std::env::args().collect(); - let name = args - .windows(2) - .find(|pair| pair[0] == "--machine-family") - .map(|pair| pair[1].clone())?; - let families = MachineFamily::from_pricing_json(EC2_PRICING).expect("committed snapshot"); - Some( - families - .into_iter() - .find(|family| family.family == name) - .unwrap_or_else(|| panic!("unknown --machine-family: {name}")), - ) -} +const REQUESTS: &str = "http_requests_total"; +const DURATION: &str = "http_request_duration_seconds"; fn label_set(names: &[&str]) -> LabelSet { names.iter().map(|s| s.to_string()).collect() @@ -89,36 +76,39 @@ fn load_cost_table() -> AtomicCostTable { .unwrap_or_else(|e| panic!("{COST_TABLE_PATH} isn't a valid AtomicCostTable: {e}")) } -fn label_sets() -> LabelSetTable { - let mut t = LabelSetTable::new(); - // labels cardinality arrival_rate (items/sec) - t.insert( - label_set(&["service", "endpoint"]), - LabelSetInfo { - cardinality: 50, - arrival_rate_per_sec: 2_000.0, - }, - ); - t.insert( - label_set(&["service"]), - LabelSetInfo { - cardinality: 5, - arrival_rate_per_sec: 2_000.0, - }, - ); - t +/// Both metrics: 5 services × 10 endpoints × 600 pods = 30,000 series +/// scraped every 15 s, so `λ` = 2,000 samples/sec each. +fn facts() -> WorkloadFacts { + let http_metric_facts = || MetricFacts { + labels: label_set(&["service", "endpoint", "pod"]), + scrape_interval_secs: 15, + cardinality: [ + (label_set(&["service"]), 5), + (label_set(&["service", "endpoint"]), 50), + (label_set(&["service", "endpoint", "pod"]), 30_000), + ] + .into(), + }; + [ + (REQUESTS.to_string(), http_metric_facts()), + (DURATION.to_string(), http_metric_facts()), + ] + .into() } fn rqes() -> Vec { let se = label_set(&["service", "endpoint"]); let s = label_set(&["service"]); + let requests = || REQUESTS.to_string(); + let duration = || DURATION.to_string(); vec![ Rqe { id: "req_rate_1h".to_string(), capability: Capability::RateOrIncrease, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -128,7 +118,8 @@ fn rqes() -> Vec { capability: Capability::RateOrIncrease, lookback_secs: 86_400, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -138,7 +129,8 @@ fn rqes() -> Vec { capability: Capability::RateOrIncrease, lookback_secs: 3_600, interval_secs: 300, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: RATE_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -148,7 +140,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -158,7 +151,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 21_600, interval_secs: 300, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -168,7 +162,8 @@ fn rqes() -> Vec { capability: Capability::Quantile, lookback_secs: 86_400, interval_secs: 60, - labels: se.clone(), + metric: duration(), + grouping_labels: se.clone(), accuracy_metric: RANK_ERR.to_string(), accuracy_tolerance: 0.05, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -178,7 +173,8 @@ fn rqes() -> Vec { capability: Capability::Cardinality, lookback_secs: 3_600, interval_secs: 60, - labels: s.clone(), + metric: requests(), + grouping_labels: s.clone(), accuracy_metric: CARDINALITY_ERR.to_string(), accuracy_tolerance: 0.1, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -192,7 +188,8 @@ fn rqes() -> Vec { capability: Capability::TopK, lookback_secs: 3_600, interval_secs: 60, - labels: se.clone(), + metric: requests(), + grouping_labels: se.clone(), accuracy_metric: TOPK_PRECISION.to_string(), accuracy_tolerance: 0.9, accuracy_direction: AccuracyDirection::HigherIsBetter, @@ -236,10 +233,11 @@ fn print_mapping( fn print_candidate(candidate_number: usize, deployment: &rqe_optimizer::Deployment) { println!( - "candidate {candidate_number}: {} {} labels={:?} (x={}s, y={}s)", + "candidate {candidate_number}: {} {} {} by {:?} (x={}s, y={}s)", deployment.config.sketch, deployment.config.sketch_config, - deployment.labels, + deployment.metric, + deployment.grouping_labels, deployment.window_secs, deployment.slide_secs, ); @@ -269,15 +267,50 @@ fn latency_bounds(rqes: &[Rqe]) -> Vec> { bounds } +fn weight_flag(name: &str, default: f64) -> f64 { + let args: Vec<_> = std::env::args().collect(); + match args.iter().position(|arg| arg == name) { + Some(index) => args + .get(index + 1) + .and_then(|value| value.parse::().ok()) + .filter(|value| *value >= 0.0) + .unwrap_or_else(|| panic!("{name} requires a non-negative number")), + None => default, + } +} + +fn print_plan_cost(label: &str, plan_cost: &PlanCost) { + println!( + "{label}: cpu={:.3e} cpu-sec/sec, memory={:.1}MB", + plan_cost.cpu_secs_per_sec(), + plan_cost.memory_bytes() / 1e6, + ); + for (phase, cost) in [ + ("ingest", &plan_cost.ingest), + ("merge", &plan_cost.merge), + ("query", &plan_cost.query), + ("storage", &plan_cost.storage), + ] { + println!( + " {phase:<7} cpu={:.3e} memory={:.1}MB", + cost.cpu_secs_per_sec, + cost.memory_bytes / 1e6, + ); + } +} + fn main() { let candidates_only = std::env::args().any(|arg| arg == "--candidates-only"); let rqes = rqes(); let cost_table = load_cost_table(); - let label_sets = label_sets(); + let facts = facts(); + if let Err(problems) = validate_facts(&rqes, &facts) { + panic!("invalid workload facts: {problems:#?}"); + } let unpruned_count = - candidates_only.then(|| build_all_candidates_unpruned(&rqes, &cost_table).len()); - let deployments = build_all_candidates(&rqes, &cost_table); + candidates_only.then(|| build_all_candidates_unpruned(&rqes, &cost_table, &facts).len()); + let deployments = build_all_candidates(&rqes, &cost_table, &facts); println!( "{} RQEs, {} candidate deployments (from {} real cost-table rows)", rqes.len(), @@ -342,36 +375,21 @@ fn main() { if std::env::args().any(|arg| arg == "--milp") { let bounds = MilpBounds { - max_peak_query_memory_bytes: None, max_query_latency_secs: latency_bounds(&rqes), }; - let family = machine_family(); - let solution = match &family { - Some(family) => minimize_cost(&rqes, &deployments, &label_sets, &bounds, family), - None => minimize_tco(&rqes, &deployments, &label_sets, &bounds), - } - .expect("small_problem MILP should be feasible"); - if let Some(family) = &family { - println!( - "MILP minimum-cost solution on {}: ${:.4}/hour, {:.4} instances, \ - retained_mem={:.0}MB", - family.family, - family.usd_per_hour(&solution.objectives), - family.instances(&solution.objectives), - solution.objectives.retained_memory_bytes / 1e6, - ); - } + let objective = Objective::AUCCost { + w_cpu: weight_flag("--w-cpu", 1.0), + w_mem: weight_flag("--w-mem", 0.0), + }; + let solution = minimize(&rqes, &deployments, &facts, &bounds, objective) + .expect("small_problem MILP should be feasible"); println!( - "MILP solution: peak_query_mem={:.0}MB, ingest={:.3e}, \ - merge={:.3e}, query={:.3e}, total={:.3e} cpu-sec/sec", - solution.objectives.peak_query_memory_bytes / 1e6, - solution.objectives.ingest_cpu_secs_per_sec, - solution.objectives.merge_cpu_secs_per_sec, - solution.objectives.query_cpu_secs_per_sec, - solution.objectives.tco_cpu_secs_per_sec, + "MILP solution for {objective:?}: {:.3e}", + objective.value(&solution.plan_cost) ); + print_plan_cost(" totals", &solution.plan_cost); print_mapping(1, &solution.mapping, &rqes, &deployments); - for (rqe, latency) in rqes.iter().zip(&solution.objectives.query_latency_secs) { + for (rqe, latency) in rqes.iter().zip(&solution.plan_cost.query_latency_secs) { println!(" {}: query_latency={latency:.3e} sec", rqe.id); } return; @@ -384,7 +402,7 @@ fn main() { let started = Instant::now(); let mut processed = 0_u64; let mapping_count = for_each_mapping(&rqes, &deployments, |mapping| { - front.consider(mapping, score(&rqes, &deployments, mapping, &label_sets)); + front.consider(mapping, score(&rqes, &deployments, mapping, &facts)); processed += 1; if processed <= print_first { print_mapping(processed, mapping, &rqes, &deployments); @@ -413,29 +431,23 @@ fn main() { let mappings = brute_force(&rqes, &deployments); println!("{} feasible full mappings", mappings.len()); - let objectives: Vec<_> = mappings + let plan_costs: Vec<_> = mappings .iter() - .map(|m| score(&rqes, &deployments, m, &label_sets)) + .map(|m| score(&rqes, &deployments, m, &facts)) .collect(); - let front = pareto_front(&objectives); + let front = pareto_front(&plan_costs); println!("{} on the Pareto front\n", front.len()); let mut front = front; front.sort_unstable(); for &i in &front { - let obj = &objectives[i]; + let plan_cost = &plan_costs[i]; let distinct_deployments: BTreeSet = mappings[i].iter().copied().collect(); - println!( - "mapping {i}: {} deployments, peak_query_mem={:.0}MB, ingest={:.3e}, \ - merge={:.3e}, query={:.3e}, total={:.3e} cpu-sec/sec", - distinct_deployments.len(), - obj.peak_query_memory_bytes / 1e6, - obj.ingest_cpu_secs_per_sec, - obj.merge_cpu_secs_per_sec, - obj.query_cpu_secs_per_sec, - obj.tco_cpu_secs_per_sec, + print_plan_cost( + &format!("mapping {i}: {} deployments", distinct_deployments.len()), + plan_cost, ); - for (rqe, latency) in rqes.iter().zip(&obj.query_latency_secs) { + for (rqe, latency) in rqes.iter().zip(&plan_cost.query_latency_secs) { let rqe_id = &rqe.id; println!(" {rqe_id}: query_latency={latency:.3e} sec"); } diff --git a/rqe-optimizer/src/analytical_cost_model.rs b/rqe-optimizer/src/analytical_cost_model.rs new file mode 100644 index 00000000..28161846 --- /dev/null +++ b/rqe-optimizer/src/analytical_cost_model.rs @@ -0,0 +1,253 @@ +//! Analytical scoring built from measured per-operation costs (§5). +//! +//! Costs split into four phases, each with CPU and memory: +//! - ingest: inserts into open windows, and their state; +//! - merge: folding a query's windows, and the merged state; +//! - query: reading the merged state, and the output; +//! - storage: closed windows kept for lookbacks (no CPU). +//! +//! [`score`] and the MILP share the per-phase functions below. +//! +//! Measured costs are per instance, and a deployment holds `card(G)` instances +//! per window. Exact accumulators hold many groups in one instance, but the +//! export divides their memory and merge cost by the group count, so +//! `card(G) ×` prices them correctly too. +// ponytail: a family with one fixed-size instance for all groups (HydraKLL, +// sketch-bench#142) needs a per-family shape so it isn't multiplied by card(G). + +use crate::{Capability, Deployment, Mapping, Rqe, WorkloadFacts}; +use std::collections::{BTreeMap, BTreeSet}; + +pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; + +/// Query output per group: one f64. +// ponytail: estimated, not measured; tiny next to sketch state. +pub const OUTPUT_BYTES_PER_VALUE: f64 = 8.0; +/// Query output per top-k entry: a 64-bit key hash and a count. +pub const OUTPUT_BYTES_PER_TOPK_ENTRY: f64 = 16.0; +/// Top-k entries per group: the heap size every top-k cost row was measured +/// at (sketch-bench's `CMS_HEAP_TOP_K`). +// ponytail: fixed k. A large k needs `k` on the RQE and a benchmark that +// varies the heap, whose memory the export leaves out. +pub const TOPK_ENTRIES: f64 = 32.0; + +/// One phase's resource use. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct PhaseCost { + /// Mean CPU-seconds per second: the area under the CPU curve over time. + pub cpu_secs_per_sec: f64, + pub memory_bytes: f64, +} + +impl std::ops::AddAssign for PhaseCost { + fn add_assign(&mut self, other: Self) { + self.cpu_secs_per_sec += other.cpu_secs_per_sec; + self.memory_bytes += other.memory_bytes; + } +} + +#[derive(Debug, Clone)] +pub struct PlanCost { + /// Paid once per active deployment. + pub ingest: PhaseCost, + /// Paid per RQE; memory as if every query runs at once. + pub merge: PhaseCost, + /// Paid per RQE; memory as if every query runs at once. + pub query: PhaseCost, + /// Paid once per active deployment, sized for its longest lookback. + pub storage: PhaseCost, + /// Index-aligned with the input RQE slice; display IDs need not be unique. + pub query_latency_secs: Vec, +} + +impl PlanCost { + pub fn cpu_secs_per_sec(&self) -> f64 { + self.phases().map(|phase| phase.cpu_secs_per_sec).sum() + } + + pub fn memory_bytes(&self) -> f64 { + self.phases().map(|phase| phase.memory_bytes).sum() + } + + fn phases(&self) -> impl Iterator { + [&self.ingest, &self.merge, &self.query, &self.storage].into_iter() + } +} + +/// `card(G)`: cardinality of `G`, so the number of parallel accumulator +/// instances per window. +fn group_count(deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + facts[&deployment.metric].cardinality[&deployment.grouping_labels] as f64 +} + +/// `x / y`: windows each sample is inserted into. +fn open_window_count(deployment: &Deployment) -> f64 { + deployment + .active_instance_count() + .expect("candidate window and slide align") as f64 +} + +/// `L / x`: windows merged per query. +fn merged_window_count(rqe: &Rqe, deployment: &Deployment) -> f64 { + deployment + .query_instance_count(rqe.lookback_secs) + .expect("only eligible pairs are costed") as f64 +} + +/// CPU `λ · (x/y) · c_ins`; memory `card(G) · m · (x/y)`. +pub(crate) fn ingest(deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let open_windows = open_window_count(deployment); + PhaseCost { + cpu_secs_per_sec: facts[&deployment.metric].arrival_rate_per_sec() + * open_windows + * deployment.config.insert_cpu_secs, + memory_bytes: group_count(deployment, facts) + * deployment.config.mem_bytes_per_instance + * open_windows, + } +} + +/// CPU `card(G) · (L/x − 1) · c_mrg / T`; memory `card(G) · m`, one +/// accumulator per group. A direct query (`L == x`) merges nothing and costs +/// neither. +pub(crate) fn merge(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = group_count(deployment, facts); + let merges_per_group = merged_window_count(rqe, deployment) - 1.0; + PhaseCost { + cpu_secs_per_sec: groups * merges_per_group * deployment.config.merge_cpu_secs + / rqe.interval_secs as f64, + memory_bytes: groups * merge_memory_per_group(rqe, deployment), + } +} + +/// One accumulator if the query merges at all. +pub(crate) fn merge_memory_per_group(rqe: &Rqe, deployment: &Deployment) -> f64 { + if merged_window_count(rqe, deployment) > 1.0 { + deployment.config.mem_bytes_per_instance + } else { + 0.0 + } +} + +/// CPU `card(G) · c_qry / T`; memory `card(G) ·` output bytes per group. +pub(crate) fn query(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> PhaseCost { + let groups = group_count(deployment, facts); + let output_bytes_per_group = match rqe.capability { + Capability::TopK => TOPK_ENTRIES * OUTPUT_BYTES_PER_TOPK_ENTRY, + _ => OUTPUT_BYTES_PER_VALUE, + }; + PhaseCost { + cpu_secs_per_sec: groups * deployment.config.query_cpu_secs / rqe.interval_secs as f64, + memory_bytes: groups * output_bytes_per_group, + } +} + +/// Closed windows kept to answer `rqe`: `card(G) · m · ((L − x)/y + 1)`. +pub(crate) fn storage_bytes(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let closed_windows = deployment + .closed_instance_count(rqe.lookback_secs) + .expect("only eligible pairs are costed") as f64; + group_count(deployment, facts) * deployment.config.mem_bytes_per_instance * closed_windows +} + +/// Serial CPU time of one query: `card(G) · (c_qry + (L/x − 1) · c_mrg)`. +pub(crate) fn query_latency_secs(rqe: &Rqe, deployment: &Deployment, facts: &WorkloadFacts) -> f64 { + let merges_per_group = merged_window_count(rqe, deployment) - 1.0; + group_count(deployment, facts) + * (deployment.config.query_cpu_secs + merges_per_group * deployment.config.merge_cpu_secs) +} + +pub fn score( + rqes: &[Rqe], + deployments: &[Deployment], + mapping: &Mapping, + facts: &WorkloadFacts, +) -> PlanCost { + assert_eq!( + mapping.len(), + rqes.len(), + "mapping must have one deployment per RQE" + ); + let active_deployments: BTreeSet = mapping.iter().copied().collect(); + let mut ingest_cost = PhaseCost::default(); + for &deployment_index in &active_deployments { + ingest_cost += ingest(&deployments[deployment_index], facts); + } + + let mut storage_bytes_by_deployment: BTreeMap = BTreeMap::new(); + let mut merge_cost = PhaseCost::default(); + let mut query_cost = PhaseCost::default(); + let query_latency_secs = rqes + .iter() + .zip(mapping) + .map(|(rqe, &deployment_index)| { + let deployment = &deployments[deployment_index]; + let stored = storage_bytes_by_deployment + .entry(deployment_index) + .or_default(); + *stored = stored.max(storage_bytes(rqe, deployment, facts)); + merge_cost += merge(rqe, deployment, facts); + query_cost += query(rqe, deployment, facts); + query_latency_secs(rqe, deployment, facts) + }) + .collect(); + + PlanCost { + ingest: ingest_cost, + merge: merge_cost, + query: query_cost, + storage: PhaseCost { + cpu_secs_per_sec: 0.0, + memory_bytes: storage_bytes_by_deployment.values().sum(), + }, + query_latency_secs, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::{deployment, facts, rqe}; + + #[test] + fn scores_each_phase() { + // 4 groups and 7 samples/sec. Window 20 s sliding by 10 s: 2 open + // windows. Lookback 60 s every 30 s: 3 windows merged, and + // (60 − 20)/10 + 1 = 5 closed windows stored. + let deployment = deployment(10.0, 2.0, 3.0, 5.0, 20, 10); + let result = score(&[rqe(60, 30)], &[deployment], &vec![0], &facts(4, 7)); + + assert_eq!(result.ingest.cpu_secs_per_sec, 28.0); // 7 × 2 × 2 + assert_eq!(result.ingest.memory_bytes, 80.0); // 4 × 10 × 2 + assert_eq!(result.merge.cpu_secs_per_sec, 24.0 / 30.0); // 4 × 2 × 3 / 30 + assert_eq!(result.merge.memory_bytes, 40.0); // 4 × 10 + assert_eq!(result.query.cpu_secs_per_sec, 20.0 / 30.0); // 4 × 5 / 30 + assert_eq!(result.query.memory_bytes, 2048.0); // 4 × 32 × 16 + assert_eq!(result.storage.cpu_secs_per_sec, 0.0); + assert_eq!(result.storage.memory_bytes, 200.0); // 4 × 10 × 5 + assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 + 2 × 3) + assert!((result.cpu_secs_per_sec() - (28.0 + 44.0 / 30.0)).abs() < 1e-12); + assert_eq!(result.memory_bytes(), 80.0 + 40.0 + 2048.0 + 200.0); + } + + #[test] + fn a_direct_query_stores_one_closed_window_and_never_merges() { + let deployment = deployment(10.0, 1.0, 1.0, 1.0, 60, 60); + let result = score(&[rqe(60, 60)], &[deployment], &vec![0], &facts(1, 1)); + assert_eq!(result.storage.memory_bytes, 10.0); + assert_eq!(result.merge, PhaseCost::default()); + } + + #[test] + fn shared_deployment_stores_for_its_longest_lookback() { + let deployment = deployment(10.0, 1.0, 1.0, 1.0, 10, 10); + let rqes = [rqe(60, 10), rqe(600, 10)]; + let result = score(&rqes, &[deployment], &vec![0, 0], &facts(2, 2)); + // 2 groups × 10 bytes × ((600 − 10)/10 + 1) closed windows. + assert_eq!(result.storage.memory_bytes, 1200.0); + // Ingest is paid once; merge once per RQE. + assert_eq!(result.ingest.cpu_secs_per_sec, 2.0); + // Two RQEs × 2 groups × 10 bytes. + assert_eq!(result.merge.memory_bytes, 2.0 * 2.0 * 10.0); + } +} diff --git a/rqe-optimizer/src/autosketch.rs b/rqe-optimizer/src/autosketch.rs index f650117c..74c0a464 100644 --- a/rqe-optimizer/src/autosketch.rs +++ b/rqe-optimizer/src/autosketch.rs @@ -72,7 +72,8 @@ pub fn plan( let (window_secs, slide_secs) = window_adapter(rqe); Deployment { capability: rqe.capability, - labels: rqe.labels.clone(), + metric: rqe.metric.clone(), + grouping_labels: rqe.grouping_labels.clone(), config: costs[s.selected.expect("unservable RQEs returned above")].clone(), window_secs, slide_secs, @@ -320,9 +321,10 @@ impl Rng { #[cfg(test)] mod tests { use super::*; + use crate::analytical_cost_model::{score, PhaseCost}; use crate::candidates::is_eligible; - use crate::objectives::score; - use crate::{AccuracyDirection, Capability, LabelSet, LabelSetInfo, LabelSetTable}; + use crate::test_support::{facts, METRIC}; + use crate::{AccuracyDirection, Capability, LabelSet}; use std::collections::BTreeSet; const ERR: &str = "err"; @@ -355,7 +357,8 @@ mod tests { capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: ERR.into(), accuracy_tolerance: tolerance, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -409,18 +412,15 @@ mod tests { assert_eq!(plan.deployments[0], plan.deployments[1]); assert_eq!(plan.mapping, vec![0, 1]); - let labels: LabelSetTable = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 10.0, - }, - )]); - let both = score(&rqes, &plan.deployments, &plan.mapping, &labels); - let one = score(&rqes[..1], &plan.deployments[..1], &vec![0], &labels); + let facts = facts(1, 10); + let both = score(&rqes, &plan.deployments, &plan.mapping, &facts); + let one = score(&rqes[..1], &plan.deployments[..1], &vec![0], &facts); assert_eq!( - both.ingest_cpu_secs_per_sec, - 2.0 * one.ingest_cpu_secs_per_sec + both.ingest, + PhaseCost { + cpu_secs_per_sec: 2.0 * one.ingest.cpu_secs_per_sec, + memory_bytes: 2.0 * one.ingest.memory_bytes, + } ); } diff --git a/rqe-optimizer/src/candidates.rs b/rqe-optimizer/src/candidates.rs index e8dc0540..bf522f13 100644 --- a/rqe-optimizer/src/candidates.rs +++ b/rqe-optimizer/src/candidates.rs @@ -1,6 +1,7 @@ //! Candidate generation and eligibility (§3). -use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds}; +use crate::analytical_cost_model::merge_memory_per_group; +use crate::{AtomicCostEntry, Capability, Deployment, LabelSet, Rqe, Seconds, WorkloadFacts}; use std::collections::{BTreeMap, BTreeSet}; pub fn gcd(a: Seconds, b: Seconds) -> Seconds { @@ -27,30 +28,40 @@ fn divisors(value: Seconds) -> Vec { out } -/// Every gcd reachable from a non-empty subset, folded incrementally rather -/// than by enumerating the powerset. +/// The gcd of every non-empty subset of `values`, in one pass without listing +/// subsets: `gcd(A ∪ {v}) = gcd(gcd(A), v)`, so each new value extends every +/// gcd found so far. fn subset_gcds(values: impl IntoIterator) -> BTreeSet { - let mut out = BTreeSet::new(); + let mut gcds = BTreeSet::new(); for value in values { - let extensions: Vec<_> = out.iter().map(|&previous| gcd(previous, value)).collect(); - out.insert(value); - out.extend(extensions); + let extended: Vec<_> = gcds.iter().map(|&found| gcd(found, value)).collect(); + gcds.insert(value); + gcds.extend(extended); } - out + gcds } -fn candidate_deployments(group: &[&Rqe], costs: &[AtomicCostEntry]) -> Vec { +/// Windows and slides are multiples of the metric's scrape interval: anything +/// finer only splits one scrape's samples. +fn candidate_deployments( + group: &[&Rqe], + costs: &[AtomicCostEntry], + scrape_interval_secs: Seconds, +) -> Vec { if group.is_empty() { return Vec::new(); } let capability = group[0].capability; - let labels = group[0].labels.clone(); let windows = group .iter() .flat_map(|r| divisors(r.lookback_secs)) + .filter(|window_secs| window_secs.is_multiple_of(scrape_interval_secs)) .collect::>(); let mut deployments = Vec::new(); for window_secs in windows { + // gcd(x, T) is the largest slide that serves an RQE. For RQEs sharing a + // deployment, the gcd of theirs is strictly better than any finer + // slide that serves them all. Any subset might share. let slides = subset_gcds( group .iter() @@ -61,48 +72,63 @@ fn candidate_deployments(group: &[&Rqe], costs: &[AtomicCostEntry]) -> Vec Vec { - prune_dominated_candidates(rqes, build_all_candidates_unpruned(rqes, costs)) +pub fn build_all_candidates( + rqes: &[Rqe], + costs: &[AtomicCostEntry], + facts: &WorkloadFacts, +) -> Vec { + prune_dominated_candidates(rqes, build_all_candidates_unpruned(rqes, costs, facts)) } /// Generate the complete v1 candidate set before dominance pruning. /// /// The public optimizer entry point is [`build_all_candidates`]. This helper /// exists so diagnostics can report exactly how much safe pruning removed. -pub fn build_all_candidates_unpruned(rqes: &[Rqe], costs: &[AtomicCostEntry]) -> Vec { - let mut groups: BTreeMap<(Capability, LabelSet), Vec<&Rqe>> = BTreeMap::new(); +pub fn build_all_candidates_unpruned( + rqes: &[Rqe], + costs: &[AtomicCostEntry], + facts: &WorkloadFacts, +) -> Vec { + let mut groups: BTreeMap<(Capability, &str, &LabelSet), Vec<&Rqe>> = BTreeMap::new(); for rqe in rqes { groups - .entry((rqe.capability, rqe.labels.clone())) + .entry((rqe.capability, &rqe.metric, &rqe.grouping_labels)) .or_default() .push(rqe); } groups - .values() - .flat_map(|group| candidate_deployments(group, costs)) + .iter() + .flat_map(|(&(_, metric, _), group)| { + candidate_deployments(group, costs, facts[metric].scrape_interval_secs) + }) .collect() } /// Remove a candidate only when another candidate can replace it in every /// mapping without making any modeled objective worse. /// -/// This comparison is deliberately local to a capability/label-set group. -/// Within such a group, label cardinality and arrival rate are common -/// multipliers, so comparing per-instance query memory and -/// `active_instances * insert_cost` is sufficient. Query latency and retained -/// memory are checked for each RQE the dominated candidate can serve. +/// This comparison is deliberately local to a (capability, metric, grouping) +/// group, where `card(G)`, arrival rate and query output size are common +/// multipliers. So it compares ingest CPU and memory per group, then latency +/// (merge and query CPU), merge memory and stored memory for each RQE the +/// dominated candidate can serve. pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> Vec { let eligibility: Vec> = candidates .iter() @@ -113,93 +139,113 @@ pub fn prune_dominated_candidates(rqes: &[Rqe], candidates: Vec) -> .iter() .enumerate() .filter_map(|(candidate_index, candidate)| { - let dominated = eligibility - .iter() - .enumerate() - .any(|(other_index, other_coverage)| { - other_index != candidate_index - && candidate_dominates( - &candidates[other_index], - other_coverage, - candidate, - &eligibility[candidate_index], - rqes, - ) - // Identical candidates dominate only in a stable direction, - // so a tie never removes both candidates. - && (strictly_better( - &candidates[other_index], - other_coverage, - candidate, - &eligibility[candidate_index], - rqes, - ) || other_index < candidate_index) - }); + let dominated = (0..candidates.len()).any(|other_index| { + if other_index == candidate_index { + return false; + } + match dominance( + &candidates[other_index], + &eligibility[other_index], + candidate, + &eligibility[candidate_index], + rqes, + ) { + Dominance::StrictlyBetter => true, + // The earlier of two identical candidates wins, so a tie + // never removes both. + Dominance::Equal => other_index < candidate_index, + Dominance::NotDominating => false, + } + }); (!dominated).then(|| candidate.clone()) }) .collect() } -fn candidate_dominates( +enum Dominance { + StrictlyBetter, + Equal, + NotDominating, +} + +/// Whether `replacement` can stand in for `original`: it serves every RQE +/// `original` serves and is no worse on any cost. +fn dominance( replacement: &Deployment, replacement_coverage: &[bool], original: &Deployment, original_coverage: &[bool], rqes: &[Rqe], -) -> bool { - if replacement.capability != original.capability || replacement.labels != original.labels { - return false; +) -> Dominance { + let same_group = replacement.capability == original.capability + && replacement.metric == original.metric + && replacement.grouping_labels == original.grouping_labels; + let covers_original = original_coverage + .iter() + .zip(replacement_coverage) + .all(|(&original_serves, &replacement_serves)| !original_serves || replacement_serves); + if !same_group || !covers_original { + return Dominance::NotDominating; } - let replacement_ingest = replacement.active_instance_count().unwrap_or(u64::MAX) as f64 - * replacement.config.insert_cpu_secs; - let original_ingest = original.active_instance_count().unwrap_or(u64::MAX) as f64 - * original.config.insert_cpu_secs; - replacement.config.mem_bytes_per_instance <= original.config.mem_bytes_per_instance - && replacement_ingest <= original_ingest - && original_coverage - .iter() - .zip(replacement_coverage) - .all(|(&original_serves, &replacement_serves)| !original_serves || replacement_serves) - && original_coverage + // Each pair is (replacement's cost, original's cost). + let mut costs = vec![ + (ingest_cpu(replacement), ingest_cpu(original)), + (ingest_memory(replacement), ingest_memory(original)), + ]; + for (rqe, _) in rqes + .iter() + .zip(original_coverage) + .filter(|(_, &serves)| serves) + { + costs.push(( + query_latency(replacement, rqe), + query_latency(original, rqe), + )); + costs.push(( + merge_memory_per_group(rqe, replacement), + merge_memory_per_group(rqe, original), + )); + costs.push(( + stored_memory(replacement, rqe), + stored_memory(original, rqe), + )); + } + + let serves_more = original_coverage + .iter() + .zip(replacement_coverage) + .any(|(&original_serves, &replacement_serves)| !original_serves && replacement_serves); + if costs + .iter() + .any(|(replacement_cost, original_cost)| replacement_cost > original_cost) + { + Dominance::NotDominating + } else if serves_more + || costs .iter() - .enumerate() - .all(|(rqe_index, &serves)| { - !serves - || (query_latency(replacement, &rqes[rqe_index]) - <= query_latency(original, &rqes[rqe_index]) - && retained_memory(replacement, &rqes[rqe_index]) - <= retained_memory(original, &rqes[rqe_index])) - }) + .any(|(replacement_cost, original_cost)| replacement_cost < original_cost) + { + Dominance::StrictlyBetter + } else { + Dominance::Equal + } } -fn strictly_better( - replacement: &Deployment, - replacement_coverage: &[bool], - original: &Deployment, - original_coverage: &[bool], - rqes: &[Rqe], -) -> bool { - let replacement_ingest = replacement.active_instance_count().unwrap_or(u64::MAX) as f64 - * replacement.config.insert_cpu_secs; - let original_ingest = original.active_instance_count().unwrap_or(u64::MAX) as f64 - * original.config.insert_cpu_secs; - replacement.config.mem_bytes_per_instance < original.config.mem_bytes_per_instance - || replacement_ingest < original_ingest - || original_coverage - .iter() - .zip(replacement_coverage) - .any(|(&original_serves, &replacement_serves)| !original_serves && replacement_serves) - || original_coverage - .iter() - .enumerate() - .any(|(rqe_index, &serves)| { - serves - && (query_latency(replacement, &rqes[rqe_index]) - < query_latency(original, &rqes[rqe_index]) - || retained_memory(replacement, &rqes[rqe_index]) - < retained_memory(original, &rqes[rqe_index])) - }) +fn open_window_count(deployment: &Deployment) -> f64 { + deployment.active_instance_count().unwrap_or(u64::MAX) as f64 +} + +/// Insert CPU per sample. Arrival rate is a common multiplier within a group, +/// so it is left out. +fn ingest_cpu(deployment: &Deployment) -> f64 { + open_window_count(deployment) * deployment.config.insert_cpu_secs +} + +/// Open-window bytes per group. `card(G)` is a common multiplier within a +/// group, so it is left out. +fn ingest_memory(deployment: &Deployment) -> f64 { + open_window_count(deployment) * deployment.config.mem_bytes_per_instance } fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { @@ -210,11 +256,10 @@ fn query_latency(deployment: &Deployment, rqe: &Rqe) -> f64 { + instances.saturating_sub(1) as f64 * deployment.config.merge_cpu_secs } -/// Retained bytes per label group when serving `rqe`. Label cardinality is a -/// common multiplier within a group, so it is left out. -fn retained_memory(deployment: &Deployment, rqe: &Rqe) -> f64 { +/// Closed-window bytes per group when serving `rqe`. +fn stored_memory(deployment: &Deployment, rqe: &Rqe) -> f64 { deployment - .retained_instance_count(rqe.lookback_secs) + .closed_instance_count(rqe.lookback_secs) .expect("candidate coverage only contains exactly tiled RQEs") as f64 * deployment.config.mem_bytes_per_instance } @@ -230,7 +275,8 @@ pub fn eligible_deployments_for(r: &Rqe, deployments: &[Deployment]) -> Vec bool { r.capability == d.capability - && r.labels == d.labels + && r.metric == d.metric + && r.grouping_labels == d.grouping_labels && d.window_secs != 0 && d.slide_secs != 0 && d.window_secs.is_multiple_of(d.slide_secs) @@ -242,6 +288,7 @@ pub fn is_eligible(r: &Rqe, d: &Deployment) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::test_support::{facts, METRIC}; use crate::{AccuracyDirection, LabelSet}; use std::collections::BTreeMap; fn rqe(id: &str, lookback: Seconds, interval: Seconds) -> Rqe { @@ -250,7 +297,8 @@ mod tests { capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: "err".into(), accuracy_tolerance: 1.0, accuracy_direction: AccuracyDirection::LowerIsBetter, @@ -270,7 +318,7 @@ mod tests { #[test] fn shared_slide_comes_from_subset_gcd_not_all_divisors() { let rqes = vec![rqe("a", 60, 20), rqe("b", 60, 30)]; - let candidates = build_all_candidates(&rqes, &[cost()]); + let candidates = build_all_candidates(&rqes, &[cost()], &facts(1, 1)); let slides: BTreeSet<_> = candidates .iter() .filter(|d| d.window_secs == 60) @@ -279,6 +327,18 @@ mod tests { assert_eq!(slides, BTreeSet::from([10, 20, 30])); } #[test] + fn windows_and_slides_are_multiples_of_the_scrape_interval() { + let rqes = vec![rqe("a", 60, 20), rqe("b", 60, 30)]; + let mut facts = facts(1, 1); + facts.get_mut(METRIC).unwrap().scrape_interval_secs = 15; + let candidates = build_all_candidates_unpruned(&rqes, &[cost()], &facts); + assert!(!candidates.is_empty()); + // Without the filter, windows 1..60 and slides 10/20 would appear. + assert!(candidates + .iter() + .all(|d| d.window_secs % 15 == 0 && d.slide_secs % 15 == 0)); + } + #[test] fn a_min_query_is_only_offered_the_min_accumulator() { let r = Rqe { capability: Capability::Min, @@ -288,7 +348,11 @@ mod tests { sketch: sketch.into(), ..cost() }; - let candidates = build_all_candidates(&[r], &[named("exact-min"), named("exact-max")]); + let candidates = build_all_candidates( + &[r], + &[named("exact-min"), named("exact-max")], + &facts(1, 1), + ); assert!(!candidates.is_empty()); assert!(candidates.iter().all(|d| d.config.sketch == "exact-min")); } @@ -298,7 +362,8 @@ mod tests { let r = rqe("r", 600, 180); let d = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost(), window_secs: 120, slide_secs: 60, @@ -325,7 +390,8 @@ mod tests { let r = rqe("r", 60, 60); let coarse = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost(), window_secs: 60, slide_secs: 60, @@ -346,7 +412,8 @@ mod tests { let cost = cost(); let large_window = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: cost.clone(), window_secs: 60, slide_secs: 60, @@ -364,12 +431,13 @@ mod tests { } #[test] - fn retains_candidate_with_lower_retained_memory() { + fn retains_candidate_with_lower_stored_memory() { let r = rqe("r", 60, 60); - // Holds (60 + 60) / 60 = 2 instances of 10 bytes. + // Stores (60 − 60) / 60 + 1 = 1 closed instance of 10 bytes. let whole_window = Deployment { capability: Capability::TopK, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), config: AtomicCostEntry { mem_bytes_per_instance: 10.0, ..cost() @@ -377,7 +445,7 @@ mod tests { window_secs: 60, slide_secs: 60, }; - // Smaller, faster sketches, but (20 + 60) / 20 = 4 of them: 24 bytes. + // Smaller, faster sketches, but (60 − 20) / 20 + 1 = 3 of them: 18 bytes. let panes = Deployment { config: AtomicCostEntry { mem_bytes_per_instance: 6.0, @@ -394,4 +462,38 @@ mod tests { assert_eq!(retained, vec![whole_window, panes]); } + + #[test] + fn retains_direct_query_candidate_that_never_merges() { + let r = rqe("r", 60, 60); + // x == L: no merge, so no merge memory. + let direct = Deployment { + capability: Capability::TopK, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + config: AtomicCostEntry { + mem_bytes_per_instance: 10.0, + ..cost() + }, + window_secs: 60, + slide_secs: 60, + }; + // Smaller and cheaper on every other cost, but merges two windows, + // holding a 4-byte accumulator per group. + let halves = Deployment { + config: AtomicCostEntry { + mem_bytes_per_instance: 4.0, + query_cpu_secs: 0.5, + merge_cpu_secs: 0.1, + ..cost() + }, + window_secs: 30, + slide_secs: 30, + ..direct.clone() + }; + + let retained = prune_dominated_candidates(&[r], vec![direct.clone(), halves.clone()]); + + assert_eq!(retained, vec![direct, halves]); + } } diff --git a/rqe-optimizer/src/enumerate.rs b/rqe-optimizer/src/enumerate.rs index 7b6b33db..5f435b9e 100644 --- a/rqe-optimizer/src/enumerate.rs +++ b/rqe-optimizer/src/enumerate.rs @@ -2,7 +2,7 @@ //! //! A mapping is one deployment choice per RQE (§4's only constraint is //! `Σ_D x_{i,D} = 1`; `y_D` is derived). No RQE is eligible outside its own -//! `(capability, labels)` group, so choices are independent and the search +//! `(capability, metric, grouping_labels)` group, so choices are independent and the search //! space is exactly the cartesian product of the per-RQE eligible lists -- //! nothing to prune against. Sharing falls out when two choices land on the //! same index. @@ -107,8 +107,9 @@ pub fn for_each_mapping_while( #[cfg(test)] mod tests { use super::*; - use crate::candidates::build_all_candidates; - use crate::{AtomicCostEntry, Capability, LabelSet}; + use crate::candidates; + use crate::test_support::{facts, METRIC}; + use crate::{AtomicCostEntry, Capability, Deployment, LabelSet}; use std::collections::BTreeMap; fn cost(sketch: &str) -> AtomicCostEntry { @@ -125,13 +126,18 @@ mod tests { } } + fn build_all_candidates(rqes: &[Rqe], costs: &[AtomicCostEntry]) -> Vec { + candidates::build_all_candidates(rqes, costs, &facts(1, 1)) + } + fn rqe(id: &str, interval: u64, lookback: u64) -> Rqe { Rqe { id: id.to_string(), capability: Capability::TopK, lookback_secs: lookback, interval_secs: interval, - labels: LabelSet::new(), + metric: METRIC.into(), + grouping_labels: LabelSet::new(), accuracy_metric: "err".to_string(), accuracy_tolerance: 1.0, accuracy_direction: crate::AccuracyDirection::LowerIsBetter, diff --git a/rqe-optimizer/src/lib.rs b/rqe-optimizer/src/lib.rs index 338f1070..4fefad39 100644 --- a/rqe-optimizer/src/lib.rs +++ b/rqe-optimizer/src/lib.rs @@ -4,15 +4,16 @@ //! //! Three independent stages, so an ILP can replace [`enumerate`] alone: //! [`candidates`] builds 𝒟 and per-RQE eligibility (§3), [`enumerate`] -//! searches (§4), [`objectives`] scores (§5). +//! searches (§4), [`analytical_cost_model`] scores (§5). //! -//! Every number the algorithm uses is caller-supplied -- no constants here. +//! Every number the algorithm uses is caller-supplied, except the query +//! output size estimates in [`analytical_cost_model`]. +pub mod analytical_cost_model; pub mod autosketch; pub mod candidates; pub mod enumerate; pub mod milp; -pub mod objectives; pub mod pareto; use std::collections::BTreeMap; @@ -70,16 +71,71 @@ impl Capability { } } -/// Property of a label set, not of an RQE (§1): RQEs sharing a label set -/// read the same grouped stream. Given as input, never estimated. -#[derive(Debug, Clone, Copy)] -pub struct LabelSetInfo { - /// `card(labels)`: distinct label-value combinations, i.e. how many - /// physical sketch instances one deployment for this label set needs. - pub cardinality: u64, - /// `λ(labels)`: aggregate items/sec flowing into this grouped stream, - /// across all of its groups. - pub arrival_rate_per_sec: f64, +/// Facts about one metric, given as input. RQEs and deployments on the same +/// metric read the same samples. +#[derive(Debug, Clone)] +pub struct MetricFacts { + /// Every label the metric's series carry. + pub labels: LabelSet, + /// Each series yields one sample per scrape. + pub scrape_interval_secs: Seconds, + /// `card(X)`: distinct value combinations of each label set `X` in use. + /// Must include `labels` itself, whose cardinality is the series count. + pub cardinality: BTreeMap, +} + +impl MetricFacts { + /// `λ`: samples/sec across all of the metric's series. + pub fn arrival_rate_per_sec(&self) -> f64 { + self.cardinality[&self.labels] as f64 / self.scrape_interval_secs as f64 + } +} + +/// [`MetricFacts`] keyed by metric name. +pub type WorkloadFacts = BTreeMap; + +/// Every problem with `facts` for serving `rqes`. The rest of the crate +/// indexes `facts` without checks, so call this first on caller input. +pub fn validate_facts(rqes: &[Rqe], facts: &WorkloadFacts) -> Result<(), Vec> { + let mut problems = BTreeSet::new(); + for rqe in rqes { + let (metric, grouping) = (&rqe.metric, &rqe.grouping_labels); + let Some(metric_facts) = facts.get(metric) else { + problems.insert(format!("{metric}: no facts for this metric")); + continue; + }; + let all_labels = &metric_facts.labels; + let cardinality = &metric_facts.cardinality; + if metric_facts.scrape_interval_secs == 0 { + problems.insert(format!("{metric}: scrape interval is 0")); + } + if !grouping.is_subset(all_labels) { + problems.insert(format!( + "{metric}: grouping {grouping:?} is not a subset of its labels {all_labels:?}" + )); + } + for labels in [grouping, all_labels] { + match cardinality.get(labels) { + None => problems.insert(format!("{metric}: no cardinality for {labels:?}")), + Some(0) => problems.insert(format!("{metric}: cardinality of {labels:?} is 0")), + Some(_) => false, + }; + } + if let (Some(&groups), Some(&series)) = + (cardinality.get(grouping), cardinality.get(all_labels)) + { + if groups > series { + problems.insert(format!( + "{metric}: {grouping:?} has {groups} groups but only {series} series" + )); + } + } + } + if problems.is_empty() { + Ok(()) + } else { + Err(problems.into_iter().collect()) + } } /// Which way an accuracy metric runs. Most comparators report an error @@ -106,7 +162,9 @@ pub struct Rqe { pub lookback_secs: Seconds, /// `T_i`: how often this RQE is queried. pub interval_secs: Seconds, - pub labels: LabelSet, + pub metric: String, + /// `G`: the query's group-by labels. + pub grouping_labels: LabelSet, /// Which `AtomicCostEntry::query_accuracy` key to check. Comparators /// name their metrics differently per capability, so the RQE picks. pub accuracy_metric: String, @@ -136,13 +194,15 @@ impl Rqe { } } -/// A candidate deployment (§3): one configuration, one label set, and a +/// A candidate deployment (§3): one configuration, one grouped stream, and a /// sliding sketch window. Retention is an execution/storage concern, not an /// optimizer candidate dimension. #[derive(Debug, Clone, PartialEq)] pub struct Deployment { pub capability: Capability, - pub labels: LabelSet, + pub metric: String, + /// `G`: one instance per group, per window. + pub grouping_labels: LabelSet, pub config: AtomicCostEntry, /// `x`: materialized sketch-window size. pub window_secs: Seconds, @@ -167,12 +227,12 @@ impl Deployment { Some(lookback_secs / self.window_secs) } - /// Instances held to serve a lookback: `x / y` open ones plus the closed - /// ones still inside the lookback, `(x + S) / y`. - pub fn retained_instance_count(&self, lookback_secs: Seconds) -> Option { + /// Closed instances kept to serve a lookback: those wholly inside it, + /// which start in `[now − L, now − x]`, so `(L − x) / y + 1`. + pub fn closed_instance_count(&self, lookback_secs: Seconds) -> Option { self.query_instance_count(lookback_secs)?; self.active_instance_count()?; - Some((self.window_secs + lookback_secs) / self.slide_secs) + Some((lookback_secs - self.window_secs) / self.slide_secs + 1) } } @@ -183,6 +243,166 @@ impl Deployment { /// separately, it's always derived from `mapping`. pub type Mapping = Vec; -/// `LabelSetInfo` lookup used throughout -- keyed by the same `LabelSet` -/// type deployments and RQEs carry. -pub type LabelSetTable = BTreeMap; +/// Fixtures shared by the unit tests: one metric `m`, grouped by nothing, +/// served by top-k. +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + + pub const METRIC: &str = "m"; + + /// `groups` groups and `series` raw series scraped every second, so + /// `λ = series`. Not validated: unit tests set `groups` freely. + pub fn facts(groups: u64, series: u64) -> WorkloadFacts { + let labels = LabelSet::from(["series".to_string()]); + WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels.clone(), + scrape_interval_secs: 1, + cardinality: BTreeMap::from([(LabelSet::new(), groups), (labels, series)]), + }, + )]) + } + + pub fn rqe(lookback_secs: Seconds, interval_secs: Seconds) -> Rqe { + Rqe { + id: "r".into(), + capability: Capability::TopK, + lookback_secs, + interval_secs, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + accuracy_metric: "err".into(), + accuracy_tolerance: 1.0, + accuracy_direction: AccuracyDirection::LowerIsBetter, + } + } + + /// Per-instance memory and insert/merge/query CPU, then window and slide. + pub fn deployment( + memory: f64, + insert: f64, + merge: f64, + query: f64, + window_secs: Seconds, + slide_secs: Seconds, + ) -> Deployment { + Deployment { + capability: Capability::TopK, + metric: METRIC.into(), + grouping_labels: LabelSet::new(), + config: AtomicCostEntry { + sketch: "cms-heap-topk-fastpath-vector2d".into(), + sketch_config: serde_json::json!(null), + mem_bytes_per_instance: memory, + insert_cpu_secs: insert, + merge_cpu_secs: merge, + query_cpu_secs: query, + query_accuracy: BTreeMap::from([("err".into(), 0.0)]), + }, + window_secs, + slide_secs, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use test_support::{deployment, rqe, METRIC}; + + fn labels(names: &[&str]) -> LabelSet { + names.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn closed_instances_lie_wholly_inside_the_lookback() { + // 10-minute windows every minute, over an hour: starts in minutes + // [now − 60, now − 10]. + let sliding = deployment(1.0, 1.0, 1.0, 1.0, 600, 60); + assert_eq!(sliding.closed_instance_count(3_600), Some(51)); + assert_eq!(sliding.closed_instance_count(600), Some(1)); + assert_eq!(sliding.closed_instance_count(900), None); // not tiled by x + } + + #[test] + fn arrival_rate_is_series_over_scrape_interval() { + let metric_facts = MetricFacts { + scrape_interval_secs: 15, + ..test_support::facts(4, 600)[METRIC].clone() + }; + assert_eq!(metric_facts.arrival_rate_per_sec(), 40.0); + } + + #[test] + fn valid_facts_pass() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint"]), + scrape_interval_secs: 15, + cardinality: BTreeMap::from([ + (labels(&["service"]), 5), + (labels(&["service", "endpoint"]), 50), + ]), + }, + )]); + let r = Rqe { + grouping_labels: labels(&["service"]), + ..rqe(60, 60) + }; + assert_eq!(validate_facts(&[r], &facts), Ok(())); + } + + #[test] + fn reports_every_problem_at_once() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service"]), + scrape_interval_secs: 0, + cardinality: BTreeMap::from([(labels(&["service"]), 0)]), + }, + )]); + let rqes = [ + Rqe { + metric: "missing".into(), + ..rqe(60, 60) + }, + Rqe { + grouping_labels: labels(&["pod"]), + ..rqe(60, 60) + }, + ]; + let problems = validate_facts(&rqes, &facts).unwrap_err(); + let has = |needle: &str| problems.iter().any(|p| p.contains(needle)); + assert!(has("missing: no facts")); + assert!(has("scrape interval is 0")); + assert!(has("not a subset")); + assert!(has("no cardinality for {\"pod\"}")); + assert!(has("cardinality of {\"service\"} is 0")); + assert_eq!(problems.len(), 5, "{problems:?}"); + } + + #[test] + fn rejects_more_groups_than_series() { + let facts = WorkloadFacts::from([( + METRIC.to_string(), + MetricFacts { + labels: labels(&["service", "endpoint"]), + scrape_interval_secs: 15, + cardinality: BTreeMap::from([ + (labels(&["service"]), 60), + (labels(&["service", "endpoint"]), 50), + ]), + }, + )]); + let r = Rqe { + grouping_labels: labels(&["service"]), + ..rqe(60, 60) + }; + let problems = validate_facts(&[r], &facts).unwrap_err(); + assert!(problems[0].contains("60 groups but only 50 series")); + } +} diff --git a/rqe-optimizer/src/milp.rs b/rqe-optimizer/src/milp.rs index ccc5c00f..d26abd06 100644 --- a/rqe-optimizer/src/milp.rs +++ b/rqe-optimizer/src/milp.rs @@ -3,59 +3,71 @@ //! The model is documented in `docs/rqe_sketch_deployment_v1.md`. It avoids //! enumerating the Cartesian product of eligible deployment choices. +use crate::analytical_cost_model::{self, score, PhaseCost, PlanCost, BYTES_PER_GIB}; use crate::candidates::eligible_deployments_for; -use crate::objectives::{score, MachineFamily, Objectives, BYTES_PER_GIB}; -use crate::{Deployment, LabelSetTable, Mapping, Rqe}; +use crate::{Deployment, Mapping, Rqe, WorkloadFacts}; use good_lp::{ default_solver, variable, Expression, ProblemVariables, ResolutionError, Solution, SolverModel, Variable, }; -/// Optional hard bounds for a minimum-TCO solve. An empty latency vector means -/// no RQE has a latency bound; otherwise it is index-aligned with `rqes`. +/// What a [`minimize`] solve minimizes. Eligibility, assignment and activation +/// rows, and bounds are the same for every objective. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Objective { + /// `w_cpu · CPU + w_mem · memory`. CPU is mean CPU-sec/sec, the area under + /// the load curve, so bursts are not priced. Memory is GiB summed over + /// every phase, as if every query evaluates at once. + AUCCost { w_cpu: f64, w_mem: f64 }, +} + +impl Default for Objective { + /// CPU only, until memory gets a price. + fn default() -> Self { + Objective::AUCCost { + w_cpu: 1.0, + w_mem: 0.0, + } + } +} + +impl Objective { + pub fn value(&self, plan_cost: &PlanCost) -> f64 { + self.weigh(PhaseCost { + cpu_secs_per_sec: plan_cost.cpu_secs_per_sec(), + memory_bytes: plan_cost.memory_bytes(), + }) + } + + fn weigh(&self, cost: PhaseCost) -> f64 { + let Objective::AUCCost { w_cpu, w_mem } = *self; + w_cpu * cost.cpu_secs_per_sec + w_mem * cost.memory_bytes / BYTES_PER_GIB + } +} + +/// Optional hard bounds for a solve. An empty latency vector means no RQE has +/// a latency bound; otherwise it is index-aligned with `rqes`. #[derive(Debug, Clone, Default)] pub struct MilpBounds { - pub max_peak_query_memory_bytes: Option, pub max_query_latency_secs: Vec>, } #[derive(Debug, Clone)] pub struct MilpSolution { pub mapping: Mapping, - pub objectives: Objectives, -} - -/// Minimize total steady-state CPU subject to optional memory and latency -/// bounds. Missing eligible deployments are a caller input error; use -/// `enumerate::unservable` to report them before calling this function. -pub fn minimize_tco( - rqes: &[Rqe], - deployments: &[Deployment], - label_sets: &LabelSetTable, - bounds: &MilpBounds, -) -> Result { - solve(rqes, deployments, label_sets, bounds, None) -} - -/// Minimize the hourly price of running the plan on `family`, in fractional -/// instances: `n ≥ CPU / vCPU` and `n ≥ retained memory / GiB`. Same inputs -/// and bounds as [`minimize_tco`]. -pub fn minimize_cost( - rqes: &[Rqe], - deployments: &[Deployment], - label_sets: &LabelSetTable, - bounds: &MilpBounds, - family: &MachineFamily, -) -> Result { - solve(rqes, deployments, label_sets, bounds, Some(family)) + pub plan_cost: PlanCost, } -fn solve( +/// Minimize `objective` subject to optional latency bounds. `facts` must pass +/// [`crate::validate_facts`]. Missing eligible deployments are a caller input +/// error; use `enumerate::unservable` to report them before calling this +/// function. +pub fn minimize( rqes: &[Rqe], deployments: &[Deployment], - label_sets: &LabelSetTable, + facts: &WorkloadFacts, bounds: &MilpBounds, - family: Option<&MachineFamily>, + objective: Objective, ) -> Result { assert!( bounds.max_query_latency_secs.is_empty() @@ -86,45 +98,45 @@ fn solve( .collect() }) .collect(); + // Weighted storage cost per deployment: the max over the RQEs it serves. + let deployment_storage_cost: Vec = deployments + .iter() + .map(|_| variables.add(variable().min(0))) + .collect(); - // Real plans cost ~1e-6 $/hour and read in microseconds, below HiGHS's - // absolute gap (1e-6) and feasibility tolerance (1e-7). So every row is - // scaled to O(1) by `reference`, a plan's resource demand without sharing - // (each RQE on its cheapest deployment); per-RQE bounds become exclusions. Results are re-scored on - // real costs below, so the scaling never leaks out. - let ingest = |deployment: &Deployment| { - let fanout = deployment - .active_instance_count() - .expect("candidate window and slide align") as f64; - label_sets[&deployment.labels].arrival_rate_per_sec - * fanout - * deployment.config.insert_cpu_secs - }; - let retained = |rqe: &Rqe, deployment: &Deployment| { - label_sets[&deployment.labels].cardinality as f64 - * deployment.config.mem_bytes_per_instance - * deployment - .retained_instance_count(rqe.lookback_secs) - .expect("assignment only contains eligible deployments") as f64 - / BYTES_PER_GIB + // Ingest is paid once per active deployment, merge and query once per + // assignment, and storage once per deployment for its longest lookback. + let ingest_cost: Vec = deployments + .iter() + .map(|deployment| objective.weigh(analytical_cost_model::ingest(deployment, facts))) + .collect(); + let merge_and_query_cost = |rqe: &Rqe, deployment: &Deployment| { + objective.weigh(analytical_cost_model::merge(rqe, deployment, facts)) + + objective.weigh(analytical_cost_model::query(rqe, deployment, facts)) }; - // Per resource, in the units the solve minimizes: CPU for TCO, and for a - // family the vCPU and GiB fractions of one instance. - let (cpu_unit, gib_unit) = match family { - Some(f) => (f.vcpu, f.memory_gib), - None => (1.0, f64::INFINITY), + let storage_cost_for_rqe_and_deployment = |rqe: &Rqe, deployment: &Deployment| { + objective.weigh(PhaseCost { + cpu_secs_per_sec: 0.0, + memory_bytes: analytical_cost_model::storage_bytes(rqe, deployment, facts), + }) }; + + // Real plans cost ~1e-6 CPU-sec/sec and read in microseconds, below + // HiGHS's absolute gap (1e-6) and feasibility tolerance (1e-7). So costs + // are divided by `reference`, a plan's cost without sharing (each RQE on + // its cheapest deployment), and per-RQE bounds become exclusions. The + // result is re-scored on real costs. let reference: f64 = rqes .iter() .zip(&eligible) .map(|(rqe, choices)| { choices .iter() - .map(|&d| { - let deployment = &deployments[d]; - let cpu = ingest(deployment) - + query_and_merge_cpu_per_sec(rqe, deployment, label_sets); - cpu / cpu_unit + retained(rqe, deployment) / gib_unit + .map(|&deployment_index| { + let deployment = &deployments[deployment_index]; + ingest_cost[deployment_index] + + merge_and_query_cost(rqe, deployment) + + storage_cost_for_rqe_and_deployment(rqe, deployment) }) .fold(f64::INFINITY, f64::min) }) @@ -135,79 +147,50 @@ fn solve( 1.0 }; - let mut cpu = Expression::with_capacity(deployments.len() + rqes.len()); - for (deployment, &active_variable) in deployments.iter().zip(&active) { - cpu.add_mul(ingest(deployment) / reference, active_variable); + let mut goal: Expression = deployment_storage_cost.iter().sum(); + for (&cost, &active_variable) in ingest_cost.iter().zip(&active) { + goal.add_mul(cost / reference, active_variable); } for (rqe_index, choices) in assignments.iter().enumerate() { for &(deployment_index, assignment) in choices { - cpu.add_mul( - query_and_merge_cpu_per_sec( - &rqes[rqe_index], - &deployments[deployment_index], - label_sets, - ) / reference, + goal.add_mul( + merge_and_query_cost(&rqes[rqe_index], &deployments[deployment_index]) / reference, assignment, ); } } - // Retained GiB per deployment, and fractional instances, priced only when - // a machine family is given. Both are in units of `reference`. - let retained_gib: Vec = match family { - Some(_) => deployments - .iter() - .map(|_| variables.add(variable().min(0))) - .collect(), - None => Vec::new(), - }; - let instances = variables.add(variable().min(0)); - // The price per instance is a positive constant, so minimizing instances - // minimizes the price. - let goal = match family { - Some(_) => Expression::from(instances), - None => cpu.clone(), - }; - let mut model = variables.minimise(goal).using(default_solver); - if let Some(f) = family { - model.add_constraint((cpu / f.vcpu - instances).leq(0)); - let total_gib: Expression = retained_gib.iter().sum(); - model.add_constraint((total_gib / f.memory_gib - instances).leq(0)); - } - for (rqe_index, choices) in assignments.iter().enumerate() { let assignment_sum: Expression = choices.iter().map(|(_, variable)| *variable).sum(); model.add_constraint(assignment_sum.eq(1)); for &(deployment_index, assignment) in choices { + let rqe = &rqes[rqe_index]; let deployment = &deployments[deployment_index]; model.add_constraint((assignment - active[deployment_index]).leq(0)); + // Zero when `w_mem` is 0; such a row can never bind. + let scaled_storage_cost = + storage_cost_for_rqe_and_deployment(rqe, deployment) / reference; + if scaled_storage_cost > 0.0 { + model.add_constraint( + (scaled_storage_cost * assignment - deployment_storage_cost[deployment_index]) + .leq(0), + ); + } // Each RQE takes exactly one deployment, so a per-RQE bound just // forbids the choices over it. Comparing in f64 here, not in the // solver, keeps µs latencies clear of its feasibility tolerance. - let memory = label_sets[&deployment.labels].cardinality as f64 - * deployment.config.mem_bytes_per_instance; - let latency = query_latency_secs(&rqes[rqe_index], deployment, label_sets); + let latency = analytical_cost_model::query_latency_secs(rqe, deployment, facts); if bounds - .max_peak_query_memory_bytes - .is_some_and(|limit| memory > limit) - || bounds - .max_query_latency_secs - .get(rqe_index) - .copied() - .flatten() - .is_some_and(|limit| latency > limit) + .max_query_latency_secs + .get(rqe_index) + .copied() + .flatten() + .is_some_and(|limit| latency > limit) { model.add_constraint(Expression::from(assignment).leq(0)); } - if family.is_some() { - // Linearized max over the RQEs a deployment serves. - let retained = retained(&rqes[rqe_index], deployment) / reference; - model.add_constraint( - (retained * assignment - retained_gib[deployment_index]).leq(0), - ); - } } } @@ -233,225 +216,115 @@ fn solve( .expect("MILP assigns exactly one deployment to every RQE") }) .collect(); - let objectives = score(rqes, deployments, &mapping, label_sets); - Ok(MilpSolution { - mapping, - objectives, - }) -} - -fn query_and_merge_cpu_per_sec( - rqe: &Rqe, - deployment: &Deployment, - label_sets: &LabelSetTable, -) -> f64 { - query_latency_secs(rqe, deployment, label_sets) / rqe.interval_secs as f64 -} - -fn query_latency_secs(rqe: &Rqe, deployment: &Deployment, label_sets: &LabelSetTable) -> f64 { - let instances = deployment - .query_instance_count(rqe.lookback_secs) - .expect("assignment only contains eligible deployments"); - let cardinality = label_sets[&deployment.labels].cardinality as f64; - cardinality - * (deployment.config.query_cpu_secs - + instances.saturating_sub(1) as f64 * deployment.config.merge_cpu_secs) + let plan_cost = score(rqes, deployments, &mapping, facts); + Ok(MilpSolution { mapping, plan_cost }) } #[cfg(test)] mod tests { use super::*; use crate::enumerate::brute_force; - use crate::{AccuracyDirection, AtomicCostEntry, Capability, LabelSet, LabelSetInfo}; - use std::collections::BTreeMap; + use crate::test_support::{self, facts}; + /// Window and slide 60 s, merge 1 CPU-sec. fn deployment(insert_cpu_secs: f64, memory: f64, query_cpu_secs: f64) -> Deployment { - Deployment { - capability: Capability::TopK, - labels: LabelSet::new(), - config: AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: memory, - insert_cpu_secs, - merge_cpu_secs: 1.0, - query_cpu_secs, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }, - window_secs: 60, - slide_secs: 60, - } + test_support::deployment(memory, insert_cpu_secs, 1.0, query_cpu_secs, 60, 60) } - fn rqe() -> Rqe { + fn rqe(id: &str, lookback_secs: u64) -> Rqe { Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs: 60, - interval_secs: 60, - labels: LabelSet::new(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, + id: id.into(), + ..test_support::rqe(lookback_secs, 60) } } - #[test] - fn minimizes_cpu_and_respects_a_memory_bound() { - let rqes = vec![rqe()]; - let deployments = vec![deployment(1.0, 20.0, 1.0), deployment(2.0, 10.0, 1.0)]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - let unconstrained = minimize_tco(&rqes, &deployments, &label_sets, &MilpBounds::default()) - .expect("feasible MILP"); - assert_eq!(unconstrained.mapping, vec![0]); - - let constrained = minimize_tco( - &rqes, - &deployments, - &label_sets, - &MilpBounds { - max_peak_query_memory_bytes: Some(10.0), - max_query_latency_secs: Vec::new(), - }, - ) - .expect("feasible MILP under memory bound"); - assert_eq!(constrained.mapping, vec![1]); + fn weights(w_cpu: f64, w_mem: f64) -> Objective { + Objective::AUCCost { w_cpu, w_mem } } - #[test] - fn matches_brute_force_minimum_with_shared_deployment_costs() { - let mut frequent = rqe(); - frequent.id = "frequent".into(); - frequent.interval_secs = 60; - let mut infrequent = rqe(); - infrequent.id = "infrequent".into(); - let rqes = vec![frequent, infrequent]; - let deployments = vec![deployment(1.0, 10.0, 400.0), deployment(3.0, 10.0, 1.0)]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - let brute_force_best = brute_force(&rqes, &deployments) - .into_iter() - .min_by(|left, right| { - score(&rqes, &deployments, left, &label_sets) - .tco_cpu_secs_per_sec - .total_cmp(&score(&rqes, &deployments, right, &label_sets).tco_cpu_secs_per_sec) - }) + /// The MILP's plan scores as well as the best of every mapping. + fn assert_matches_brute_force(rqes: &[Rqe], deployments: &[Deployment], objective: Objective) { + let facts = facts(1, 1); + let best = brute_force(rqes, deployments) + .iter() + .map(|mapping| objective.value(&score(rqes, deployments, mapping, &facts))) + .min_by(f64::total_cmp) .expect("test workload is servable"); - let expected = score(&rqes, &deployments, &brute_force_best, &label_sets); - - let milp = minimize_tco(&rqes, &deployments, &label_sets, &MilpBounds::default()) + let milp = minimize(rqes, deployments, &facts, &MilpBounds::default(), objective) .expect("feasible MILP"); - - assert_eq!(milp.mapping, brute_force_best); + let got = objective.value(&milp.plan_cost); assert!( - (milp.objectives.tco_cpu_secs_per_sec - expected.tco_cpu_secs_per_sec).abs() < 1e-12 + (got - best).abs() <= 1e-9 * best, + "{objective:?}: {got} vs {best}" ); } - fn family(memory_gib: f64) -> MachineFamily { - MachineFamily { - family: format!("{memory_gib} GiB"), - vcpu: 4.0, - memory_gib, - usd_per_hour: 1.0, - } + #[test] + fn minimizes_cpu_and_respects_a_latency_bound() { + let rqes = vec![rqe("r", 60)]; + // CPU 1 + 3/60 with latency 3, or 2 + 1/60 with latency 1. + let deployments = vec![deployment(1.0, 20.0, 3.0), deployment(2.0, 10.0, 1.0)]; + let solve = |bounds: &MilpBounds| { + minimize( + &rqes, + &deployments, + &facts(1, 1), + bounds, + Objective::default(), + ) + .expect("feasible MILP") + .mapping + }; + + assert_eq!(solve(&MilpBounds::default()), vec![0]); + let bounded = MilpBounds { + max_query_latency_secs: vec![Some(2.0)], + }; + assert_eq!(solve(&bounded), vec![1]); } #[test] - fn minimize_cost_matches_brute_force_minimum() { - let mut frequent = rqe(); - frequent.id = "frequent".into(); - let mut long = rqe(); - long.id = "long".into(); - long.lookback_secs = 600; - let rqes = vec![frequent, long]; + fn matches_brute_force_with_shared_deployment_costs() { + let rqes = vec![rqe("frequent", 60), rqe("long", 600)]; let deployments = vec![ deployment(1.0, 0.5 * BYTES_PER_GIB, 400.0), deployment(3.0, 0.1 * BYTES_PER_GIB, 1.0), deployment(0.2, 2.0 * BYTES_PER_GIB, 1.0), ]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - - for family in [family(8.0), family(32.0)] { - let best = brute_force(&rqes, &deployments) - .iter() - .map(|mapping| { - family.usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) - }) - .min_by(f64::total_cmp) - .expect("test workload is servable"); - let milp = minimize_cost( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - &family, - ) - .expect("feasible MILP"); - assert!((family.usd_per_hour(&milp.objectives) - best).abs() < 1e-9); + for objective in [weights(1.0, 0.0), weights(0.0, 1.0), weights(1.0, 4.0)] { + assert_matches_brute_force(&rqes, &deployments, objective); } } #[test] - fn binding_resource_decides_the_plan_per_family() { - let rqes = vec![rqe()]; - // Holds 2 instances: CPU-heavy with 2 GiB, or CPU-light with 4 GiB. + fn memory_weight_trades_cpu_for_memory() { + let rqes = vec![rqe("r", 60)]; + // CPU-heavy and small, or CPU-light and twice the size. let deployments = vec![ deployment(1.0, 1.0 * BYTES_PER_GIB, 0.0), deployment(0.05, 2.0 * BYTES_PER_GIB, 0.0), ]; - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - let solve = |memory_gib| { - minimize_cost( + let solve = |objective| { + minimize( &rqes, &deployments, - &label_sets, + &facts(1, 1), &MilpBounds::default(), - &family(memory_gib), + objective, ) .expect("feasible MILP") .mapping }; - assert_eq!(solve(8.0), vec![0]); // memory is scarce: 0.25 vs 0.5 instances - assert_eq!(solve(32.0), vec![1]); // CPU is scarce: 0.25 vs 0.125 instances + assert_eq!(solve(weights(1.0, 0.0)), vec![1]); + assert_eq!(solve(weights(0.0, 1.0)), vec![0]); } #[test] fn tiny_magnitudes_match_brute_force_and_respect_latency_bounds() { - // Real W2 plans cost ~1e-6 $/hour with µs latencies: below HiGHS's + // Real plans cost ~1e-6 CPU-sec/sec with µs latencies: below HiGHS's // absolute gap and feasibility tolerances unless the model is scaled. - let mut frequent = rqe(); - frequent.id = "frequent".into(); - let mut long = rqe(); - long.id = "long".into(); - long.lookback_secs = 600; - let rqes = vec![frequent, long]; + let rqes = vec![rqe("frequent", 60), rqe("long", 600)]; let tiny = 1e-9; let deployments = vec![ deployment(1.0 * tiny, 0.5 * tiny * BYTES_PER_GIB, 400.0 * tiny), @@ -459,57 +332,33 @@ mod tests { deployment(0.2 * tiny, 2.0 * tiny * BYTES_PER_GIB, 1.0 * tiny), ] .into_iter() - .map(|mut d| { - d.config.merge_cpu_secs = tiny; - d + .map(|mut candidate| { + candidate.config.merge_cpu_secs = tiny; + candidate }) .collect::>(); - let label_sets = BTreeMap::from([( - LabelSet::new(), - LabelSetInfo { - cardinality: 1, - arrival_rate_per_sec: 1.0, - }, - )]); - for family in [family(8.0), family(32.0)] { - let best = brute_force(&rqes, &deployments) - .iter() - .map(|mapping| { - family.usd_per_hour(&score(&rqes, &deployments, mapping, &label_sets)) - }) - .min_by(f64::total_cmp) - .expect("test workload is servable"); - let milp = minimize_cost( - &rqes, - &deployments, - &label_sets, - &MilpBounds::default(), - &family, - ) - .expect("feasible MILP"); - let got = family.usd_per_hour(&milp.objectives); - assert!((got - best).abs() <= 1e-9 * best, "{got} vs {best}"); + for objective in [weights(1.0, 0.0), weights(1.0, 4.0)] { + assert_matches_brute_force(&rqes, &deployments, objective); } // The cheap deployment's latency is 1.5e-7 s, over a 1e-7 s bound by // less than HiGHS's absolute feasibility tolerance. - let rqes = vec![rqe()]; + let rqes = vec![rqe("r", 60)]; let deployments = vec![ deployment(tiny, tiny, 1.5e-7), deployment(10.0 * tiny, tiny, 0.5e-7), ]; - let milp = minimize_cost( + let milp = minimize( &rqes, &deployments, - &label_sets, + &facts(1, 1), &MilpBounds { - max_peak_query_memory_bytes: None, max_query_latency_secs: vec![Some(1e-7)], }, - &family(8.0), + Objective::default(), ) .expect("feasible MILP"); assert_eq!(milp.mapping, vec![1]); - assert!(milp.objectives.query_latency_secs[0] <= 1e-7); + assert!(milp.plan_cost.query_latency_secs[0] <= 1e-7); } } diff --git a/rqe-optimizer/src/objectives.rs b/rqe-optimizer/src/objectives.rs deleted file mode 100644 index ab41aa8e..00000000 --- a/rqe-optimizer/src/objectives.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! Analytical scoring built from measured per-operation costs (§5). - -use crate::{Deployment, LabelSetTable, Mapping, Rqe}; -use std::collections::{BTreeMap, BTreeSet}; - -pub(crate) const BYTES_PER_GIB: f64 = (1u64 << 30) as f64; - -#[derive(Debug, Clone)] -pub struct Objectives { - pub peak_query_memory_bytes: f64, - pub ingest_cpu_secs_per_sec: f64, - pub merge_cpu_secs_per_sec: f64, - pub query_cpu_secs_per_sec: f64, - pub tco_cpu_secs_per_sec: f64, - /// State held by all active deployments: each keeps the instances needed - /// by the longest lookback it serves. - pub retained_memory_bytes: f64, - /// Index-aligned with the input RQE slice; display IDs need not be unique. - pub query_latency_secs: Vec, -} - -pub fn score( - rqes: &[Rqe], - deployments: &[Deployment], - mapping: &Mapping, - label_sets: &LabelSetTable, -) -> Objectives { - assert_eq!( - mapping.len(), - rqes.len(), - "mapping must have one deployment per RQE" - ); - let active: BTreeSet = mapping.iter().copied().collect(); - let ingest_cpu_secs_per_sec = active - .iter() - .map(|&di| { - let d = &deployments[di]; - let fanout = - d.active_instance_count() - .expect("eligible deployment aligns window and slide") as f64; - label_sets[&d.labels].arrival_rate_per_sec * fanout * d.config.insert_cpu_secs - }) - .sum(); - - let mut retained_instances: BTreeMap = BTreeMap::new(); - for (r, &di) in rqes.iter().zip(mapping) { - let count = deployments[di] - .retained_instance_count(r.lookback_secs) - .expect("mapping only contains eligible pairs"); - let held = retained_instances.entry(di).or_default(); - *held = (*held).max(count); - } - let retained_memory_bytes = retained_instances - .iter() - .map(|(&di, &count)| { - let d = &deployments[di]; - label_sets[&d.labels].cardinality as f64 - * d.config.mem_bytes_per_instance - * count as f64 - }) - .sum(); - - let mut peak_query_memory_bytes = 0.0_f64; - let mut merge_cpu_secs_per_sec = 0.0; - let mut query_cpu_secs_per_sec = 0.0; - let query_latency_secs = rqes - .iter() - .zip(mapping) - .map(|(r, &di)| { - let d = &deployments[di]; - let card = label_sets[&d.labels].cardinality as f64; - peak_query_memory_bytes = - peak_query_memory_bytes.max(card * d.config.mem_bytes_per_instance); - let instances = d - .query_instance_count(r.lookback_secs) - .expect("mapping only contains eligible pairs"); - let query = card * d.config.query_cpu_secs; - let merge = card * instances.saturating_sub(1) as f64 * d.config.merge_cpu_secs; - query_cpu_secs_per_sec += query / r.interval_secs as f64; - merge_cpu_secs_per_sec += merge / r.interval_secs as f64; - query + merge - }) - .collect(); - let tco_cpu_secs_per_sec = - ingest_cpu_secs_per_sec + merge_cpu_secs_per_sec + query_cpu_secs_per_sec; - Objectives { - peak_query_memory_bytes, - ingest_cpu_secs_per_sec, - merge_cpu_secs_per_sec, - query_cpu_secs_per_sec, - tco_cpu_secs_per_sec, - retained_memory_bytes, - query_latency_secs, - } -} - -/// One instance type standing for an EC2 machine family (§4 of the -/// evaluation plan, ProjectASAP/ASAPQuery#777). -#[derive(Debug, Clone, PartialEq)] -pub struct MachineFamily { - pub family: String, - pub vcpu: f64, - pub memory_gib: f64, - pub usd_per_hour: f64, -} - -impl MachineFamily { - /// Reads the `families` of a `scripts/fetch_ec2_pricing.py` snapshot. - pub fn from_pricing_json(json: &str) -> Result, String> { - let snapshot: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?; - let families = snapshot["families"] - .as_array() - .ok_or("pricing snapshot has no families array")?; - families - .iter() - .map(|f| { - let number = |key: &str| { - f[key] - .as_f64() - .ok_or_else(|| format!("family is missing numeric {key}")) - }; - Ok(Self { - family: f["family"] - .as_str() - .ok_or("family is missing its name")? - .to_string(), - vcpu: number("vcpu")?, - memory_gib: number("memory_gib")?, - usd_per_hour: number("usd_per_hour")?, - }) - }) - .collect() - } - - /// Fractional instances needed for the plan: whichever of CPU or memory - /// runs out first. - pub fn instances(&self, objectives: &Objectives) -> f64 { - (objectives.tco_cpu_secs_per_sec / self.vcpu) - .max(objectives.retained_memory_bytes / BYTES_PER_GIB / self.memory_gib) - } - - pub fn usd_per_hour(&self, objectives: &Objectives) -> f64 { - self.usd_per_hour * self.instances(objectives) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{AccuracyDirection, AtomicCostEntry, Capability, LabelSet, LabelSetInfo}; - use std::collections::BTreeMap; - - #[test] - fn scores_overlapping_ingest_and_non_overlapping_query_merges() { - let labels = LabelSet::new(); - let config = AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: 10.0, - insert_cpu_secs: 2.0, - merge_cpu_secs: 3.0, - query_cpu_secs: 5.0, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }; - let deployment = Deployment { - capability: Capability::TopK, - labels: labels.clone(), - config, - window_secs: 20, - slide_secs: 10, - }; - let rqe = Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs: 60, - interval_secs: 30, - labels: labels.clone(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, - }; - let tables = BTreeMap::from([( - labels, - LabelSetInfo { - cardinality: 4, - arrival_rate_per_sec: 7.0, - }, - )]); - let result = score(&[rqe], &[deployment], &vec![0], &tables); - assert_eq!(result.peak_query_memory_bytes, 40.0); - assert_eq!(result.ingest_cpu_secs_per_sec, 28.0); // 7 items × 2 active × 2 CPU - assert_eq!(result.query_latency_secs, vec![44.0]); // 4 × (5 query + 2 merges × 3) - assert_eq!(result.query_cpu_secs_per_sec, 20.0 / 30.0); - assert_eq!(result.merge_cpu_secs_per_sec, 24.0 / 30.0); - assert_eq!(result.retained_memory_bytes, 320.0); // 4 × 10 × (20 + 60) / 10 - } - - #[test] - fn shared_deployment_retains_for_its_longest_lookback() { - let labels = LabelSet::new(); - let deployment = Deployment { - capability: Capability::TopK, - labels: labels.clone(), - config: AtomicCostEntry { - sketch: "cms-heap-topk-fastpath-vector2d".into(), - sketch_config: serde_json::json!(null), - mem_bytes_per_instance: 10.0, - insert_cpu_secs: 1.0, - merge_cpu_secs: 1.0, - query_cpu_secs: 1.0, - query_accuracy: BTreeMap::from([("err".into(), 0.0)]), - }, - window_secs: 10, - slide_secs: 10, - }; - let rqe = |lookback_secs| Rqe { - id: "r".into(), - capability: Capability::TopK, - lookback_secs, - interval_secs: 10, - labels: labels.clone(), - accuracy_metric: "err".into(), - accuracy_tolerance: 1.0, - accuracy_direction: AccuracyDirection::LowerIsBetter, - }; - let tables = BTreeMap::from([( - labels.clone(), - LabelSetInfo { - cardinality: 2, - arrival_rate_per_sec: 1.0, - }, - )]); - let result = score(&[rqe(60), rqe(600)], &[deployment], &vec![0, 0], &tables); - // One copy of state, sized for the 600 s lookback: 2 × 10 × (10 + 600) / 10. - assert_eq!(result.retained_memory_bytes, 1220.0); - } - - #[test] - fn machine_family_is_sized_by_its_binding_resource() { - let family = MachineFamily { - family: "f".into(), - vcpu: 4.0, - memory_gib: 8.0, - usd_per_hour: 2.0, - }; - let mut objectives = Objectives { - peak_query_memory_bytes: 0.0, - ingest_cpu_secs_per_sec: 0.0, - merge_cpu_secs_per_sec: 0.0, - query_cpu_secs_per_sec: 0.0, - tco_cpu_secs_per_sec: 2.0, - retained_memory_bytes: BYTES_PER_GIB, - query_latency_secs: Vec::new(), - }; - assert_eq!(family.instances(&objectives), 0.5); // CPU binds - objectives.retained_memory_bytes = 16.0 * BYTES_PER_GIB; - assert_eq!(family.usd_per_hour(&objectives), 4.0); // memory binds: 2 instances - } - - #[test] - fn reads_committed_pricing_snapshot() { - let families = - MachineFamily::from_pricing_json(include_str!("../data/ec2-pricing-2026-10-04.json")) - .expect("committed snapshot parses"); - let names: Vec<_> = families.iter().map(|f| f.family.as_str()).collect(); - assert_eq!( - names, - ["compute_optimized", "general_purpose", "memory_optimized"] - ); - assert!(families.iter().all(|f| f.usd_per_hour > 0.0)); - } -} diff --git a/rqe-optimizer/src/pareto.rs b/rqe-optimizer/src/pareto.rs index a48b6181..66d9e0e1 100644 --- a/rqe-optimizer/src/pareto.rs +++ b/rqe-optimizer/src/pareto.rs @@ -1,6 +1,6 @@ -//! Non-dominated filtering for `(peak memory, TCO CPU, per-RQE latency)`. +//! Non-dominated filtering for `(CPU, memory, per-RQE latency)`. -use crate::{objectives::Objectives, Mapping}; +use crate::{analytical_cost_model::PlanCost, Mapping}; fn dominates(a: &[f64], b: &[f64]) -> bool { let mut strict = false; @@ -15,12 +15,9 @@ fn dominates(a: &[f64], b: &[f64]) -> bool { strict } -fn objective_vector(objectives: &Objectives) -> Vec { - let mut vector = vec![ - objectives.peak_query_memory_bytes, - objectives.tco_cpu_secs_per_sec, - ]; - vector.extend(&objectives.query_latency_secs); +fn pareto_vector(plan_cost: &PlanCost) -> Vec { + let mut vector = vec![plan_cost.cpu_secs_per_sec(), plan_cost.memory_bytes()]; + vector.extend(&plan_cost.query_latency_secs); vector } @@ -28,7 +25,7 @@ fn objective_vector(objectives: &Objectives) -> Vec { #[derive(Debug, Clone)] pub struct ParetoEntry { pub mapping: Mapping, - pub objectives: Objectives, + pub plan_cost: PlanCost, } /// Retains only non-dominated mappings while a streaming enumerator visits @@ -45,20 +42,20 @@ impl ParetoFront { /// Consider one scored mapping. Returns true when it remains on the /// frontier. Equal objective vectors are both retained. - pub fn consider(&mut self, mapping: &Mapping, objectives: Objectives) -> bool { - let candidate = objective_vector(&objectives); + pub fn consider(&mut self, mapping: &Mapping, plan_cost: PlanCost) -> bool { + let candidate = pareto_vector(&plan_cost); if self .entries .iter() - .any(|entry| dominates(&objective_vector(&entry.objectives), &candidate)) + .any(|entry| dominates(&pareto_vector(&entry.plan_cost), &candidate)) { return false; } self.entries - .retain(|entry| !dominates(&candidate, &objective_vector(&entry.objectives))); + .retain(|entry| !dominates(&candidate, &pareto_vector(&entry.plan_cost))); self.entries.push(ParetoEntry { mapping: mapping.clone(), - objectives, + plan_cost, }); true } @@ -68,25 +65,28 @@ impl ParetoFront { } } -pub fn pareto_front(objs: &[Objectives]) -> Vec { - let vectors: Vec> = objs.iter().map(objective_vector).collect(); - (0..objs.len()) - .filter(|&i| !(0..objs.len()).any(|j| j != i && dominates(&vectors[j], &vectors[i]))) +pub fn pareto_front(plan_costs: &[PlanCost]) -> Vec { + let vectors: Vec> = plan_costs.iter().map(pareto_vector).collect(); + (0..plan_costs.len()) + .filter(|&i| !(0..plan_costs.len()).any(|j| j != i && dominates(&vectors[j], &vectors[i]))) .collect() } #[cfg(test)] mod tests { use super::*; + use crate::analytical_cost_model::PhaseCost; - fn objectives(memory: f64, cpu: f64, latency: f64) -> Objectives { - Objectives { - peak_query_memory_bytes: memory, - retained_memory_bytes: 0.0, - ingest_cpu_secs_per_sec: 0.0, - merge_cpu_secs_per_sec: 0.0, - query_cpu_secs_per_sec: 0.0, - tco_cpu_secs_per_sec: cpu, + fn plan_cost(memory: f64, cpu: f64, latency: f64) -> PlanCost { + let phase = PhaseCost { + cpu_secs_per_sec: cpu, + memory_bytes: memory, + }; + PlanCost { + ingest: phase, + merge: PhaseCost::default(), + query: PhaseCost::default(), + storage: PhaseCost::default(), query_latency_secs: vec![latency], } } @@ -94,9 +94,9 @@ mod tests { #[test] fn incremental_front_discards_dominated_mappings() { let mut front = ParetoFront::new(); - assert!(front.consider(&vec![0], objectives(10.0, 10.0, 10.0))); - assert!(!front.consider(&vec![1], objectives(20.0, 20.0, 20.0))); - assert!(front.consider(&vec![2], objectives(5.0, 5.0, 5.0))); + assert!(front.consider(&vec![0], plan_cost(10.0, 10.0, 10.0))); + assert!(!front.consider(&vec![1], plan_cost(20.0, 20.0, 20.0))); + assert!(front.consider(&vec![2], plan_cost(5.0, 5.0, 5.0))); assert_eq!(front.entries().len(), 1); assert_eq!(front.entries()[0].mapping, vec![2]); } diff --git a/scripts/fetch_ec2_pricing.py b/scripts/fetch_ec2_pricing.py deleted file mode 100755 index f33cba19..00000000 --- a/scripts/fetch_ec2_pricing.py +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env python3 -"""Snapshot on-demand EC2 prices for the rqe-optimizer machine families. - -Reads the public price file behind aws.amazon.com/ec2/pricing/on-demand -(us-east-1, Linux, shared tenancy) and writes the three instance types the -optimizer prices plans with. Never edit the output by hand; rerun this. - -Usage: - scripts/fetch_ec2_pricing.py rqe-optimizer/data/ec2-pricing-$(date +%F).json -""" -import datetime -import gzip -import json -import sys -import urllib.request - -SOURCE = ( - "https://b0.p.awsstatic.com/pricing/2.0/meteredUnitMaps/ec2/USD/current/" - "ec2-ondemand-without-sec-sel/US%20East%20(N.%20Virginia)/Linux/index.json" -) -REGION = "US East (N. Virginia)" -# One size per family: plans are priced in fractional instances, so the size -# within a family does not change the result. -INSTANCE_TYPES = { - "compute_optimized": "c7i.xlarge", - "general_purpose": "m7i.xlarge", - "memory_optimized": "r7i.xlarge", -} - - -def main(out_path): - with urllib.request.urlopen(SOURCE) as response: - body = response.read() - if body[:2] == b"\x1f\x8b": - body = gzip.decompress(body) - data = json.loads(body) - rows = {row["Instance Type"]: row for row in data["regions"][REGION].values()} - - families = [] - for family, instance_type in INSTANCE_TYPES.items(): - row = rows[instance_type] - memory, unit = row["Memory"].split() - assert unit == "GiB", row["Memory"] - families.append( - { - "family": family, - "instance_type": instance_type, - "vcpu": int(row["vCPU"]), - "memory_gib": float(memory), - "usd_per_hour": float(row["price"]), - "rate_code": row["rateCode"], - } - ) - - snapshot = { - "source": SOURCE, - "region": REGION, - "operating_system": "Linux", - "pricing": "on-demand", - "publication_date": data["manifest"]["hawkFilePublicationDate"], - "fetched": datetime.date.today().isoformat(), - "families": families, - } - with open(out_path, "w") as out: - json.dump(snapshot, out, indent=2) - out.write("\n") - - -if __name__ == "__main__": - main(sys.argv[1])