From c9461f4159a1fc6508115543b9ca9a492200a4bc Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:35:31 +0000 Subject: [PATCH 1/2] feat(executor): restore a public state view bytes API (view_bytes, from_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. --- crates/executor/src/values/batch/mod.rs | 13 +- crates/executor/src/values/mapped_states.rs | 351 ++++++++++++++- crates/executor/src/values/mod.rs | 1 + crates/executor/src/values/state_column.rs | 97 +++- crates/integration-tests/tests/main.rs | 1 + crates/integration-tests/tests/state_views.rs | 415 ++++++++++++++++++ 6 files changed, 850 insertions(+), 28 deletions(-) create mode 100644 crates/integration-tests/tests/state_views.rs diff --git a/crates/executor/src/values/batch/mod.rs b/crates/executor/src/values/batch/mod.rs index 1fa5f9623..ebbec096b 100644 --- a/crates/executor/src/values/batch/mod.rs +++ b/crates/executor/src/values/batch/mod.rs @@ -339,10 +339,14 @@ impl Batch { if 2 * indices.len() >= state_column.len() { continue; } - // Mapped states a deployment holds cost the run nothing: - // indices into them are kept as they are. - if matches!(state_column.storage(), super::StateStorage::Mapped(_)) - && state_column.is_held_outside_run() + // States in their view layout that something outside the run + // holds cost the run nothing: indices into them are kept as + // they are. + if matches!( + state_column.storage(), + super::StateStorage::Mapped(_) + | super::StateStorage::Exact(super::state_column::ExactRecords::Mapped(_)) + ) && state_column.is_held_outside_run() { continue; } @@ -527,6 +531,7 @@ impl Batch { kernel, selected.into_iter(), )), + 0, ) }))); continue; diff --git a/crates/executor/src/values/mapped_states.rs b/crates/executor/src/values/mapped_states.rs index 28fc0ad0c..babc591a6 100644 --- a/crates/executor/src/values/mapped_states.rs +++ b/crates/executor/src/values/mapped_states.rs @@ -1,14 +1,19 @@ -//! Summary states held in their view layout: a sealed sketch column -//! ([`super::StateColumn::from_sealed_views`]) and the columns joined from -//! such columns, read in place instead of being rebuilt as objects. A merge -//! folds each sketch into the run's accumulator through `asap_sketchlib`'s -//! read-only views. +//! Summary states held in their view layout, read in place instead of +//! being rebuilt as objects: a sealed sketch column +//! ([`super::StateColumn::from_sealed_views`]), the columns joined from such +//! columns, and states a runtime stored and hands back over its own bytes +//! ([`super::StateColumn::from_views`]). A merge folds each sketch into the +//! run's accumulator through `asap_sketchlib`'s read-only views. //! -//! The bytes of state `i` are `bytes[offsets[i]..offsets[i + 1]]`, each -//! state 8-byte aligned, in `asap_sketchlib`'s view layout for DDSketch, -//! KLL and Count-Min ([`state_view_bytes`]). Other families have no view +//! The bytes of state `i` are `bytes[offsets[i]..offsets[i + 1]]`, in a +//! state's view layout ([`super::StateColumn::view_bytes`]): +//! `asap_sketchlib`'s for DDSketch, KLL and Count-Min, each view starting +//! 8-byte aligned ([`MappedSketches`]), and a fixed little-endian record for +//! each exact family ([`MappedRecords`]). Other families have no view //! layout; their states stay objects. +use crate::summary_kernels::exact::ScalarState; +use crate::summary_kernels::increase::IncreaseAccumulator; use crate::summary_kernels::{ CountMinSketchAccumulator, DDSketchAccumulator, DatasketchesKLLAccumulator, }; @@ -16,7 +21,7 @@ use crate::{AggregateCore, Error}; use arrow::buffer::{Buffer, ScalarBuffer}; use asap_sketchlib::{CountMinF64View, DdSketchView, KllView}; use planner_types::ir::schema::FieldDataType; -use planner_types::summary_type::SketchAlgorithm; +use planner_types::summary_type::{ExactKind, SketchAlgorithm}; use std::sync::Arc; /// Which sketch kernel a mapped column's states belong to. @@ -29,7 +34,7 @@ pub(crate) enum MappedSketchKernel { impl MappedSketchKernel { /// The kernel of a sketch column of `family`; `None` for a family with - /// no view layout. + /// no sketch view layout. pub(crate) fn of(family: &FieldDataType) -> Option { match family { FieldDataType::Sketch(SketchAlgorithm::DDSketch) => Some(Self::DDSketch), @@ -40,6 +45,30 @@ impl MappedSketchKernel { } } +/// The view layout of a family's states: a sketch view, or an exact record. +pub(crate) enum ViewLayout { + Sketch(MappedSketchKernel), + Record(ExactKind), +} + +impl ViewLayout { + /// `None` for a family with no view layout. + pub(crate) fn of(family: &FieldDataType) -> Option { + match family { + FieldDataType::ExactAggregate(kind, _) => Some(Self::Record(*kind)), + family => MappedSketchKernel::of(family).map(Self::Sketch), + } + } +} + +/// 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 { + ViewLayout::of(family).is_some() +} + fn invalid(message: impl Into) -> Error { Error::Invalid(message.into()) } @@ -57,6 +86,36 @@ impl MappedPart { } } +/// Checks `offsets` over `bytes`: at least one, ascending, within `bytes`. +fn check_offsets(bytes: &Buffer, offsets: &ScalarBuffer) -> Result<(), Error> { + if offsets.is_empty() { + return Err(invalid("view offsets need the end offset")); + } + if offsets.windows(2).any(|pair| pair[0] > pair[1]) + || offsets + .last() + .is_some_and(|&end| end as usize > bytes.len()) + { + return Err(invalid("view offsets descend or run past the bytes")); + } + Ok(()) +} + +/// Checks that every state of `part` is a `kernel` view, so the reads below +/// cannot fail. +fn check_views(kernel: MappedSketchKernel, part: &MappedPart) -> Result<(), Error> { + for index in 0..part.offsets.len() - 1 { + let view = part.state(index); + match kernel { + MappedSketchKernel::DDSketch => DdSketchView::from_bytes(view).map(|_| ()), + MappedSketchKernel::Kll => KllView::from_bytes(view).map(|_| ()), + MappedSketchKernel::CountMin => CountMinF64View::from_bytes(view).map(|_| ()), + } + .map_err(|e| invalid(format!("state {index}: {e}")))?; + } + Ok(()) +} + /// Mapped sketch states, possibly from several buffers (a column joined /// from several mapped columns keeps pointing at their buffers). pub struct MappedSketches { @@ -89,7 +148,8 @@ impl MappedSketches { } } - fn state_bytes(&self, index: usize) -> &[u8] { + /// State `index`'s view bytes, where they lie. + pub(crate) fn state_bytes(&self, index: usize) -> &[u8] { match &self.states { Some(states) => { let (part, state) = states[index]; @@ -137,6 +197,25 @@ impl MappedSketches { } } + /// The `kernel` views at `offsets` over `bytes`, which something + /// outside the run holds, read where they lie. Each view is checked + /// here (in range, 8-byte aligned, a `kernel` view), so reading it + /// later cannot fail. + pub(crate) fn over( + kernel: MappedSketchKernel, + bytes: Buffer, + offsets: ScalarBuffer, + ) -> Result { + check_offsets(&bytes, &offsets)?; + let part = MappedPart { bytes, offsets }; + check_views(kernel, &part)?; + Ok(Self { + kernel, + parts: vec![Arc::new(part)], + states: None, + }) + } + /// The column of `selected` states (column, index), their bytes copied /// into one new buffer of exactly their size ([`Self::packed`]): what a /// run holds for states it keeps without the rest of their source @@ -185,14 +264,7 @@ impl MappedSketches { }; // Views written by `to_view_bytes` read back; every read below // expects them to. - debug_assert!((0..part.offsets.len() - 1).all(|index| { - let view = part.state(index); - match kernel { - MappedSketchKernel::DDSketch => DdSketchView::from_bytes(view).is_ok(), - MappedSketchKernel::Kll => KllView::from_bytes(view).is_ok(), - MappedSketchKernel::CountMin => CountMinF64View::from_bytes(view).is_ok(), - } - })); + debug_assert!(check_views(kernel, &part).is_ok()); Ok(( Self { kernel, @@ -299,6 +371,169 @@ pub(crate) fn state_view_bytes( } } +/// The record of an exact state: little-endian 8-byte words. A presence +/// word is 0 or 1; the words of an absent part are zero. +/// +/// | kind | words | +/// |---|---| +/// | SUM | `sum`, `compensation` (f64), `seen` (presence word, last) | +/// | COUNT | `count` (u64) | +/// | MIN, MAX | presence word, `value` (f64) | +/// | counter (rate, increase) | presence word, `starting_value` (f64), `starting_timestamp` (i64), `last_seen_value` (f64), `last_seen_timestamp` (i64), `total_increase` (f64), `sample_count` (u64) | +/// | irate | twice (older first): presence word, `timestamp` (i64), `value` (f64) | +pub(crate) fn exact_record_bytes(record: &ScalarState) -> Vec { + let mut out = Vec::with_capacity(56); + let mut word = |value: u64| out.extend_from_slice(&value.to_le_bytes()); + match record { + ScalarState::Sum { + sum, + compensation, + seen, + } => { + word(sum.to_bits()); + word(compensation.to_bits()); + word(u64::from(*seen)); + } + ScalarState::Count(count) => word(*count), + ScalarState::Min(value) | ScalarState::Max(value) => { + word(u64::from(value.is_some())); + word(value.unwrap_or(0.0).to_bits()); + } + ScalarState::Counter(counter) => { + word(u64::from(counter.is_some())); + let c = counter + .clone() + .unwrap_or_else(|| IncreaseAccumulator::new(0.0, 0, 0.0, 0)); + word(c.starting_value.to_bits()); + word(c.starting_timestamp as u64); + word(c.last_seen_value.to_bits()); + word(c.last_seen_timestamp as u64); + word(c.total_increase.to_bits()); + word(c.sample_count); + } + ScalarState::LastTwoSamples(samples) => { + for sample in samples { + word(u64::from(sample.is_some())); + let (time, value) = sample.unwrap_or((0, 0.0)); + word(time as u64); + word(value.to_bits()); + } + } + } + out +} + +/// The size in bytes of an exact kind's record ([`exact_record_bytes`]). +fn record_size(kind: ExactKind) -> usize { + match kind { + ExactKind::Sum => 24, + ExactKind::Count => 8, + ExactKind::Min | ExactKind::Max => 16, + ExactKind::Counter => 56, + ExactKind::IRate => 48, + } +} + +/// The byte offsets of a record's presence words, each 0 or 1. +fn presence_offsets(kind: ExactKind) -> &'static [usize] { + match kind { + ExactKind::Sum => &[16], + ExactKind::Count => &[], + ExactKind::Min | ExactKind::Max | ExactKind::Counter => &[0], + ExactKind::IRate => &[0, 24], + } +} + +fn u64_at(record: &[u8], at: usize) -> u64 { + u64::from_le_bytes(record[at..at + 8].try_into().expect("8 bytes")) +} + +fn f64_at(record: &[u8], at: usize) -> f64 { + f64::from_bits(u64_at(record, at)) +} + +fn i64_at(record: &[u8], at: usize) -> i64 { + u64_at(record, at) as i64 +} + +/// Exact records of one kind ([`exact_record_bytes`]) back to back in bytes +/// something outside the run holds, read where they lie. +pub(crate) struct MappedRecords { + kind: ExactKind, + bytes: Buffer, +} + +impl MappedRecords { + /// The `kind` records at `offsets` over `bytes`: record `i` must start + /// at `i` times its kind's size, and each presence word be 0 or 1. + pub(crate) fn over( + kind: ExactKind, + bytes: Buffer, + offsets: ScalarBuffer, + ) -> Result { + check_offsets(&bytes, &offsets)?; + let size = record_size(kind); + if offsets + .iter() + .enumerate() + .any(|(i, &offset)| offset as usize != i * size) + { + return Err(invalid(format!( + "{kind:?} records are not {size} bytes each" + ))); + } + let bytes = bytes.slice_with_length(0, (offsets.len() - 1) * size); + if let Some(index) = bytes.chunks_exact(size).position(|record| { + presence_offsets(kind) + .iter() + .any(|&at| u64_at(record, at) > 1) + }) { + return Err(invalid(format!("{kind:?} record {index} is malformed"))); + } + Ok(Self { kind, bytes }) + } + + pub(crate) fn len(&self) -> usize { + self.bytes.len() / record_size(self.kind) + } + + /// Record `index`'s bytes, where they lie. + pub(crate) fn record_bytes(&self, index: usize) -> &[u8] { + let size = record_size(self.kind); + &self.bytes[index * size..(index + 1) * size] + } + + /// Record `index`. + pub(crate) fn get(&self, index: usize) -> ScalarState { + let record = self.record_bytes(index); + let present = |at: usize| u64_at(record, at) == 1; + match self.kind { + ExactKind::Sum => ScalarState::Sum { + sum: f64_at(record, 0), + compensation: f64_at(record, 8), + seen: present(16), + }, + ExactKind::Count => ScalarState::Count(u64_at(record, 0)), + ExactKind::Min => ScalarState::Min(present(0).then(|| f64_at(record, 8))), + ExactKind::Max => ScalarState::Max(present(0).then(|| f64_at(record, 8))), + ExactKind::Counter => ScalarState::Counter(present(0).then(|| IncreaseAccumulator { + starting_value: f64_at(record, 8), + starting_timestamp: i64_at(record, 16), + last_seen_value: f64_at(record, 24), + last_seen_timestamp: i64_at(record, 32), + total_increase: f64_at(record, 40), + sample_count: u64_at(record, 48), + })), + ExactKind::IRate => { + let sample = |at: usize| { + present(at).then(|| (i64_at(record, at + 8), f64_at(record, at + 16))) + }; + ScalarState::LastTwoSamples([sample(0), sample(24)]) + } + } + } +} + #[cfg(test)] mod tests { //! Joining view-layout columns keeps their states in that layout, and @@ -758,4 +993,82 @@ mod tests { "views {view_peak} B, objects {object_peak} B" ); } + + /// Every exact kind's record, present and absent, is its kind's size + /// and reads back as the state it was written from. + #[test] + fn exact_records_read_back_as_written() { + let counter = IncreaseAccumulator::new(3.0, 1_000, 10.5, 9_000); + let cases = [ + ( + ExactKind::Sum, + vec![ + ScalarState::Sum { + sum: 7.25, + compensation: -1e-17, + seen: true, + }, + ScalarState::Sum { + sum: 0.0, + compensation: 0.0, + seen: false, + }, + ], + ), + ( + ExactKind::Count, + vec![ScalarState::Count(42), ScalarState::Count(0)], + ), + ( + ExactKind::Min, + vec![ScalarState::Min(Some(-2.5)), ScalarState::Min(None)], + ), + ( + ExactKind::Max, + vec![ScalarState::Max(Some(f64::NAN)), ScalarState::Max(None)], + ), + ( + ExactKind::Counter, + vec![ + ScalarState::Counter(Some(counter)), + ScalarState::Counter(None), + ], + ), + ( + ExactKind::IRate, + vec![ + ScalarState::LastTwoSamples([Some((1_000, 1.0)), Some((2_000, 4.0))]), + ScalarState::LastTwoSamples([None, Some((-5, 0.5))]), + ScalarState::LastTwoSamples([None, None]), + ], + ), + ]; + for (kind, states) in cases { + let records: Vec> = states.iter().map(exact_record_bytes).collect(); + assert!( + records.iter().all(|r| r.len() == record_size(kind)), + "{kind:?}" + ); + let offsets: Vec = (0..=records.len()) + .map(|i| (i * record_size(kind)) as u32) + .collect(); + let mapped = MappedRecords::over( + kind, + Buffer::from_vec(records.concat()), + ScalarBuffer::from(offsets), + ) + .unwrap(); + assert_eq!(mapped.len(), states.len()); + for (index, state) in states.iter().enumerate() { + assert_eq!(format!("{:?}", mapped.get(index)), format!("{state:?}")); + // Bit-equal, so a NaN compares equal to itself. + assert_eq!( + exact_record_bytes(&mapped.get(index)), + records[index], + "{kind:?} {state:?}" + ); + assert_eq!(mapped.record_bytes(index), &records[index][..]); + } + } + } } diff --git a/crates/executor/src/values/mod.rs b/crates/executor/src/values/mod.rs index 5cf79f8a7..56d3f8de4 100644 --- a/crates/executor/src/values/mod.rs +++ b/crates/executor/src/values/mod.rs @@ -10,6 +10,7 @@ mod batch; mod mapped_states; mod state_column; pub use batch::{Batch, BatchColumn}; +pub use mapped_states::family_has_view_layout; #[cfg(test)] pub(crate) use mapped_states::state_view_bytes; pub(crate) use mapped_states::MappedSketchKernel; diff --git a/crates/executor/src/values/state_column.rs b/crates/executor/src/values/state_column.rs index 38d03a8c3..857e6ebf8 100644 --- a/crates/executor/src/values/state_column.rs +++ b/crates/executor/src/values/state_column.rs @@ -1,11 +1,15 @@ //! The summary states of one batch column. -use super::mapped_states::{MappedSketchKernel, MappedSketches}; +use super::mapped_states::{ + exact_record_bytes, state_view_bytes, MappedRecords, MappedSketchKernel, MappedSketches, + ViewLayout, +}; use crate::summary_kernels::exact::{ExactAccumulator, ScalarState}; use crate::summary_kernels::increase::IncreaseAccumulator; use crate::AggregateCore; use arrow::buffer::BooleanBuffer; use planner_types::ir::schema::FieldDataType; use planner_types::summary_type::ExactKind; +use std::borrow::Cow; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -43,7 +47,7 @@ pub(crate) enum StateStorage { /// Sketch states in their view layout, read through read-only views /// ([`super::mapped_states`]): sealed windows the run holds in that /// layout ([`StateColumn::from_sealed_views`]), or stored ones something - /// outside the run holds (charged nothing). + /// outside the run holds ([`StateColumn::from_views`], charged nothing). Mapped(MappedSketches), } @@ -64,6 +68,9 @@ pub(crate) enum ExactRecords { Counter(Optional), /// irate: the last two samples. LastTwoSamples(Box<[LastTwoSamples]>), + /// Records of any exact kind in their view layout, in bytes something + /// outside the run holds ([`StateColumn::from_views`]). + Mapped(MappedRecords), } /// An irate record: the last two samples, `(time, value)`, the newer second. @@ -184,6 +191,7 @@ impl ExactRecords { Self::Max(records) => ScalarState::Max(records.get(index)), Self::Counter(records) => ScalarState::Counter(records.get(index)), Self::LastTwoSamples(records) => ScalarState::LastTwoSamples(records[index]), + Self::Mapped(records) => records.get(index), } } @@ -195,6 +203,7 @@ impl ExactRecords { Self::Min(records) | Self::Max(records) => records.values.len(), Self::Counter(records) => records.values.len(), Self::LastTwoSamples(records) => records.len(), + Self::Mapped(records) => records.len(), } } @@ -206,6 +215,8 @@ impl ExactRecords { Self::Min(records) | Self::Max(records) => records.memory_bytes(), Self::Counter(records) => records.memory_bytes(), Self::LastTwoSamples(records) => std::mem::size_of_val(&**records), + // Held outside the run; `StateColumn::from_views` sizes them. + Self::Mapped(_) => 0, } } } @@ -294,6 +305,47 @@ 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, + ) -> Result { + let stored_bytes = match (offsets.first(), offsets.last()) { + (Some(&first), Some(&last)) => last.saturating_sub(first) as usize, + _ => 0, + } + std::mem::size_of_val(&*offsets); + let storage = match ViewLayout::of(&family) { + Some(ViewLayout::Sketch(kernel)) => { + StateStorage::Mapped(MappedSketches::over(kernel, bytes, offsets)?) + } + Some(ViewLayout::Record(kind)) => { + // The family's parameters must be those of its kind. + ExactAccumulator::new(family.clone(), false).map_err(crate::Error::Invalid)?; + StateStorage::Exact(ExactRecords::Mapped(MappedRecords::over( + kind, bytes, offsets, + )?)) + } + None => { + return Err(crate::Error::Invalid(format!( + "{family:?} has no view layout" + ))) + } + }; + Ok(Self::mapped_column(family, storage, stored_bytes)) + } + /// The column of view-layout `storage` the run holds, charged /// `state_memory_bytes`. pub(crate) fn stored_views( @@ -310,12 +362,17 @@ impl StateColumn { } } - /// The column of mapped `storage`: held outside any run, charged nothing. - pub(crate) fn mapped_column(family: FieldDataType, storage: StateStorage) -> Self { + /// The column of mapped `storage`: held outside any run, so charged + /// nothing, with `state_memory_bytes` its stored size. + pub(crate) fn mapped_column( + family: FieldDataType, + storage: StateStorage, + state_memory_bytes: usize, + ) -> Self { Self { family, storage, - state_memory_bytes: 0, + state_memory_bytes, held_outside_run: AtomicBool::new(true), objects_held_outside_run: None, } @@ -340,6 +397,36 @@ impl StateColumn { } } + /// 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`]). + pub fn view_bytes(&self, index: usize) -> Option> { + match &self.storage { + StateStorage::Mapped(sketches) => Some(Cow::Borrowed(sketches.state_bytes(index))), + StateStorage::Exact(ExactRecords::Mapped(records)) => { + Some(Cow::Borrowed(records.record_bytes(index))) + } + StateStorage::Exact(records) => { + Some(Cow::Owned(exact_record_bytes(&records.get(index)))) + } + StateStorage::Objects(states) => { + let state = states[index].as_ref(); + match ViewLayout::of(&self.family)? { + ViewLayout::Sketch(kernel) => state_view_bytes(kernel, state), + ViewLayout::Record(_) => state + .as_any() + .downcast_ref::()? + .scalar() + .map(exact_record_bytes), + } + .map(Cow::Owned) + } + } + } + /// Whether the column holds no state. pub fn is_empty(&self) -> bool { self.len() == 0 diff --git a/crates/integration-tests/tests/main.rs b/crates/integration-tests/tests/main.rs index c88c27873..60c0393ba 100644 --- a/crates/integration-tests/tests/main.rs +++ b/crates/integration-tests/tests/main.rs @@ -44,6 +44,7 @@ mod sql_frequency; mod sql_relational_execution; mod sql_to_post_asap; mod stage3_objective; +mod state_views; mod storage_costs; mod time_range; mod view_state_key; diff --git a/crates/integration-tests/tests/state_views.rs b/crates/integration-tests/tests/state_views.rs new file mode 100644 index 000000000..6e723dfe2 --- /dev/null +++ b/crates/integration-tests/tests/state_views.rs @@ -0,0 +1,415 @@ +//! A runtime that persists states and reads them back in place, through the +//! executor's public API only: it takes each state's view bytes from a state +//! column, lays them out in a buffer it owns (here a `Vec`, as a mapped +//! file would be), and builds a state column over that buffer again. The +//! rebuilt column answers and merges as the original, and reads each state +//! where the buffer holds it. +use asap_executor::arrow::array::{DictionaryArray, UInt32Array}; +use asap_executor::arrow::buffer::{Buffer, ScalarBuffer}; +use asap_executor::arrow::datatypes::UInt32Type; +use asap_executor::operators::Operator; +use asap_executor::plan::PhysicalDAG; +use asap_executor::planner::ir::schema::DataType; +use asap_executor::planner::ir::schema::{Field, FieldDataType, Schema}; +use asap_executor::planner::stages::Lifetime; +use asap_executor::planner::summary_type::{ + ExactKind, ExactParams, SketchAlgorithm, SketchParams, SketchStatistic, +}; +use asap_executor::runtime::{Limits, RunContext, Scope}; +use asap_executor::summary_kernels::exact::ExactAccumulator; +use asap_executor::summary_kernels::CountMinSketchAccumulator; +use asap_executor::values::{ + family_has_view_layout, Batch, BatchColumn, SchemaRef, StateColumn, Value, +}; +use asap_executor::{AggregateCore, StateColumnUpdater}; +use futures::{executor::block_on, StreamExt}; +use std::borrow::Cow; +use std::sync::Arc; + +const GROUPS: u32 = 5; + +/// A sealed column of `GROUPS` states of `family`, group `g` fed +/// `40 + 10 g` samples of a counter that grows by 1 to 9 per sample. +fn sealed(family: &FieldDataType, params: Option) -> StateColumn { + let mut updater = StateColumnUpdater::new(family, params.as_ref()).unwrap(); + for group in 0..GROUPS { + updater.add_group().unwrap(); + let mut value = 0.0; + for sample in 0..40 + 10 * group as i64 { + value += 1.0 + ((sample * 7 + group as i64) % 9) as f64; + updater.update(group, value, 1_000 + sample * 10).unwrap(); + } + } + updater.seal() +} + +/// A column of `GROUPS` Count-Min states built as objects (a keyless +/// Count-Min has no per-sample updater), through literal rows. +fn count_min_column() -> Arc { + let family = FieldDataType::Sketch(SketchAlgorithm::CountMinSketch); + let schema = state_schema(&family); + let rows = (0..GROUPS) + .map(|group| { + let mut cms = CountMinSketchAccumulator::new(3, 64).unwrap(); + for item in 0..20 + group { + cms.update(&format!("i{}", item % 7), 1.0 + item as f64); + } + vec![Value::Summary { + family: family.clone(), + state: Arc::new(cms), + }] + }) + .collect(); + Batch::try_new(schema, rows) + .unwrap() + .state_column(0) + .unwrap() + .clone() +} + +/// The view bytes of `column`'s states laid out as a runtime would store +/// them: back to back in one 8-byte-aligned buffer, each padded to 8 bytes, +/// and the `u32` offsets of their starts and the end. +fn stored(column: &StateColumn) -> (Buffer, ScalarBuffer) { + let mut words: Vec = Vec::new(); + let mut offsets = vec![0u32]; + for index in 0..column.len() { + let view = column.view_bytes(index).expect("a family with views"); + for chunk in view.chunks(8) { + let mut word = [0u8; 8]; + word[..chunk.len()].copy_from_slice(chunk); + words.push(u64::from_le_bytes(word)); + } + offsets.push((words.len() * 8) as u32); + } + (Buffer::from_vec(words), ScalarBuffer::from(offsets)) +} + +/// `original` written as view bytes and read back over the stored buffer: +/// every view reads where the buffer holds it, and the column is held +/// outside the run, so a batch of it is charged no state memory. +fn round_trip(original: &StateColumn, family: &FieldDataType) -> StateColumn { + assert!(family_has_view_layout(family), "{family:?}"); + let (bytes, offsets) = stored(original); + let stored_range = bytes.as_ptr() as usize..bytes.as_ptr() as usize + bytes.len(); + let rebuilt = StateColumn::from_views(family.clone(), bytes.clone(), offsets).unwrap(); + assert_eq!(rebuilt.len(), original.len()); + for index in 0..rebuilt.len() { + let Some(Cow::Borrowed(view)) = rebuilt.view_bytes(index) else { + panic!("{family:?} state {index} is not read in place"); + }; + assert!(stored_range.contains(&(view.as_ptr() as usize))); + assert!(stored_range.contains(&(view.as_ptr() as usize + view.len() - 1))); + // The same view the original state wrote, up to the padding. + let written = original.view_bytes(index).unwrap(); + assert_eq!(&view[..written.len()], &written[..]); + assert!(view[written.len()..].iter().all(|&byte| byte == 0)); + } + let schema = state_schema(family); + let rebuilt = Arc::new(rebuilt); + let batch = Batch::try_from_columns( + schema, + vec![BatchColumn::States { + indices: UInt32Array::from_iter_values(0..rebuilt.len() as u32), + states: rebuilt.clone(), + }], + ) + .unwrap(); + // Charged none of the states, whose stored size is what they read. + assert!(rebuilt.state_memory_bytes() > 0); + assert_eq!( + batch.stored_bytes() - batch.memory_bytes(), + rebuilt.state_memory_bytes() + ); + drop(batch); + Arc::into_inner(rebuilt).unwrap() +} + +/// `query`'s answer on each state and on each adjacent pair merged, the same +/// on both columns. +fn assert_same_answers(original: &StateColumn, rebuilt: &StateColumn, query: &SketchStatistic) { + for index in 0..original.len() { + assert_eq!( + original.state(index).estimate(query).unwrap(), + rebuilt.state(index).estimate(query).unwrap(), + "state {index}" + ); + } + for index in 1..original.len() { + let merged = |column: &StateColumn| { + column + .state(index - 1) + .merge_with(column.state(index).as_ref()) + .unwrap() + .estimate(query) + .unwrap() + }; + assert_eq!(merged(original), merged(rebuilt), "merge {index}"); + } +} + +#[test] +fn ddsketch_kll_and_count_min_states_read_back_in_place() { + for (algorithm, params) in [ + ( + SketchAlgorithm::DDSketch, + SketchParams::DDSketch { alpha: 0.01 }, + ), + // `k` above every group's sample count: no compaction coin flips, + // so merging owned states is reproducible. + (SketchAlgorithm::KLL, SketchParams::Kll { k: 1024 }), + ] { + let family = FieldDataType::Sketch(algorithm); + let original = sealed(&family, Some(params)); + let rebuilt = round_trip(&original, &family); + for q in [0.1, 0.5, 0.99] { + assert_same_answers(&original, &rebuilt, &SketchStatistic::Quantile { q }); + } + } + let family = FieldDataType::Sketch(SketchAlgorithm::CountMinSketch); + let original = count_min_column(); + let rebuilt = round_trip(&original, &family); + let total = SketchStatistic::PointCount { + key: asap_executor::planner::ir::scalar::ColumnRef::SampleValue, + value: None, + }; + assert_same_answers(&original, &rebuilt, &total); + for index in 0..original.len() { + let point = |column: &StateColumn, item: &str| { + let state = column.state(index); + state + .as_any() + .downcast_ref::() + .unwrap() + .query_key(&[item.to_string()]) + }; + for item in ["i0", "i3", "i6", "absent"] { + assert_eq!(point(&original, item), point(&rebuilt, item)); + } + } +} + +/// The schema of one state column of `family`. +fn state_schema(family: &FieldDataType) -> SchemaRef { + Arc::new(Schema { + fields: vec![Field { + name: "state".into(), + dtype: family.clone(), + nullable: false, + }], + time_index: None, + unique_keys: vec![], + closed: false, + }) +} + +/// An exact state as its JSON, equal for equal states. +fn exact_json(state: &dyn AggregateCore) -> serde_json::Value { + serde_json::to_value(state.as_any().downcast_ref::().unwrap()).unwrap() +} + +#[test] +fn exact_states_read_back_in_place() { + let families = [ + (ExactKind::Sum, ExactParams::Sum), + (ExactKind::Count, ExactParams::Count), + (ExactKind::Min, ExactParams::Min), + (ExactKind::Max, ExactParams::Max), + (ExactKind::Counter, ExactParams::Counter), + (ExactKind::IRate, ExactParams::IRate), + ]; + for (kind, params) in families { + let family = FieldDataType::ExactAggregate(kind, params); + // Objects, as literal rows hold them: one state per group, the + // last one empty. + let rows = (0..GROUPS) + .map(|group| { + let mut state = ExactAccumulator::new(family.clone(), false).unwrap(); + for sample in 0..(GROUPS - 1 - group) as i64 * 3 { + state.update(None, 1.5 + (sample % 4) as f64, 1_000 + sample * 10); + } + vec![Value::Summary { + family: family.clone(), + state: Arc::new(state), + }] + }) + .collect(); + let objects = Batch::try_new(state_schema(&family), rows) + .unwrap() + .state_column(0) + .unwrap() + .clone(); + let mut originals = vec![objects]; + // Sealed exact records, for the families a per-sample build takes. + if kind != ExactKind::IRate { + originals.push(Arc::new(sealed(&family, None))); + } + for original in originals { + let rebuilt = round_trip(&original, &family); + for index in 0..original.len() { + assert_eq!( + exact_json(original.state(index).as_ref()), + exact_json(rebuilt.state(index).as_ref()), + "{kind:?} state {index}" + ); + } + } + } +} + +/// `SummaryMerge` of `states` by `series`: each series' merged state, by +/// series. The merge reads a column built from views where it lies. +fn merged_by_series( + family: &FieldDataType, + series: &[&str], + states: Arc, +) -> Vec> { + let schema: SchemaRef = Arc::new(Schema { + fields: vec![ + Field { + name: "series".into(), + dtype: FieldDataType::Plain(DataType::Utf8), + nullable: false, + }, + Field { + name: "state".into(), + dtype: family.clone(), + nullable: false, + }, + ], + time_index: None, + unique_keys: vec![], + closed: false, + }); + let labels: DictionaryArray = series.iter().copied().collect(); + let batch = Batch::try_from_columns( + schema.clone(), + vec![ + BatchColumn::Plain(Arc::new(labels)), + BatchColumn::States { + indices: UInt32Array::from_iter_values(0..states.len() as u32), + states, + }, + ], + ) + .unwrap(); + let mut dag = PhysicalDAG::default(); + dag.add( + 0, + vec![], + Operator::source(schema.clone(), vec![batch]).unwrap(), + Lifetime::None, + ) + .unwrap(); + dag.add( + 1, + vec![0], + Operator::summary_merge(schema, 1, vec![0]).unwrap(), + Lifetime::None, + ) + .unwrap(); + let context = RunContext::new( + Scope::Query { + evaluation_time_ms: 0, + }, + Limits { max_bytes: 1 << 30 }, + ) + .unwrap(); + let mut rows: Vec<(String, Arc)> = block_on(async { + let mut output = dag.execute(&[1], context).unwrap().remove(0); + let mut rows = Vec::new(); + while let Some(batch) = output.next().await { + for row in batch.unwrap().to_rows() { + let (Value::Utf8(series), Value::Summary { state, .. }) = (&row[0], &row[1]) else { + panic!("a series and its merged state"); + }; + rows.push((series.to_string(), state.clone())); + } + } + rows + }); + rows.sort_by(|a, b| a.0.cmp(&b.0)); + rows.into_iter().map(|(_, state)| state).collect() +} + +/// A plan merging states read back in place answers as over the original +/// states: DDSketch and KLL quantiles, Count-Min totals, exact sums. +#[test] +fn a_merge_over_states_read_back_in_place_answers_as_over_the_originals() { + let series = ["a", "b", "a", "b", "a"]; + let quantiles = [0.1, 0.5, 0.99].map(|q| SketchStatistic::Quantile { q }); + let total = [SketchStatistic::PointCount { + key: asap_executor::planner::ir::scalar::ColumnRef::SampleValue, + value: None, + }]; + let sketches: [(FieldDataType, Arc, &[SketchStatistic]); 3] = [ + ( + FieldDataType::Sketch(SketchAlgorithm::DDSketch), + Arc::new(sealed( + &FieldDataType::Sketch(SketchAlgorithm::DDSketch), + Some(SketchParams::DDSketch { alpha: 0.01 }), + )), + &quantiles, + ), + ( + FieldDataType::Sketch(SketchAlgorithm::KLL), + Arc::new(sealed( + &FieldDataType::Sketch(SketchAlgorithm::KLL), + Some(SketchParams::Kll { k: 1024 }), + )), + &quantiles, + ), + ( + FieldDataType::Sketch(SketchAlgorithm::CountMinSketch), + count_min_column(), + &total, + ), + ]; + for (family, original, queries) in sketches { + let rebuilt = Arc::new(round_trip(&original, &family)); + let expected = merged_by_series(&family, &series, original); + let actual = merged_by_series(&family, &series, rebuilt); + assert_eq!(expected.len(), 2); + for (expected, actual) in expected.iter().zip(&actual) { + for query in queries { + assert_eq!( + expected.estimate(query).unwrap(), + actual.estimate(query).unwrap(), + "{family:?} {query:?}" + ); + } + } + } + let family = FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Sum); + let original = Arc::new(sealed(&family, None)); + let rebuilt = Arc::new(round_trip(&original, &family)); + let expected = merged_by_series(&family, &series, original); + let actual = merged_by_series(&family, &series, rebuilt); + for (expected, actual) in expected.iter().zip(&actual) { + assert_eq!(exact_json(expected.as_ref()), exact_json(actual.as_ref())); + } +} + +#[test] +fn malformed_views_are_refused() { + let family = FieldDataType::Sketch(SketchAlgorithm::DDSketch); + let (bytes, offsets) = stored(&sealed( + &family, + Some(SketchParams::DDSketch { alpha: 0.01 }), + )); + // Not a DDSketch view: a KLL column refuses it. + assert!(StateColumn::from_views( + FieldDataType::Sketch(SketchAlgorithm::KLL), + bytes.clone(), + offsets.clone(), + ) + .is_err()); + // An offset past the bytes. + let mut past = offsets.to_vec(); + *past.last_mut().unwrap() += 8; + assert!(StateColumn::from_views(family.clone(), bytes.clone(), past.into()).is_err()); + // A family with no view layout. + let hll = FieldDataType::Sketch(SketchAlgorithm::HLL); + assert!(!family_has_view_layout(&hll)); + assert!(StateColumn::from_views(hll, bytes, offsets).is_err()); +} From 38285e366a0c0f23e42ebea6487721b4ca5460d7 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:07:09 +0000 Subject: [PATCH 2/2] fix(executor): review fixes for the state view bytes API 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. --- crates/executor/src/values/batch/mod.rs | 2 ++ crates/executor/src/values/state_column.rs | 2 +- crates/integration-tests/tests/state_views.rs | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/executor/src/values/batch/mod.rs b/crates/executor/src/values/batch/mod.rs index ebbec096b..d01da6af4 100644 --- a/crates/executor/src/values/batch/mod.rs +++ b/crates/executor/src/values/batch/mod.rs @@ -531,6 +531,8 @@ impl Batch { kernel, selected.into_iter(), )), + // It points into its inputs' bytes, whose own + // columns report their stored size. 0, ) }))); diff --git a/crates/executor/src/values/state_column.rs b/crates/executor/src/values/state_column.rs index 857e6ebf8..6471bc753 100644 --- a/crates/executor/src/values/state_column.rs +++ b/crates/executor/src/values/state_column.rs @@ -402,7 +402,7 @@ impl StateColumn { /// 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`]). + /// ([`super::family_has_view_layout`]) or a keyed exact state. pub fn view_bytes(&self, index: usize) -> Option> { match &self.storage { StateStorage::Mapped(sketches) => Some(Cow::Borrowed(sketches.state_bytes(index))), diff --git a/crates/integration-tests/tests/state_views.rs b/crates/integration-tests/tests/state_views.rs index 6e723dfe2..ce1293f2f 100644 --- a/crates/integration-tests/tests/state_views.rs +++ b/crates/integration-tests/tests/state_views.rs @@ -412,4 +412,18 @@ fn malformed_views_are_refused() { let hll = FieldDataType::Sketch(SketchAlgorithm::HLL); assert!(!family_has_view_layout(&hll)); assert!(StateColumn::from_views(hll, bytes, offsets).is_err()); + // Exact records: a presence word above 1, a record off its slot, and + // parameters of another kind. + let sum = FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Sum); + let mut record = [0u8; 24]; + record[16] = 2; + let one = || ScalarBuffer::from(vec![0u32, 24]); + assert!( + StateColumn::from_views(sum.clone(), Buffer::from_vec(record.to_vec()), one()).is_err() + ); + record[16] = 1; + let shifted = ScalarBuffer::from(vec![0u32, 16]); + assert!(StateColumn::from_views(sum, Buffer::from_vec(record.to_vec()), shifted).is_err()); + let mismatched = FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Count); + assert!(StateColumn::from_views(mismatched, Buffer::from_vec(record.to_vec()), one()).is_err()); }