Skip to content

refactor(cost): one OutputFacts per node, one costing per Stage 3 execution - #1520

Merged
zzylol merged 3 commits into
mainfrom
refactor/cost-one-node-usage-shape
Nov 26, 2026
Merged

zzylol merged 3 commits into
mainfrom
refactor/cost-one-node-usage-shape

Conversation

@zzylol

@zzylol zzylol commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: the cost crate and Stage 3's coefficients repeated themselves. NodeResourceUsageAndCost restated 14 fields of ProducerOutput, so each new output fact went in three places. Stage 3 also called cost_node a second time per execution, with the same arguments, only to read two byte counts. The exact and rounded raw-row closures, the answer-cache amount, and the LCM were each written more than once.
  • Change: one OutputFacts struct now sits in both ProducerOutput and NodeResourceUsageAndCost. Stage 3's cost_reading returns the kept-result and output bytes with the quantity, so at_rate costs each execution once. raw_rows_back is now the exact count rounded. answers_kept (returning AnswersKept) and least_common_multiple are shared. The result-cache and answer-cache settings are read from SelectionInputs instead of being copied into ExecutionCosts. Each ResidentRead carries the one window count its quantity charges.
  • Effect: no behavior change. Every plan, cost and snapshot is unchanged: the planner-cli corpus, golden and sketch snapshots and the cost integration tests pass with no regeneration. With a result or answer cache on, Stage 3 makes one node_resource_usage_and_cost call per execution instead of two.

Review guide

  • Base: main. Not stacked.
  • Read first: crates/stage3-plan-selection/src/cost.rs (QuantityAtRate, cost_reading, the at_rate map, and the kept-bytes block that replaces the second costing loop). Then crates/cost/src/node/usage/mod.rs (OutputFacts, producer_output, and the raw_rows_exact / raw_rows_back closures).
  • Mechanical:
    • The doc of NodeMemoryAndDisk::disk_read_bytes_per_second is reworded. It said the field was 0 "until reads of windows not in the window cache are costed ([Design] Stored views' disk and reads: describe the demo's storage, add file slack, cache bound and cold reads to the existing cost terms #1469)". That has since landed, so it now says the node alone has 0 and plan_cost adds the windows a cached view's readers read while they are not in the window cache.
    • Every x.output / x.sources / … access on a producer or usage becomes x.output_facts.…, and output inside it is now statistics (usage.output_facts.statistics.bytes). That covers usage/mod.rs, plan/cost.rs, and Stage 3's logical_output. The 31 ProducerOutput { .. } literals in usage/tests.rs were nested by a script. In milp/model/tests.rs, 18 SelectionInputs literals gain kept_query_time_results: None, answer_cache: None.
  • Needs care:
    • raw_rows_back = round(raw_rows_back_exact) must equal the old max(min(round(rate·t), held), 1). It does: held is an integer and round is monotone, so round(max(min(x, h), 1)) = max(min(round x, h), 1) for x ≥ 0.
    • per_resident_window is now per_kept_byte × bytes_per_window. That is the same product, and both are None for the same quantities.
  • Touches milp/ lightly. This was needed because the settings and resident_at_most were read there:
    • milp/kept_results.rs, dominance.rs, upper_bound.rs and retention.rs change one or two lines each.
    • milp/model/mod.rs gains two fields.
    • milp/model/cluster/mod.rs changes one line: it reads answer_cache from selection, so the MILP has one path to that setting.

Behavior: before → after

The same workload, e.g. crates/integration-tests/tests/storage_costs.rs with an answer cache and kept query-time results, gives the same selected plan, per-node costs, resident windows and answer bytes before and after. Only the work done to cost it changes: before, Stage 3 costed each execution twice (at_rate, then again for the kept bytes); after, it costs each once. This serves design and maintenance: an output fact is declared once, and one costing per execution keeps the two passes from drifting.

Interfaces

Files at the PR head: https://github.com/ProjectASAP/ASAPPlanner/tree/be5f7f2b615284f9c72b2d8822363982ac91359b/crates (cost/src/node/usage/mod.rs, cost/src/plan/kept_results.rs, types/src/workload/query.rs, stage3-plan-selection/src/cost.rs).

crates/cost/src/node/usage/mod.rs, crates/cost/src/lib.rs

+/// What a node outputs, as its consumers read it: its output statistics,
+/// the sources it reads, its state family, and the facts about its rows
+/// a consumer's cost depends on (new; the 14 fields moved here unchanged).
+pub struct OutputFacts<'a> {
+    /// Its output rows and bytes.
+    pub statistics: EdgeStatistics,
+    pub sources: BTreeSet<&'a str>,
+    pub family: StateFamily<'a>,
+    pub unchanged_columns: BTreeSet<&'a str>,
+    pub tumbling_windows: f64,
+    pub chain_tumbling_window_width_ms: Option<u64>,
+    pub state_input_rows: Option<StateInputRows>,
+    pub states_last_merged: bool,
+    pub raw_rows_span_ms: Option<u64>,
+    pub raw_rows_per_ms: Option<f64>,
+    pub folded_per_row: Option<StateInputRows>,
+    pub raw_rows_short_of_range: Option<RawRowsShortOfRange>,
+    pub state_data_span_ms: Option<u64>,
+    pub raw_rows_shifted_back_ms: u64,
+}

 /// One producer of a node being costed (stays).
 pub struct ProducerOutput<'a> {
     pub payload: &'a Payload,
     pub output_schema: &'a Schema,
-    pub output: EdgeStatistics,
-    pub sources: BTreeSet<&'a str>,
-    pub family: StateFamily<'a>,
-    pub unchanged_columns: BTreeSet<&'a str>,
-    pub tumbling_windows: f64,
-    pub chain_tumbling_window_width_ms: Option<u64>,
-    pub state_input_rows: Option<StateInputRows>,
-    pub states_last_merged: bool,
-    pub raw_rows_span_ms: Option<u64>,
-    pub raw_rows_per_ms: Option<f64>,
-    pub folded_per_row: Option<StateInputRows>,
-    pub raw_rows_short_of_range: Option<RawRowsShortOfRange>,
-    pub state_data_span_ms: Option<u64>,
-    pub raw_rows_shifted_back_ms: u64,
+    /// What it outputs.
+    pub output_facts: OutputFacts<'a>,
 }

 /// What one node uses and outputs (stays).
 pub struct NodeResourceUsageAndCost<'a> {
-    pub output: EdgeStatistics,
-    pub sources: BTreeSet<&'a str>,
-    pub family: StateFamily<'a>,
-    pub unchanged_columns: BTreeSet<&'a str>,
-    pub tumbling_windows: f64,
-    pub chain_tumbling_window_width_ms: Option<u64>,
-    pub state_input_rows: Option<StateInputRows>,
-    pub states_last_merged: bool,
-    pub raw_rows_span_ms: Option<u64>,
-    pub raw_rows_per_ms: Option<f64>,
-    pub folded_per_row: Option<StateInputRows>,
-    pub raw_rows_short_of_range: Option<RawRowsShortOfRange>,
-    pub state_data_span_ms: Option<u64>,
-    pub raw_rows_shifted_back_ms: u64,
+    /// What it outputs, as its consumers read it.
+    pub output_facts: OutputFacts<'a>,
     pub work_ms_per_execution: f64,
     pub cpu_ops_per_second: f64,
     pub scanned_bytes_per_second: f64,
     pub maintained: Option<u64>,
     pub cached_windows: Option<CachedViewWindows>,
     pub kept_result_bytes: f64,
     pub raw_scan: Option<(&'a Source, f64)>,
     pub fit: CalibrationFit,
     pub series: Option<u64>,
     pub cost: NodeCost,
 }

