Skip to content

refactor(stage3): one cost-row builder and model setup for cost models 1 and 3 - #1519

Merged
zzylol merged 4 commits into
mainfrom
refactor/stage3-one-cost-row-builder
Nov 26, 2026
Merged

zzylol merged 4 commits into
mainfrom
refactor/stage3-one-cost-row-builder

Conversation

@zzylol

@zzylol zzylol commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: cost model 3's MILP (cluster/solve.rs) re-implemented cost model 1's cost rows, model setup, HiGHS status handling and read-back. It also re-implemented two asap_cost rules: refresh queueing and the fixed cost of each request. Every change had to be made twice and kept in sync by hand. feat: storage description in the cost inputs, disk cost in the presets, and exact raw-data disk cost in Stage 3 (#1469) #1474 had to do this for the raw-data rows.
  • Change: one shared builder for the cost rows (selection_cost_terms, with each source's $r_s$ passed in through a closure and keyed by &Source instead of a debug string). Shared helpers for model setup and solving. asap_cost::{refresh_queue, request_fixed_cost, requests_per_second} used on both sides. Reader::{variable, is_selected} replace six copies of a match. Dead or one-variant items are deleted.
  • Effect: plans, costs and latencies do not change. Every snapshot workload gets the same plan, and corpus snapshots, goldens and sketch plan snapshots pass without being regenerated. the_milp_latencies_are_the_plan_costs_on_every_snapshot_workload (MILP latency == plan_cost latency) and the debug assert that the MILP objective equals plan_cost still hold. Net change: −551 / +564 lines; the additions include doc comments on the new shared helpers.

Review guide

  • Base: main. Not stacked.
  • Read first: crates/stage3-plan-selection/src/milp/model/mod.rs: selection_cost_terms, selection_model, structure_constraints, solution_columns, selected_executions_and_edges / answering_executions, objective_scale. Then cluster/solve.rs (quantity_expression, build_and_solve), which now calls them.
  • Needs careful review: whether the order of variables and rows sent to HiGHS stays the same (see Decisions). Cost model 3's order is unchanged. Cost model 1's raw-data rows now come after the (R)/(X) rows.
  • Mechanical: retention.rs and selection_cost_per_second (Reader methods), dominance.rs (Pairing removed, no_more / answers_per_execution / input_of moved to module level), exclusions.rs (D8), lib.rs (O4), measured.rs (X1), and lowest_mean_latency.rs (D14).

Behavior: before → after

asap-planner --format json on any workload, under cost model 1 or cost model 3 (lowest_mean_latency): the same selected plan, cost per second, per-query latencies, and the same accepted/rejected lines, before and after. Evidence: the planner-cli snapshot suites and the exactness tests in Verification, which compare complete plan outputs over the snapshot corpus. The only visible difference is the label in the log_solver stderr line for tie-break solves: Memory / Disk become Limit(MemoryBytes) / Limit(DiskBytes). The PR serves maintainability: one place to change each cost row and each queueing rule.

Interfaces

crates/cost/src/plan/cost.rs, crates/cost/src/lib.rs, crates/cost/src/measured.rs (cost.rs, measured.rs)

+/// The runtime's fixed cost of one request of a query: ns_per_evaluation once
+/// and ns_per_evaluation_step per step of its computed range (1 step without one).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct RequestFixedCost {
+    /// Rounds of the request's steps over the query threads (`step_rounds`).
+    pub step_rounds: f64,
+    /// Fixed latency, ms: the per-step part once per round.
+    pub latency_ms: f64,
+    /// Fixed CPU, ms: every step's.
+    pub cpu_ms: f64,
+}
+/// RequestFixedCost of one request of `entry`; used by plan_cost and Stage 3's query shapes.
+pub fn request_fixed_cost(entry: Option<&QueryWorkloadEntry>, settings: &CostInputs) -> RequestFixedCost;
+/// Requests per second of `entry` (one per evaluation of its recurrence); 0 without an entry.
+pub fn requests_per_second(entry: Option<&QueryWorkloadEntry>, settings: &CostInputs) -> Result<f64, AnalyticalCostError>;
-/// Rounds of `steps` over `query_threads` (now private: callers read `RequestFixedCost::step_rounds`).
-pub fn step_rounds(steps: f64, query_threads: u32) -> f64;
+fn step_rounds(steps: f64, query_threads: u32) -> f64;
+/// The other refresh groups `group` queues behind, in group order: `true` = it reads
+/// that group (waits for its whole refresh), `false` = closes at the same instant
+/// (waits for its refresh over the precompute threads).
+pub fn refresh_queue<'a>(group: usize, windows: &'a [RefreshWindow], reads: &'a BTreeSet<usize>) -> impl Iterator<Item = (usize, bool)> + 'a;
-/// The price of `operator` at `phase` on `family` (no series count).
-pub fn lookup(table: &MeasuredOperationCosts, operator: OperatorKind, phase: ExecutionTiming, family: StateFamily<'_>, size_of: impl Fn(&SketchParams) -> f64) -> Option<UnitPrice>;

lookup is removed because only tests called it. Production code calls lookup_at_scale, which now carries lookup's doc. The tests call lookup_at_scale(..., None).

crates/stage3-plan-selection/src/selectable.rs (file), crate-private

 pub(crate) enum Reader {
     Edge(usize),
     Output(QueryId),
 }
+impl Reader {
+    /// This read's y (edge) or z (query output) variable; None when not selectable.
+    pub(crate) fn variable(self, execution: usize, y: &BTreeMap<usize, Variable>, z: &BTreeMap<(QueryId, usize), Variable>) -> Option<Variable>;
+    /// Whether this read is among the selected edges / outputs.
+    pub(crate) fn is_selected(self, execution: usize, edges: &HashSet<usize>, outputs: &HashSet<(QueryId, usize)>) -> bool;
+}

crates/stage3-plan-selection/src/milp/model/mod.rs (file), module-private

-fn raw_data_disk_rows(inputs: &SelectionInputs<'_>, variables: &SelectionVariables, kept: &[bool]) -> Vec<(Variable, f64, Variable)>;
-fn raw_data_read_variable(read: &RawDataRead, y: &BTreeMap<usize, Variable>, z: &BTreeMap<(QueryId, usize), Variable>) -> Option<Variable>;
+/// One raw-data row (r_s, coefficient, variable): r_s >= coefficient × variable, unscaled.
+pub(super) type RawDataRow = (Variable, f64, Variable);
+/// x/y/h terms and raw-data rows of `costs`; `raw_data_on_disk_of` gives source s's r_s.
+pub(super) fn selection_cost_terms<'c>(selectable: &SelectableExecutions, costs: &'c ExecutionCosts, variables: &SelectionVariables, kept: &[bool], raw_data_on_disk_of: impl FnMut(&'c Source) -> Variable) -> (Vec<(f64, Variable)>, Vec<RawDataRow>);
+/// Variables, components, (K) rows and the selection-variable count every solve builds first.
+pub(super) struct SelectionModel { pub(super) variables: SelectionVariables, pub(super) components: Components, pub(super) accuracy_rows: Vec<Constraint>, pub(super) selection_variable_count: usize }
+pub(super) fn selection_model(inputs: &SelectionInputs<'_>, kept: &[bool], rules: Option<&AccuracyRules>, problem: &mut ProblemVariables) -> SelectionModel;
+/// (A), (B), (C)/(D), (E), (F), (R), (X) in order.
+pub(super) fn structure_constraints(inputs: &SelectionInputs<'_>, variables: &SelectionVariables, components: &Components) -> Vec<Constraint>;
+pub(super) fn column_of(problem: &ProblemVariables) -> HashMap<Variable, usize>;
+/// Columns of an empty model (all 0) or a feasible plan (optimum or node limit); else HiGHS's status.
+pub(super) fn solution_columns(solved: &highs::SolvedModel, variable_count: usize) -> Result<Vec<f64>, highs::HighsModelStatus>;
+pub(super) fn selected_executions_and_edges(variables: &SelectionVariables, chosen: impl Fn(Variable) -> bool) -> (Vec<usize>, Vec<usize>);
+pub(super) fn answering_executions(selectable: &SelectableExecutions, variables: &SelectionVariables, chosen: impl Fn(Variable) -> bool) -> Vec<(QueryId, usize)>;
+/// Factor that scales the largest coefficient to LARGEST_SCALED_OBJECTIVE_COEFFICIENT (1 if 0 or not finite).
+pub(super) fn objective_scale(largest: f64) -> f64;

crates/stage3-plan-selection/src/milp/model/cluster/{solve,mod}.rs, milp/dominance.rs, lib.rs, crate-private

-pub(super) const LARGEST_SCALED_COEFFICIENT: f64 = 1e6;
 pub(super) enum Objective {
     MeanLatency,
     Relaxation,
-    Memory,
-    Disk,
     Limit(ClusterLimit),
 }
-pub(crate) enum Pairing { LifetimeTwin }
-pub(crate) fn dominated_in_every_quantity(inputs: &SelectionInputs<'_>, quantities: &[&ExecutionCosts], pairing: Pairing) -> Vec<bool>;
+pub(crate) fn dominated_in_every_quantity(inputs: &SelectionInputs<'_>, quantities: &[&ExecutionCosts]) -> Vec<bool>;
-fn diagnose(limits: &[ClusterLimit], solve: impl Fn(Objective, &[ClusterLimit]) -> Option<Solution>) -> ClusterSelectionError;
+fn diagnose(inputs: &ClusterInputs<'_>, limits: &[ClusterLimit], solve: impl Fn(Objective, &[ClusterLimit]) -> Option<Solution>) -> ClusterSelectionError;

available() moved from lib.rs to cluster/mod.rs. ClusterLimitShortfall.available is now set when the shortfall is built, with no NaN placeholder.

Usage (flow, unchanged in behavior): asap-planner --format json → select_plan → under cost model 1, solve_selection → selection_model → selection_cost_terms(…, |source| variables.raw_data_on_disk[source]) → structure_constraints + raw-data rows scaled by objective_scale → HiGHS → solution_columns → read-back. Under cost model 3, solve_cluster_selection → build_and_solve → selection_model → quantity_expression once per memory, disk and CPU (each calls selection_cost_terms with a closure that adds one $r_s$ per source) → f_G and big-M from asap_cost::refresh_queue → per-query fixed latency and CPU from asap_cost::request_fixed_cost → the same read-back. The output is the selected plan, as before.

Algorithm changes

None. The rules and formulas are the same; only where they are written changes. The order of variables (HiGHS columns) and rows is preserved for cost model 3. For cost model 1, only the raw-data rows move (see below).

Decisions and open questions

Needs reviewer decision: None.

Decided (2026-11-25, by the implementer, within the behavior-preserving rule):

  • kept_result_terms / resident_window_terms stay outside the shared builder. Cost model 1 calls them in the order resident, then kept; cost model 3 calls them kept, then resident. Each adds variables, so moving them into one builder would reorder HiGHS columns for one of the two models. Both are already shared functions.
  • Cost model 1's raw-data rows now come after (R) and (X), not before them, so all seven structure rows can come from one structure_constraints. This only reorders rows in a gap-0 solve, so the optimum is the same. Among plans that cost exactly the same, HiGHS may now return a different one, because its search follows row order, and solve time may shift; neither was measured. No snapshot changed.
  • Cost model 1's invariants are checked again: every $y$ is on a costed edge and every $h_v$ has a retention share. The old code used expect and indexing; it is now an assert! in solve_selection. The shared builder reads a missing value as 0, which only cost model 3's quantities have.
  • D12 not done: over_a_limit_alone keeps its own || test, so it skips the disk sum when memory alone is over the limit (review nit).
  • solution_columns accepts ReachedSolutionLimit with a feasible solution for both models. Cost model 1 sets no node or solution limit, so it never gets that status.
  • D3: refresh_queue returns which kind of wait applies (bool), not a coefficient. Each site applies its own form (/ threads in f64, * (1/threads) on an Expression), so the floats are identical bit for bit. Not shared: grouping by refresh window and building group reads. plan_cost groups DAG nodes and updates their phase times at the same time, while Stage 3 groups executions. The parts that have to stay in sync with plan_cost are the queueing rule and the request cost, and both are now shared.
  • D4: plan_cost's per-query fixed latency now uses request_fixed_cost(..).latency_ms = (a + b·r)·1e-6 instead of a·1e-6 + b·1e-6·r. These can differ in the last bit; no snapshot or golden changed.
  • O3 folded: Objective is crate-private and never serialized, so no input or output file format changes.
  • D14: the shared assert_close has a 1e-9 floor, where the deleted local copy had 1e-7. All lowest_mean_latency tests pass with it.

Deleted

Item Why nothing needs it
asap_cost::lookup only tests called it; they call lookup_at_scale(.., None)
asap_cost::step_rounds (now private, not re-exported) its only caller is request_fixed_cost; others read RequestFixedCost::step_rounds
Pairing { LifetimeTwin } and its parameter (dominance.rs) one variant; every caller passed it
LARGEST_SCALED_COEFFICIENT (cluster/solve.rs) duplicate of LARGEST_SCALED_OBJECTIVE_COEFFICIENT, via objective_scale
Objective::Memory, Objective::Disk same goal as Objective::Limit(MemoryBytes / DiskBytes)
raw_data_disk_rows, raw_data_read_variable (model/mod.rs) replaced by selection_cost_terms and Reader::variable
group_of closure (exclusions.rs) same as memo_group_of
local assert_close (lowest_mean_latency.rs) same as the common one in lowest_mean_latency_common.rs
available in lib.rs moved next to diagnose in cluster/mod.rs

Verification

Scope Result Notes
cargo fmt --all --check pass
cargo clippy -p asap-cost -p asap-stage3-plan-selection -p asap-integration-tests -p asap-devtools --all-targets -- -D warnings pass after the review fixes: -p asap-cost -p asap-stage3-plan-selection
After the review fixes (e752f9d): stage3 lib / cost lib + measured_operation_costs / integration lowest_mean_latency + stage3_objective / planner-cli goldens 55 / 134 + 9 / 54 (1 ignored) / 14 passed the other rows are from the first push (1d09a01)
asap-stage3-plan-selection lib (debug: MILP objective == plan_cost assert) 55 passed includes big_m_bounds_the_freshness_of_every_selection, which checks freshness_big_m against its own copy of the queueing rule
asap-cost lib / measured_operation_costs / cost_inputs_json 134 / 9 / 2 passed lookup tests moved to lookup_at_scale(.., None)
asap-integration-tests (lowest_mean_latency, stage3_objective, storage_costs, calibration_terms, …) 331 passed, 8 ignored
planner-cli corpus_snapshots / goldens 7 passed (2 ignored) / 14 passed no snapshot regenerated
planner-cli tests/main.rs (sketch plan snapshots, lowest_mean_latency_exactness) 64 passed, 2 ignored 2 exactness tests first failed because the shared disk filled up (empty plan file, ENOSPC); rerun on the same binaries: 6 passed, 1 ignored
devtools (tests/main.rs, asap_lane_conformance, lib) 31 / 1 / 11 passed
asap-cost doctests not run ENOSPC when creating the doctest temp dir; the only doc change is prose in measured.rs

No new tests: this PR is a refactor, and the suites above already cover each changed path.

Follow-ups

  • Stage O2: move LatencySelectionChecks out of asap_cost::CostInputs into Stage 3. Left out because it changes the cost-inputs format.
  • Not in this PR (other review fix PRs cover them): the kept-bytes loop and ExecutionCosts fields in stage3 cost.rs, and the D7/O6 cover code.
  • Remaining stage findings not in scope: D9 (refresh_wait_ms_per_run), D10, D11, D13, O5, O7, X2–X4.

…fixed cost

Add refresh_queue (which groups a refresh group waits behind, whole or
shared over the precompute threads), request_fixed_cost and
requests_per_second, used by plan_cost and, next, by Stage 3. Delete
lookup, which only tests called; they call lookup_at_scale.
…s 1 and 3

selection_cost_terms builds the x/y/h terms and raw-data rows for both
objectives (the per-source r_s comes from a closure, keyed by Source);
selection_model, structure_constraints, column_of, solution_columns and
the read-back helpers replace the duplicated setup and HiGHS handling.
Use asap_cost's refresh_queue and request_fixed_cost. Reader::variable
and Reader::is_selected replace six matches. Delete Pairing,
LARGEST_SCALED_COEFFICIENT and Objective::{Memory, Disk}; fill
ClusterLimitShortfall::available in the cluster module.
@zzylol zzylol added optimizer Workload optimization and plan selection refactor labels Nov 25, 2026
Make step_rounds private (RequestFixedCost::step_rounds replaces it);
compute request_fixed_cost once per query in plan_cost and
query_latencies; assert cost model 1's costed-edge and retention-share
invariants again; if/else on refresh_queue's kind; keep
over_a_limit_alone's short-circuit.
@zzylol
zzylol merged commit e45cbb2 into main Nov 26, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimizer Workload optimization and plan selection refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant