Skip to content

fix(stage3): retention and resident windows as shares of their largest need (#1533) - #1537

Merged
zzylol merged 3 commits into
mainfrom
fix/1533-max-variable-unit
Nov 27, 2026
Merged

zzylol merged 3 commits into
mainfrom
fix/1533-max-variable-unit

Conversation

@zzylol

@zzylol zzylol commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #1533.

  • Problem. Stage 3's selection MILP had two families of unbounded continuous columns with whole-number row coefficients: the retention $h_v$, in seconds (rows $h_v \ge 60 \cdot y$, $300$, $3{,}600$, up to $86{,}400$), and the resident windows $r_v$, in windows. HiGHS's presolve takes such a column for an implied integer. Its root reduced-cost fixing (HighsRedcostFixing::addRootRedcost) then steps through up to 1,024 values of each one at every root LP solve, in time quadratic in the steps. On random-mixed-seed-862-long/workload-01, 149 such columns made that bookkeeping 81 % of a 12 s root-node solve. fix(cost): charge each operation the executor's measured time, so a sketch plan is no longer predicted cheaper than a faster exact plan #1355's measured unit costs kept more executions, so there were more $h_v$ columns (33 → 302), and the solve went from 0.9 s to 7.5 s ([Bug] Stage 3 solve on the dag-viewer random-mixed workloads ~8x slower since #1355 (measured unit costs) #1533).
  • Change. $h_v$ is now RetentionShare: a share in $[0, 1]$ times $H_v$, the longest need of its (R) rows. The rows still read $H_v \cdot \text{share}$ in seconds, so HiGHS's absolute tolerances stay in seconds. $r_v$ is likewise the most windows times a share in $[0, 1]$. The objective terms, the raw-data rows and the answer-cache horizon take $H_v$ (or the most windows) as a factor.
  • Effect (release build, same idle host, one workload at a time, HiGHS seeds 0–2, median per workload): viewer34 planning stages go from 343.3 s to 99.2 s; long-01 from 14.7 s to 2.5 s. r197 goes from 79.6 s to 53.9 s, and paper from 439.6 s to 196.9 s. Plan cost is equal in 742 of 747 runs (workload × seed). The 5 that differ are paper runs within HiGHS's optimality tolerance, at most 2e-7 relative, and are accepted as solver ties; see Decisions.

Review guide

  • Base: main (daaa2a207). Not stacked.
  • Read first: crates/stage3-plan-selection/src/milp/retention.rs. It holds RetentionShare, retention_variables (computes $H_v$), retention_constraints (rows over h.seconds()) and resident_window_terms (the share of the most windows).
  • Then read the three sites that take $H_v$ as a factor: the retention term and the raw-data rows in selection_cost_terms (milp/model/mod.rs), and the answer horizon in milp/kept_results.rs.
  • Careful review: whether $H_v$ bounds every (R) coefficient, so that share ≤ 1 never cuts off a plan. Mechanical: the type change of h in SelectionVariables and KeptResultVariables.
  • The first commit adds the two tests, which fail on main. The second commit is the fix. The third applies review fixes: names (cost_per_retained_second for $\pi_v$, so "share" means only the $[0, 1]$ variable), docs (module table, cost-terms-from-calibration.md), and the first test now checks the $h_v$ share itself instead of every continuous column.

Behavior: before → after

asap_planner --workload tools/dag-viewer/workloads/random-mixed-seed-862-long/workload-01.json \
  --deployment-capabilities caps_mvp.json --ignore-accuracy-guarantees --run-until stage3 --format json --out plan.json
main (daaa2a207) this PR
MILP 7,570 columns, 13,822 rows same
after presolve 590 columns: 507 binary, 83 implied integer 590 columns: 507 binary, 54 implied integer, 29 continuous
HiGHS solve (root node only) 13.1 s 1.6 s
planning stages (median of 3 seeds) 14.7 s 2.5 s
plan cost per second 4036.38709293 4036.38709293

The selected plan is the same. Only the MILP's formulation of two maxima changes: the user waits less for the same plan. This serves the dag-viewer and evaluation workloads, whose planning time #1533 tracks.

Interfaces

All of these are crate-internal (pub(crate) / pub(super)). No public interface changes.

crates/stage3-plan-selection/src/milp/retention.rs

+/// $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) reads `seconds()`, so its rows keep their tolerance in seconds.
+#[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;
+}
 /// $h_v$ for each candidate with a retention cost and an execution kept.
 pub(crate) fn retention_variables(
     inputs: &SelectionInputs<'_>,
     kept: &[bool],
     problem: &mut ProblemVariables,
-) -> BTreeMap<PhysicalCandidateId, Variable>;
+) -> BTreeMap<PhysicalCandidateId, RetentionShare>;
 /// (R) over $h_v$.
 pub(crate) fn retention_constraints(
     inputs: &SelectionInputs<'_>,
-    h: &BTreeMap<PhysicalCandidateId, Variable>,
+    h: &BTreeMap<PhysicalCandidateId, RetentionShare>,
     x: &[Variable],
     y: &BTreeMap<usize, Variable>,
     z: &BTreeMap<(QueryId, usize), Variable>,
 ) -> Vec<Constraint>;
 /// Per view, (cost of the most resident windows, the share of them in [0, 1]); unchanged signature,
 /// the variable is now the share and its coefficient the most windows times the cost per window.
 pub(crate) fn resident_window_terms(/* unchanged */) -> Vec<(f64, Variable)>;

crates/stage3-plan-selection/src/milp/model/mod.rs, crates/stage3-plan-selection/src/milp/kept_results.rs

 pub(super) struct SelectionVariables {
     pub(super) x: Vec<Variable>,
     pub(super) y: BTreeMap<usize, Variable>,
     pub(super) z: BTreeMap<(QueryId, usize), Variable>,
     t: Vec<Option<Variable>>,
-    /// $h_v$ in seconds retained.
-    pub(super) h: BTreeMap<PhysicalCandidateId, Variable>,
+    /// $h_v$ as a share of its longest need.
+    pub(super) h: BTreeMap<PhysicalCandidateId, RetentionShare>,
     raw_data_on_disk: BTreeMap<Source, Variable>,
     read_by_query: BTreeMap<(QueryId, usize), Variable>,
 }
 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>,
 }

Usage (end to end, the chain from retention_is_a_share_of_the_longest_need):

// The workload: m[1m] every 10 s and m[5m] every 20 s over one 10 s tumbling-window chain
// (candidate 1), stored across evaluations at 1e-3 per retained second.
let (selectable, costs) = selection_inputs(&physical, &entries, &[1.0; 4], &[], &[(1, 1e-3)]);
// Stage 3 builds the MILP: retention_variables gives candidate 1 one RetentionShare with
// longest_need_s = 300 (the 5 m read); retention_constraints adds 300 * share >= 60 * y_1m and
// 300 * share >= 300 * y_5m; selection_cost_terms adds the term (1e-3 * 300, share).
let solved = solve_selection(&inputs).unwrap();
// The plan retains 300 s (share = 1) at 4 + 1e-3 * 300 = 4.3 per second, as on main.
assert_eq!(solved.retention_ms.get(&PhysicalCandidateId(1)), Some(&300_000));
assert!((solved.milp_optimum_per_second.unwrap() - 4.3).abs() <= 1e-9 * 4.3);

Algorithm changes

MILP formulation of the retention and resident-window maxima

  • Problem. See Summary. On long-01, HiGHS spent 81 % of its 12 s at the root node in addRootRedcost (perf). That covers std::_Rb_tree_increment (55 %) under the erase loop of findLurkingBounds, which runs for every implied-integer column with a nonzero reduced cost and a domain wider than 1, at every root LP resolve.
  • Before / after.
    • Before: $h_v \in [0, \infty)$ s, with rows $h_v \ge \text{need}_e,\text{read}_e$ and the term $\pi_v h_v$.
    • After: $\sigma_v \in [0, 1]$, with rows $H_v \sigma_v \ge \text{need}_e,\text{read}_e$ and the term $(\pi_v H_v), \sigma_v$, where $H_v = \max_e \text{need}_e$ (retention_variables).
    • The same holds for $r_v = R_v s_v$, with $R_v$ the most windows any kept read keeps (resident_window_terms).
  • Correctness. This is the substitution $h_v = H_v \sigma_v$. $H_v$ is at least every coefficient of $v$'s (R) rows, so $\sigma_v \le 1$ admits every value (R) can force, and every feasible plan and its optimum are kept. Nothing reads $h_v$'s or $r_v$'s column back: retention and plan cost come from the selected $x$, $y$ and $z$. The rows stay in seconds and windows, so HiGHS's absolute feasibility tolerance keeps its old meaning. A first version with rows over the share alone, $\sigma_v \ge (\text{need}/H_v),\text{read}$, let a 1e-6 slack stand for 1e-6 of $H_v$ seconds; lowest_mean_latency::a8 then found a plan 1 byte over a disk limit. The tests:
    • retention_is_a_share_of_the_longest_need (every continuous variable of the selection model is in $[0, 1]$; the optimum is still 4.3 and retains 300 s);
    • resident_windows_are_a_share_of_the_most_any_read_keeps (the term is 2 × 30, the bound is $[0, 1]$, and the optimum of 64 is what plan_cost charges);
    • the existing Stage 3, planner-cli and integration suites;
    • the A/B below: plan cost is equal in 742 of 747 runs, and the other 5 are tolerance ties.
  • Complexity. Building the model adds one pass over the reads per candidate ($O(\text{edges} + \text{executions})$) to find $H_v$, and one over the resident reads to find $R_v$. On the solver side, the root redcost bookkeeping drops from up to $1{,}024^2/2$ map steps per such column per root LP resolve to at most 1 step.
  • Assumptions and limits.
    • Other unbounded continuous columns are left as they are: $r_s$, the answer horizon's $w$, and the accuracy variables. In the dumped MILPs they did not show up as implied integers with large domains.
    • The objective's largest coefficient can now be $\pi_v H_v$, which can change objective_scale. On the paper workload with differing plans the scale is unchanged (same objective coefficients in the dumped MILP).

Decisions and open questions

  • Needs reviewer decision. None.
  • Decided (2026-11-27).
    1. Plan-cost ties on paper (5 of 747 runs) are accepted as solver-tolerance ties; no tie-break on plan_cost and no tighter MIP tolerance. Every difference is at most 2e-7 relative, within HiGHS's optimality tolerance, which cuts off improvements under about 1e-6 of the objective. The 5 runs:

      workload seed MILP optimum, main → PR plan cost, main → PR relative
      paperwhole_rollupheavy 0 0.0075521492208 → same 0.00755213985348 → 0.00755214125513 1.9e-7
      paperwhole_rollupheavy-8users 0 0.0086253461096 → same 0.00862533486881 → 0.00862533655079 2.0e-7
      paperwhole_rollupheavy-8users 1, 2 0.0086253461096 → same 0.00862533486881 → 0.00862533514914 3.3e-8
      paperwhole_rangeheavy-8users 2 3.89619149979e-05 → 3.89619157517e-05 same as the MILP optimum 1.9e-8
      • In four runs the MILP optimum is identical on both sides. Those plans tie in the MILP, and only plan_cost tells them apart.
      • main itself returns the dearer of those plans on paperwhole_rollupheavy with seed 1.
      • In one run HiGHS stops 1.9e-8 above the other optimum.
    2. This PR closes [Bug] Stage 3 solve on the dag-viewer random-mixed workloads ~8x slower since #1355 (measured unit costs) #1533. viewer34 is 99.2 s against about 85 s (2 × 42.6 s). The same-host facaec8b2 sum is 48.7 s, which is wall time because its planner panics after Stage 3, so the PR is 2.0× of it. long-01 is 2.48 s against facaec8b2's 1.73 s, within 2×. The remaining viewer34 gap over the 11-14 baseline is the expected cost of the larger model (more executions kept by the measured unit costs), not a solver trap, and is not tracked further.

    3. The rows stay in seconds and windows (h.seconds() >= need * read), not over the bare share. The bare-share rows were just as fast, but they turned HiGHS's absolute tolerance into 1e-6 of $H_v$ seconds, and lowest_mean_latency::a8 caught a plan 1 byte over a disk limit.

    4. $H_v$ is the largest need over all of $v$'s reads, kept or not. That is at least the largest (R) coefficient, so the model stays exact; a tighter $H_v$ over kept reads only, or one shared with the answer horizon's largest_retention_ms (which adds the newest-output floor), would change the measured MILP for no solver gain, so neither is done here.

Verification

scope result newly failing vs base notes
cargo fmt --all -- --check pass –
cargo clippy -p asap-stage3-plan-selection --all-targets -D warnings pass –
cargo test -p asap-stage3-plan-selection 57 passed 0 2 new tests, red on main (term 2 instead of 60; h_v bound (0, inf))
cargo test -p asap-planner-cli (includes goldens) 68 passed, 2 ignored, + small suites 0 snapshots unchanged
cargo test -p asap-integration-tests 338 passed, 8 ignored 0 lowest_mean_latency::a8 caught the share-only rows (see Algorithm changes)
A/B planning stages, release, same idle host, one workload at a time, HiGHS random_seed 0/1/2 see table – plan cost compared per workload and seed, relative 1e-9. The binary predates the last commit's seconds() helper and doc edits, which build the same MILP
set workloads planning s, main → PR (median of 3 seeds, summed) Stage 3 s slowest workload s plan cost differs (workload × seed)
viewer34 34 343.3 → 99.2 320.9 → 76.5 16.5 → 4.5 0
r197 197 79.6 → 53.9 64.9 → 39.2 5.9 → 6.0 0
paper 18 439.6 → 196.9 436.0 → 193.3 146.3 → 55.5 5 (tolerance ties, see Decisions)

No wall-clock test is added (the repo ignores them). The guard is structural: both new tests fail if either maximum is unbounded again.

Follow-ups

  • HiGHS's findLurkingBounds is quadratic in its steps. That is an upstream solver cost, worth reporting there.

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.
…t 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.
@zzylol zzylol added bug Something isn't working cost-model Cost formulas, statistics, ranking, and selection optimizer Workload optimization and plan selection labels Nov 27, 2026
…are; 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.
@zzylol
zzylol merged commit e727be3 into main Nov 27, 2026
3 of 4 checks passed
zzylol added a commit that referenced this pull request Nov 27, 2026
…two stale snapshots (#1429)

#1537 changed two sketch plans at the committed cost, so their
snapshots on main passed without being rewritten: chains-10m-5m-3m-10s
now sizes its KLL chains with k = 2863 (was 1404), and
sql-rollup-quantile-same-window keeps one more node's result. With
plan_id and view_state_key removed, every regenerated snapshot equals
the one main writes itself. The pinned 5-minute chain key follows
(k = 2863).
zzylol added a commit that referenced this pull request Nov 27, 2026
…id (#1429) (#1536)

* test(types): failing tests for the view state key and plan id (#1429)

Phase 2 of #1429, tests first. A materialized view's stored state is
named by ViewStateKey { definition_id, window, logical_properties },
taken from the view node alone, and an installed plan by its content id,
PhysicalASAPDAG::plan_id. The tests check that:

- views differing only in θ or in the view node's window width get
  different keys;
- views differing only in refresh mode, retention or storage medium get
  one key and different plan ids;
- merges of one range over 1-minute and 5-minute chains share a key;
- the three planned views of one coverage in the chains-10m-5m-3m-10s
  workload get distinct keys;
- a view planned in two workloads keeps its key;
- the key is pinned and round-trips through JSON;
- the plan id round-trips through a plan file, changes only with the
  plan, and is pinned for a committed plan file;
- a store keyed by (view state key, time range) answers the five
  tumbling windows, and a k = 400 query misses k = 200 states.

Two known limitations are ignored tests: #1493 (a finalized exact
aggregate has no coverage) and #1494 (coverage depends on where a
filter sits).

plan_id, MaterializedView::plan_id and MaterializedView::view_state_key
are todo!() stubs. LogicalProperties gains PartialEq, Eq, Hash and serde,
and SketchParams gains Eq and Hash, so the key can key a hash map.

* feat(types): name a materialized view by its view state key and plan id (#1429)

A deployment filed stored view states by the view's coverage
(definition_id and selection), which leaves out θ and the view's
tumbling-window width: the three views of the planned
chains-10m-5m-3m-10s workload (a 5-minute chain, a 10-second chain and
60-second windows merged from it) share one coverage.

- PhysicalASAPDAG::plan_id: the content id of the plan's DAG (128-bit
  FNV-1a of its JSON, the hash definition_id already uses, moved to
  plan::content_id). With node_id it names a view in one installed plan.
- MaterializedView::view_state_key: ViewStateKey { definition_id,
  window, logical_properties }, from the view node alone. A store keys
  states by it and the concrete selection, across plans.
- MaterializedView::plan_id; MaterializedView::coverage and
  ViewCoverage::definition_id/selection are public.
- asap-types turns on serde_json's float_roundtrip, so a plan file read
  back has the plan id it was written with.
- Docs: physical-planning-and-deployment.md section 4 explains the two
  scopes and the layering; the DataStore doc, the primitive-schema
  proposal and the DAG viewer README follow.

* fix(types): a TimeRange, TimeShift or TimeRangeCover view keeps its chain's windows in its key (#1429)

Review fixes:
- ViewWindow::of_node walks a TimeRange or TimeShift down to the chain
  it selects windows from, and gives a TimeRangeCover its levels' widths
  (ViewWindow::TumblingLevels): TimeRange(5m, Chain[1m]) and
  TimeRange(5m, Chain[5m]) hold 5 rows and 1 row and no longer share a
  key.
- ViewStateKey::of_view builds the key next to its type.
- The two-workload test matches views by operator before comparing keys.
- Docs: plan-id equality is equality of serializations; the five-window
  example names the views it means; the store contract names the key.

* test(planner-cli): regenerate snapshots with each view's plan_id and view_state_key (#1429)

22 snapshots with materialized views gain plan_id and view_state_key
per view. Nothing else changes: every plan, cost and coverage is as
before. 43 of the 54 views share their coverage with another view of
their plan; all 54 have distinct keys.

* docs: MaterializedView's fields and methods in the plan-file block (#1429)

* test(types): a finalized counter rate has the view coverage of the rate (#1429)

#1535 gave a finalized exact state its aggregate's coverage, so the
#1493 known-limitation test is no longer ignored and now asserts full
equality of the two view coverages. The design doc keeps #1494 as the
one known limitation.

* refactor(types): view state key review fixes (#1429)

- ViewStateKey::of_view takes the view's coverage and the DAG's node map
  instead of a lookup closure; Candidate::new builds its logical
  properties with LogicalProperties::of_parameters.
- A TimeRangeCover level that is no chain is a planner bug
  (debug_assert) rather than a silent loss of the window; a test keys a
  cover view's levels' widths.
- The #1493 test duplicated #1535's a_finalized_rate_covers_what_the_rate_covers:
  removed, and that test now also asserts equal view coverages.
- The integration tests share one view_over_chain helper.
- Docs: concrete selection throughout; the key relies on chains serving
  only readers on their grid; the test table names the θ test.

* test(planner-cli): pin the view state key at main's plan; regenerate two stale snapshots (#1429)

#1537 changed two sketch plans at the committed cost, so their
snapshots on main passed without being rewritten: chains-10m-5m-3m-10s
now sizes its KLL chains with k = 2863 (was 1404), and
sql-rollup-quantile-same-window keeps one more node's result. With
plan_id and view_state_key removed, every regenerated snapshot equals
the one main writes itself. The pinned 5-minute chain key follows
(k = 2863).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working cost-model Cost formulas, statistics, ranking, and selection optimizer Workload optimization and plan selection

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Stage 3 solve on the dag-viewer random-mixed workloads ~8x slower since #1355 (measured unit costs)

1 participant