-pub fn query_time_computation_short_of_source_rows(
+fn query_time_computation_short_of_source_rows(
     node: &PhysicalASAPDAGNode,
     producers: &[ProducerOutput<'_>],
 ) -> Option<RawRowsShortOfRange>;

query_time_computation_short_of_source_rows is now private and no longer re-exported from the crate root. Its only caller is in the same file, and Stage 3's doc link now points at AnalyticalCostError::FewerSourceRowsThanItsRange. The plan report's JSON is unchanged: neither struct is serialized.

crates/cost/src/plan/kept_results.rs

+/// The answers an answer cache keeps: each query's answer per evaluation
+/// time back to the plan's longest retention plus the cache's margin.
+pub struct AnswersKept {
+    /// How far back answers are kept, in ms.
+    pub horizon_ms: u64,
+    /// The bytes of every query's kept answers.
+    pub total_bytes: f64,
+    /// The bytes the cache holds of them, at most its bound.
+    pub held_bytes: f64,
+}
+impl AnswersKept {
+    /// The bytes kept of one query (answer bytes, evaluation period).
+    pub fn bytes_of(&self, answer_bytes: f64, period_ms: u64) -> f64;
+}
+/// What an answer cache keeps of the queries' answers (bytes, period) under
+/// a plan's longest retention. Used by `plan_cost` and Stage 3's MILP.
+pub fn answers_kept(
+    longest_retention_ms: u64,
+    answers: AnswerCache,
+    answer_bytes_and_period_ms: impl IntoIterator<Item = (f64, u64)>,
+) -> AnswersKept;
-pub fn steps_computed_per_request(range: Option<RangeEvaluation>, interval_ms: Option<u64>) -> f64;
+fn steps_computed_per_request(range: Option<RangeEvaluation>, interval_ms: Option<u64>) -> f64;

steps_computed_per_request is now private: its only non-test caller is computed_range in the same file.

crates/types/src/workload/query.rs (re-exported from asap_types::workload)

+/// The least common multiple of `a` and `b`, both nonzero: the period after
+/// which two cadences line up again (15 s and 20 s: 60 s).
+pub fn least_common_multiple(a: u64, b: u64) -> u64;

Stage 3, crate-private (crates/stage3-plan-selection/src/{cost.rs, resident_windows.rs, milp/model/mod.rs})

 pub(crate) struct ExecutionCosts {
     /* ...the other fields are unchanged... */
-    pub(crate) resident_at_most: bool,
-    pub(crate) kept_query_time_results: Option<KeptQueryTimeResults>,
-    pub(crate) answer_cache: Option<AnswerCache>,
 }
 pub(crate) struct ResidentRead {
     pub(crate) execution: usize,
     pub(crate) reader: Reader,
-    pub(crate) mean_windows: f64,
-    pub(crate) most_windows: u64,
+    /// The windows it keeps resident: the mean, or the most for peak memory.
+    pub(crate) resident_windows: f64,
     pub(crate) bytes_read_from_disk_per_second: f64,
     pub(crate) most_bytes_read_from_disk_per_run: f64,
 }
 pub(crate) fn resident_reads(
     physical: &PhysicalASAPMemoCandidates,
     selectable: &SelectableExecutions,
     entries: &[QueryWorkloadEntry],
     (cache, answer_cache): (ViewWindowCache, Option<AnswerCache>),
     cached: &HashMap<PhysicalCandidateId, CachedViewWindows>,
-    need_ms_per_edge: &[Option<u64>],
-    retained_ms_of_read: impl Fn(PhysicalCandidateId, u64) -> u64,
+    /// Each read's need and the retention it keeps (both were read from it).
+    costs: &ExecutionCosts,
+    /// Whether each read carries its most resident windows (peak memory),
+    /// not its mean.
+    most_windows: bool,
 ) -> Vec<ResidentRead>;
 pub(crate) struct SelectionInputs<'a> {
     pub(crate) physical: &'a PhysicalASAPMemoCandidates,
     pub(crate) entries: &'a [QueryWorkloadEntry],
     pub(crate) selectable: &'a SelectableExecutions,
     pub(crate) costs: &'a ExecutionCosts,
+    /// The data plane's result cache; `None` without one.
+    pub(crate) kept_query_time_results: Option<KeptQueryTimeResults>,
+    /// The data plane's answer cache; `None` without one.
+    pub(crate) answer_cache: Option<AnswerCache>,
 }

Deleted

Item Why nothing needs it
asap_cost::query_time_computation_short_of_source_rows (re-export; now private) One caller, in usage/mod.rs.
pub on kept_results::steps_computed_per_request One non-test caller, computed_range, in the same file.
ExecutionCosts::{kept_query_time_results, answer_cache} Moved to SelectionInputs, the MILP's inputs, which the cluster path now also reads answer_cache from.
ExecutionCosts::resident_at_most, ResidentRead::{mean_windows, most_windows} Each read now carries the one count its quantity charges (resident_windows).
The 14 duplicated fields on ProducerOutput / NodeResourceUsageAndCost Moved into OutputFacts.

Usage: node_resource_usage_and_cost(node, producers, …) returns usage. A consumer's input is usage.producer_output(&node.payload, &node.output_schema), which now clones one OutputFacts. Stage 3's execution_quantities costs each execution once (cost_reading → QuantityAtRate { own, raw_data, per_second, kept_result_bytes, output_bytes }). The MILP then reads the cache settings from SelectionInputs::{kept_query_time_results, answer_cache}, e.g. kept_results_quantity → answers_kept(longest_retention_ms, answers, …).held_bytes. Exercised end to end by storage_costs::, multi_level_windows:: and the planner-cli snapshot suites.

Algorithm changes

None. The cost model and selection are unchanged; only duplicated computation was removed.

Decisions and open questions

  • Decided:
    • The shared struct is named OutputFacts, and the field holding it is output_facts, as the review suggested. Its rows-and-bytes field is statistics (after its type, EdgeStatistics), so accesses read usage.output_facts.statistics.bytes and not …output_facts.output…. Deref was rejected because it would hide the nesting.
    • cost_reading returns QuantityAtRate, a private struct, not a tuple, so its call sites name what they take and at_rate reuses it as is.
    • resident_reads keeps a most_windows: bool. Only execution_quantities knows the quantity being costed, and passing Quantity would carry the same one bit. Its retention inputs are now one &ExecutionCosts, so it needs no too_many_arguments allow.
    • SelectionInputs carries only the two cache settings the MILP reads, not the whole DataPlaneExecution.
  • Skipped, left to other PRs:
    • Building cached-view readers once for plan_cost and Stage 3 (review D7), and one reader_period_ms helper (part of D5). Both build or read WindowRead::Cover, which a separate cover PR is changing.
    • Removing lowest_mean_latency.rs's own assert_close (T1). This belongs to the MILP cleanup PR.
  • Needs reviewer decision: None.

Verification

Run at the PR head with no snapshot regeneration; the test run changed no file in the tree (snapshots and goldens identical).

Scope Result Notes
cargo fmt --all --check pass
cargo clippy -p asap-types -p asap-cost -p asap-stage3-plan-selection -p asap-integration-tests --all-targets -- -D warnings pass
cargo test -p asap-types -p asap-cost --lib 134 + 214 passed, 0 failed
cargo test -p asap-stage3-plan-selection --lib 55 passed, 0 failed
cargo test -p asap-integration-tests --test integration (all modules: storage_costs, deployment_exclusions, lowest_mean_latency, default_cost_plan_ranking, multi_level_windows, ...) 331 passed, 0 failed, 8 ignored (wall-clock), none newly failing
cargo test -p asap-planner-cli (corpus snapshots, goldens, sketch plan snapshots, lowest_mean_latency_exactness) all suites pass: 64 + 14 + 7 + 1 + 1 passed, 4 ignored, 0 failed No snapshot changed.

Follow-ups

  • After the cover PR lands: one WindowRead builder shared by plan_cost::window_cache_charges and Stage 3's resident_reads, plus reader_period_ms (review D5/D7).
  • Not in this PR's scope, still open from the same review: D3/D4 (MILP raw-data rows and Reader lookups), D8, D10, D11, D13, O3, X3.

@zzylol zzylol added cost-model Cost formulas, statistics, ranking, and selection refactor labels Nov 25, 2026
@zzylol
zzylol force-pushed the refactor/cost-one-node-usage-shape branch from be5f7f2 to b398c43 Compare November 26, 2026 04:23
@zzylol
zzylol merged commit ca11e26 into main Nov 26, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cost-model Cost formulas, statistics, ranking, and selection refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant