Skip to content

feat(executor): restore a public state view bytes API (view_bytes, from_views) - #1542

Merged
zzylol merged 2 commits into
mainfrom
feat/state-view-bytes-public-api
Nov 27, 2026
Merged

zzylol merged 2 commits into
mainfrom
feat/state-view-bytes-public-api

Conversation

@zzylol

@zzylol zzylol commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: a runtime that persists states and reads them back in place has no public way to do either. It cannot get a state's view bytes from a state column, and it cannot build a state column over stored bytes again. refactor: one home for chain cover windows and view packing; delete the mapped-bytes input path #1521 made state_view_bytes private and deleted StateColumn::from_mapped, family_has_mapped_form and the stored exact-record form, because no crate in the workspace called them.
  • Change: three public items in asap_executor::values. StateColumn::view_bytes(index) gives a state's view layout. StateColumn::from_views(family, bytes, offsets) reads stored views where they lie. family_has_view_layout(family) says whether a family has a view layout. Sketch views reuse MappedSketches (the new MappedSketches::over shares check_views with packed). Exact states use a fixed little-endian record.
  • Effect: the round trip works through the public API. Example: 5 sealed DDSketch states (α = 0.01, 40 to 80 samples each) are written with view_bytes, packed by the caller into one Vec<u64> buffer and read back with from_views. Every state's bytes lie inside the caller's buffer, and p10 / p50 / p99 plus pairwise merges equal the originals. The same holds for KLL (k = 1024), Count-Min (3 × 64) and all six exact kinds, also through a SummaryMerge plan over the rebuilt column. A batch over the column is charged none of its states. No plan, cost or answer changes.

Review guide

  • Base: main. Not stacked.
  • Read first:
    1. crates/executor/src/values/state_column.rs: StateColumn::from_views, StateColumn::view_bytes, the ExactRecords::Mapped variant.
    2. crates/executor/src/values/mapped_states.rs: ViewLayout, family_has_view_layout, check_offsets / check_views, MappedSketches::over, exact_record_bytes, MappedRecords.
    3. crates/integration-tests/tests/state_views.rs: the public-API round trip.
  • Review carefully: the validation in from_views. The view readers (accumulator, merge_into, ddsketch_quantile) expect valid views, so every view handed in must be checked once, up front. Also review the memory charge: the column is held outside the run, and its stored size is the bytes the offsets span plus the offsets.
  • Mechanical: the ExactRecords match arms, mapped_column's new stored-size argument (0 at its existing call), the compaction skip in Batch now also covering exact records held outside the run, and the module doc of mapped_states.rs.

Behavior: before → after

The caller is a runtime that stores the sealed tumbling windows of a plan and, after a restart, hands them back to plans as stored windows.

Before (main) After
Write a sealed DDSketch / KLL / Count-Min / exact column no public API. The only option is to serialize each state object (ExactAccumulator is serde-able; sketch objects are not, apart from their sketchlib types) column.view_bytes(i) for each state: borrowed when the column already holds views (a sealed DDSketch column, or a column read with from_views), else written
Read it back rebuild one object per state and a column of objects (a copy and an allocation per state) StateColumn::from_views(family, Buffer, ScalarBuffer<u32>): zero-copy over the caller's buffer, for example an Arrow Buffer over a mapped file. The view is checked once, then read in place by quantile reads and merges. The run is charged nothing for the states
A family with no view layout (HLL, KMV, UnivMon, Hydra) — family_has_view_layout is false, view_bytes is None, and from_views is bad input. The caller keeps such states as objects

#1521 removed this path because no crate in the workspace called it (its row "StateColumn::from_mapped … accepted (no caller in the workspace) → API removed"). That path had a real caller outside the workspace, so under "delete legacy only when replaced" it comes back here as a smaller public API. The removed duplicates stay removed: pack_words and the old construction-time view check are now MappedSketches::packed and the shared check_views.

The executor defines no file format. A caller lays out the states, offsets, padding, compression and headers however it likes. The executor only fixes each state's own bytes: asap_sketchlib's view layout for sketches, and the exact record documented on exact_record_bytes.

Interfaces

Permalinks are at the PR head.

crates/executor/src/values/state_column.rs

 impl StateColumn {
+    /// The column of `family` states a runtime stored as view bytes
+    /// ([`Self::view_bytes`]) and hands back over bytes it holds: state `i`
+    /// at `bytes[offsets[i]..offsets[i + 1]]`, read where it lies (a buffer
+    /// over a mapped file stays mapped). A sketch view must start 8-byte
+    /// aligned and may end in zero padding; exact records lie back to back
+    /// from the start of `bytes` (`offsets[i]` is `i` times the record's
+    /// size). Each state is checked here, once. The run is not charged for
+    /// the states (they are held outside it); their stored size is the
+    /// bytes the offsets span plus the offsets. Fails with
+    /// [`crate::Error::Invalid`] for a family with no view layout
+    /// ([`super::family_has_view_layout`]), offsets out of order or past
+    /// `bytes`, or a state that is not a view of `family`.
+    pub fn from_views(
+        family: FieldDataType,
+        bytes: arrow::buffer::Buffer,
+        offsets: arrow::buffer::ScalarBuffer<u32>,
+    ) -> Result<Self, crate::Error>;
+    /// State `index` in its view layout, the bytes [`Self::from_views`]
+    /// reads back: a sketch's `asap_sketchlib` view (read back, it must
+    /// start at an 8-byte-aligned address), or an exact state's fixed
+    /// record. Borrowed where the column already holds it in that layout,
+    /// else written. `None` for a family with no view layout
+    /// ([`super::family_has_view_layout`]) or a keyed exact state.
+    pub fn view_bytes(&self, index: usize) -> Option<Cow<'_, [u8]>>;
 }

crates/executor/src/values/mapped_states.rs (re-exported as asap_executor::values::family_has_view_layout)

+/// Whether states of `family` have a view layout, so a column of them can
+/// be written as view bytes ([`super::StateColumn::view_bytes`]) and read
+/// back in place ([`super::StateColumn::from_views`]): DDSketch, KLL,
+/// Count-Min and every exact family.
+pub fn family_has_view_layout(family: &FieldDataType) -> bool;

What #1521 removed, and what replaces it (paths abridged):

-pub fn family_has_mapped_form(family: &FieldDataType) -> bool;
+pub fn family_has_view_layout(family: &FieldDataType) -> bool;
-pub fn state_view_bytes(state: &dyn AggregateCore) -> Option<Vec<u8>>;
+pub fn view_bytes(&self, index: usize) -> Option<Cow<'_, [u8]>>; // on StateColumn
-pub fn from_mapped(family: FieldDataType, bytes: Buffer, offsets: ScalarBuffer<u32>) -> Result<Self, Error>;
+pub fn from_views(family: FieldDataType, bytes: Buffer, offsets: ScalarBuffer<u32>) -> Result<Self, Error>;

The view bytes now come from a column, not from a lone state object. That way a column that already holds views lends them without re-encoding.

Usage (from state_views.rs, abridged):

// A sealed tumbling window of 5 DDSketch states, as a runtime builds it sample by sample.
let mut updater = StateColumnUpdater::new(&family, Some(&SketchParams::DDSketch { alpha: 0.01 }))?;
/* add_group + update per sample */
let sealed: StateColumn = updater.seal();
// The runtime writes each state's view, padded to 8 bytes, into storage it owns.
let mut words: Vec<u64> = Vec::new();            // the stored states (8-byte aligned)
let mut offsets = vec![0u32];                    // state i: the bytes of `words` at [offsets[i]..offsets[i+1]]
for i in 0..sealed.len() {
    let view = sealed.view_bytes(i).expect("DDSketch has a view layout");
    /* append view, zero-padded to a word boundary; push the end offset */
}
// After a restart: the stored bytes (here a Vec; in a runtime, e.g. a mapped file) back into a column.
let bytes = Buffer::from_vec(words);
let stored = StateColumn::from_views(family.clone(), bytes, ScalarBuffer::from(offsets))?;
// Installed as a stored window; plans read and merge each state where it lies.
let batch = Batch::try_from_columns(schema, vec![BatchColumn::States {
    indices: UInt32Array::from_iter_values(0..stored.len() as u32),
    states: Arc::new(stored),
}])?;
// stored.state(i).estimate(&Quantile { q: 0.5 }) equals sealed.state(i)'s; batch.memory_bytes() charges no states.

Algorithm changes

None. Validation, view reads and merges are the existing MappedSketches code. The exact record is the layout that #1521 removed, unchanged.

Decisions and open questions

  • Decided (2026-11-27, option B, approved): restore a minimal, format-agnostic public API, rather than leave runtimes that store states with no public way to do so. The only caller in the workspace is the integration test; the restore is intentional.
  • Decided: a column read with from_views reports its stored size (the bytes the offsets span plus the offsets). refactor: one home for chain cover windows and view packing; delete the mapped-bytes input path #1521's from_mapped reported 0.
  • Decided: exact states keep a fixed record rather than reuse ExactAccumulator's serde form. Serde would rebuild one object per state, which is not in place, and the column would no longer be the compact exact-record storage that operators read.
  • Decided: view_bytes takes a column and a state index rather than a lone state, so a column that already holds views lends them (Cow::Borrowed) instead of re-encoding them.

Verification

All runs used cargo 1.100, at this PR's head on main f17bd9924.

Scope Result Newly failing vs main Notes
cargo fmt --all --check clean
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings clean
cargo test -p asap-executor lib 159 passed, 1 ignored; integration 223 passed, 1 ignored; memory-limit tests 6 passed none +1 unit test
cargo test -p asap-integration-tests 353 passed, 8 ignored none +4 tests (state_views::)
cargo test -p asap-stage3-plan-selection --lib 57 passed none
cargo test --release -p asap-planner-cli --test corpus_snapshots -- --include-ignored (corpus + sketch snapshots) 10 passed none no snapshot regenerated; no "plan changed at the committed plan's cost" line
cargo test --release -p asap-planner-cli --test goldens 14 passed none

New tests in crates/integration-tests/tests/state_views.rs (public API only). On main (f17bd9924) the file does not compile: 8 errors, all for the missing API (1 × unresolved import family_has_view_layout, 4 × no from_views, 3 × no view_bytes).

  • ddsketch_kll_and_count_min_states_read_back_in_place: writes sealed DDSketch and KLL columns and a Count-Min object column as views, then reads them back over a caller buffer. Each state's bytes lie inside that buffer and equal the written view up to zero padding. Quantiles, the Count-Min total and point counts, and merges of adjacent states equal the originals. A batch of the column is charged none of its states (its stored size minus its charged memory is the column's stored size).
  • exact_states_read_back_in_place: all six exact kinds (SUM, COUNT, MIN, MAX, counter, irate) as objects with one empty state, plus sealed exact records. Each reads back in place and serializes equal.
  • a_merge_over_states_read_back_in_place_answers_as_over_the_originals: a SummaryMerge by series over a batch of the rebuilt column (this merges through the in-place view reads) gives the same DDSketch and KLL quantiles, Count-Min totals and exact sums as over the original column.
  • malformed_views_are_refused: these are bad input: DDSketch views read as KLL, an end offset past the bytes, a family with no view layout (HLL), an exact record with a presence word of 2, a record off its slot, and exact parameters of another kind.

Unit test in crates/executor/src/values/mapped_states.rs:

  • exact_records_read_back_as_written: each exact kind's record, present and absent (NaN included), has its kind's size and decodes to the state it was written from.

Follow-ups

…om_views)

A runtime that persists states and reads them back in place needs to write a
state column's view bytes and to build a state column over stored bytes again.
#1521 removed StateColumn::from_mapped, state_view_bytes and
family_has_mapped_form because no workspace crate called them; this restores
the capability as a smaller public API:

- StateColumn::view_bytes(index): a state's view layout, borrowed when the
  column already holds it that way
- StateColumn::from_views(family, bytes, offsets): states read in place,
  checked, held outside the run
- values::family_has_view_layout(family)

Sketch views reuse MappedSketches (one check shared with packed); exact
states use a fixed little-endian record.
@zzylol zzylol added enhancement New feature or request extensibility labels Nov 27, 2026
Document that a keyed exact state has no view bytes, say why a gathered
view column reports no stored size, and refuse malformed exact records in
the public-API test.
@zzylol
zzylol merged commit f2da999 into main Nov 27, 2026
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request extensibility

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant