Skip to content

fix(cost): stored view windows have a decoded and a stored size; rows hold an offset and a key per label column (#1486) - #1487

Merged
zzylol merged 4 commits into
mainfrom
test/1486-stored-bytes
Nov 26, 2026
Merged

zzylol merged 4 commits into
mainfrom
test/1486-stored-bytes

Conversation

@zzylol

@zzylol zzylol commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: the planner charged one size per view window, the decoded one, for memory, disk, disk writes and cold reads, and added a fixed 72 bytes beside each per-series state. The executor's compact view files hold far less: on a measured run, per-view bytes per window were a median 0.055 of predicted (range 0.002–0.23), and the calibration gate failed 107 rows.
  • Change: each stored view window now has two sizes.
    • Decoded bytes are used for memory: resident windows, the window being built, and the cache bound.
    • Stored bytes are used for disk, disk writes and cold reads. They are the window's states × a measured stored_bytes_per_state (file bytes per state's row), else the decoded size.
    • The 72-byte constant becomes a 4-byte state offset plus a 4-byte dictionary key per label column.
  • Effect: on the same run, with stored sizes taken from a different run, per-view bytes per window measured ÷ predicted moves from a median 0.11 → 0.92, and 57 of 80 views pass (0 before). Cold reads now pass (1.36; 0.20 before). Memory rows stay within 1.5×. The remaining failures are listed under Verification.

Review guide

  • Base: main (241353319). Commits:
    1. 653510468: the failing tests, already approved.
    2. The fix.
    3. Review follow-ups.
  • Read first:
    • crates/cost/src/node/usage/mod.rs: stored_output_bytes, decoded_to_stored_bytes, and the window-cache branch of node_usage_and_cost_terms.
    • crates/cost/src/node/state_bytes/mod.rs: state_row_bytes_beside_state.
    • crates/cost/src/plan/cost.rs: window_cache_charges.
    • crates/stage3-plan-selection/src/resident_windows.rs: resident_reads.
  • Mechanical:
    • stored_bytes_per_state threaded through crates/cost/src/measured.rs: interpolation identical to memory_bytes_per_state, plus validation.
    • The report field in crates/planner/src/installable/mod.rs.
    • Struct literals in tests and devtools.
  • Changed expectations of existing tests (each explained under Verification):
    • deployment_exclusions observed costs;
    • lowest_mean_latency a18;
    • stage3_objective an_instant_at_end_input_shares_the_evaluation_context;
    • planner_fuzz witness workload;
    • the state_bytes unit test default (72 → 12).

Behavior: before → after

max_over_time(m[5m]) every 10 s over 1,000 gauge series is one ingestion-time chain of 10 s windows, under a 60 s window cache. The chain's measured entry is {"exact": "Max", "memory_bytes_per_state": 16, "stored_bytes_per_state": 3.2}.

report field (chain node) before after
cost inputs refused: unknown field stored_bytes_per_state load
bytes_per_window (decoded, memory) 1,000 × (16 + 72) = 88,000 1,000 × (16 + 4 + 4) = 24,000
stored_bytes_per_window (files) absent 1,000 × 3.2 = 3,200
disk_bytes 88,000 × ⌈retention ÷ width⌉ 3,200 × ⌈retention ÷ width⌉
disk_written_bytes_per_second 8,800 320
average_memory_bytes from decoded bytes unchanged against the same plan without stored_bytes_per_state

This makes the cost model's storage estimates match measured execution, so that disk limits and disk cost select the plan the executor can actually hold.

Interfaces

crates/cost/src/measured.rs

 /// One measured entry per (operator, phase, family); stays.
 pub struct OperatorCost {
     pub operator: OperatorKind,
     pub phase: Option<ExecutionTiming>,
     pub sketch: Option<SketchParams>,
     pub exact: Option<ExactKind>,
     pub measure: Option<String>,
     pub ns_per_unit: f64,
     pub ns_per_invocation: f64,
     pub memory_bytes_per_state: Option<f64>,
+    /// For a node that keeps summary state: the bytes one state's row takes in a stored view's files,
+    /// as the executor writes them (file bytes ÷ states, keys and offset included). Sizes the view's
+    /// disk, disk writes and cold reads. `None` (default): stored = decoded. Needs `sketch` or `exact`.
+    pub stored_bytes_per_state: Option<f64>,
     pub ns_per_state_emitted: f64,
     pub measured_series_count: Option<u64>,
     pub measures: Vec<String>,
 }

 /// A node's unit price from its entry or interpolated between two; stays.
 pub struct UnitPrice {
     pub ns_per_unit: f64,
     pub ns_per_invocation: f64,
     pub memory_bytes_per_state: Option<f64>,
+    /// File bytes per state's row (`OperatorCost::stored_bytes_per_state`), interpolated like memory bytes.
+    pub stored_bytes_per_state: Option<f64>,
     pub ns_per_state_emitted: f64,
     pub outside_measured_scale: bool,
 }

