Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions crates/stage3-plan-selection/src/milp/kept_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PhysicalCandidateId, Variable>,
pub(crate) h: &'a BTreeMap<PhysicalCandidateId, RetentionShare>,
}

/// The result cache's and the answer cache's terms of `costs`' quantity
Expand Down Expand Up @@ -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;
Expand Down
15 changes: 8 additions & 7 deletions crates/stage3-plan-selection/src/milp/model/cluster/solve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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;
Expand All @@ -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
}
Expand Down
33 changes: 18 additions & 15 deletions crates/stage3-plan-selection/src/milp/model/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) | $r_v$ | (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`] |
//!
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -85,9 +85,10 @@ pub(crate) struct SelectionVariables {
/// $t$, by execution: only for executions on a cycle of selectable
/// edges (a strongly connected component); `None` elsewhere.
t: Vec<Option<Variable>>,
/// $h_v$ in seconds retained, for a candidate with a retention cost and
/// $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<PhysicalCandidateId, Variable>,
pub(super) h: BTreeMap<PhysicalCandidateId, RetentionShare>,
/// 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`]).
Expand Down Expand Up @@ -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$
Expand Down Expand Up @@ -347,16 +349,16 @@ 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)
.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((cost_per_retained_second(v) * h.longest_need_s, h.share));
}
}
let mut executions_of: HashMap<PhysicalCandidateId, Vec<usize>> = HashMap::new();
Expand All @@ -373,10 +375,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) {
let per_retained_second = retention_share(v);
if let Some(h) = variables.h.get(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));
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() {
Expand Down Expand Up @@ -669,7 +671,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
Expand Down Expand Up @@ -740,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
Expand All @@ -754,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.
Expand Down
170 changes: 170 additions & 0 deletions crates/stage3-plan-selection/src/milp/model/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,176 @@ 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). 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();
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()];
let model = selection_model(&inputs, &kept, None, &mut problem);
let [(&v, h)] = model.variables.h.iter().collect::<Vec<_>>()[..] 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()
.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)),
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<usize, Variable> = (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
Expand Down
Loading
Loading