From bf2be7c76427e577f36b4a95adc0135e0f5e6bb1 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:46:09 +0000 Subject: [PATCH 1/3] test(stage3): retention and resident windows are shares in [0, 1] Two selection tests over the chain retaining 300 s for its 1 m and 5 m readers: - every continuous variable of its selection model is within [0, 1], the retention h_v included, and the optimum still retains 300 s at 4.3 per second; - under a window cache keeping 6 and 30 windows at 2 per window, the resident-windows variable is within [0, 1] with the term 2 * 30, and the optimum (64 per second) is what plan_cost charges. Both fail on main: h_v is in seconds and r_v in windows, both unbounded. --- .../src/milp/model/tests.rs | 173 ++++++++++++++++++ 1 file changed, 173 insertions(+) diff --git a/crates/stage3-plan-selection/src/milp/model/tests.rs b/crates/stage3-plan-selection/src/milp/model/tests.rs index 2208a7657..abc606064 100644 --- a/crates/stage3-plan-selection/src/milp/model/tests.rs +++ b/crates/stage3-plan-selection/src/milp/model/tests.rs @@ -483,6 +483,179 @@ fn a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back() { assert_eq!(chain_node.retention_ms, Some(300_000)); } +/// The chain of [`a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back`]: +/// its $h_v$, in seconds, would be at least 60 or 300 times a read, an +/// unbounded column with whole-number coefficients that HiGHS's presolve +/// takes for an integer (#1533). Every continuous +/// variable of its selection model is within $[0, 1]$: $h_v$ is held as a +/// share of the 300 s the longest read needs, and the optimum still +/// retains 300 s. +#[test] +fn retention_is_a_share_of_the_longest_need() { + let mut memo = empty_memo(); + let m = scan(&mut memo); + let chain = group( + &mut memo, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: m, + summary_type: FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Sum), + input: SummaryUpdate::column(ColumnRef::SampleValue), + reduction: Reduction::PerEntity, + filter: None, + tumbling_window_width_ms: 10_000, + }), + ); + let last_1m = range(&mut memo, 60, chain); + let last_5m = range(&mut memo, 300, chain); + query(&mut memo, last_1m, None); + query(&mut memo, last_5m, None); + let physical = physical( + memo, + &[ + (own_candidate(m), NONE), + (own_candidate(chain), ACROSS_EVALUATIONS), + (own_candidate(last_1m), NONE), + (own_candidate(last_5m), NONE), + ], + ); + let entries = [every(10_000), every(20_000)]; + let (selectable, costs) = selection_inputs( + &physical, + &entries, + &[1.0, 1.0, 1.0, 1.0], + &[], + &[(1, 1e-3)], + ); + let inputs = SelectionInputs { + physical: &physical, + entries: &entries, + selectable: &selectable, + costs: &costs, + kept_query_time_results: None, + answer_cache: None, + }; + let mut problem = ProblemVariables::new(); + let kept = vec![true; selectable.executions().len()]; + selection_model(&inputs, &kept, None, &mut problem); + let continuous: Vec<(f64, f64)> = problem + .iter_variables_with_def() + .filter(|(_, definition)| !definition.is_integer()) + .map(|(_, definition)| (definition.get_min(), definition.get_max())) + .collect(); + assert!(!continuous.is_empty()); + assert!( + continuous + .iter() + .all(|&(min, max)| min >= 0.0 && max <= 1.0), + "{continuous:?}" + ); + let solved = solve_selection(&inputs).unwrap(); + assert_eq!( + solved.retention_ms.get(&PhysicalCandidateId(1)), + Some(&300_000) + ); + let optimum = solved.milp_optimum_per_second.unwrap(); + assert!((optimum - 4.3).abs() <= 1e-9 * 4.3, "{optimum}"); +} + +/// The chain of [`a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back`] +/// under a window cache: its 1 m reader keeps 6 windows resident, its 5 m +/// reader 30, at 2 per window. $r_v$ is the most over the selected reads, +/// 30, held as a share of the most any read keeps: in $[0, 1]$, its term +/// 2 · 30 per unit. Unbounded and in windows (whole numbers), HiGHS's +/// presolve takes it for an integer and its root reduced-cost fixing steps +/// through up to 1,024 of its values at every root LP solve (#1533). +#[test] +fn resident_windows_are_a_share_of_the_most_any_read_keeps() { + let mut memo = empty_memo(); + let m = scan(&mut memo); + let chain = group( + &mut memo, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: m, + summary_type: FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Sum), + input: SummaryUpdate::column(ColumnRef::SampleValue), + reduction: Reduction::PerEntity, + filter: None, + tumbling_window_width_ms: 10_000, + }), + ); + let last_1m = range(&mut memo, 60, chain); + let last_5m = range(&mut memo, 300, chain); + query(&mut memo, last_1m, None); + query(&mut memo, last_5m, None); + let physical = physical( + memo, + &[ + (own_candidate(m), NONE), + (own_candidate(chain), ACROSS_EVALUATIONS), + (own_candidate(last_1m), NONE), + (own_candidate(last_5m), NONE), + ], + ); + let entries = [every(10_000), every(20_000)]; + let (selectable, mut costs) = + selection_inputs(&physical, &entries, &[1.0, 1.0, 1.0, 1.0], &[], &[]); + let executions = selectable.executions(); + costs.resident_reads = selectable + .edges() + .iter() + .enumerate() + .filter(|(_, edge)| executions[edge.producer].candidate == PhysicalCandidateId(1)) + .map(|(position, edge)| { + let reader = executions[edge.consumer].candidate; + crate::resident_windows::ResidentRead { + execution: edge.producer, + reader: crate::selectable::Reader::Edge(position), + resident_windows: if reader == PhysicalCandidateId(2) { + 6.0 + } else { + 30.0 + }, + bytes_read_from_disk_per_second: 0.0, + most_bytes_read_from_disk_per_run: 0.0, + } + }) + .collect(); + assert_eq!(costs.resident_reads.len(), 2); + costs.per_resident_window = HashMap::from([(PhysicalCandidateId(1), 2.0)]); + let mut problem = ProblemVariables::new(); + let y: BTreeMap = (0..selectable.edges().len()) + .map(|position| (position, problem.add(variable().binary()))) + .collect(); + let mut rows = Vec::new(); + let terms = resident_window_terms( + &costs, + &selectable, + &y, + &BTreeMap::new(), + &mut problem, + &mut rows, + ); + let [(per_unit, share)] = terms[..] else { + panic!("one r_v: {terms:?}"); + }; + assert_eq!(per_unit, 2.0 * 30.0); + let (_, definition) = problem + .iter_variables_with_def() + .find(|&(variable, _)| variable == share) + .unwrap(); + assert_eq!((definition.get_min(), definition.get_max()), (0.0, 1.0)); + assert_eq!(rows.len(), 2); + let solved = solve_selection(&SelectionInputs { + physical: &physical, + entries: &entries, + selectable: &selectable, + costs: &costs, + kept_query_time_results: None, + answer_cache: None, + }) + .unwrap(); + let optimum = solved.milp_optimum_per_second.unwrap(); + assert!((optimum - 64.0).abs() <= 1e-9 * 64.0, "{optimum}"); + assert!((solved.cost_per_second_without_request_overhead - optimum).abs() <= 1e-9 * optimum); +} + /// A chain of 10 s windows materialized across evaluations, read every /// 10 s at its newest output only (no range above it): no read needs a /// retention, but a store always keeps the newest output, so the chain From 3e670d51bec1113377fc4b94066ac45de9fcead9 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:46:09 +0000 Subject: [PATCH 2/3] fix(stage3): retention and resident windows as shares of their largest need The selection MILP held h_v (seconds retained) and r_v (resident windows) as unbounded continuous columns with whole-number row coefficients (60 to 86,400 seconds; window counts). HiGHS's presolve takes such columns for integers, and its root reduced-cost fixing then steps through up to 1,024 values per column at every root LP solve, in time quadratic in the steps. On a dag-viewer random-mixed workload, 149 h_v columns took about 80 % of a 12 s solve. #1355's measured unit costs kept more executions, so more h_v columns (33 to 302 on the same workload) and the solve went from 0.9 s to 7.5 s. h_v is now RetentionShare: a share in [0, 1] of the longest need of its (R) rows, which read longest_need_s * share, so the rows keep their tolerance in seconds. The retention term, the raw-data rows and the answer horizon take the longest need as a factor. r_v is likewise a share of the most windows any kept read keeps. The feasible plans and the optimum are unchanged; plan_cost is unchanged. --- .../src/milp/kept_results.rs | 9 +- .../src/milp/model/mod.rs | 21 +-- .../src/milp/retention.rs | 153 +++++++++++++----- 3 files changed, 133 insertions(+), 50 deletions(-) diff --git a/crates/stage3-plan-selection/src/milp/kept_results.rs b/crates/stage3-plan-selection/src/milp/kept_results.rs index 15dc46a64..9213defdf 100644 --- a/crates/stage3-plan-selection/src/milp/kept_results.rs +++ b/crates/stage3-plan-selection/src/milp/kept_results.rs @@ -24,16 +24,17 @@ use asap_cost::plan::kept_results::{answers_kept, held_by_bounded_cache, kept_pe use asap_types::stages::PhysicalCandidateId; use super::model::SelectionInputs; +use super::retention::RetentionShare; use crate::cost::ExecutionCosts; use crate::retention::ms_to_seconds; use crate::selectable::QueryId; /// The variables the terms read: $x$ by execution, $z$ by (query, -/// execution), $h_v$ in seconds by candidate. +/// execution), $h_v$ by candidate ([`RetentionShare`]). pub(crate) struct KeptResultVariables<'a> { pub(crate) x: &'a [Variable], pub(crate) z: &'a BTreeMap<(QueryId, usize), Variable>, - pub(crate) h: &'a BTreeMap, + pub(crate) h: &'a BTreeMap, } /// The result cache's and the answer cache's terms of `costs`' quantity @@ -82,8 +83,8 @@ pub(crate) fn kept_result_terms( .max() .unwrap_or(0); let horizon = problem.add(variable().min(0).max(ms_to_seconds(longest))); - for &h in variables.h.values() { - rows.push(constraint!(horizon >= h)); + for h in variables.h.values() { + rows.push(constraint!(horizon >= h.seconds())); } let mut pool = Expression::default(); let mut largest = 0.0; diff --git a/crates/stage3-plan-selection/src/milp/model/mod.rs b/crates/stage3-plan-selection/src/milp/model/mod.rs index 5922c688e..9753ac54c 100644 --- a/crates/stage3-plan-selection/src/milp/model/mod.rs +++ b/crates/stage3-plan-selection/src/milp/model/mod.rs @@ -7,7 +7,7 @@ //! | baseline (section 3) over execution contexts (section 5) | $x_{\kappa,v}$ (with $x^{\mathrm{mat}}_v = x_{\mathrm{Materialized}(v),v}$), $y_{\kappa,u,c,i}$, $z_{q,v}$, $t$, $r_s$ ([`SelectionVariables`]) | (A) [`input_satisfaction_constraints`], (B) [`producer_selection_constraints`], (C)/(D) [`query_coverage_constraints`], (E) [`acyclicity_constraints`], (F) and one consumer per context of a query-time result that is not materialized [`use_constraints`], each source's raw data on disk once [`selection_cost_terms`]; (G), (H): $y$ exists only on admissible edges where the producer delivers on the consumer's context | //! | retention (section 5) | $h_v$ | (R) [`super::retention::retention_constraints`] | //! | result and answer caches (`cost-terms-from-calibration.md`, section 2) | $t$, $b$, $H$, $w_{q,e}$ | [`super::kept_results::kept_result_terms`] | -//! | resident windows under a window cache (`cost-terms-from-calibration.md`, section 1) | $r_v$ | (W) [`super::retention::resident_window_terms`] | +//! | resident windows under a window cache (`cost-terms-from-calibration.md`, section 1) | $s_v$, the share of its most windows | (W) [`super::retention::resident_window_terms`] | //! | exact-only reads per query | $a_{q,e}$ | (X) [`super::exact_only::exact_only_constraints`] | //! | accuracy (`accuracy-models.md`, constraint (K)), per execution | $E_{\kappa,c,m}$, $D_{\kappa,c}$ ([`AccuracyVariables`]); $F_{\kappa,c,i,m}$, $H_{\kappa,c,i}$ | (K) [`accuracy_constraints`], over [`ErrorModel`] | //! @@ -39,7 +39,7 @@ use super::graph::Components; use super::kept_results::{kept_result_terms, kept_results_quantity, KeptResultVariables}; use super::retention::{ least_retention_ms, resident_window_terms, resident_windows_quantity, retention_constraints, - retention_variables, + retention_variables, RetentionShare, }; use super::upper_bound::dearer_than_a_feasible_plan; use crate::cost::ExecutionCosts; @@ -85,9 +85,9 @@ pub(crate) struct SelectionVariables { /// $t$, by execution: only for executions on a cycle of selectable /// edges (a strongly connected component); `None` elsewhere. t: Vec>, - /// $h_v$ in seconds retained, for a candidate with a retention cost and - /// an execution kept ([`retention_variables`]). - pub(super) h: BTreeMap, + /// $h_v$ as a share of its longest need, for a candidate with a + /// retention cost and an execution kept ([`retention_variables`]). + pub(super) h: BTreeMap, /// Per raw-data source a query-time scan keeps on disk at a cost: the /// cost per second of keeping it, at least each selected scan's, /// scaled by the objective's scale ([`selection_cost_terms`]). @@ -354,9 +354,9 @@ pub(super) fn selection_cost_terms<'c>( .copied() .unwrap_or(0.0) }; - for (v, &h) in &variables.h { + for (v, h) in &variables.h { if !costs.raw_data_source.contains_key(v) { - terms.push((retention_share(v), h)); + terms.push((retention_share(v) * h.longest_need_s, h.share)); } } let mut executions_of: HashMap> = HashMap::new(); @@ -373,10 +373,10 @@ pub(super) fn selection_cost_terms<'c>( scans.sort_unstable_by_key(|(v, _)| **v); for (v, source) in scans { let r = raw_data_on_disk_of(source); - if let Some(&h) = variables.h.get(v) { + if let Some(h) = variables.h.get(v) { let per_retained_second = retention_share(v); if per_retained_second > 0.0 { - raw_data_rows.push((r, per_retained_second, h)); + raw_data_rows.push((r, per_retained_second * h.longest_need_s, h.share)); } } else if let Some(&d) = costs.unbounded_raw_data_on_disk_cost_per_second.get(v) { for &index in executions_of.get(v).into_iter().flatten() { @@ -669,7 +669,8 @@ pub(super) fn objective_scale(largest: f64) -> f64 { /// $\sum_v W^{\mathrm{mat}}_v x^{\mathrm{mat}}_v + \sum_{\kappa,v} /// \rho_\kappa c_{\kappa,v} x_{\kappa,v} + \sum \rho_\kappa c_{\kappa,u,c,i} /// y_{\kappa,u,c,i} + \sum_v \pi_v h_v + \sum_s r_s$ ($\pi_v h_v$ of a -/// query-time scan is in $r_s$) under (A)–(F), [`use_constraints`], +/// query-time scan is in $r_s$; $h_v$ in seconds, held as a share of its +/// longest need, [`RetentionShare`]) under (A)–(F), [`use_constraints`], /// the raw-data rows of [`selection_cost_terms`], (R), (X) and (K), with HiGHS at gap 0 on one /// thread. The executions dearer than a feasible plan /// ([`dearer_than_a_feasible_plan`]) or dominated by their lifetime twin diff --git a/crates/stage3-plan-selection/src/milp/retention.rs b/crates/stage3-plan-selection/src/milp/retention.rs index 8f6e294e4..1b08214e4 100644 --- a/crates/stage3-plan-selection/src/milp/retention.rs +++ b/crates/stage3-plan-selection/src/milp/retention.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; -use good_lp::{constraint, variable, Constraint, ProblemVariables, Variable}; +use good_lp::{constraint, variable, Constraint, Expression, ProblemVariables, Variable}; use asap_types::stages::PhysicalCandidateId; @@ -15,9 +15,36 @@ use crate::cost::ExecutionCosts; use crate::retention::ms_to_seconds; use crate::selectable::QueryId; -/// $h_v$ in seconds retained (the unit keeps (R)'s coefficients near the -/// others'), added to `problem`, for each candidate with a retention cost -/// ([`crate::cost::ExecutionCosts::retention_cost_per_retained_second`]) +/// $h_v$, the seconds candidate $v$ retains, as the share $h_v / H_v \in +/// [0, 1]$ of $H_v$, the longest any read of $v$ needs ((R)'s largest +/// coefficient): $h_v$ is `longest_need_s` times `share`, and (R) reads +/// that product, so its rows keep their tolerance in seconds (a row over +/// the share alone would let HiGHS's absolute tolerance of 1e-6 stand for +/// 1e-6 of $H_v$). +/// +/// In seconds, $h_v$ would be unbounded with whole-number row coefficients +/// (60 to 86,400). HiGHS's presolve takes such a column for an integer, and +/// its root reduced-cost fixing then steps through up to 1,024 of its +/// values at every root LP solve, in time quadratic in the steps: 149 such +/// columns took about 80 % of a 12 s solve of a dag-viewer workload. +#[derive(Debug, Clone, Copy)] +pub(crate) struct RetentionShare { + /// $h_v / H_v$, in $[0, 1]$. + pub(crate) share: Variable, + /// $H_v$ in seconds; 1 when no read needs any retention. + pub(crate) longest_need_s: f64, +} + +impl RetentionShare { + /// $h_v$ in seconds, `longest_need_s` times `share`: what (R) and the + /// answer horizon read. + pub(crate) fn seconds(&self) -> Expression { + self.longest_need_s * self.share + } +} + +/// $h_v$ ([`RetentionShare`]), added to `problem`, for each candidate +/// with a retention cost ([`ExecutionCosts::retention_cost_per_retained_second`]) /// one of whose executions is `kept` (by position in /// `SelectableExecutions::executions`): one whose executions are all left /// out retains nothing. @@ -25,11 +52,10 @@ pub(crate) fn retention_variables( inputs: &SelectionInputs<'_>, kept: &[bool], problem: &mut ProblemVariables, -) -> BTreeMap { +) -> BTreeMap { let retaining = &inputs.costs.retention_cost_per_retained_second; - let mut retained: Vec = inputs - .selectable - .executions() + let executions = inputs.selectable.executions(); + let mut retained: Vec = executions .iter() .zip(kept) .filter(|(execution, &kept)| kept && retaining.contains_key(&execution.candidate)) @@ -37,9 +63,41 @@ pub(crate) fn retention_variables( .collect(); retained.sort_unstable(); retained.dedup(); + // Per candidate, the longest need of (R)'s rows, in ms. + let mut longest_need_ms: HashMap = HashMap::new(); + let reads_back = inputs + .selectable + .reads_back(&inputs.costs.retention_need_ms_per_edge) + .filter_map(|(index, _, need_ms)| Some((index, need_ms?))); + let least = (inputs + .costs + .least_retention_ms_per_execution + .iter() + .enumerate()) + .filter_map(|(index, need_ms)| Some((index, (*need_ms)?))); + for (index, need_ms) in reads_back.chain(least) { + let v = executions[index].candidate; + if retaining.contains_key(&v) { + let longest = longest_need_ms.entry(v).or_default(); + *longest = (*longest).max(need_ms); + } + } retained .into_iter() - .map(|v| (v, problem.add(variable().min(0)))) + .map(|v| { + let longest_need_s = match longest_need_ms.get(&v) { + Some(&ms) if ms > 0 => ms_to_seconds(ms), + _ => 1.0, + }; + let share = problem.add(variable().min(0).max(1)); + ( + v, + RetentionShare { + share, + longest_need_s, + }, + ) + }) .collect() } @@ -60,7 +118,7 @@ pub(crate) fn retention_variables( /// $z$, but tightens the relaxation where fractional $y$ leave $h_v$ low. pub(crate) fn retention_constraints( inputs: &SelectionInputs<'_>, - h: &BTreeMap, + h: &BTreeMap, x: &[Variable], y: &BTreeMap, z: &BTreeMap<(QueryId, usize), Variable>, @@ -76,7 +134,7 @@ pub(crate) fn retention_constraints( }; if let Some(read) = reader.variable(index, y, z) { let need_ms = need_ms.expect("a candidate with h_v is read within a bound"); - constraints.push(constraint!(h >= ms_to_seconds(need_ms) * read)); + constraints.push(constraint!(h.seconds() >= ms_to_seconds(need_ms) * read)); } } for (index, need_ms) in inputs @@ -87,7 +145,9 @@ pub(crate) fn retention_constraints( { if let (Some(&h), Some(need_ms)) = (h.get(&executions[index].candidate), *need_ms) { if need_ms > 0 { - constraints.push(constraint!(h >= ms_to_seconds(need_ms) * x[index])); + constraints.push(constraint!( + h.seconds() >= ms_to_seconds(need_ms) * x[index] + )); } } } @@ -127,14 +187,18 @@ pub(crate) fn least_retention_ms( /// $r_v$, the windows a view under the data plane's window cache keeps /// resident in memory (`docs/design_docs/proposals/cost-terms-from-calibration.md`, -/// section 1), one per view with a read kept: (W) $r_v \ge -/// \operatorname{res}_{e}\, \mathrm{read}_e$ for each read $e$ of its -/// executions (`ExecutionCosts::resident_reads`: an edge $y$ or a query -/// output $z$; the read's mean windows, its most when `costs` is peak -/// memory). Its quantity per window is positive, so at the optimum $r_v$ is -/// the most over the selected reads, what `plan_cost` charges. The -/// variables are added to `problem` and (W) to `rows`; returns each -/// $r_v$'s term (quantity per window, $r_v$), unscaled. +/// section 1), one per view with a read kept, as the share $s_v = r_v / +/// R_v \in [0, 1]$ of $R_v$, the most windows any of its kept reads keeps: +/// (W) $R_v s_v \ge \operatorname{res}_{e}\, \mathrm{read}_e$ for each +/// read $e$ of its executions (`ExecutionCosts::resident_reads`: an edge +/// $y$ or a query output $z$; the read's mean windows, its most when +/// `costs` is peak memory). Its quantity per window is positive, so at the +/// optimum $R_v s_v$ is the most over the selected reads, what `plan_cost` +/// charges. The variables are added to `problem` and (W) to `rows`; returns +/// each view's term ($R_v$ times its quantity per window, $s_v$), unscaled. +/// +/// $r_v$ itself, in windows, would be unbounded with whole-number row +/// coefficients, the shape [`RetentionShare`] avoids for $h_v$. pub(crate) fn resident_window_terms( costs: &ExecutionCosts, selectable: &crate::selectable::SelectableExecutions, @@ -143,27 +207,44 @@ pub(crate) fn resident_window_terms( problem: &mut ProblemVariables, rows: &mut Vec, ) -> Vec<(f64, Variable)> { + // Each read kept: (view, its windows, its read variable). + let kept_reads: Vec<(PhysicalCandidateId, f64, Variable)> = costs + .resident_reads + .iter() + .filter_map(|read| { + let v = selectable.executions()[read.execution].candidate; + let per_window = *costs.per_resident_window.get(&v)?; + let read_variable = read.reader.variable(read.execution, y, z)?; + let windows = read.resident_windows; + (per_window > 0.0 && windows > 0.0 && windows.is_finite()).then_some(( + v, + windows, + read_variable, + )) + }) + .collect(); + let mut most_resident_windows: BTreeMap = BTreeMap::new(); + for &(v, read_windows, _) in &kept_reads { + let most = most_resident_windows.entry(v).or_default(); + *most = most.max(read_windows); + } let mut resident: BTreeMap = BTreeMap::new(); - for read in &costs.resident_reads { - let v = selectable.executions()[read.execution].candidate; - let Some(&per_window) = costs.per_resident_window.get(&v) else { - continue; - }; - let Some(read_variable) = read.reader.variable(read.execution, y, z) else { - continue; - }; - let windows = read.resident_windows; - if per_window <= 0.0 || windows <= 0.0 { - continue; - } - let r = *resident + for (v, read_windows, read_variable) in kept_reads { + let share = *resident .entry(v) - .or_insert_with(|| problem.add(variable().min(0))); - rows.push(constraint!(r >= windows * read_variable)); + .or_insert_with(|| problem.add(variable().min(0).max(1))); + rows.push(constraint!( + most_resident_windows[&v] * share >= read_windows * read_variable + )); } resident .into_iter() - .map(|(v, r)| (costs.per_resident_window[&v], r)) + .map(|(v, share)| { + ( + costs.per_resident_window[&v] * most_resident_windows[&v], + share, + ) + }) .collect() } From 3938f6be6fba5d2461733042529119f1764ecbc9 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:31:36 +0000 Subject: [PATCH 3/3] refactor(stage3): name the retention cost apart from the retention share; doc the share scaling - cost_per_retained_second for pi_v in selection_cost_terms, so "share" means only the [0, 1] variable; cost coefficients in quantity_expression and the resident-window caller named for what they hold. - Module table and the SelectionVariables::h doc describe h_v and r_v as held over a share; cost-terms-from-calibration.md notes the scaling. - retention_is_a_share_of_the_longest_need checks the h_v share and its 300 s longest need instead of every continuous column. --- .../src/milp/model/cluster/solve.rs | 15 +++++----- .../src/milp/model/mod.rs | 22 +++++++------- .../src/milp/model/tests.rs | 29 +++++++++---------- .../src/milp/retention.rs | 6 ++-- .../proposals/cost-terms-from-calibration.md | 5 +++- 5 files changed, 40 insertions(+), 37 deletions(-) diff --git a/crates/stage3-plan-selection/src/milp/model/cluster/solve.rs b/crates/stage3-plan-selection/src/milp/model/cluster/solve.rs index 272f1af9d..afe1941e6 100644 --- a/crates/stage3-plan-selection/src/milp/model/cluster/solve.rs +++ b/crates/stage3-plan-selection/src/milp/model/cluster/solve.rs @@ -151,7 +151,8 @@ pub(super) fn freshness_big_m( } /// `costs` over the selection as one linear expression: each execution's -/// and edge's share times its variable, each retention share times $h_v$, +/// and edge's share times its variable, each cost per retained second +/// times $h_v$, /// and per source the most raw data a selected scan keeps (a variable at /// least each, added to `problem` with its rows). pub(super) fn quantity_expression( @@ -172,11 +173,11 @@ pub(super) fn quantity_expression( .entry(source) .or_insert_with(|| problem.add(variable().min(0))) }); - for (share, variable) in terms { - expression += share * variable; + for (coefficient, variable) in terms { + expression += coefficient * variable; } - for (r, share, variable) in raw_data_rows { - rows.push(constraint!(r >= share * variable)); + for (r, coefficient, variable) in raw_data_rows { + rows.push(constraint!(r >= coefficient * variable)); } for r in most_of_source.into_values() { expression += r; @@ -195,10 +196,10 @@ pub(super) fn quantity_expression( ) { expression += per_unit * variable; } - for (per_window, r) in + for (cost_of_most_windows, share) in resident_window_terms(costs, selectable, &variables.y, &variables.z, problem, rows) { - expression += per_window * r; + expression += cost_of_most_windows * share; } expression } diff --git a/crates/stage3-plan-selection/src/milp/model/mod.rs b/crates/stage3-plan-selection/src/milp/model/mod.rs index 9753ac54c..f64c116b6 100644 --- a/crates/stage3-plan-selection/src/milp/model/mod.rs +++ b/crates/stage3-plan-selection/src/milp/model/mod.rs @@ -5,9 +5,9 @@ //! | Family | Variables | Constraints | //! |---|---|---| //! | baseline (section 3) over execution contexts (section 5) | $x_{\kappa,v}$ (with $x^{\mathrm{mat}}_v = x_{\mathrm{Materialized}(v),v}$), $y_{\kappa,u,c,i}$, $z_{q,v}$, $t$, $r_s$ ([`SelectionVariables`]) | (A) [`input_satisfaction_constraints`], (B) [`producer_selection_constraints`], (C)/(D) [`query_coverage_constraints`], (E) [`acyclicity_constraints`], (F) and one consumer per context of a query-time result that is not materialized [`use_constraints`], each source's raw data on disk once [`selection_cost_terms`]; (G), (H): $y$ exists only on admissible edges where the producer delivers on the consumer's context | -//! | retention (section 5) | $h_v$ | (R) [`super::retention::retention_constraints`] | +//! | retention (section 5) | $h_v$, held as a share of its longest need ([`super::retention::RetentionShare`]) | (R) [`super::retention::retention_constraints`] | //! | result and answer caches (`cost-terms-from-calibration.md`, section 2) | $t$, $b$, $H$, $w_{q,e}$ | [`super::kept_results::kept_result_terms`] | -//! | resident windows under a window cache (`cost-terms-from-calibration.md`, section 1) | $s_v$, the share of its most windows | (W) [`super::retention::resident_window_terms`] | +//! | resident windows under a window cache (`cost-terms-from-calibration.md`, section 1) | $r_v$, held as a share of the most windows any kept read keeps | (W) [`super::retention::resident_window_terms`] | //! | exact-only reads per query | $a_{q,e}$ | (X) [`super::exact_only::exact_only_constraints`] | //! | accuracy (`accuracy-models.md`, constraint (K)), per execution | $E_{\kappa,c,m}$, $D_{\kappa,c}$ ([`AccuracyVariables`]); $F_{\kappa,c,i,m}$, $H_{\kappa,c,i}$ | (K) [`accuracy_constraints`], over [`ErrorModel`] | //! @@ -85,8 +85,9 @@ pub(crate) struct SelectionVariables { /// $t$, by execution: only for executions on a cycle of selectable /// edges (a strongly connected component); `None` elsewhere. t: Vec>, - /// $h_v$ as a share of its longest need, for a candidate with a - /// retention cost and an execution kept ([`retention_variables`]). + /// $h_v$ in seconds, [`RetentionShare::seconds`]: its longest need + /// times a share in $[0, 1]$, for a candidate with a retention cost and + /// an execution kept ([`retention_variables`]). pub(super) h: BTreeMap, /// Per raw-data source a query-time scan keeps on disk at a cost: the /// cost per second of keeping it, at least each selected scan's, @@ -317,7 +318,8 @@ pub(super) type RawDataRow = (Variable, f64, Variable); /// `costs` over the selection, unscaled: the terms (coefficient, /// variable) of each kept execution's share ($x$), each edge's ($y$) and -/// each retention share ($h_v$) of a candidate that is not a query-time +/// each retention cost ($\pi_v h_v$, over [`RetentionShare::share`]) of a +/// candidate that is not a query-time /// scan, and the rows ($r_s$, coefficient, variable) that keep each /// source's raw data on disk once, for the selected scan that keeps the /// most: $r_s \ge \pi_v h_v$ for each query-time `Scan` $v$ of source $s$ @@ -347,7 +349,7 @@ pub(super) fn selection_cost_terms<'c>( for (&position, &y) in &variables.y { terms.push((costs.per_edge[position].unwrap_or(0.0), y)); } - let retention_share = |v: &PhysicalCandidateId| { + let cost_per_retained_second = |v: &PhysicalCandidateId| { costs .retention_cost_per_retained_second .get(v) @@ -356,7 +358,7 @@ pub(super) fn selection_cost_terms<'c>( }; for (v, h) in &variables.h { if !costs.raw_data_source.contains_key(v) { - terms.push((retention_share(v) * h.longest_need_s, h.share)); + terms.push((cost_per_retained_second(v) * h.longest_need_s, h.share)); } } let mut executions_of: HashMap> = HashMap::new(); @@ -374,7 +376,7 @@ pub(super) fn selection_cost_terms<'c>( for (v, source) in scans { let r = raw_data_on_disk_of(source); if let Some(h) = variables.h.get(v) { - let per_retained_second = retention_share(v); + let per_retained_second = cost_per_retained_second(v); if per_retained_second > 0.0 { raw_data_rows.push((r, per_retained_second * h.longest_need_s, h.share)); } @@ -741,7 +743,7 @@ pub(crate) fn solve_selection_reporting_lp_bound( &mut resident_rows, ); // Cost model 1's objective is `costs` itself: every y is on a costed - // edge and every h_v has a retention share (`selection_cost_terms` + // edge and every h_v has a retention cost (`selection_cost_terms` // reads a missing one as 0, which only cost model 3's quantities have). assert!( variables @@ -755,7 +757,7 @@ pub(crate) fn solve_selection_reporting_lp_bound( .h .keys() .all(|v| costs.retention_cost_per_retained_second.contains_key(v)), - "a retention share for each h_v" + "a retention cost for each h_v" ); // The objective's terms per second, unscaled: (cost, variable). A // query-time scan's retention is in its source's r_s. diff --git a/crates/stage3-plan-selection/src/milp/model/tests.rs b/crates/stage3-plan-selection/src/milp/model/tests.rs index abc606064..19f411601 100644 --- a/crates/stage3-plan-selection/src/milp/model/tests.rs +++ b/crates/stage3-plan-selection/src/milp/model/tests.rs @@ -486,10 +486,9 @@ fn a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back() { /// The chain of [`a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back`]: /// its $h_v$, in seconds, would be at least 60 or 300 times a read, an /// unbounded column with whole-number coefficients that HiGHS's presolve -/// takes for an integer (#1533). Every continuous -/// variable of its selection model is within $[0, 1]$: $h_v$ is held as a -/// share of the 300 s the longest read needs, and the optimum still -/// retains 300 s. +/// takes for an integer (#1533). Its selection model holds $h_v$ as a +/// share in $[0, 1]$ of the 300 s the longest read needs, and the optimum +/// still retains 300 s. #[test] fn retention_is_a_share_of_the_longest_need() { let mut memo = empty_memo(); @@ -536,19 +535,17 @@ fn retention_is_a_share_of_the_longest_need() { }; let mut problem = ProblemVariables::new(); let kept = vec![true; selectable.executions().len()]; - selection_model(&inputs, &kept, None, &mut problem); - let continuous: Vec<(f64, f64)> = problem + let model = selection_model(&inputs, &kept, None, &mut problem); + let [(&v, h)] = model.variables.h.iter().collect::>()[..] else { + panic!("one h_v"); + }; + assert_eq!(v, PhysicalCandidateId(1)); + assert_eq!(h.longest_need_s, 300.0); + let (_, definition) = problem .iter_variables_with_def() - .filter(|(_, definition)| !definition.is_integer()) - .map(|(_, definition)| (definition.get_min(), definition.get_max())) - .collect(); - assert!(!continuous.is_empty()); - assert!( - continuous - .iter() - .all(|&(min, max)| min >= 0.0 && max <= 1.0), - "{continuous:?}" - ); + .find(|&(variable, _)| variable == h.share) + .unwrap(); + assert_eq!((definition.get_min(), definition.get_max()), (0.0, 1.0)); let solved = solve_selection(&inputs).unwrap(); assert_eq!( solved.retention_ms.get(&PhysicalCandidateId(1)), diff --git a/crates/stage3-plan-selection/src/milp/retention.rs b/crates/stage3-plan-selection/src/milp/retention.rs index 1b08214e4..4576c46d3 100644 --- a/crates/stage3-plan-selection/src/milp/retention.rs +++ b/crates/stage3-plan-selection/src/milp/retention.rs @@ -228,16 +228,16 @@ pub(crate) fn resident_window_terms( let most = most_resident_windows.entry(v).or_default(); *most = most.max(read_windows); } - let mut resident: BTreeMap = BTreeMap::new(); + let mut resident_share: BTreeMap = BTreeMap::new(); for (v, read_windows, read_variable) in kept_reads { - let share = *resident + let share = *resident_share .entry(v) .or_insert_with(|| problem.add(variable().min(0).max(1))); rows.push(constraint!( most_resident_windows[&v] * share >= read_windows * read_variable )); } - resident + resident_share .into_iter() .map(|(v, share)| { ( diff --git a/docs/design_docs/proposals/cost-terms-from-calibration.md b/docs/design_docs/proposals/cost-terms-from-calibration.md index 4d7abfac3..4e501e016 100644 --- a/docs/design_docs/proposals/cost-terms-from-calibration.md +++ b/docs/design_docs/proposals/cost-terms-from-calibration.md @@ -116,7 +116,10 @@ the windows written within the idle time of those the read's retention need keeps. $r_v$ costs more the larger it is, so at the optimum it is the most over the selected reads, what `plan_cost` charges. The mean counts are in cost model 1's objective, the most in cost model 3's memory -row. +row. The MILP holds $r_v$ as $R_v s_v$, with $s_v \in [0, 1]$ and $R_v$ +the most windows any kept read keeps, so that the solver's presolve does +not take $r_v$ for an integer column; it holds $h_v$ the same way, as a +share of its longest need. On the dashboard above, the plan's predicted memory goes from 5,475 MiB to 292 MiB against a measured 570 MiB working set (the rest of