crates/cost/src/model.rs

 /// How the executor runs a plan; stays.
 pub struct DataPlaneExecution {
     pub ingest_threads: Option<u32>,
     pub precompute_threads: u32,
     pub query_threads: u32,
     pub allowed_lateness_ms: u64,
     pub max_thread_utilization: f64,
     pub ingest_work_at_refresh: bool,
     pub view_window_cache: Option<ViewWindowCache>,
     pub kept_query_time_results: Option<KeptQueryTimeResults>,
     pub answer_cache: Option<AnswerCache>,
-    pub stored_row_bytes_beside_state: u64,
+    /// Bytes a stored per-series state's row holds for its state's offset in the state column. Default 4.
+    pub state_offset_bytes_per_row: u64,
+    /// Bytes a stored per-series state's row holds per label column, each text column (the series
+    /// identity is one): a dictionary key; label text is kept once per series per file. Default 4.
+    pub key_bytes_per_label_column: u64,
 }

stored_row_bytes_beside_state is removed. The 64-byte series key it assumed is not how rows are stored, and a cost-inputs file that still sets it is refused.

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

 /// A node's memory, disk and disk traffic; stays.
 pub struct NodeMemoryAndDisk {
     pub average_memory_bytes: f64,
     pub peak_memory_bytes: u64,
     /// An ingestion-time view's decoded bytes per window (one output), as memory holds it; 0 for any other node.
     pub bytes_per_window: u64,
+    /// An ingestion-time view's bytes per window in its files (disk, disk writes, cold reads);
+    /// `bytes_per_window` without a measured `stored_bytes_per_state`; 0 for any other node.
+    pub stored_bytes_per_window: u64,
     pub disk_bytes: u64,
     pub disk_written_bytes_per_second: f64,
     pub disk_read_bytes_per_second: f64,
 }

 /// An in-memory ingestion-time view's windows under a window cache; stays.
 pub struct CachedViewWindows {
     /// The decoded bytes of one window, as the cache holds it.
     pub bytes_per_window: u64,
+    /// The bytes of one window in the view's files, as a cold read reads it.
+    pub stored_bytes_per_window: u64,
     pub width_ms: u64,
     pub retained: u64,
 }

crates/cost/src/node/analytical.rs

 pub enum AnalyticalCostError {
+    /// Bad input: a measured entry gives `stored_bytes_per_state` without a sketch or exact accumulator.
+    StoredBytesWithoutState(String),
 }

The AnalyticalCostError enum stays; only the new variant is shown. The plan report's per-node PredictedNodeUsage (crates/planner/src/installable/mod.rs) gains stored_bytes_per_window (serde(default)). tools/calibration_gate compares measured bytes/window with it when present.

Usage (S1 in crates/integration-tests/tests/storage_costs.rs, run at the PR head):

// The workload: one query over 1,000 series of the gauge `m` at 1 Hz.
let workload = over_m(vec![every("max_over_time(m[5m])", 10_000, None)], 1000);
// The executor's calibration run measured a Max state at 16 decoded bytes and 3.2 bytes per
// row in its files; a 60 s window cache keeps every window in files.
let inputs = cost_inputs(
    usage_over_time(),
    chain_table(json!({"memory_bytes_per_state": 16.0, "stored_bytes_per_state": 3.2}), vec![]),
    json!({}),
    json!({"view_window_cache": {"idle_ms": 60_000}}),
);
// Planning selects one 10 s ingestion-time chain. Its node's usage gets decoded
// bytes_per_window 24,000 (memory: building window, resident windows, cache bound) and
// stored_bytes_per_window 3,200 (disk_bytes = 3,200 × retained windows, 320 B/s written,
// cold reads at 3,200 per window).
let (plan, report) = single_chain_plan(&workload, &inputs).await?;

Algorithm changes

Stored view sizing

  • Problem: with one size per window, a view's files were charged at its decoded size, at 0.002–0.23 of what the executor writes. Cold reads were charged at decoded bytes too. Because both the cache-bound share and the read bytes followed that size, the overestimate counted twice.
  • Before:
    1. state = a window's decoded bytes (out.bytes, with the row overhead fixed at 72 B beside each per-series state).
    2. Disk = state × windows on disk; writes = state ÷ width.
    3. Cold reads = windows from disk × state.
  • After:
    1. state = decoded bytes, with row overhead state_offset_bytes_per_row + key_bytes_per_label_column × text columns (state_row_bytes_beside_state).
    2. stored_output_bytes = out.rows × measured stored_bytes_per_state when the node outputs states and the table has it; else state.
    3. Disk, disk_bytes_charged and writes use stored_output_bytes. For disk-medium lifetimes, a decoded total is scaled by stored ÷ decoded (decoded_to_stored_bytes).
    4. window_cache_charges (plan cost) and resident_reads (Stage 3) keep decoded bytes for residency and the cache bound, and read stored_bytes_per_window per cold window.
  • Correctness: without a stored entry, stored = decoded and every disk, write and read figure is what it was at the new row layout (S2, and the unchanged storage_costs K/F/D tests). Memory never reads the stored size (S1, D4, D5). Tests R1–R3 and S1–S4 cover this, along with D4, D5 and gate K10.
  • Complexity: unchanged. There is one more scan over a schema's few fields per row-size call, and one multiply per node.
  • Assumptions and limits:
    • One stored size per family, α and series count. A DDSketch's stored bytes grow with the rows per state (wider windows hold more buckets), which one value cannot follow (Verification).
    • The stored size does not follow a node's label count.
    • Label text in files is not charged (decided: option (a)).

Decisions and open questions

Decided (2026-11-24, by the user on #1486):

  • per-family measured stored_bytes_per_state entries, each counting the whole stored row per state;
  • two sizes per window;
  • the per-column row layout replacing 72 bytes;
  • R1–R3 as report-level tests;
  • label text per series per file left out (option (a)), revisited only if the acceptance disk-written or disk-peak rows fail (they do at plan level; see below).

Needs reviewer decision:

  1. DDSketch stored bytes vary with rows per state.
    • Measured in the compact format, per row: the 15 s chain is 50 B, its 1 min level 66, its 5 min level 96, its 15 min level 120 (same source, α 0.05).
    • One value per (family, α) leaves these views at 0.58–1.41 of measured.
    • Proposal: add measured_rows_per_state to an entry and interpolate log–log by a node's rows per state, as measured_series_count already does by series count.
  2. The plan's disk-written row: measured 396,760 B/s vs 177,737 predicted (2.23×).
    • The views' own files account for only 166,318 B/s: fragment bytes plus their share of headers and label text (34,095 B/s of label text).
    • The other ~230 KB/s is written by the executor and is no longer on disk at the scan, so it looks like rewrites rather than view bytes.
    • Proposal: open an issue for the executor's write amplification. Label text (option (b)) would close only 34 KB/s of the gap.
  3. a18 now checks a weaker property. The test now accepts any plan within the bound and within the solve's 1% stop gap, not the same plan. An alternative is to run that test with an exact solve, if one can be requested from the test helper.

Verification

Tests

All tests below were run at the PR head, with cargo test (cargo-nextest is not installed here).

scope result notes
cargo test -p asap-integration-tests --test integration 337 passed, 8 ignored includes storage_costs:: (17)
cargo test -p asap-cost (lib + measured_operation_costs) 134 + 9 passed
cargo test -p asap-stage3-plan-selection --lib 55 passed
cargo test -p asap-devtools (lib, bins, devtools, goldens, corpus_snapshots, lane conformance) all pass (95 + 12 + 8 + 7 + 1, 4 ignored) Correction: the plan snapshot tests (corpus_plans_match_snapshots, sketch_plans_match_snapshots) are #[ignore] tests and did not run here. Run with --include-ignored, they failed at this head (see Snapshot changes).
cargo test -p asap-planner pass
python3 -m unittest test_calibration_gate 9 passed
cargo clippy --workspace --all-targets -- -D warnings, cargo fmt --check clean

Changed expectations of existing tests

test change why
state_bytes_per_row_leave_out_what_the_row_holds_beside_its_state 72 → 12 beside the state (4 + 2 × 4) the new layout (approved)
deployment_exclusions, observed plan costs 0.105237 → 0.089237; 0.274034 → 0.226034; 1.374738 → 0.782737; 3.953712 → 3.953688; 0.367670 → 0.367668; 0.057933 → 0.057445 smaller per-series rows. The selected operators and builds are unchanged in every case.
lowest_mean_latency::a18, renamed a18_a_bound_at_the_selected_latency_keeps_a_plan_within_it was: the same DAG is selected under a bound equal to its latency. Now: the plan under the bound is within the bound and within the 1% stop gap of the unbounded latency. At 40,000 ns per state the unbounded solve (1% gap) stops at a SummaryAgg plan of 30.301 ms. Under the bound it finds an Aggregate plan of 30.300 ms, which is faster and in bound.
stage3_objective::an_instant_at_end_input_shares_the_evaluation_context runs with ingestion-time chains excluded A stored chain now answers the plain query more cheaply than any query-time read, and the @ end() query cannot read it. The test is about sharing m[5m] in the evaluation context.
planner_fuzz summed_over_a_chain window 30 min → 5 min At 30 min a cover over wider chain levels is cheaper. The relation's witness needs a TimeRange over one chain.

Snapshot changes

After the rebase onto main (after #1519–#1521), run with cargo test --release -p asap-planner-cli --test goldens --test corpus_snapshots -- --include-ignored. The snapshots are regenerated with UPDATE_SNAPSHOTS=1 and now pass (goldens 14, corpus + sketch 9).

  • Why: the per-series row overhead beside a state falls from 72 to 12 bytes (4 + 2 × 4, the approved layout). Disk, writes and cold reads now use stored sizes instead of decoded sizes. Kept bytes, and the costs built on them, go down.
  • Plan structure: unchanged. With every number masked, each changed file is identical to the old one: the same nodes are selected, and only cost_per_second, average_memory_bytes, peak_memory_bytes and the byte counts in detail strings change.
  • Changed corpus plans (10): o11y_bench q02, q05, q06, q18, q19, q21, q22, q23, q25, q26.
  • Changed sketch plans (16): chains-10m-5m-3m-10s-mvp, distinct-over-time-5pct-raw-retained, distinct-two-forms-raw-retained, entropy-and-distinct-raw-retained, mixed-quantiles-raw-retained, nested-windows-15m-1h-mvp, quantile-grouped-mvp, quantile-over-time-phase-0-raw-retained, quantile-single-mvp, random-mixed-seed-862-long-w01-q3-mvp, random-mixed-seed-862-w01-q3-q8-mvp, random-mixed-seed-862-w02-q2-q7-mvp, ratio-of-quantiles-1h-mvp, shared-quantiles-1h-mvp, topk-rate-counter-raw-retained, topk-rate-guarantees-ignored-mvp.

Example, o11y_bench q18 (same nodes):

-      "cost_per_second": 32.8014583462,
+      "cost_per_second": 23.9418953469,
-          "detail": "build exact Counter accumulator in tumbling windows of 60000 ms for 1000 groups: ...; keeps 58201000 bytes",
+          "detail": "build exact Counter accumulator in tumbling windows of 60000 ms for 1000 groups: ...; keeps 31265000 bytes",
-          "detail": "merge tumbling windows of 60000 ms into 300000 ms for 1000 groups: ...; keeps 11737000 bytes",
+          "detail": "merge tumbling windows of 60000 ms into 300000 ms for 1000 groups: ...; keeps 5917000 bytes",
-          "detail": "time range cover 3600s: ...; holds 121 bytes for 0.100 ms",
+          "detail": "time range cover 3600s: ...; holds 61 bytes for 0.100 ms",

Tests after the rebase onto main

scope result
cargo test -p asap-cost 134 + 9 passed
cargo test -p asap-stage3-plan-selection 55 + 2 passed
cargo test -p asap-planner 14 + 65 passed
cargo test -p asap-integration-tests --test integration 338 passed, 8 ignored
cargo test -p asap-devtools all pass (planner_fuzz and the other devtools tests 31)
cargo test --release -p asap-planner-cli --test goldens --test corpus_snapshots -- --include-ignored 14 + 9 passed after regeneration
python3 -m unittest test_calibration_gate 9 passed
cargo fmt --check, cargo clippy -p asap-cost -p asap-stage3-plan-selection -p asap-planner -p asap-devtools -p asap-integration-tests --all-targets -- -D warnings clean

New tests

  • From the approved set: R1–R3, S1–S3, D4, D5 and gate K10.
  • S4 is new, added from the correctness review: an entry giving stored_bytes_per_state without a state family is refused. It was written together with the fix, not before it.

Reviews

Four separate reviewers looked at the diff; each review was read-only.

dimension outcome applied
correctness no bugs. Low: stored size could apply to a plain-row entry stored size only for state outputs, and validation rejects such entries (S4); library-api.md lists the field
dead code / duplication none in production code stale "Today" test text removed; D4's redundant uncached plan removed; S3 reuses chain_node_with_table; measured_stored_bytes_per_state inlined at its use; the disk-medium chain multiplies directly
efficiency nothing that matters none needed
naming / docs arithmetic correct split default constants; "label column" wording; "sizes", not "prices"; closure decoded_to_stored_bytes, stored_output_bytes; detail strings say decoded vs in files; a18 renamed; analytical-resource-cost.md row sentence updated

Acceptance A1–A3: calibration gate on the compact-format run

The gate was run on the run's plan, workload and measured file (format 4, +31 min), using this branch's planner (--price-plan).

variant stored sizes from per-view bytes/window: ok of 80, median ratio plan disk written plan disk read (A2) memory / peak (A3)
main n/a 0 of 80, 0.055 0.24 FAIL 0.01 FAIL 0.71 ok / 0.66 FAIL
this PR, no stored entries n/a 0 of 80, 0.11 0.31 FAIL 0.20 FAIL 0.77 ok / 0.70 ok
this PR, stored entries from a different run (re-encoded with zstd-1: Sum 3.7, Counter 8.1, Max 2.8, DDSketch α 0.02 112.5, α 0.05 87.0 B per state's row) another run 57 of 80, 0.92 2.23 FAIL 1.36 ok 0.77 ok / 0.70 ok
this PR, stored entries from the gated run itself (medians; reference only) same run 59 of 80 2.53 FAIL 1.57 FAIL 0.77 ok / 0.70 ok

Of the 23 per-view bytes/window rows still failing in the different-run variant:

class views ratio cause
DDSketch, rows per state n220, n221, n223, n314, n316, n317, n368, n370, n371 0.58–1.41 stored bytes grow with window width (decision 1)
rows per window ≠ declared series n359–n362, n377, n383, n323–n326 0.03–0.43 data facts (#1364)
exact states at the longest widths n216, n247, n248, n278 0.58–1.29 a little more variation per width than one value per family

Follow-ups

@zzylol zzylol added resource cost-model Cost formulas, statistics, ranking, and selection testing Corpus, regression, differential, or benchmark tests labels Nov 24, 2026
@zzylol zzylol changed the title test: stored view bytes follow the row layout and a measured stored size per state (#1486) fix(cost): stored view windows have a decoded and a stored size; rows hold an offset and a key per label column (#1486) Nov 24, 2026
@zzylol
zzylol marked this pull request as ready for review November 24, 2026 20:58
@zzylol zzylol added the bug Something isn't working label Nov 24, 2026
…ize per state (#1486)

Failing tests for #1486, before the fix: a per-series row holds a 4-byte
state offset and a 4-byte key per label column beside its state; a
measured stored_bytes_per_state gives the bytes in the view's files
(disk, writes, cold reads) while memory keeps decoded bytes; the cache
bound counts decoded bytes; the calibration gate compares bytes per
window with the stored size.
…ffset and a key per label column (#1486)

A view's window is charged at two sizes: its decoded bytes for memory
(resident and building windows, the cache bound) and its bytes in the
view's files for disk, disk writes and cold reads. The stored size is the
window's states at a measured stored_bytes_per_state (file bytes per
state's row), else the decoded size. A per-series row holds a state
offset and a dictionary key per label column (state_offset_bytes_per_row
and key_bytes_per_label_column, 4 each), replacing the fixed 72-byte
stored_row_bytes_beside_state. The calibration gate compares bytes per
window with the stored size.
Stored size only for outputs of states, and a measured entry giving
stored_bytes_per_state without a sketch or exact state is refused (S4);
separate defaults for the row layout fields; clearer names
(stored_output_bytes, decoded_to_stored_bytes); detail text says decoded
vs in files; test and doc wording; library-api lists the new field.
…d sizes (#1486)

Only cost numbers and byte detail strings change; every plan selects the
same nodes.
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 resource testing Corpus, regression, differential, or benchmark tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant