Skip to content

fix: seal KLL and Count-Min into their view layout and price that layout - #1518

Open
zzylol wants to merge 3 commits into
mainfrom
fix/one-window-sealing-rule
Open

zzylol wants to merge 3 commits into
mainfrom
fix/one-window-sealing-rule

Conversation

@zzylol

@zzylol zzylol commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: only DDSketch was sealed into its view layout. A sealed KLL or Count-Min was held as an owned sketch, and the cost model priced it that way. That price was 2.3x the view at 15 rows, and past k it charged the open buffer (5.4x what is retained). A chain level merged from narrower windows held a KLL or Count-Min in yet another form: views on main, or unshrunk owned sketches at this PR's first head (133,200 B for 50 states).
  • Change: StateColumn::sealed is the one sealing rule. Every family with a view layout (DDSketch, KLL, Count-Min) is sealed into it at every sealing site: a chain's own window, a query-time build, and a merged level. The cost model prices a sealed KLL and a sealed Count-Min at that layout. Past k, a KLL's retained items come from the library's own compaction schedule. A merge also shrinks the states it builds.
  • Effect:
    • 50 KLL (k = 200) states of 12 x 15 rows each, merged into one level: 74,604 B held. Priced at 1,488 B per view plus a 4 B offset, they match exactly. Before: 133,200 B held, 1,704 B priced.
    • In the nested-windows-15m-1h-mvp sketch plan, the quantile moves from a DDSketch chain to a KLL (k = 132) chain: 5.73e-6 → 3.96e-6 $/s.

Review guide

  • Base: main (b3351bc, which includes refactor: one home for chain cover windows and view packing; delete the mapped-bytes input path #1521 and fix(cost): stored view windows have a decoded and a stored size; rows hold an offset and a key per label column (#1486) #1487). This replaces the earlier head of this PR (option 1, owned KLL/Count-Min). The branch was rebased; the old head is kept locally as a backup.
  • Commits:
    1. test: — the failing tests, approved before implementation.
    2. fix: — the change, the updated existing tests, and the regenerated snapshots.
    3. fix: review follow-ups — the offset on grouped rows, the cache, naming and error text, and two snapshots.
  • Read first:
    • crates/executor/src/values/state_column.rs — StateColumn::sealed
    • crates/executor/src/values/mapped_states.rs — MappedSketches::estimate
    • crates/executor/src/operators/summary/mod.rs — evaluate_states (the view readout), and ObjectMerger::finish (shrink)
    • crates/cost/src/node/state_bytes/kll.rs — kll_view_bytes, kll_retained_levels_and_items, kll_retained_with_seed, KllCoin
    • crates/cost/src/node/state_bytes/mod.rs — sketch_state_bytes, open_sketch_state_bytes, count_min_view_bytes, ddsketch_state_bytes (offset removed)
  • Mechanical:
    • The old KLL helpers moved into state_bytes/kll.rs (kll_sealed_bytes became kll_owned_bytes, unchanged).
    • The 11 regenerated sketch plan snapshots.
    • The two manifest covers texts that named DDSketch.
    • values/batch/tests.rs builds its object columns from KMV, a family with no view layout.

Behavior: before → after

Planning the nested-windows-15m-1h-mvp workload (tools/dag-viewer/memo-examples/promql/rangeheavy-t5-q09-15m-1h.json: q0.9 over 15 min and over 1 h, 10,000 series, MVP deployment):

asap_planner --run-until stage3 \
  --deployment-capabilities crates/planner-cli/tests/sketch_plan_snapshots/deployments/mvp.capabilities.json \
  --cost-inputs tools/dag-viewer/cost-inputs/aws-fargate-us-east-1.json ...
before after
selected chain DDSketch α = 0.05, 60 s windows merged into 300 s levels KLL k = 132, same windows and levels
chain build CPU 0.4486 core-s/s (210 ops/row) 0.1966 core-s/s (84 ops/row)
cost per second 5.733e-6 3.958e-6
average memory 410 MB 1.22 GB

Before, a sealed KLL with 12,000 rows per window was priced at its open buffer (kll_buffer_items, more than 1,000 items). The KLL plan was never chosen.

After, it is priced at the items its compaction schedule retains, in the view layout the executor holds. The CPU saving now outweighs the larger states.

In the executor, a sealed KLL or Count-Min column now holds exactly its view bytes (S2):

50 states main this PR's previous head after
KLL window, 15 rows (owned) 19,200 B 19,200 B 8,604 B
KLL level, 12 x 15 rows 74,604 B (views) 133,200 B (owned, unshrunk) 74,604 B
Count-Min 3 x 64 level 78,604 B (views) 84,800 B (owned) 78,604 B

This serves the cost-accuracy goal: planned bytes equal the bytes held.

Interfaces

crates/executor/src/summary_kernels/traits.rs

 /// In-memory state of one population's summary; stays.
 pub trait AggregateCore: Send + Sync {
     fn clone_boxed_core(&self) -> Box<dyn AggregateCore>;
     fn as_any(&self) -> &dyn std::any::Any;
     fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
     fn merge_with(&self, other: &dyn AggregateCore) -> Result<Box<dyn AggregateCore>, KernelError>;
     fn estimate(&self, query: &SketchStatistic) -> Result<f64, KernelError>;
     fn is_empty(&self) -> bool;
     fn approx_memory_bytes(&self) -> usize;
     fn shared_state(&self) -> Option<(usize, usize)>;
+    /// Free what the state holds only for later updates and merges, once
+    /// no more come (a sealed window, a finished merge). Answers, merges
+    /// and encodings are unchanged; a state that holds no such room keeps
+    /// the default, which does nothing.
+    fn shrink_to_fit(&mut self) {}
 }

crates/cost/src/node/state_bytes/mod.rs (the signatures are unchanged; what they return changes)

 /// Bytes of a sealed sketch state; stays. KLL and Count-Min are now priced at their view
 /// layout (DDSketch already was); a DDSketch's 4-byte column offset is no longer included.
 pub fn sketch_state_bytes(params: &SketchParams, input_rows: StateInputRows) -> u64;
 /// Bytes of a state still receiving values, an owned sketch; stays. KLL and Count-Min now
 /// differ from `sketch_state_bytes` (owned struct and buffer), as DDSketch did.
 pub fn open_sketch_state_bytes(params: &SketchParams, input_rows: StateInputRows) -> u64;

Crate-internal (not public):

  • MappedSketches::ddsketch_quantile became MappedSketches::estimate(index, &SketchStatistic) -> Result<Option<f64>, String>. It answers DDSketch and KLL quantiles and Count-Min totals on views.
  • StateColumn::sealed decides by from_sealed_views (it returns None for a family with no view layout).
  • The values::MappedSketchKernel re-export is now test-only. Nothing outside values names it any more.

Usage (the path a sealed KLL takes, as the tests run it):

// A chain's window: one KLL (k = 200) per series, 15 samples each.
let mut updater = StateColumnUpdater::new(&FieldDataType::Sketch(SketchAlgorithm::Kll),
                                          Some(&SketchParams::Kll { k: 200 }))?;
// ... update(series, value, t) for 50 series ...
// Sealed by StateColumn::sealed into the KLL view layout:
// 50 x (40 + 8 + 8 x 15 + 4) + 4 = 8,604 bytes charged.
let window = updater.seal();
// A SummaryMergeWindows over 12 such windows seals its level the same way: 74,604 bytes.
// A SummaryEstimate reads q0.9 on each view (MappedSketches::estimate); no owned sketch is built.
// The planner prices each of those states at sketch_state_bytes(Kll { k: 200 }, 180 rows)
// = 1,488 bytes, plus the row's 4-byte offset (state_offset_bytes_per_row): what is held.

Algorithm changes

Sealed KLL bytes past k (cost model)

  • Problem: a sealed KLL of k = 200 over 1,100 rows holds 1,536–1,552 B as a view. It was priced at 8,320 B, the open buffer (kll_buffer_items). The capacity of its levels, which bounds it, is 3,928 B (2.5x).
  • Before:
    • n ≤ k: 248 + 8(L+1) + 8n.
    • n > k: 248 + 8(L+1) + 8 · kll_buffer_items(k, n).
  • After (kll_view_bytes):
    • n ≤ k: 40 + pad8(4(L+1)) + 8n.
    • n > k: kll_retained_levels_and_items(k, n) returns them (cached by (k, n)). It runs the library's compaction schedule on level sizes alone:
      1. Fill level 0 to its capacity + 1.
      2. Compact it, keeping ceil((pop − coin)/2).
      3. Cascade up while a level is over its capacity.
      4. Add a level when the top compacts.
    • The capacities are max(ceil(k(2/3)^i), 8) by height from the top.
    • The library's coin (KllCoin, the same xorshift-multiply bits) is run with seeds 1–16, and the most items is taken.
  • Correctness:
    • With seed s, the schedule returns exactly the levels and items of Kll::with_seed(k, 8, s) after n updates. the_schedule_retains_what_the_library_retains checks this for k ∈ {8, 200, 1,000}, n ∈ {1, 15, 200, 201, 1,100, 2,000, 13,200, 100,000} and three seeds.
    • The executor's KLLs use random coins, so the count is random: at 13,200 rows, 50 states range from 240 to 298 items. The maximum over 16 seeds bounds a column's mean state. P1 checks mean ≤ price ≤ 1.25 x mean, at 1,100 rows (window) and 12 x 1,100 (level).
  • Complexity: O(n / level-0 capacity) compactions per seed, x 16 seeds, once per (k, n) (cached; about 20 ms near the cap). At most 2^20 rows are simulated (about 10^5 compactions per seed). Past that, the capacity of the L(n) levels is used, an upper bound. The sketch snapshot suite takes 5.76 s before and 6.46 s after (the run includes the corpus test).
  • Assumptions and limits:
    • A merged level is priced with the single-stream schedule at its merged rows. Merge order changes the count (12 x 1,100 merged: mean 260 items; the price takes 291).
    • m = 8, the executor's Kll::with_k.

Sealing rule and view readouts (executor)

  • Before: sealed put DDSketch into views and everything else into objects. Estimates read DDSketch quantiles on views; every other Mapped state was rebuilt as an owned sketch for each estimate.
  • After: sealed uses views for every family with a view layout. MappedSketches::estimate answers DDSketch and KLL quantiles and Count-Min totals on the view, so no owned sketch is built per estimate. ObjectMerger::finish calls shrink_to_fit on every state the merge owns alone (Arc::get_mut). A merged KLL of 180 rows then holds 1,704 B, not 2,664 B.
  • Correctness:
    • S3: sealed levels answer the same KLL quantiles (past compaction) and Count-Min totals as unsealed ones.
    • The existing view-merge tests pass.

Decisions and open questions

Decided (2026-11-26, user):

  • Option 2: seal every view-layout family into views, and price the layout (rejected: option 1, owned KLL/Count-Min).
  • Q1: compute KLL's retained count from n and k with the compaction schedule, keeping the 1.25x tolerance.
    • Implemented as the schedule with the library's coin over 16 seeds.
    • The P1 lower bound is the column's mean state, not every state: the count is random per state, which no single number bounds.
  • Q2: query-time builds also seal into views; one rule for all families.
  • Q3: a DDSketch's 4 B column offset moves to the row (state_offset_bytes_per_row, fix(cost): stored view windows have a decoded and a stored size; rows hold an offset and a key per label column (#1486) #1487) and is counted once. DDSketch prices drop by 4 B. A grouped (non-series) row of a DDSketch, KLL or Count-Min state now also holds that offset (state_row_bytes_beside_state), so no row type drops it.
  • Q4: merges shrink the states they build. The test is S4.
  • Q5: for Count-Min, only the level-merge site. No updater builds a plain Count-Min (executor: the per-group updater cannot build plain Count-Min (or Count Sketch) states #1522).

Needs reviewer decision: none.

Verification

All run on the remote build host. The suites ran at 8321079 and again with the review follow-ups (5bc2c29), all passing; the clippy, fmt and snapshot rows are for 5bc2c29.

scope result newly failing vs base notes
cargo test -p asap-executor (lib + 7 test binaries) 162 + 230 passed, 2 ignored none S1–S4 new
cargo test -p asap-cost 136 + 9 passed none KLL schedule tests new; KLL/Count-Min/DDSketch expectations updated
cargo test -p asap-integration-tests 340 passed, 8 ignored none P1/P2 new; a_kll_k_range_moves_the_quantile_to_a_larger_k updated
cargo test -p asap-devtools 11 + 1 + 31 passed none
cargo test -p asap-stage3-plan-selection 55 + 2 passed none
corpus_snapshots --ignored (release) 2 passed none corpus (exact plans) unchanged; sketch snapshots regenerated
cargo fmt --all --check ok
cargo clippy -p asap-executor -p asap-cost -p asap-integration-tests -p asap-planner-cli --all-targets -D warnings ok

New tests:

  • S1 every_family_with_a_view_layout_seals_into_views_at_both_sites: each family sealed into views exactly when it has a view layout, at the chain window and at the merged level.
  • S2 sealed_kll_and_count_min_hold_their_view_layout_bytes: exact byte charges, 8,604 / 74,604 / 78,604 B.
  • S3 sealed_kll_and_count_min_levels_answer_as_unsealed: the view readouts answer as owned sketches.
  • S4 a_merge_shrinks_the_kll_states_it_builds: a merged KLL holds 248 + 16 + 1,440 = 1,704 B.
  • P1 a_sealed_states_price_is_the_view_the_executor_holds: the price equals the held bytes up to k; past k, mean ≤ price ≤ 1.25 x mean.
  • P2 a_sealed_ddsketchs_price_bounds_its_view.
  • the_schedule_retains_what_the_library_retains: the schedule matches the library sketch for each seed.
  • kll_view_bytes_are_the_views_length.

Changed expectations of existing tests:

  • kll_state_bytes_grow_with_the_samples_it_sees: sealed = view, past k = the most over seeds 1–16; open = owned.
  • state_bytes_bound_the_executors_charge and priced_bytes_agree_with_the_executor compare owned KLL/Count-Min accumulators with the open price.
  • open_ddsketch_states_hold_their_first_blocks: KLL open 1,064 vs sealed 848.
  • stored_ddsketch_states_are_priced_at_their_view_layout: 92 → 88 B header (Q3).
  • a_kll_k_range_moves_the_quantile_to_a_larger_k:
    • unrestricted, stored KLL k = 547 at 0.030563 (was k = 1,404 at 0.057445);
    • k ≤ 1,403 excluded, stored k = 1,404 at 0.055804;
    • k ≤ 2,862 excluded, unchanged.
  • values/batch/tests.rs object-column tests now use KMV.

Snapshot changes (sketch plan snapshots; 11 of the 45 changed)

snapshot plan cost $/s average memory (B) reason
nested-windows-15m-1h-mvp DDSketch α 0.05 chain → KLL k 132 chain (same shape) 5.733e-6 → 3.958e-6 4.10e8 → 1.22e9 sealed KLL now priced at retained items as views; its CPU (84 vs 210 ops/row) wins
shared-quantiles-1h-mvp DDSketch chain + level → KLL k 132 chain, no 1 h level view (one materialized view instead of two) 5.702e-6 → 3.877e-6 4.10e8 → 9.68e8 same
chains-10m-5m-3m-10s-mvp KLL k 1,404 → k 2,863 4.468e-7 → 3.841e-7 7.84e7 → 2.66e7 sealed KLL views far smaller than the open-buffer price; a larger k is now cheaper to keep
sql-rollup-quantile-same-window-raw-retained same 1.67483e-8 → 1.61487e-8 9.96e5 → 4.83e5 KLL states priced as views; the grouped row's 4 B offset added
sql-rollup-quantile-different-windows-raw-retained same 2.71791e-8 → 2.65794e-8 1.00e6 → 4.88e5 same
quantile-single-mvp same 8.0080e-7 → 7.9914e-7 1.4854e8 → 1.4710e8 DDSketch offset counted once (−4 B per state)
quantile-grouped-mvp same 8.7615e-7 → 8.7449e-7 1.5002e8 → 1.4858e8 same
ratio-of-quantiles-1h-mvp same 6.2464e-6 → 6.2431e-6 8.831e8 → 8.802e8 same
random-mixed-seed-862-long-w01-q3-mvp same 2.01369e-5 → 2.01229e-5 5.707e8 → 5.585e8 same
random-mixed-seed-862-w01-q3-q8-mvp same 3.01081e-5 → 3.01035e-5 2.808e8 → 2.768e8 same
random-mixed-seed-862-w02-q2-q7-mvp same 3.03721e-5 → 3.03675e-5 2.808e8 → 2.768e8 same

mixed-quantiles-raw-retained and quantile-over-time-phase-0-raw-retained select KLL but do not change, because they hold no sealed KLL state. The corpus snapshots (exact plans) do not change.

Calibration still needed

  • CPU, re-measured with sketch-bench (through its own PR and pin):
    • SummaryEstimate ns_per_unit for KLL and Count-Min read on views (the atomic-cost conversion has 400 and 350 ns);
    • SummaryMerge ns_per_unit for merges reading KLL/Count-Min views (merge_view);
    • the extra copy into views at seal: ns_per_state_emitted for KLL/Count-Min chains and query-time builds.
  • Memory: no in-repo measured memory_bytes_per_state exists for KLL or Count-Min. A deployment's measured tables fitted from owned sizes need refitting to view bytes (the memory_bytes_per_state doc now says so).
  • Stored bytes: re-measure stored_bytes_per_state (fix(cost): stored view windows have a decoded and a stored size; rows hold an offset and a key per label column (#1486) #1487) for KLL/Count-Min view files.

Follow-ups

  • executor: the per-group updater cannot build plain Count-Min (or Count Sketch) states #1522: the per-group updater cannot build plain Count-Min or Count Sketch states, so only stored Count-Min windows merged into a level are sealed.
  • Unsealed merge outputs are still priced open (open_sketch_state_bytes, the grown buffer), although the merge now shrinks them. Pricing them shrunk would lower query-time memory in the two plans that flipped to KLL.
  • Past 2^20 rows a sealed KLL is priced at its levels' capacity, about 1.4–2.5x what it retains. The price jumps there; with the cache, a higher cap is now affordable.
  • An open KLL is under-priced (kll_owned_bytes, unchanged by this PR): an open sketch holds 62 level slots and a buffer that doubles from 16 items, for example 872 B at 1 row, priced at 272 B. This affects the newest window of a chain and the working memory of query-time builds.
  • A merged level is priced with the single-stream schedule at its merged rows.

@zzylol zzylol added bug Something isn't working cost-model Cost formulas, statistics, ranking, and selection window Window functions, frames, panes, or temporal semantics labels Nov 25, 2026
… view

KLL and Count-Min seal into their view layout, as DDSketch does, at
every sealing site (a chain's own window, a query-time build, a level
merged from narrower windows), and the cost model prices a sealed KLL or
Count-Min state at that layout.

- values::tests::sealing: the rule per family and site; the exact bytes
  a sealed KLL (k = 200) and Count-Min (3 x 64) column holds (8,604 B,
  74,604 B, 78,604 B); sealed levels answer as unsealed; a merge's KLL
  output holds 1,704 B, shrunk, not the 2,664 B the merge grew.
- integration sealed_state_bytes: sketch_state_bytes equals what the
  executor holds per state (exact up to k; past k at least the column's
  mean state and within 1.25x of it), and a DDSketch guard.

Fails on main: KLL and Count-Min are held as owned sketches (a 15-row
KLL window 19,200 B, a 180-row level 133,200 B, a Count-Min level
84,800 B), priced as owned (384 B vs a 168 B view at 15 rows), and a
merge's KLL output keeps its doubled buffer.
One sealing rule, StateColumn::sealed: every family with a view layout
(DDSketch, KLL, Count-Min) is held in it, any other as owned sketches,
at a chain's own window, a query-time build and a merged chain level.

- Executor: KLL quantiles and Count-Min totals are read on their views
  (MappedSketches::estimate), as DDSketch quantiles were, so no owned
  sketch is built per estimate. AggregateCore::shrink_to_fit, and a
  merge shrinks each state it built before handing it on.
- Cost: a sealed KLL is priced at its view (40-byte header, level
  boundaries, retained items); past k its retained items come from the
  library's compaction schedule, run with its own coin over 16 seeds, the
  most taken. A sealed Count-Min is priced at 32 + 8 per counter. Open
  states (merge targets, builds) keep the owned prices. A DDSketch's
  4-byte column offset is now counted once, in the row beside the state
  (state_offset_bytes_per_row), not in its price.
- Eleven sketch plan snapshots regenerated: two DDSketch plans move to
  KLL, the rest change only their cost and memory.
@zzylol
zzylol force-pushed the fix/one-window-sealing-rule branch from b9d85a0 to 8321079 Compare November 26, 2026 05:53
@zzylol zzylol changed the title fix(executor): one sealing rule for a chain's windows and its merged levels fix: seal KLL and Count-Min into their view layout and price that layout Nov 26, 2026
- A grouped (non-series) state row of a view-layout sketch holds its
  4-byte column offset too, so the offset is counted once on every row.
- kll_retained -> kll_retained_levels_and_items, cached by (k, rows):
  one run of all 16 seeds near 2^20 rows takes about 20 ms.
- kll_owned_bytes documents that an open sketch holds more than it
  charges (level slots, doubling buffer).
- An empty view quantile's error names the sketch ("Kll quantile of an
  empty population").
- Two SQL rollup snapshots regenerated (+4 B per grouped KLL row).
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 window Window functions, frames, panes, or temporal semantics

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant