diff --git a/Cargo.lock b/Cargo.lock index 88c5f11f..3b78efe2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -978,6 +978,7 @@ dependencies = [ "tower", "tracing", "tracing-subscriber", + "zstd", ] [[package]] diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index d1d1dc85..1bec98cf 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -8,6 +8,8 @@ asap-planner.workspace = true asap-executor.workspace = true asap_sketchlib.workspace = true serde_bytes = "0.11" +# Each view fragment is compressed (segment.rs). +zstd = "0.13" ahash = "0.8" # The per-thread series cache of the Remote Write decoder (a table of # indices hashed by the keys they point to). diff --git a/data_plane/examples/view_read_bench.rs b/data_plane/examples/view_read_bench.rs index c3b41190..bdea03ee 100644 --- a/data_plane/examples/view_read_bench.rs +++ b/data_plane/examples/view_read_bench.rs @@ -1,11 +1,12 @@ //! Cold view reads, `mmap` versus `pread` (docs/design/tiered-view-storage.md, -//! B3): writes `WINDOWS` windows of `SERIES` rows of one view (KLL states of -//! `SAMPLES` samples each, a series identity and a value) to a segment, -//! seals it, then decodes every window both ways, with the page cache warm -//! and after dropping it, and prints ns per window and per row, and the -//! process's `RssAnon`/`RssFile`. +//! B3): writes `WINDOWS` windows of `SERIES` rows of one view (states of +//! `SAMPLES` samples each of `FAMILY`, `kll` (default), `ddsketch` (alpha +//! 0.02) or `counter` (exact); a series identity and a value) to a +//! segment, timing the writes, seals it, then decodes every window both +//! ways, with the page cache warm and after dropping it, and prints ns per +//! window and per row, and the process's `RssAnon`/`RssFile`. //! -//! `cargo run --release -p data_plane --example view_read_bench -- [SERIES] [WINDOWS] [SAMPLES] [DIR]` +//! `cargo run --release -p data_plane --example view_read_bench -- [SERIES] [WINDOWS] [SAMPLES] [DIR] [FAMILY]` #[global_allocator] static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; @@ -17,8 +18,9 @@ use std::time::{Duration, Instant}; use asap_executor::planner::ir::schema::{ DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY, }; -use asap_executor::planner::summary_type::SketchAlgorithm; -use asap_executor::summary_kernels::DatasketchesKLLAccumulator; +use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm}; +use asap_executor::summary_kernels::exact::ExactAccumulator; +use asap_executor::summary_kernels::{DDSketchAccumulator, DatasketchesKLLAccumulator}; use asap_executor::values::{Batch, Value}; use asap_executor::AggregateCore; use data_plane::persist::{ViewFiles, ViewRead}; @@ -29,9 +31,15 @@ fn main() { let windows: i64 = args.get(2).map_or(40, |a| a.parse().unwrap()); let samples: usize = args.get(3).map_or(15, |a| a.parse().unwrap()); let dir = PathBuf::from(args.get(4).map_or("view-read-bench", String::as_str)); + let family_name = args.get(5).map_or("kll", String::as_str); let _ = std::fs::remove_dir_all(&dir); - let family = FieldDataType::Sketch(SketchAlgorithm::Kll); + let family = match family_name { + "kll" => FieldDataType::Sketch(SketchAlgorithm::Kll), + "ddsketch" => FieldDataType::Sketch(SketchAlgorithm::DDSketch), + "counter" => FieldDataType::ExactAggregate(ExactKind::Counter, ExactParams::Counter), + other => panic!("unknown family {other}: kll, ddsketch or counter"), + }; let schema = Arc::new(Schema::with_time_index( vec![ Field::plain("ts", DataType::Timestamp, false), @@ -44,14 +52,35 @@ fn main() { )); let mut files = ViewFiles::open(&dir, 1, Duration::from_secs(5)).unwrap(); let mut locations = Vec::new(); + let mut write = Duration::ZERO; for window in 0..windows { let end = (window + 1) * 15_000; let rows = (0..series) .map(|s| { - let mut kll = DatasketchesKLLAccumulator::new(132); - for i in 0..samples { - kll.update(((s * 31 + i * 7 + window as usize) % 1000) as f64); - } + let sample = |i: usize| ((s * 31 + i * 7 + window as usize) % 1000) as f64; + let state: Arc = match family_name { + "kll" => { + let mut kll = DatasketchesKLLAccumulator::new(132); + (0..samples).for_each(|i| kll.update(sample(i))); + Arc::new(kll) + } + "ddsketch" => { + let mut dd = asap_sketchlib::DdSketch::new(0.02); + (0..samples).for_each(|i| dd.add(&sample(i))); + Arc::new(DDSketchAccumulator::restore_from_disk(dd).unwrap()) + } + _ => { + let mut counter = ExactAccumulator::new(family.clone(), false).unwrap(); + (0..samples).for_each(|i| { + counter.update( + None, + (window as usize * samples + i) as f64, + end - 15_000 + i as i64 * 100, + ) + }); + Arc::new(counter) + } + }; vec![ Value::Timestamp(end), Value::Utf8( @@ -64,15 +93,17 @@ fn main() { Value::Float64(s as f64), Value::Summary { family: family.clone(), - state: Arc::new(kll) as Arc, + state, }, ] }) .collect(); let batch = Batch::try_new(schema.clone(), rows).unwrap(); + let started = Instant::now(); let written = files .append(0, (end - 15_000, end), &[(1, std::slice::from_ref(&batch))]) .unwrap(); + write += started.elapsed(); let location = written .locations .into_iter() @@ -84,8 +115,10 @@ fn main() { files.seal(0).unwrap(); let bytes: u64 = locations.iter().map(|l| u64::from(l.len())).sum(); println!( - "{windows} windows x {series} rows, {samples} samples per KLL: {:.1} MiB of fragments", - bytes as f64 / 1048576.0 + "{windows} windows x {series} rows, {samples} samples per {family_name} state: {:.1} MiB of fragments, {:.1} B per row; write {:.0} ns per row", + bytes as f64 / 1048576.0, + bytes as f64 / (windows as f64 * series as f64), + write.as_nanos() as f64 / (windows as f64 * series as f64) ); // pread first: a mapped page cannot be dropped from the page cache. for how in [ViewRead::Pread, ViewRead::Mmap] { diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 9e59b2b4..773a0cdc 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -22,6 +22,7 @@ pub mod remote_write; pub mod result_cache; pub mod segment; pub mod series_ids; +mod state_codec; pub mod store; pub mod window_cache; diff --git a/data_plane/src/persist.rs b/data_plane/src/persist.rs index bcd7b018..6f272249 100644 --- a/data_plane/src/persist.rs +++ b/data_plane/src/persist.rs @@ -1105,12 +1105,13 @@ mod tests { // docs/design/tiered-view-storage.md, tests V2, V3, V9, V12, V13, // V18, V19. They fail until the segment format is implemented. - use asap_executor::arrow::array::{DictionaryArray, Float64Array}; + use asap_executor::arrow::array::DictionaryArray; use asap_executor::arrow::datatypes::UInt32Type; use asap_executor::planner::ir::schema::{ DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY, }; use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm}; + use asap_executor::values::state_view_bytes; /// A fresh directory for one test's segments. fn segment_dir(test: &str) -> PathBuf { @@ -1314,6 +1315,59 @@ mod tests { out } + /// One 1 s pane of 1,000 series, ten samples each, in a DDSketch at + /// alpha 0.02 (the demo's finest quantile view): the window's stored + /// fragment, with its series and label columns. + fn ten_sample_ddsketch_window() -> Batch { + // Samples uniform in [50, 100), full precision (xorshift). + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut sample = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + 50.0 + 50.0 * (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let states = (0..1000) + .map(|_| { + let mut sketch = DdSketch::new(0.02); + for _ in 0..10 { + sketch.add(&sample()); + } + Arc::new(DDSketchAccumulator::restore_from_disk(sketch).unwrap()) + as Arc + }) + .collect(); + window_batch( + 1_000, + FieldDataType::Sketch(SketchAlgorithm::DDSketch), + states, + ) + } + + /// The window of [`ten_sample_ddsketch_window`] takes 30.2 kB on disk + /// (30 B a series, most of it the full-precision sum, min and max), not + /// the 126 kB of the mapped layout (106 kB of DDSketch views alone). + #[test] + fn a_ten_sample_ddsketch_window_is_stored_compact() { + let dir = segment_dir("dd-bytes"); + let batch = ten_sample_ddsketch_window(); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append(0, (0, 1_000), &[(1, std::slice::from_ref(&batch))]) + .unwrap(); + let views: usize = batch + .to_rows() + .iter() + .map(|row| match &row[4] { + Value::Summary { state, .. } => state_view_bytes(state.as_ref()).unwrap().len(), + _ => unreachable!(), + }) + .sum(); + assert_eq!(views, 106_176); + assert_eq!(location_of(&written, 1).len(), 30_196); + let _ = std::fs::remove_dir_all(&dir); + } + /// V2. A cold window decodes, from its columnar fragment, to the rows /// that were committed, read from the active segment (by `pread`) and /// again once the segment is sealed (mapped), and with `ViewRead::Pread`. @@ -1404,25 +1458,28 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } - /// V18. Reading a sealed segment borrows the text keys and plain - /// columns from the mapping, and every window of the segment shares one - /// dictionary; `ViewRead::Pread` copies them and reads the same rows. + /// A cold read rebuilds a KLL column (no compact form) in the mapped + /// layout in buffers of its own and reports their bytes, which the + /// batch's own memory count leaves out; every window of a segment + /// shares one dictionary of texts; `ViewRead::Pread` reads the same rows. #[test] - fn mapped_reads_borrow_fixed_width_columns() { - let dir = segment_dir("borrow"); + fn cold_reads_report_state_bytes_and_share_one_dictionary() { + let dir = segment_dir("cold-read"); let (_, a, b) = states().remove(1); let (a, b): (Arc, Arc) = (Arc::from(a), Arc::from(b)); let kll = FieldDataType::Sketch(SketchAlgorithm::Kll); - let rows = |end| { - window_batch( - end, - kll.clone(), - (0..1000) - .map(|i| if i % 2 == 0 { a.clone() } else { b.clone() }) - .collect(), - ) - }; - let (first, second) = (rows(10), rows(20)); + let states: Vec> = (0..1000) + .map(|i| if i % 2 == 0 { a.clone() } else { b.clone() }) + .collect(); + let held = 4 * (states.len() + 1) + + states + .iter() + .map(|s| state_view_bytes(s.as_ref()).unwrap().len().div_ceil(8) * 8) + .sum::(); + let (first, second) = ( + window_batch(10, kll.clone(), states.clone()), + window_batch(20, kll, states), + ); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let w1 = files .append(0, (0, 10), &[(1, std::slice::from_ref(&first))]) @@ -1432,9 +1489,11 @@ mod tests { .unwrap(); files.seal(0).unwrap(); let (l1, l2) = (location_of(&w1, 1), location_of(&w2, 1)); - let r1 = l1.read(first.schema(), ViewRead::Mmap).unwrap().0; - let r2 = l2.read(second.schema(), ViewRead::Mmap).unwrap().0; + let (r1, state_bytes) = l1.read(first.schema(), ViewRead::Mmap).unwrap(); + let (r2, _) = l2.read(second.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&first, &r1, "mapped"); + assert_eq!(state_bytes, held); + assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), 0); let identity = |batch: &Batch| { batch .column(1) @@ -1443,34 +1502,15 @@ mod tests { .expect("a cold text column is a dictionary over the segment's texts") .clone() }; - let keys = identity(&r1).keys().values().as_ptr() as usize; - assert!(l1.maps(keys), "text keys are copied, not borrowed"); - let values = r1 - .column(3) - .as_any() - .downcast_ref::() - .unwrap(); - assert!( - l1.maps(values.values().as_ptr() as usize), - "values are copied, not borrowed" - ); - // The KLL states are read in place (a mapped column, charged - // nothing), not rebuilt as objects. - let states = r1.state_column(4).expect("a state column"); - assert_eq!(states.state_memory_bytes(), 0); assert!( Arc::ptr_eq(identity(&r1).values(), identity(&r2).values()), "one dictionary per segment" ); - let copied = l1.read(first.schema(), ViewRead::Pread).unwrap().0; + let (copied, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap(); assert_same_rows(&first, &copied, "pread"); - // The mapped states' bytes, which the batch does not count, are + // The rebuilt states' bytes, which the batch does not count, are // reported for the window's charge, mapped or copied alike. - let (_, mapped_state_bytes) = l1.read(first.schema(), ViewRead::Mmap).unwrap(); - let (_, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap(); - assert!(mapped_state_bytes > (first.num_rows() + 1) * 4); - assert_eq!(mapped_state_bytes, copied_state_bytes); - assert!(!l1.maps(identity(&copied).keys().values().as_ptr() as usize)); + assert_eq!(copied_state_bytes, state_bytes); let _ = std::fs::remove_dir_all(&dir); } @@ -1551,7 +1591,9 @@ mod tests { let (l1, l2) = (location_of(&written, 1), location_of(&written, 2)); // `job` (other) is stored in view 2 only; `region` and `zone` in // neither. - assert_eq!(l2.len() - l1.len(), series as u32 * 4); + // (Fragments are compressed: only the order of their lengths is + // fixed.) + assert!(l2.len() > l1.len()); for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; assert_same_rows(batch, &active, &format!("{what}, active segment")); @@ -1794,7 +1836,7 @@ mod tests { files.seal(0).unwrap(); assert!(locations[4].is_cold(), "sealing (60, 80] cools (40, 60]"); assert!(!locations[6].is_cold()); - let read = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap().0; + let (read, _) = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&batch, &read, "a cold segment"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/data_plane/src/segment.rs b/data_plane/src/segment.rs index 304a12a7..22d156e3 100644 --- a/data_plane/src/segment.rs +++ b/data_plane/src/segment.rs @@ -3,18 +3,20 @@ //! //! A segment is an append-only file of frames, each an 8-byte head (a //! little-endian `u32` payload length and a `u32` kind) and its payload, -//! padded to a multiple of 8 bytes so every frame and every part inside a -//! record starts 8-byte aligned. The first frame is the segment's header; -//! each later frame is one refreshed window's record: its parts (the texts -//! new to the segment, the Hydra-Count-Min grids, one fragment per view), -//! then its head (MessagePack) and the head's length as the last 4 bytes. +//! padded to a multiple of 8 bytes. The first frame is the segment's +//! header; each later frame is one refreshed window's record: its parts +//! (the texts new to the segment, the Hydra-Count-Min grids, one fragment +//! per view), then its head (MessagePack) and the head's length as the last +//! 4 bytes. //! -//! A fragment holds one view's rows of one window by column, so a cold read -//! decodes one (view, window) without the record's other views, and a -//! fixed-width column of a sealed (mapped) segment is used in place. A text -//! column holding each row's series label is not stored: it is rebuilt from -//! the series identity column. - +//! A fragment holds one view's rows of one window by column, compressed +//! (zstd), so a cold read decodes one (view, window) without the record's +//! other views. State and text columns are stored compact +//! ([`crate::state_codec`]) and rebuilt in the executor's mapped state +//! layout when read. A text column holding each row's series label is not +//! stored: it is rebuilt from the series identity column. + +use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::fs::File; use std::os::unix::fs::FileExt; @@ -33,6 +35,7 @@ use asap_executor::arrow::datatypes::{ }; use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL_SERIES_IDENTITY}; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; +use asap_executor::planner::summary_type::{ExactKind, SketchAlgorithm}; use asap_executor::summary_kernels::HydraCms; use asap_executor::values::{ family_has_mapped_form, state_view_bytes, Batch, BatchColumn, SchemaRef, Value, @@ -42,9 +45,12 @@ use serde::{Deserialize, Serialize}; use crate::persist::{decode_stored_state, encode_state, Grids, StoredValue}; use crate::series_ids::labels_of_identity; +use crate::state_codec::{ + decode_states, decode_text_keys, encode_states, encode_text_keys, CompactKind, +}; /// The view file format version these segments are. -pub const FORMAT_VERSION: u32 = 3; +pub const FORMAT_VERSION: u32 = 4; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -54,6 +60,8 @@ const RECORD_FRAME: u32 = 1; const MAX_FRAME_BYTES: u64 = 1 << 31; /// Column kinds in a fragment. +/// Text: each row's key into the segment's texts, a signed varint delta +/// from the previous row's. const TEXT: u32 = 1; const FLOAT64: u32 = 2; const INT64: u32 = 3; @@ -62,24 +70,30 @@ const TIMESTAMP: u32 = 4; const GENERIC: u32 = 5; const STATES: u32 = 6; /// A state column in the executor's mapped layout: `u32` offsets in the -/// data section, the states (each 8-byte aligned) in the second section; -/// read in place, never rebuilt. +/// data section, the states (each 8-byte aligned) in the second section. +/// For a family with a mapped form but no compact one (KLL, Count-Min). const MAPPED_STATES: u32 = 7; /// A text column whose every row holds its series identity's label of the /// column's name (`""` when the series has none): no data, rebuilt on read /// from the identity column, whose index is the descriptor's flags. const IDENTITY_LABEL: u32 = 8; +/// A state column in compact form ([`crate::state_codec`]); its flags are +/// the [`CompactKind`] code. Read back into the mapped layout. +const COMPACT_STATES: u32 = 9; /// Flag: a timestamp column whose rows all hold one value, stored once. const CONSTANT: u32 = 1; /// Bytes of one column descriptor: kind, flags, data offset and length, /// validity offset and length. const DESCRIPTOR_BYTES: usize = 40; +/// The zstd level fragments are compressed at: level 1 compresses view +/// fragments within a few percent of level 3 at about half the CPU. +const ZSTD_LEVEL: i32 = 1; /// How a cold window's fragment is read. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum ViewRead { - /// Sealed segments mapped and decoded in place; the active segment - /// read with `pread`. + /// Sealed segments mapped, each fragment decompressed from the + /// mapping; the active segment read with `pread`. #[default] Mmap, /// Every fragment read with `pread` into a buffer. @@ -613,21 +627,17 @@ pub struct WindowLocation { grids: (u64, u32), } -/// Bytes read for a decode: borrowed from a mapping, or owned (8-byte -/// aligned). +/// Bytes read for a decode: borrowed from a mapping, or owned. enum Bytes { Mapped(Arc, usize, usize), - Owned(Vec, usize), + Owned(Vec), } impl Bytes { fn slice(&self) -> &[u8] { match self { Bytes::Mapped(mapping, offset, len) => &mapping.bytes()[*offset..*offset + *len], - Bytes::Owned(words, len) => { - // SAFETY: `words` holds at least `len` initialized bytes. - unsafe { std::slice::from_raw_parts(words.as_ptr().cast::(), *len) } - } + Bytes::Owned(bytes) => bytes, } } } @@ -672,17 +682,6 @@ impl WindowLocation { self.segment.is_cold() } - /// Whether `address` lies inside its segment's mapping. - pub fn maps(&self, address: usize) -> bool { - match self.segment.mapping.get() { - Some(Ok(mapping)) => { - let start = mapping.ptr.as_ptr() as usize; - (start..start + mapping.len).contains(&address) - } - _ => false, - } - } - /// `len` bytes at `offset` of the segment. fn bytes(&self, (offset, len): (u64, u32), how: ViewRead) -> Result { let len = len as usize; @@ -709,21 +708,18 @@ impl WindowLocation { }; return Ok(Bytes::Mapped(mapping, offset as usize, len)); } - let mut words = vec![0u64; len.div_ceil(8)]; - // SAFETY: `words` is `len.div_ceil(8) * 8` writable bytes. - let buffer = - unsafe { std::slice::from_raw_parts_mut(words.as_mut_ptr().cast::(), len) }; + let mut bytes = vec![0u8; len]; self.segment .file - .read_exact_at(buffer, offset) + .read_exact_at(&mut bytes, offset) .map_err(|e| Error::Invalid(format!("{}: {e}", self.segment.path.display())))?; - Ok(Bytes::Owned(words, len)) + Ok(Bytes::Owned(bytes)) } - /// The fragment's rows as one batch of `schema`, and the bytes of its - /// state columns in the executor's mapped layout, which - /// [`Batch::memory_bytes`] does not count (`StateColumn::from_mapped`): - /// borrowed from the mapping, or copied to the heap by `pread`. + /// The fragment's rows as one batch of `schema`, and the bytes its + /// state columns hold: they are rebuilt in the mapped layout, which + /// [`Batch::memory_bytes`] counts as held outside the run, so a cache + /// holding the batch charges them itself. pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result<(Batch, usize), Error> { let grids: Vec>> = if self.grids.1 == 0 { Vec::new() @@ -739,8 +735,13 @@ impl WindowLocation { }) .collect() }; - let bytes = self.bytes((self.offset, self.len), how)?; - decode_fragment(&bytes, schema, &self.segment, &grids) + let compressed = self.bytes((self.offset, self.len), how)?; + decode_fragment( + &decompress(compressed.slice())?, + schema, + &self.segment, + &grids, + ) } /// The segment holding the fragment. @@ -824,8 +825,8 @@ fn validity(nulls: &[bool]) -> Option> { Some(bits) } -/// `rows` (of `schema`) as one columnar fragment; `None` when a state has -/// no byte encoding. +/// `rows` (of `schema`) as one compressed columnar fragment; `None` when a +/// state has no byte encoding. pub(crate) fn encode_fragment( schema: &Schema, rows: &[Vec], @@ -856,96 +857,113 @@ pub(crate) fn encode_fragment( && labels.holds_label(rows, column, &field.name) }) .map(|labels| labels.column as u32); - let (kind, mut flags, data): (u32, u32, Vec) = if let Some(identity_column) = - label_of_identity_column - { - (IDENTITY_LABEL, identity_column, Vec::new()) - } else { - match &field.dtype { - FieldDataType::Plain(DataType::Utf8) => { - let mut data = Vec::with_capacity(rows.len() * 4); - for value in values { - let key = match value { - Value::Utf8(text) => texts.key(text), - _ => 0, - }; - data.extend_from_slice(&key.to_le_bytes()); - } - (TEXT, 0, data) - } - FieldDataType::Plain(DataType::Float64) => { - let mut data = Vec::with_capacity(rows.len() * 8); - for value in values { - let v = match value { - Value::Float64(v) => *v, - _ => 0.0, - }; - data.extend_from_slice(&v.to_le_bytes()); - } - (FLOAT64, 0, data) - } - FieldDataType::Plain(DataType::Int64) => { - let mut data = Vec::with_capacity(rows.len() * 8); - for value in values { - let v = match value { - Value::Int64(v) => *v, - _ => 0, - }; - data.extend_from_slice(&v.to_le_bytes()); - } - (INT64, 0, data) - } - FieldDataType::Plain(DataType::Timestamp) => { - let times: Vec = values - .map(|value| match value { - Value::Timestamp(t) => *t, - _ => 0, - }) - .collect(); - let constant = !times.is_empty() - && !nulls.iter().any(|&n| n) - && times.iter().all(|&t| t == times[0]); - let data: Vec = if constant { - times[0].to_le_bytes().to_vec() - } else { - times.iter().flat_map(|t| t.to_le_bytes()).collect() + // A state column of a family with a compact form, compacted from + // each state's mapped layout (`None` when a state has none, e.g. a + // keyed exact state, or the column has no compact form). + let mut compact = compact_kind(&field.dtype).and_then(|kind| { + let views = rows + .iter() + .map(|row| match &row[column] { + Value::Summary { state, .. } => state_view_bytes(state.as_ref()), + _ => None, + }) + .collect::>>()?; + Some((kind, encode_states(kind, views.iter())?)) + }); + // Otherwise the column in the mapped layout, when it has one. + let mut mapped = match &field.dtype { + FieldDataType::Plain(_) => None, + _ if compact.is_some() => None, + family if family_has_mapped_form(family) => mapped_states(rows, column), + _ => None, + }; + let (kind, mut flags, data): (u32, u32, Vec) = match &field.dtype { + _ if label_of_identity_column.is_some() => ( + IDENTITY_LABEL, + label_of_identity_column.expect("checked"), + Vec::new(), + ), + FieldDataType::Plain(DataType::Utf8) => { + let keys = values.map(|value| match value { + Value::Utf8(text) => texts.key(text), + _ => 0, + }); + (TEXT, 0, encode_text_keys(keys)) + } + FieldDataType::Plain(DataType::Float64) => { + let mut data = Vec::with_capacity(rows.len() * 8); + for value in values { + let v = match value { + Value::Float64(v) => *v, + _ => 0.0, }; - (TIMESTAMP, if constant { CONSTANT } else { 0 }, data) - } - FieldDataType::Plain(_) => { - let values: Vec<&Value> = values.collect(); - (GENERIC, 0, rmp_serde::to_vec(&values).ok()?) + data.extend_from_slice(&v.to_le_bytes()); } - family - if family_has_mapped_form(family) && mapped_states(rows, column).is_some() => - { - let (offsets, states) = mapped_states(rows, column).expect("checked"); - second = Some(states); - (MAPPED_STATES, 0, offsets) + (FLOAT64, 0, data) + } + FieldDataType::Plain(DataType::Int64) => { + let mut data = Vec::with_capacity(rows.len() * 8); + for value in values { + let v = match value { + Value::Int64(v) => *v, + _ => 0, + }; + data.extend_from_slice(&v.to_le_bytes()); } - _ => { - // States: u32 offsets[rows + 1], then each state's stored bytes. - let mut offsets = Vec::with_capacity(rows.len() + 1); - let mut bytes = Vec::new(); - offsets.push(0u32); - for value in values { - let Value::Summary { state, .. } = value else { - return None; - }; - let stored = encode_state(state.as_ref(), grids)?; - bytes.extend(rmp_serde::to_vec(&stored).ok()?); - offsets.push(u32::try_from(bytes.len()).ok()?); - } - let mut data: Vec = offsets.iter().flat_map(|o| o.to_le_bytes()).collect(); - data.extend(bytes); - (STATES, 0, data) + (INT64, 0, data) + } + FieldDataType::Plain(DataType::Timestamp) => { + let times: Vec = values + .map(|value| match value { + Value::Timestamp(t) => *t, + _ => 0, + }) + .collect(); + let constant = !times.is_empty() + && !nulls.iter().any(|&n| n) + && times.iter().all(|&t| t == times[0]); + let data: Vec = if constant { + times[0].to_le_bytes().to_vec() + } else { + times.iter().flat_map(|t| t.to_le_bytes()).collect() + }; + (TIMESTAMP, if constant { CONSTANT } else { 0 }, data) + } + FieldDataType::Plain(_) => { + let values: Vec<&Value> = values.collect(); + (GENERIC, 0, rmp_serde::to_vec(&values).ok()?) + } + _ if compact.is_some() => { + let (compact_kind, compact) = compact.take().expect("checked"); + (COMPACT_STATES, compact_kind.code(), compact) + } + _ if mapped.is_some() => { + let (offsets, states) = mapped.take().expect("checked"); + second = Some(states); + (MAPPED_STATES, 0, offsets) + } + _ => { + // States: u32 offsets[rows + 1], then each state's stored bytes. + let mut offsets = Vec::with_capacity(rows.len() + 1); + let mut bytes = Vec::new(); + offsets.push(0u32); + for value in values { + let Value::Summary { state, .. } = value else { + return None; + }; + let stored = encode_state(state.as_ref(), grids)?; + bytes.extend(rmp_serde::to_vec(&stored).ok()?); + offsets.push(u32::try_from(bytes.len()).ok()?); } + let mut data: Vec = offsets.iter().flat_map(|o| o.to_le_bytes()).collect(); + data.extend(bytes); + (STATES, 0, data) } }; let (data_offset, data_len) = section(&mut out, &data); let (valid_offset, valid_len) = match (kind, validity(&nulls)) { (MAPPED_STATES, _) => section(&mut out, &second.take().expect("states")), - (STATES, _) | (GENERIC, _) => (0, 0), + (STATES | GENERIC | COMPACT_STATES, _) => (0, 0), (_, Some(bits)) => section(&mut out, &bits), (_, None) => (0, 0), }; @@ -966,8 +984,22 @@ pub(crate) fn encode_fragment( out[at + i * 8..at + i * 8 + 8].copy_from_slice(&word.to_le_bytes()); } } - out.resize(padded(out.len()), 0); - Some(out) + compress(&out) +} + +/// The compact form of a state family's column, if it has one. +fn compact_kind(family: &FieldDataType) -> Option { + Some(match family { + FieldDataType::Sketch(SketchAlgorithm::DDSketch) => CompactKind::DDSketch, + FieldDataType::ExactAggregate(kind, _) => match kind { + ExactKind::Sum => CompactKind::Sum, + ExactKind::Count => CompactKind::Count, + ExactKind::Min | ExactKind::Max => CompactKind::MinMax, + ExactKind::Counter => CompactKind::Counter, + ExactKind::IRate => CompactKind::LastTwoSamples, + }, + _ => return None, + }) } /// The labels of each row's series, from the series identity column, for @@ -1058,36 +1090,74 @@ fn damaged() -> Error { Error::Invalid("a damaged view fragment".into()) } -/// A buffer over `bytes[offset..offset + len]`: borrowed from the mapping -/// when `source` is one, copied otherwise. -fn buffer(source: &Bytes, offset: usize, len: usize) -> Result { - let slice = source - .slice() - .get(offset..offset + len) - .ok_or_else(damaged)?; - match source { - Bytes::Mapped(mapping, ..) => { - let ptr = NonNull::new(slice.as_ptr().cast_mut()).ok_or_else(damaged)?; - // SAFETY: `ptr` points at `len` bytes of the mapping, which the - // buffer keeps alive through its owner. - Ok(unsafe { Buffer::from_custom_allocation(ptr, len, mapping.clone()) }) - } - // Copied into 8-byte words, so the buffer is aligned for any - // fixed-width type (an empty `Vec` is not). - Bytes::Owned(..) => { - let mut words = vec![0u64; len.div_ceil(8)]; - // SAFETY: `words` is at least `len` writable bytes. - unsafe { - std::ptr::copy_nonoverlapping(slice.as_ptr(), words.as_mut_ptr().cast::(), len) - }; - Ok(Buffer::from(words).slice_with_length(0, len)) +/// `bytes[offset..offset + len]` copied into a buffer of its own, 8-byte +/// aligned (for any fixed-width type) and charged exactly its size. +fn buffer(bytes: &[u8], offset: usize, len: usize) -> Result { + let slice = bytes.get(offset..offset + len).ok_or_else(damaged)?; + let mut words = vec![0u64; len.div_ceil(8)]; + // SAFETY: `words` is at least `len` writable bytes. + unsafe { std::ptr::copy_nonoverlapping(slice.as_ptr(), words.as_mut_ptr().cast::(), len) }; + Ok(Buffer::from(words).slice_with_length(0, len)) +} + +/// A stored fragment: the length of its columnar bytes (`u32`), then +/// those bytes compressed. +/// `None` past [`MAX_FRAME_BYTES`], which a read rejects as damaged. +fn compress(columnar: &[u8]) -> Option> { + if columnar.len() as u64 > MAX_FRAME_BYTES { + return None; + } + let mut out = u32::try_from(columnar.len()).ok()?.to_le_bytes().to_vec(); + // One zstd context per thread, not one per fragment. + let compressed = COMPRESSOR.with(|compressor| { + let mut compressor = compressor.borrow_mut(); + if compressor.is_none() { + *compressor = Some(zstd::bulk::Compressor::new(ZSTD_LEVEL).ok()?); } + compressor.as_mut()?.compress(columnar).ok() + })?; + out.extend(compressed); + Some(out) +} + +thread_local! { + static COMPRESSOR: RefCell>> = const { RefCell::new(None) }; + static DECOMPRESSOR: RefCell>> = + const { RefCell::new(None) }; +} + +/// The columnar bytes of a stored fragment. +fn decompress(stored: &[u8]) -> Result, Error> { + let length = u32::from_le_bytes(stored.get(..4).ok_or_else(damaged)?.try_into().unwrap()); + // The length is checked against the frame's own content size before it + // sizes an allocation. + let content_size = zstd::zstd_safe::get_frame_content_size(&stored[4..]); + if u64::from(length) > MAX_FRAME_BYTES + || !matches!(content_size, Ok(Some(size)) if size == u64::from(length)) + { + return Err(damaged()); + } + let columnar = DECOMPRESSOR + .with(|decompressor| { + let mut decompressor = decompressor.borrow_mut(); + if decompressor.is_none() { + *decompressor = Some(zstd::bulk::Decompressor::new().ok()?); + } + decompressor + .as_mut()? + .decompress(&stored[4..], length as usize) + .ok() + }) + .ok_or_else(damaged)?; + if columnar.len() != length as usize { + return Err(damaged()); } + Ok(columnar) } /// A primitive column of `rows` values at `offset`, with nulls. fn primitive( - source: &Bytes, + source: &[u8], (offset, len): (usize, usize), rows: usize, nulls: Option, @@ -1128,15 +1198,15 @@ fn descriptor(bytes: &[u8], column: usize) -> Result { }) } -/// The fragment in `source` as one batch of `schema`, and the bytes of its -/// mapped state columns ([`WindowLocation::read`]). +/// The columnar fragment `bytes` as one batch of `schema`, and the bytes +/// its state columns hold. fn decode_fragment( - source: &Bytes, + bytes: &[u8], schema: &SchemaRef, segment: &Segment, grids: &[Option>], ) -> Result<(Batch, usize), Error> { - let bytes = source.slice(); + let mut state_bytes = 0; let header = word(bytes, 0)?; let rows = (header & 0xffff_ffff) as usize; let columns = (header >> 32) as usize; @@ -1146,7 +1216,9 @@ fn decode_fragment( // The Arrow layout of each plain column, as the executor builds it. let empty = Batch::try_new(schema.clone(), Vec::new())?; let mut out = Vec::with_capacity(columns); - let mut mapped_state_bytes = 0; + // The series identity column's index and keys, decoded once for every + // label column read back from it. + let mut identity_keys: Option<(usize, ScalarBuffer)> = None; for (column, field) in schema.fields.iter().enumerate() { let Descriptor { kind, @@ -1154,7 +1226,7 @@ fn decode_fragment( data, valid, } = descriptor(bytes, column)?; - let nulls = if valid.1 == 0 || kind == MAPPED_STATES { + let nulls = if valid.1 == 0 || kind == MAPPED_STATES || kind == COMPACT_STATES { None } else { if valid.1 != rows.div_ceil(8) { @@ -1166,8 +1238,14 @@ fn decode_fragment( let expected = empty.column(column).data_type().clone(); let array: ArrayRef = match kind { TEXT => { - let keys = primitive::(source, data, rows, nulls)?; + let keys = + decode_text_keys(&bytes[data.0..data.0 + data.1], rows).ok_or_else(damaged)?; + let keys = UInt32Array::try_new(keys.into(), nulls) + .map_err(|e| Error::Invalid(e.to_string()))?; let needed = keys.iter().flatten().max().map_or(0, |k| k as usize + 1); + if field.name == PROMQL_SERIES_IDENTITY && keys.null_count() == 0 { + identity_keys = Some((column, keys.values().clone())); + } let values = segment.dictionary(needed)?; Arc::new( DictionaryArray::::try_new(keys, values) @@ -1185,7 +1263,23 @@ fn decode_fragment( if identity.kind != TEXT || identity.valid.1 != 0 || data.1 != 0 || valid.1 != 0 { return Err(damaged()); } - let keys = primitive::(source, identity.data, rows, None)?; + // Each label column holds a copy of the identity column's + // keys, so its charge is what it holds. + let keys = match &identity_keys { + Some((at, keys)) if *at == identity_column => keys.clone(), + _ => { + let keys = ScalarBuffer::from( + decode_text_keys( + &bytes[identity.data.0..identity.data.0 + identity.data.1], + rows, + ) + .ok_or_else(damaged)?, + ); + identity_keys = Some((identity_column, keys.clone())); + keys + } + }; + let keys = UInt32Array::from(keys.to_vec()); let needed = keys.values().iter().max().map_or(0, |&k| k as usize + 1); let values = segment.label_values(&field.name, needed)?; Arc::new( @@ -1193,8 +1287,8 @@ fn decode_fragment( .map_err(|e| Error::Invalid(e.to_string()))?, ) } - FLOAT64 => Arc::new(primitive::(source, data, rows, nulls)?), - INT64 => Arc::new(primitive::(source, data, rows, nulls)?), + FLOAT64 => Arc::new(primitive::(bytes, data, rows, nulls)?), + INT64 => Arc::new(primitive::(bytes, data, rows, nulls)?), TIMESTAMP if flags & CONSTANT != 0 => { if data.1 != 8 { return Err(damaged()); @@ -1206,7 +1300,7 @@ fn decode_fragment( ])) } TIMESTAMP => Arc::new(primitive::( - source, data, rows, nulls, + bytes, data, rows, nulls, )?), GENERIC => { let values: Vec = rmp_serde::from_slice(&bytes[data.0..data.0 + data.1]) @@ -1216,16 +1310,32 @@ fn decode_fragment( } one_column(field, values.into_iter().map(|v| vec![v]).collect())?.0 } + COMPACT_STATES => { + let compact = CompactKind::from_code(flags) + .filter(|&kind| Some(kind) == compact_kind(&field.dtype)) + .ok_or_else(damaged)?; + let (states, offsets) = + decode_states(compact, &bytes[data.0..data.0 + data.1], rows) + .ok_or_else(damaged)?; + state_bytes += states.len() * 8 + offsets.len() * 4; + let column = asap_executor::values::StateColumn::from_mapped( + field.dtype.clone(), + Buffer::from(states), + ScalarBuffer::from(offsets), + )?; + out.push(BatchColumn::States { + indices: UInt32Array::from_iter_values(0..rows as u32), + states: Arc::new(column), + }); + continue; + } MAPPED_STATES => { - // Read in place: the offsets and the states are borrowed - // from the mapping (copied for `pread`), never rebuilt. if data.1 != (rows + 1) * 4 { return Err(damaged()); } - mapped_state_bytes += data.1 + valid.1; - let offsets = - ScalarBuffer::::new(buffer(source, data.0, data.1)?, 0, rows + 1); - let states = buffer(source, valid.0, valid.1)?; + state_bytes += data.1 + valid.1; + let offsets = ScalarBuffer::::new(buffer(bytes, data.0, data.1)?, 0, rows + 1); + let states = buffer(bytes, valid.0, valid.1)?; let column = asap_executor::values::StateColumn::from_mapped( field.dtype.clone(), states, @@ -1299,10 +1409,7 @@ fn decode_fragment( } out.push(BatchColumn::Plain(array)); } - Ok(( - Batch::try_from_columns(schema.clone(), out)?, - mapped_state_bytes, - )) + Ok((Batch::try_from_columns(schema.clone(), out)?, state_bytes)) } /// `rows` of one column `field` built by the executor: its array, and its diff --git a/data_plane/src/state_codec.rs b/data_plane/src/state_codec.rs new file mode 100644 index 00000000..c84dc241 --- /dev/null +++ b/data_plane/src/state_codec.rs @@ -0,0 +1,1092 @@ +//! Compact encodings of a fragment's state and text columns +//! (docs/design/tiered-view-storage.md, "On-disk format"). +//! +//! A state column is written in the executor's mapped layout +//! ([`asap_executor::values::state_view_bytes`]): fixed-width fields and +//! 8-byte-aligned arrays. That layout is large for the small +//! states of narrow panes: a DDSketch of ten samples is an 88-byte header +//! plus a dense run of 1-byte bucket counts, most of them empty. This module +//! stores the same states in a compact form and rebuilds the mapped layout, +//! byte for byte, when a window is read cold: +//! +//! - DDSketch: only non-empty buckets, as a varint gap from the previous +//! bucket and a varint count; the first bucket of each row as a signed +//! delta from the previous row's; the index mapping (`alpha`) and the +//! admission rate once per column; the sample count left out (it is the +//! sum of the bucket and zero counts). +//! - Exact records: a tag byte of which fields are present, the floats +//! that are, and timestamps as varint deltas. +//! - Text keys: each row's dictionary key as a signed varint delta from +//! the previous row's. +//! +//! Everything here is lossless: decoding gives the bytes the mapped layout +//! held, so every answer read from a compact column is the one read from +//! the mapped column. A state the encoder does not recognize as canonical +//! is kept whole (a raw-record tag), never approximated. + +/// The state families with a compact form, as the mapped layout names +/// them: which fixed-size exact record, or which sketch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CompactKind { + DDSketch, + /// Exact sum: `sum`, `compensation` (f64), `seen` (0 or 1). + Sum, + /// Exact count: one `u64`. + Count, + /// Exact minimum or maximum: `present` (0 or 1), `value` (f64). + MinMax, + /// Exact counter: `present`, `starting_value`, `starting_timestamp`, + /// `last_seen_value`, `last_seen_timestamp`, `total_increase`, + /// `sample_count`. + Counter, + /// Exact last two samples: two of (`present`, `timestamp`, `value`). + LastTwoSamples, +} + +impl CompactKind { + /// Its code in a fragment's column descriptor. + pub fn code(self) -> u32 { + match self { + Self::DDSketch => 1, + Self::Sum => 2, + Self::Count => 3, + Self::MinMax => 4, + Self::Counter => 5, + Self::LastTwoSamples => 6, + } + } + + pub fn from_code(code: u32) -> Option { + Some(match code { + 1 => Self::DDSketch, + 2 => Self::Sum, + 3 => Self::Count, + 4 => Self::MinMax, + 5 => Self::Counter, + 6 => Self::LastTwoSamples, + _ => return None, + }) + } + + /// The bytes of one record in the mapped layout, for an exact kind. + fn record_bytes(self) -> Option { + Some(match self { + Self::DDSketch => return None, + Self::Sum => 24, + Self::Count => 8, + Self::MinMax => 16, + Self::Counter => 56, + Self::LastTwoSamples => 48, + }) + } +} + +// ---------------------------------------------------------------- varints + +fn put_uvarint(out: &mut Vec, mut value: u64) { + while value >= 0x80 { + out.push(value as u8 | 0x80); + value >>= 7; + } + out.push(value as u8); +} + +fn uvarint(bytes: &[u8], at: &mut usize) -> Option { + let mut value = 0u64; + for shift in (0..64).step_by(7) { + let byte = *bytes.get(*at)?; + *at += 1; + if shift == 63 && byte > 1 { + return None; + } + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Some(value); + } + } + None +} + +fn put_ivarint(out: &mut Vec, value: i64) { + put_uvarint(out, ((value << 1) ^ (value >> 63)) as u64); +} + +fn ivarint(bytes: &[u8], at: &mut usize) -> Option { + let zigzag = uvarint(bytes, at)?; + Some((zigzag >> 1) as i64 ^ -((zigzag & 1) as i64)) +} + +fn put_u64(out: &mut Vec, value: u64) { + out.extend_from_slice(&value.to_le_bytes()); +} + +fn u64_at(bytes: &[u8], at: &mut usize) -> Option { + let raw = bytes.get(*at..*at + 8)?; + *at += 8; + Some(u64::from_le_bytes(raw.try_into().ok()?)) +} + +fn u32_at(bytes: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} + +fn padded(n: usize) -> usize { + n.div_ceil(8) * 8 +} + +// --------------------------------------------------------------- DDSketch + +const DD_MAGIC: [u8; 4] = *b"DDV1"; +const VIEW_LAYOUT_VERSION: u32 = 1; +/// Bytes of a DDSketch view before its arrays: magic and version, seven +/// 8-byte fields, six 4-byte fields. +const DD_HEAD_BYTES: usize = 88; +/// The widest store a DDSketch view may span, in buckets (the view +/// reader's limit): bucket index arithmetic stays far inside `i32`. +const MAX_SPAN: i64 = 1 << 20; + +/// One DDSketch store's non-empty buckets: absolute bucket index, count. +type Buckets = Vec<(i32, u64)>; + +/// A DDSketch view's contents, as its compact form keeps them. +#[derive(Debug, Default, Clone, PartialEq)] +struct DdContents { + alpha: u64, + sum: u64, + min: u64, + max: u64, + zero_count: u64, + admission_rate: u64, + positive: Buckets, + negative: Buckets, +} + +/// Count bytes of a store's counts at `width` (padded to 8). +fn counts_bytes(entries: usize, width: usize) -> usize { + padded(entries * width) +} + +/// The width the view writer picks for counts up to `largest`. +fn count_width(largest: u64) -> usize { + match largest { + 0..=0xff => 1, + 0x100..=0xffff => 2, + 0x1_0000..=0xffff_ffff => 4, + _ => 8, + } +} + +/// The dense span of a store: last index - first index + 1. +fn span(buckets: &Buckets) -> usize { + match (buckets.first(), buckets.last()) { + (Some(first), Some(last)) => (i64::from(last.0) - i64::from(first.0) + 1) as usize, + _ => 0, + } +} + +/// Reads a DDSketch view's contents into `dd` (its bucket lists reused); +/// `None` when the bytes are not a DDSketch view of layout version 1 in the +/// form its writer writes. +fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { + if view.get(..4)? != DD_MAGIC || u32_at(view, 4)? != VIEW_LAYOUT_VERSION { + return None; + } + let mut at = 8; + let alpha = u64_at(view, &mut at)?; + let count = u64_at(view, &mut at)?; + let sum = u64_at(view, &mut at)?; + let min = u64_at(view, &mut at)?; + let max = u64_at(view, &mut at)?; + let zero_count = u64_at(view, &mut at)?; + let admission_rate = u64_at(view, &mut at)?; + let width = u32_at(view, 64)? as usize; + let sparse = match u32_at(view, 68)? { + 0 => false, + 1 => true, + _ => return None, + }; + if ![1, 2, 4, 8].contains(&width) { + return None; + } + let mut at = DD_HEAD_BYTES; + // An array, and the zero padding after it. + let mut array = |bytes: usize| -> Option<&[u8]> { + let array = view.get(at..at + bytes)?; + let end = padded(at + bytes); + if view.get(at + bytes..end)?.iter().any(|&b| b != 0) { + return None; + } + at = end; + Some(array) + }; + let mut store = |offset: i32, len: usize, buckets: &mut Buckets| -> Option<()> { + buckets.clear(); + let keys = if sparse { Some(array(len * 4)?) } else { None }; + let counts = array(len * width)?; + for i in 0..len { + let raw = &counts[i * width..(i + 1) * width]; + let mut word = [0u8; 8]; + word[..width].copy_from_slice(raw); + let count = u64::from_le_bytes(word); + let relative = match keys { + Some(keys) => u32::from_le_bytes(keys[i * 4..i * 4 + 4].try_into().ok()?), + None => i as u32, + }; + let index = offset.checked_add(i32::try_from(relative).ok()?)?; + if buckets.last().is_some_and(|&(last, _)| last >= index) { + return None; + } + if count != 0 { + buckets.push((index, count)); + } else if sparse { + // The writer keeps only non-empty buckets in a sparse store. + return None; + } + } + Some(()) + }; + let (positive_offset, negative_offset) = (u32_at(view, 72)? as i32, u32_at(view, 80)? as i32); + store( + positive_offset, + u32_at(view, 76)? as usize, + &mut dd.positive, + )?; + store( + negative_offset, + u32_at(view, 84)? as usize, + &mut dd.negative, + )?; + if at != view.len() { + return None; + } + (dd.alpha, dd.sum, dd.min, dd.max) = (alpha, sum, min, max); + (dd.zero_count, dd.admission_rate) = (zero_count, admission_rate); + let contents = &*dd; + // Only the form the view writer writes, so the compact form rebuilds + // these bytes exactly: the narrowest count width, the smaller of the + // dense and sparse forms, a dense store trimmed to non-empty ends, an + // empty store at offset 0. The count is left out of the compact form: + // it must be the buckets'. + let (form_width, form_sparse) = contents.form(); + let trimmed = |buckets: &Buckets, offset: i32, len: usize| match buckets.first() { + None => offset == 0 && len == 0, + Some((first, _)) => *first == offset && (sparse || span(buckets) == len), + }; + let canonical = width == form_width + && span(&contents.positive) as i64 <= MAX_SPAN + && span(&contents.negative) as i64 <= MAX_SPAN + && sparse == form_sparse + && trimmed( + &contents.positive, + positive_offset, + u32_at(view, 76)? as usize, + ) + && trimmed( + &contents.negative, + negative_offset, + u32_at(view, 84)? as usize, + ); + (canonical && contents.count()? == count).then_some(()) +} + +impl DdContents { + /// Its sample count: the bucket counts and the zero count. + fn count(&self) -> Option { + self.positive + .iter() + .chain(&self.negative) + .try_fold(self.zero_count, |total, (_, count)| { + total.checked_add(*count) + }) + } + + /// The count width and store form (sparse or not) the view writer + /// picks for its buckets. + fn form(&self) -> (usize, bool) { + let largest = self + .positive + .iter() + .chain(&self.negative) + .map(|(_, count)| *count) + .max() + .unwrap_or(0); + let width = count_width(largest); + let (positive, negative) = (&self.positive, &self.negative); + let dense = counts_bytes(span(positive), width) + counts_bytes(span(negative), width); + let sparse = padded(positive.len() * 4) + + counts_bytes(positive.len(), width) + + padded(negative.len() * 4) + + counts_bytes(negative.len(), width); + (width, sparse < dense) + } + + /// Its view bytes, as `DdSketch::to_view_bytes` writes them. + fn view_bytes(&self, out: &mut Vec) -> Option<()> { + let (width, sparse) = self.form(); + let (positive, negative) = (&self.positive, &self.negative); + let start = out.len(); + out.extend_from_slice(&DD_MAGIC); + out.extend_from_slice(&VIEW_LAYOUT_VERSION.to_le_bytes()); + for word in [ + self.alpha, + self.count()?, + self.sum, + self.min, + self.max, + self.zero_count, + self.admission_rate, + ] { + put_u64(out, word); + } + let entries = |store: &Buckets| if sparse { store.len() } else { span(store) }; + let offset = |store: &Buckets| store.first().map_or(0, |(index, _)| *index); + for word in [ + width as u32, + u32::from(sparse), + offset(positive) as u32, + entries(positive) as u32, + offset(negative) as u32, + entries(negative) as u32, + ] { + out.extend_from_slice(&word.to_le_bytes()); + } + let pad = |out: &mut Vec| out.resize(start + padded(out.len() - start), 0); + for store in [positive, negative] { + let first = offset(store); + if sparse { + for (index, _) in store { + out.extend_from_slice(&((index - first) as u32).to_le_bytes()); + } + pad(out); + for (_, count) in store { + out.extend_from_slice(&count.to_le_bytes()[..width]); + } + } else { + let mut next = first; + for (index, count) in store { + let empty = (index - next) as usize * width; + out.resize(out.len() + empty, 0); + out.extend_from_slice(&count.to_le_bytes()[..width]); + next = index + 1; + } + } + pad(out); + } + Some(()) + } +} + +// ---------------------------------------------------------------- streams + +/// Float fields a kind keeps per row, at most. +const FLOAT_FIELDS: usize = 3; + +/// A compact column as it is written: the varints and tags of every row in +/// one stream, and each float field of every row in a stream of its own, +/// stored as byte planes (all rows' first bytes, then all second bytes, +/// ...): the sign and exponent bytes of one field across series repeat, +/// which a general-purpose codec over the fragment then compresses. +#[derive(Default)] +struct Streams { + ints: Vec, + floats: [Vec; FLOAT_FIELDS], +} + +impl Streams { + /// `uvarint` lengths of the int stream and each float stream, then the + /// int stream, then each float stream's byte planes. + fn finish(self) -> Vec { + let mut out = Vec::with_capacity( + 8 + self.ints.len() + self.floats.iter().map(|f| f.len() * 8).sum::(), + ); + put_uvarint(&mut out, self.ints.len() as u64); + for floats in &self.floats { + put_uvarint(&mut out, floats.len() as u64); + } + out.extend_from_slice(&self.ints); + for floats in &self.floats { + for plane in 0..8 { + out.extend(floats.iter().map(|word| (word >> (8 * plane)) as u8)); + } + } + out + } +} + +/// Reads a column [`Streams::finish`] wrote. +struct StreamReader<'a> { + ints: &'a [u8], + at: usize, + floats: [Vec; FLOAT_FIELDS], + next: [usize; FLOAT_FIELDS], +} + +impl<'a> StreamReader<'a> { + fn new(bytes: &'a [u8]) -> Option { + let mut at = 0; + let ints_len = usize::try_from(uvarint(bytes, &mut at)?).ok()?; + let mut lens = [0usize; FLOAT_FIELDS]; + for len in &mut lens { + *len = usize::try_from(uvarint(bytes, &mut at)?).ok()?; + } + let ints = bytes.get(at..at.checked_add(ints_len)?)?; + at += ints_len; + let mut floats: [Vec; FLOAT_FIELDS] = Default::default(); + for (field, &len) in lens.iter().enumerate() { + let planes = bytes.get(at..at.checked_add(len.checked_mul(8)?)?)?; + at += len * 8; + let mut words = vec![0u64; len]; + for (plane, bytes) in planes.chunks_exact(len.max(1)).take(8).enumerate() { + for (word, &byte) in words.iter_mut().zip(bytes) { + *word |= u64::from(byte) << (8 * plane); + } + } + floats[field] = words; + } + (at == bytes.len()).then_some(Self { + ints, + at: 0, + floats, + next: [0; FLOAT_FIELDS], + }) + } + + fn uvarint(&mut self) -> Option { + uvarint(self.ints, &mut self.at) + } + + fn ivarint(&mut self) -> Option { + ivarint(self.ints, &mut self.at) + } + + fn byte(&mut self) -> Option { + let byte = *self.ints.get(self.at)?; + self.at += 1; + Some(byte) + } + + fn raw(&mut self, len: usize) -> Option<&'a [u8]> { + let raw = self.ints.get(self.at..self.at.checked_add(len)?)?; + self.at += len; + Some(raw) + } + + fn u64(&mut self) -> Option { + Some(u64::from_le_bytes(self.raw(8)?.try_into().ok()?)) + } + + fn float(&mut self, field: usize) -> Option { + let word = *self.floats[field].get(self.next[field])?; + self.next[field] += 1; + Some(word) + } + + /// Whether every stream was read to its end. + fn finished(&self) -> bool { + self.at == self.ints.len() + && self + .next + .iter() + .zip(&self.floats) + .all(|(&next, floats)| next == floats.len()) + } +} + +// --------------------------------------------------------------- buckets + +fn uvarint_len(value: u64) -> usize { + (64 - value.max(1).leading_zeros() as usize).div_ceil(7) +} + +/// Appends one store's buckets: a header (the entry count, and whether the +/// store is dense), the first index (a delta from `previous_first`, the +/// previous row's), then either the gaps between non-empty buckets and +/// their counts (sparse) or the count of every bucket from the first to the +/// last, empty ones as 0 (dense), whichever is shorter: a narrow pane's few +/// samples are spread out, a wide pane's buckets are mostly filled. +fn put_buckets(out: &mut Vec, buckets: &Buckets, previous_first: &mut i32) { + let Some(&(first, _)) = buckets.first() else { + put_uvarint(out, 0); + return; + }; + let gaps: usize = buckets + .windows(2) + .map(|pair| uvarint_len((pair[1].0 - pair[0].0 - 1) as u64)) + .sum(); + // Both forms write the non-empty counts; dense adds a byte per empty + // bucket, sparse the gaps. + let empty = span(buckets) - buckets.len(); + let dense = empty < gaps; + let entries = if dense { span(buckets) } else { buckets.len() }; + put_uvarint(out, (entries as u64) << 1 | u64::from(dense)); + put_ivarint(out, i64::from(first) - i64::from(*previous_first)); + *previous_first = first; + if dense { + let mut next = first; + for (index, count) in buckets { + out.resize(out.len() + (index - next) as usize, 0); + put_uvarint(out, *count); + next = index + 1; + } + } else { + for pair in buckets.windows(2) { + put_uvarint(out, (pair[1].0 - pair[0].0 - 1) as u64); + } + for (_, count) in buckets { + put_uvarint(out, *count); + } + } +} + +/// Reads one store's buckets into `out` (cleared first). +fn buckets(reader: &mut StreamReader, previous_first: &mut i32, out: &mut Buckets) -> Option<()> { + out.clear(); + let header = reader.uvarint()?; + let (entries, dense) = (usize::try_from(header >> 1).ok()?, header & 1 == 1); + if entries == 0 { + return (!dense).then_some(()); + } + // Every entry takes at least a byte; a bad length must not size an + // allocation. + if entries > reader.ints.len() - reader.at { + return None; + } + let first = i64::from(*previous_first).checked_add(reader.ivarint()?)?; + let first = i32::try_from(first).ok()?; + *previous_first = first; + out.reserve(entries); + if dense { + for slot in 0..entries { + let count = reader.uvarint()?; + if count != 0 { + out.push((first.checked_add(i32::try_from(slot).ok()?)?, count)); + } else if slot == 0 || slot == entries - 1 { + // A dense store spans exactly its non-empty buckets. + return None; + } + } + } else { + let mut index = first; + out.push((index, 0)); + for _ in 1..entries { + let gap = i32::try_from(reader.uvarint()?).ok()?; + index = index.checked_add(gap)?.checked_add(1)?; + out.push((index, 0)); + } + for bucket in out.iter_mut() { + bucket.1 = reader.uvarint()?; + if bucket.1 == 0 { + return None; + } + } + } + (span(out) as i64 <= MAX_SPAN).then_some(()) +} + +// ------------------------------------------------------------ the columns + +/// The tag of an exact record kept whole, in its mapped layout. +const RAW: u8 = 0xff; + +/// A column of `states` (each the mapped-layout bytes of one state of +/// `kind`) in compact form; `None` when the column has no compact form +/// (its sketches differ in index mapping or admission rate, or a state is +/// not of `kind`'s layout). +pub fn encode_states( + kind: CompactKind, + states: impl Iterator>, +) -> Option> { + let mut out = Streams::default(); + match kind { + CompactKind::DDSketch => { + let mut shared: Option<(u64, u64)> = None; + let mut previous = (0i32, 0i32); + let mut dd = DdContents::default(); + for state in states { + read_dd(state.as_ref(), &mut dd)?; + match shared { + None => { + shared = Some((dd.alpha, dd.admission_rate)); + put_u64(&mut out.ints, dd.alpha); + put_u64(&mut out.ints, dd.admission_rate); + } + Some(shared) if shared != (dd.alpha, dd.admission_rate) => return None, + Some(_) => {} + } + put_uvarint(&mut out.ints, dd.zero_count); + out.floats[0].push(dd.sum); + out.floats[1].push(dd.min); + out.floats[2].push(dd.max); + put_buckets(&mut out.ints, &dd.positive, &mut previous.0); + put_buckets(&mut out.ints, &dd.negative, &mut previous.1); + } + } + _ => { + let size = kind.record_bytes().expect("an exact kind"); + let mut previous_times = [0i64; 2]; + let mut words = [0u64; 7]; + for state in states { + let state = state.as_ref(); + if state.len() != size { + return None; + } + for (word, bytes) in words.iter_mut().zip(state.as_chunks::<8>().0) { + *word = u64::from_le_bytes(*bytes); + } + if !put_record(&mut out, kind, &words[..size / 8], &mut previous_times) { + out.ints.push(RAW); + out.ints.extend_from_slice(state); + } + } + } + } + Some(out.finish()) +} + +/// The absent counter's record after its presence word, as +/// `IncreaseAccumulator::new(0.0, 0, 0.0, 0)` writes it. +const ABSENT_COUNTER: [u64; 6] = [0, 0, 0, 0, 0, 1]; + +/// Appends exact record `words` of `kind` in compact form; `false` when +/// the record is not in the form the executor writes (it is then kept +/// whole). Each timestamp is a delta from the same field of the previous +/// record that had one (`previous_times`). +fn put_record( + out: &mut Streams, + kind: CompactKind, + words: &[u64], + previous_times: &mut [i64; 2], +) -> bool { + let mut time = |ints: &mut Vec, field: usize, word: u64| { + put_ivarint(ints, (word as i64).wrapping_sub(previous_times[field])); + previous_times[field] = word as i64; + }; + match (kind, words) { + (CompactKind::Count, [count]) => { + out.ints.push(0); + put_uvarint(&mut out.ints, *count); + } + (CompactKind::Sum, [sum, compensation, seen @ (0 | 1)]) => { + let tag = *seen as u8 | u8::from(*compensation != 0) << 1; + out.ints.push(tag); + out.floats[0].push(*sum); + if *compensation != 0 { + out.floats[1].push(*compensation); + } + } + (CompactKind::MinMax, [0, 0]) => out.ints.push(0), + (CompactKind::MinMax, [1, value]) => { + out.ints.push(1); + out.floats[0].push(*value); + } + (CompactKind::Counter, [0, rest @ ..]) if *rest == ABSENT_COUNTER => out.ints.push(0), + (CompactKind::Counter, [1, start, start_time, last, last_time, total, samples]) => { + // The increase, when it is the plain difference (no reset). + // (Never for a NaN difference: its payload need not repeat.) + let difference = f64::from_bits(*last) - f64::from_bits(*start); + let plain = !difference.is_nan() && difference.to_bits() == *total; + out.ints.push(1 | u8::from(plain) << 1); + time(&mut out.ints, 0, *start_time); + time(&mut out.ints, 1, *last_time); + put_uvarint(&mut out.ints, *samples); + out.floats[0].push(*start); + out.floats[1].push(*last); + if !plain { + out.floats[2].push(*total); + } + } + (CompactKind::LastTwoSamples, [p0 @ (0 | 1), t0, v0, p1 @ (0 | 1), t1, v1]) => { + let samples = [(*p0, *t0, *v0), (*p1, *t1, *v1)]; + if samples + .iter() + .any(|&(present, t, v)| present == 0 && (t, v) != (0, 0)) + { + return false; + } + out.ints.push(*p0 as u8 | (*p1 as u8) << 1); + for (field, (present, t, v)) in samples.into_iter().enumerate() { + if present == 1 { + time(&mut out.ints, field, t); + out.floats[field].push(v); + } + } + } + _ => return false, + } + true +} + +/// Decodes `rows` states of `kind` from their compact form into the mapped +/// layout: the states back to back in 8-byte words (each state starting on +/// a word), and their byte offsets (`rows + 1`). `None` when the bytes are +/// damaged. +pub fn decode_states(kind: CompactKind, bytes: &[u8], rows: usize) -> Option<(Vec, Vec)> { + let mut reader = StreamReader::new(bytes)?; + // Every row takes at least a byte: `rows` past that is damage, and must + // not size an allocation. + if rows > bytes.len() { + return None; + } + let mut words: Vec = Vec::new(); + let mut offsets = Vec::with_capacity(rows + 1); + offsets.push(0u32); + let offset = |words: &Vec| u32::try_from(words.len() * 8).ok(); + match kind { + CompactKind::DDSketch => { + if rows > 0 { + let mut dd = DdContents { + alpha: reader.u64()?, + admission_rate: reader.u64()?, + ..DdContents::default() + }; + let mut previous = (0i32, 0i32); + let mut view = Vec::new(); + for _ in 0..rows { + dd.zero_count = reader.uvarint()?; + buckets(&mut reader, &mut previous.0, &mut dd.positive)?; + buckets(&mut reader, &mut previous.1, &mut dd.negative)?; + (dd.sum, dd.min, dd.max) = + (reader.float(0)?, reader.float(1)?, reader.float(2)?); + view.clear(); + dd.view_bytes(&mut view)?; + let (view_words, _) = view.as_chunks::<8>(); + words.extend(view_words.iter().map(|w| u64::from_le_bytes(*w))); + offsets.push(offset(&words)?); + } + // The window cache charges `len`: hold no more than that. + words.shrink_to_fit(); + } + } + _ => { + let size = kind.record_bytes().expect("an exact kind"); + words.reserve(rows * size / 8); + let mut previous_times = [0i64; 2]; + for _ in 0..rows { + record(kind, &mut reader, &mut previous_times, &mut words)?; + offsets.push(offset(&words)?); + } + } + } + reader.finished().then_some((words, offsets)) +} + +/// One exact record of `kind`, appended to `view` in its mapped layout. +fn record( + kind: CompactKind, + reader: &mut StreamReader, + previous_times: &mut [i64; 2], + view: &mut Vec, +) -> Option<()> { + let size = kind.record_bytes().expect("an exact kind"); + let tag = reader.byte()?; + if tag == RAW { + let (raw, _) = reader.raw(size)?.as_chunks::<8>(); + view.extend(raw.iter().map(|w| u64::from_le_bytes(*w))); + return Some(()); + } + let mut time = |reader: &mut StreamReader, field: usize| -> Option { + let t = previous_times[field].wrapping_add(reader.ivarint()?); + previous_times[field] = t; + Some(t as u64) + }; + let mut words = [0u64; 7]; + let record: &[u64] = match (kind, tag) { + (CompactKind::Count, 0) => { + words[0] = reader.uvarint()?; + &words[..1] + } + (CompactKind::Sum, 0..=3) => { + words[0] = reader.float(0)?; + words[1] = if tag & 2 != 0 { reader.float(1)? } else { 0 }; + words[2] = u64::from(tag & 1); + &words[..3] + } + (CompactKind::MinMax, 0) => &words[..2], + (CompactKind::MinMax, 1) => { + words[..2].copy_from_slice(&[1, reader.float(0)?]); + &words[..2] + } + (CompactKind::Counter, 0) => { + words[1..].copy_from_slice(&ABSENT_COUNTER); + &words + } + (CompactKind::Counter, 1 | 3) => { + let start_time = time(reader, 0)?; + let last_time = time(reader, 1)?; + let samples = reader.uvarint()?; + let (start, last) = (reader.float(0)?, reader.float(1)?); + let total = if tag & 2 != 0 { + (f64::from_bits(last) - f64::from_bits(start)).to_bits() + } else { + reader.float(2)? + }; + words = [1, start, start_time, last, last_time, total, samples]; + &words + } + (CompactKind::LastTwoSamples, 0..=3) => { + for sample in 0..2 { + if tag >> sample & 1 == 1 { + let t = time(reader, sample)?; + words[sample * 3..sample * 3 + 3].copy_from_slice(&[ + 1, + t, + reader.float(sample)?, + ]); + } + } + &words[..6] + } + _ => return None, + }; + view.extend_from_slice(record); + Some(()) +} + +/// A column of text keys in compact form: each a signed varint delta from +/// the previous row's. +pub fn encode_text_keys(keys: impl ExactSizeIterator) -> Vec { + let mut out = Vec::with_capacity(keys.len()); + let mut previous = 0i64; + for key in keys { + put_ivarint(&mut out, i64::from(key) - previous); + previous = i64::from(key); + } + out +} + +/// `rows` text keys from their compact form. +pub fn decode_text_keys(bytes: &[u8], rows: usize) -> Option> { + if rows > bytes.len() { + return None; + } + let mut keys = Vec::with_capacity(rows); + let (mut at, mut previous) = (0, 0i64); + for _ in 0..rows { + previous = previous.checked_add(ivarint(bytes, &mut at)?)?; + keys.push(u32::try_from(previous).ok()?); + } + (at == bytes.len()).then_some(keys) +} + +#[cfg(test)] +mod tests { + use super::*; + use asap_sketchlib::{DdSketch, DdSketchView}; + + fn dd_contents(view: &[u8]) -> Option { + let mut dd = DdContents::default(); + read_dd(view, &mut dd).map(|()| dd) + } + + fn dd(alpha: f64, samples: &[f64]) -> Vec { + let mut sketch = DdSketch::new(alpha); + for sample in samples { + sketch.add(sample); + } + sketch.to_view_bytes() + } + + /// `bytes` copied to an 8-byte-aligned buffer, as a view needs. + fn aligned(bytes: &[u8]) -> Vec { + let mut words = vec![0u64; bytes.len().div_ceil(8)]; + for (word, chunk) in words.iter_mut().zip(bytes.chunks(8)) { + let mut raw = [0u8; 8]; + raw[..chunk.len()].copy_from_slice(chunk); + *word = u64::from_le_bytes(raw); + } + words + } + + fn view_of(words: &[u64], len: usize) -> DdSketchView<'_> { + // SAFETY: `words` holds at least `len` initialized bytes. + let bytes = unsafe { std::slice::from_raw_parts(words.as_ptr().cast::(), len) }; + DdSketchView::from_bytes(bytes).unwrap() + } + + /// The states `decode_states` rebuilds, one byte vector each. + fn round_trip(kind: CompactKind, states: &[Vec]) -> Vec> { + let compact = encode_states(kind, states.iter().map(Vec::as_slice)).expect("compact"); + let (words, offsets) = decode_states(kind, &compact, states.len()).expect("decodes"); + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + offsets + .windows(2) + .map(|pair| bytes[pair[0] as usize..pair[1] as usize].to_vec()) + .collect() + } + + /// Ten samples per series in a 1 s pane at alpha 0.02 (the demo's + /// finest DDSketch view): the mapped layout takes 120 bytes a state (an + /// 88-byte head and a dense run of 1-byte counts, half of them empty), + /// the compact column 47 before compression. + #[test] + fn a_ten_sample_ddsketch_state_takes_47_compact_bytes() { + let samples: Vec = (0..10).map(|i| 40.0 + 7.3 * f64::from(i)).collect(); + let view = dd(0.02, &samples); + assert_eq!(view.len(), 120); + let rows = 1000; + let states = vec![view; rows]; + let compact = + encode_states(CompactKind::DDSketch, states.iter().map(Vec::as_slice)).unwrap(); + // Per row, 23 varint bytes (the zero count, two store headers, the + // first bucket's delta from the previous row's, 9 gaps, 10 counts) + // and 24 float bytes (sum, min, max); per column, alpha and the + // admission rate (16), the stream lengths (9), and one more byte + // for the first row's first bucket (no previous row). + assert_eq!(compact.len(), rows * (23 + 24) + 16 + 9 + 1); + } + + /// Decoding gives the mapped layout's bytes exactly, so every answer + /// read from a compact column is the answer read from the mapped one: + /// empty sketches, zeros, negative samples, counts past one byte, + /// dense and sparse stores. + #[test] + fn compact_ddsketch_columns_rebuild_the_view_bytes() { + let wide: Vec = (1..=2000).map(|i| 1.0 + f64::from(i % 7)).collect(); + let spread: Vec = (0..50).map(|i| 1.5f64.powi(i)).collect(); + let dense: Vec = (0..400).map(|i| 100.0 + f64::from(i) * 0.25).collect(); + let states = vec![ + dd(0.02, &[]), + dd(0.02, &[0.0, 0.0, 3.0]), + dd(0.02, &[-5.0, -1.0, 0.0, 2.0, 9.5]), + dd(0.02, &wide), + dd(0.02, &spread), + dd(0.02, &dense), + dd(0.02, &[-1e300, 1e-300, 7.0]), + ]; + assert_ne!(states[4][68], states[5][68], "both store forms are covered"); + let back = round_trip(CompactKind::DDSketch, &states); + assert_eq!(back, states); + for (a, b) in states.iter().zip(&back) { + let (wa, wb) = (aligned(a), aligned(b)); + let (va, vb) = (view_of(&wa, a.len()), view_of(&wb, b.len())); + for q in [0.0, 0.25, 0.5, 0.9, 0.99, 1.0] { + assert_eq!(va.quantile_interpolated(q), vb.quantile_interpolated(q)); + } + } + } + + /// Sketches of different index mappings have no shared column head: + /// the column keeps its mapped layout. + #[test] + fn ddsketches_of_two_alphas_have_no_compact_column() { + let states = [dd(0.02, &[1.0]), dd(0.05, &[1.0])]; + assert!(encode_states(CompactKind::DDSketch, states.iter().map(Vec::as_slice)).is_none()); + } + + /// Views the writer never writes (keys out of order, non-zero padding) + /// have no compact form: their column keeps the mapped layout rather + /// than being rebuilt differently. + #[test] + fn non_writer_ddsketch_views_have_no_compact_form() { + let spread: Vec = (0..5).map(|i| 1.5f64.powi(i * 3)).collect(); + let view = dd(0.02, &spread); + assert_eq!(view[68], 1, "a sparse store"); + assert!(dd_contents(&view).is_some()); + let mut swapped = view.clone(); + // Swap the second and third sparse keys. + let (a, b) = (DD_HEAD_BYTES + 4, DD_HEAD_BYTES + 8); + let key = swapped[a..a + 4].to_vec(); + swapped.copy_within(b..b + 4, a); + swapped[b..b + 4].copy_from_slice(&key); + assert!(dd_contents(&swapped).is_none()); + let mut padding = view.clone(); + *padding.last_mut().unwrap() = 1; + assert!(dd_contents(&padding).is_none()); + } + + fn words(words: &[u64]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// Every exact record kind decodes to the bytes it was encoded from, + /// including records the executor never writes (kept whole). + #[test] + fn compact_exact_columns_rebuild_the_records() { + let f = f64::to_bits; + let cases: Vec<(CompactKind, Vec>)> = vec![ + ( + CompactKind::Sum, + vec![ + vec![f(1.5), 0, 1], + vec![f(-2.0), f(1e-17), 1], + vec![0, 0, 0], + vec![1, 2, 7], + ], + ), + (CompactKind::Count, vec![vec![0], vec![12], vec![u64::MAX]]), + ( + CompactKind::MinMax, + vec![vec![0, 0], vec![1, f(-3.25)], vec![0, 5]], + ), + ( + CompactKind::Counter, + vec![ + vec![1, f(10.0), 1_000, f(25.0), 1_900, f(15.0), 10], + // a reset: the increase is not the difference + vec![1, f(10.0), 1_000, f(3.0), 1_900, f(13.0), 10], + [0].into_iter().chain(ABSENT_COUNTER).collect(), + vec![0, 1, 2, 3, 4, 5, 6], + ], + ), + ( + CompactKind::LastTwoSamples, + vec![ + vec![1, 900, f(1.0), 1, 1_000, f(2.0)], + vec![0, 0, 0, 1, 5, f(1.0)], + vec![0, 0, 0, 0, 0, 0], + vec![0, 3, 0, 0, 0, 0], + ], + ), + ]; + for (kind, records) in cases { + let states: Vec> = records.iter().map(|r| words(r)).collect(); + assert_eq!(round_trip(kind, &states), states, "{kind:?}"); + } + } + + /// A counter takes 56 bytes in the mapped layout and 20 in a compact + /// column: a tag, two timestamp deltas from the previous row's, the + /// sample count, and the start and last value; the increase is their + /// difference (no reset), so it is left out. + #[test] + fn a_counter_record_takes_20_compact_bytes() { + let f = f64::to_bits; + let rows = 1000; + let states: Vec> = (0..rows) + .map(|row| { + let start = 10.0 + row as f64; + words(&[1, f(start), 1_000, f(start + 15.0), 1_900, f(15.0), 10]) + }) + .collect(); + let compact = + encode_states(CompactKind::Counter, states.iter().map(Vec::as_slice)).unwrap(); + // The first row's timestamps are 2-byte deltas from 0; the stream + // lengths take 7 bytes. + assert_eq!(compact.len(), rows * (4 + 16) + 2 + 7); + } + + /// Damaged bytes are an error, never a panic or a huge allocation. + #[test] + fn damaged_compact_columns_are_rejected() { + let states = [dd(0.02, &[1.0, 2.0, 3.0]), dd(0.02, &[4.0])]; + let compact = + encode_states(CompactKind::DDSketch, states.iter().map(Vec::as_slice)).unwrap(); + for cut in 0..compact.len() { + assert!(decode_states(CompactKind::DDSketch, &compact[..cut], 2).is_none()); + } + assert!(decode_states(CompactKind::DDSketch, &compact, 3).is_none()); + let mut huge = Vec::new(); + put_uvarint(&mut huge, u64::MAX / 2); + assert!(decode_states(CompactKind::Counter, &huge, 1).is_none()); + assert!(decode_text_keys(&[0xff; 3], 2).is_none()); + } + + /// Text keys round-trip; sorted series keys take one byte each. + #[test] + fn text_keys_round_trip() { + let keys: Vec = vec![0, 1, 2, 7, 3, u32::MAX, 0]; + let compact = encode_text_keys(keys.iter().copied()); + assert_eq!(decode_text_keys(&compact, keys.len()).unwrap(), keys); + assert_eq!(encode_text_keys(0..1000).len(), 1000); + } +} diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index fb8012a4..7809da79 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -823,7 +823,7 @@ impl WindowSlot { std::thread::sleep(tier.decode_delay); } let timer = Timer::start(); - let (batch, mapped_state_bytes) = + let (batch, state_bytes) = location.read(&self.schema, tier.read).map_err(|error| { Error::Invalid(format!( "materialized view {} window ending {}: {error}", @@ -834,7 +834,7 @@ impl WindowSlot { tier.cold_reads.fetch_add(1, Ordering::Relaxed); tier.cold_read_bytes .fetch_add(location.read_bytes(), Ordering::Relaxed); - let bytes = (window_batch_bytes(&batch) + mapped_state_bytes) as u64; + let bytes = (window_batch_bytes(&batch) + state_bytes) as u64; Ok((Arc::new(vec![batch]), bytes)) }) } diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index 0111d785..a7bdc7c2 100644 --- a/docs/design/tiered-view-storage.md +++ b/docs/design/tiered-view-storage.md @@ -201,10 +201,10 @@ holding a 1 h and a 6 h view would otherwise keep the 1 h view's bytes thread rolls to the next one; a sealed segment never changes again until it is deleted whole. A segment holds the existing framing (a little-endian `u32` length and a payload per frame), with every frame starting on an -8-byte boundary (zero padding) so fixed-width columns can be borrowed in -place: +8-byte boundary (zero padding; format 2 borrowed fixed-width columns in +place, format 4 decompresses each fragment): -- a header frame (MessagePack): plan hash, group, **format version 3**, +- a header frame (MessagePack): plan hash, group, **format version 4**, and the segment start; - one record frame per refreshed window. Its head is a small MessagePack map, followed by the parts it points at: @@ -216,7 +216,7 @@ Record v2 head = { start_ms, end_ms, views: [(view id, offset, len)] } // one columnar fragment per view ``` -**Columnar fragments.** Each view's rows of the window are one fragment, +**Columnar fragments** (format 2; format 4 changes the encodings, see "Compact, compressed fragments" below). Each view's rows of the window are one fragment, laid out by column (all offsets relative to the fragment, every section 8-byte aligned): @@ -259,6 +259,44 @@ identity's JSON once per label name per segment). At 10k series that array is ab 100–150 KB per label name per segment, counted with the segment's dictionary; on disk it saves 4 B per row per label column. +**Compact, compressed fragments (format version 4).** The mapped state +layout is large for the small states of narrow panes. In the live demo a +DDSketch of the ten samples one series has in a 1 s pane took 160 B a +row on disk (an 88-byte head with `alpha`, the admission rate and a count +that every row repeats, then sparse `u32` keys), more than the raw samples; +an exact counter took 72 B. Format 4 keeps the columnar fragment and +changes two things (format 3 added the label columns above): + +- **Compact state and text columns.** A DDSketch column stores `alpha` + and the admission rate once, leaves out the count (the bucket and zero + counts sum to it), and keeps only non-empty buckets: per store a varint + header, the first bucket index as a delta from the previous row's, then + either varint gaps and counts (sparse) or every count from the first + non-empty bucket to the last (dense), whichever is shorter. Exact records + keep a tag byte of which fields are set, the floats that are, and + timestamps as varint deltas from the previous row's; a counter's + increase is left out when it is the plain difference of its values. A + column's varints form one stream and each float field (sum, min, max; + start, last value) its own stream of byte planes, so the sign and + exponent bytes of one field across series sit together. Text keys are + varint deltas from the previous row's key. KLL and Count-Min columns keep + the mapped layout. Every encoding is lossless: a read rebuilds the mapped + layout byte for byte, so answers do not change; a state not in the form + the executor writes is kept whole. +- **zstd level 1 per fragment.** A stored fragment is its columnar bytes' + length (`u32`) and those bytes compressed. A cold read still reads one + (view, window) fragment; level 3 saved under 2% more for twice the + encode CPU. + +Measured on the demo's segments (27 minutes, 7.1 GB, format 2), bytes a +row including the record frame: DDSketch at a 1 s pane 160 → 17, at 5 s +233 → 31, at 60 s 272 → 89; exact counter at 1 s 72 → 7.5; exact sum at +1 s 40 → 3.2. A cold read now decompresses and rebuilds the states into +buffers of its own instead of borrowing the mapping, and the window cache +charges those bytes; the page cache holds the smaller compressed +fragments. Segments of formats 2 and 3 are set aside at startup like those of +another plan. + Index: `WindowLocation { segment: Arc, offset: u64, len: u32 }` points at a view's fragment. It lives in the `ViewWindow` in memory (about 40 B per (view, window)); there is no index file. At startup the index is @@ -297,8 +335,10 @@ not 240 decoded windows. **`mmap` of sealed segments.** A sealed segment is mapped once, read-only (`MAP_SHARED`, `PROT_READ`), when its first window is read cold, and -unmapped when its last `Arc` drops. Decoding reads directly from -the mapped bytes: +unmapped when its last `Arc` drops. (Format 4 decompresses each +fragment from the mapping and decodes the copy: columns are no longer +borrowed from the mapping; see "Compact, compressed fragments".) In +format 2, decoding read directly from the mapped bytes: - text keys, timestamps and plain columns become Arrow buffers over the mapping itself (`Buffer::from_custom_allocation` with the @@ -322,8 +362,8 @@ instead of an error; `--view-read=pread` reads every fragment with where that matters or a measured case prefers it. B3 compares the two. **The active segment** holds the newest windows, which are mostly still -in the cache. A cold read of one of them uses `pread` of the fragment -into an 8-byte-aligned buffer, then the same decoder; mapping a file that +in the cache. A cold read of one of them uses `pread` of the fragment, +then the same decoder; mapping a file that is still growing would need re-mapping as it grows and is not worth it for the few windows involved. When the segment is sealed, later reads map it. @@ -360,6 +400,8 @@ levels: each level is its own view, tiered the same way. ### Zero-copy state views (revision, for approval) +*Superseded for storage by format 4 ("Compact, compressed fragments"): a cold read decompresses its fragment and rebuilds the states in buffers of its own, so they are no longer read in place from the mapping. The executor's mapped-state API below is what those rebuilt buffers use.* + **Why.** Decoding a cold window rebuilds every state on the heap. The implementation measured so far (sketch states rebuilt from their mapped ASAPv1 bytes) bounds the *steady* heap, but not a query's: the executor's @@ -644,7 +686,7 @@ here changes the Planner. | Question | Decision | Rejected and why | | --- | --- | --- | | Where cold windows live | the persistence files | a second cold file (double write); encoded bytes in the heap (compact, but not reclaimable, so the cgroup OOM stays) | -| Read primitive | `mmap` of sealed segments, decoding in place (fixed-width columns and the dictionary borrowed, states rebuilt from the mapped bytes); `pread` for the active segment and as `--view-read=pread` | `pread` everywhere: copies every fragment into a buffer, and the row data again into Arrow arrays; kept as the fallback. `mmap` of the active segment: needs re-mapping as it grows, for windows that are mostly still cached | +| Read primitive | `mmap` of sealed segments (format 4: each fragment decompressed from the mapping and decoded into buffers of its own; format 2: decoding in place (fixed-width columns and the dictionary borrowed, states rebuilt from the mapped bytes); `pread` for the active segment and as `--view-read=pread` | `pread` everywhere: copies every fragment into a buffer, and the row data again into Arrow arrays; kept as the fallback. `mmap` of the active segment: needs re-mapping as it grows, for windows that are mostly still cached | | Fragment encoding | columnar per (view, window), state bytes unchanged | row-wise `Vec>` as today: per-value tags and interleaved identity indices (140 B per exact state), a row-to-batch conversion on every decode, nothing to borrow | | Index granularity | (view, window) → slice, in memory | (series, window) → offset: no reader reads one series of a view window; an index file: rebuilt from the frames at startup instead | | Hot policy | CLOCK recency + idle time + byte budget, insert on commit | plan-derived next-read (couples the store to the executor's tiling; follow-up if B2 shows bad evictions); LRU list (a lock on every read) | @@ -660,8 +702,9 @@ here changes the Planner. `pread` only for the active segment and as a fallback option. B3 still compares the two. - **Hot policy:** recency (CLOCK, idle time, byte budget). -- **Fragment encoding:** columnar, with format version 3; label columns - are read back from the series identity, not stored. +- **Fragment encoding:** columnar, format version 4: label columns are + read back from the series identity, not stored (format 3); compact state + and text columns, zstd level 1 per fragment (format 4). - **No cgroup limit:** no budget, plus idle eviction. - **Old view files:** renamed `*.stale`. - **Revision (pending approval):** states are used from the mapping @@ -699,10 +742,10 @@ same build with tiering off (`--view-cache-max-bytes` unbounded and | V17 | Metrics. | Any plan, a few windows, budget zero. | `asap_view_cache_{bytes,entries}`, `asap_view_{pending,pinned,file}_bytes`, `asap_view_cache_{hits,misses,evictions}_total`, `asap_view_cold_reads_total`, `asap_view_cold_read_bytes_total`, `phase="view_decode"` CPU. | Fails: new series. | | B1 | Bench at 10k (reported, not CI). | Dashboard-heavy and typical-dashboard at 10k series, 1 sample/s, in the harness's cgroups with the same `memory.max` for both engines; tiering off, on with the default budget, on with a budget of zero. | RSS, `memory.current` split into anon and file, peak and steady; query latency per query; CPU per phase incl. `view_decode`; disk bytes. | Tiering-off numbers come from today's code. | | B2 | Cold versus warm page cache (reported). | As B1, budget zero; before a round of queries, drop the segments' pages (`POSIX_FADV_DONTNEED` on each file) for the cold case. | Query latency and read bytes cold vs warm; cache hit ratio over a run (checks the recency policy). | — | -| V18 (revised) | States and fixed-width columns are used from the mapping. | A window of 1,000 KLL and 1,000 DDSketch rows read cold from a sealed segment. | Each view's item and bucket slices lie inside the segment's mapping; text keys and plain columns too; the dictionary is shared by every window of the segment. With `--view-read=pread` they lie outside it, and the answers are equal. | Fails: no view types. | -| V18 (implemented, kept) | Fixed-width columns and texts are borrowed from the mapping, not copied. | A window of 1,000 rows read cold from a sealed segment. | The text keys' and timestamps' buffer addresses lie inside the segment's mapping; the dictionary values array is shared by every window of the segment. With `--view-read=pread` they lie outside it, and the rows are equal. | Fails: as V2. | +| V18 (revised; superseded by format 4) | States and fixed-width columns are used from the mapping. | A window of 1,000 KLL and 1,000 DDSketch rows read cold from a sealed segment. | Each view's item and bucket slices lie inside the segment's mapping; text keys and plain columns too; the dictionary is shared by every window of the segment. With `--view-read=pread` they lie outside it, and the answers are equal. | Fails: no view types. | +| V18 (format 4) | A cold read rebuilds its state columns in buffers of its own and reports their bytes; the segment's texts stay one shared dictionary. | A KLL window of 1,000 rows read cold from a sealed segment, and by `--view-read=pread`. | Same rows; the reported state bytes equal the states' mapped layout plus offsets; the dictionary values array is shared by every window of the segment. | Fails in formats 2 and 3: columns are borrowed, nothing is reported. | | V19 | No `SIGBUS`: only sealed segments are mapped, and a sealed segment is never shortened. | Read a window of the active segment (by `pread`), seal it, read again (mapped); unlink a mapped segment and read through a held location; restart over a segment with a torn tail. | All reads equal; the torn tail is cut before any mapping; no crash. | Fails: as V2. | -| V20 | A query over cold windows allocates only its accumulators. | Dashboard plan, 1k series, 1 h of windows, window cache budget 0, all segments sealed; a counting global allocator in the test binary; `quantile_over_time(0.99, lat[1h])` and `max_over_time(lat[30m])`. | Bytes allocated during the run ≤ accumulators (series × one accumulator state) + output + a fixed bound, and at least 10× below the decoded windows' bytes; same answers as tiering off. | Fails: windows are decoded, and `SummaryMerge` collects them. | +| V20 (format 2; format 4 also holds each read window's rebuilt states) | A query over cold windows allocates only its accumulators. | Dashboard plan, 1k series, 1 h of windows, window cache budget 0, all segments sealed; a counting global allocator in the test binary; `quantile_over_time(0.99, lat[1h])` and `max_over_time(lat[30m])`. | Bytes allocated during the run ≤ accumulators (series × one accumulator state) + output + a fixed bound, and at least 10× below the decoded windows' bytes; same answers as tiering off. | Fails: windows are decoded, and `SummaryMerge` collects them. | | V21 | Executor: `SummaryMerge` folds batch by batch and accepts mapped states. | Executor test (ASAPPlanner): a stream of 240 batches whose state columns are `Mapped`; a stream mixing owned and mapped batches; Counter windows out of order in the stream. | Same output as over owned states; at most one input batch held at a time; Counter merged in time order. | Fails: no `Mapped` storage; merge collects. | | V22 | Compressed-sample windows through the data plane. | A plan with a `CompressedSamples` chain (Planner fixture): commit, persist, read sealed and active, restart; a query reading the open window. | Blob bytes on disk equal the block the executor sealed; decoded rows equal the raw samples; the open window's samples are included when `reads_unsealed_window`; decoded rows are not kept after the run. | Fails: no compressed-sample chains in the pinned Planner. | | B3 | `pread` versus `mmap` (reported). | `examples/view_read_bench.rs` over one 10k-series segment of the dashboard plan: decode each window with `--view-read=mmap` and `pread`, page cache warm and cold. | ns per window and per state by family, bytes copied, `RssAnon`/`RssFile`. | — |