diff --git a/Cargo.lock b/Cargo.lock index db00f6d2..c823459c 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 e9b9affd..e08a01bf 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 9cd5cf7a..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] { @@ -95,7 +128,7 @@ fn main() { } let started = Instant::now(); for location in &locations { - std::hint::black_box(location.read(&schema, how).unwrap()); + std::hint::black_box(location.read(&schema, how).unwrap().0); } let ns = started.elapsed().as_nanos() as f64; println!( diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 908f79d7..e0caf301 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -21,6 +21,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; @@ -266,7 +267,9 @@ async fn query( let instant = match InstantQuery::parse(query.0.as_deref(), &body) { Ok(Some(instant)) => instant, Ok(None) if state.no_forward => { - return not_answered("the request has no query parameter"); + return not_answered( + "the request has no query parameter, or names Prometheus' min or max time", + ); } Ok(None) => return forward(state, "query", method, query, headers, body).await, Err(bad) => { @@ -322,7 +325,7 @@ async fn query_range( Ok(Some(range)) => range, Ok(None) if state.no_forward => { return not_answered( - "the request lacks query, start, end or step, or names a time that is not in Unix seconds", + "the request lacks query, start, end or step, or names Prometheus' min or max time", ); } Ok(None) => return forward(state, "query_range", method, query, headers, body).await, diff --git a/data_plane/src/persist.rs b/data_plane/src/persist.rs index f3d46dc7..aa4f286d 100644 --- a/data_plane/src/persist.rs +++ b/data_plane/src/persist.rs @@ -129,6 +129,9 @@ pub type ViewIndex = BTreeMap, texts: HashMap, u32>, + /// The labels of each series identity its records held, looked up once + /// per segment ([`SegmentTexts::identity_labels`]). + labels_by_identity: crate::segment::LabelsByIdentity, /// The start of its first window: it rolls once a window starts /// `segment_ms` or more after it. first_start_ms: i64, @@ -415,15 +418,25 @@ impl ViewFiles { written.segments_marked_cold = files.cool(); } let no_texts = HashMap::new(); - let mut texts = match &files.active { - Some(active) => SegmentTexts { - known: &active.texts, - base: active.segment.text_count() as u32, + // The segment is created only once a fragment is encoded; until then + // the identities' labels go to a map that becomes the new segment's. + let mut no_labels = crate::segment::LabelsByIdentity::new(); + let mut texts = match files.active.as_mut() { + Some(ActiveSegment { + segment, + texts, + labels_by_identity, + .. + }) => SegmentTexts { + known: texts, + labels_by_identity, + base: segment.text_count() as u32, new: Vec::new(), new_index: HashMap::new(), }, None => SegmentTexts { known: &no_texts, + labels_by_identity: &mut no_labels, base: 0, new: Vec::new(), new_index: HashMap::new(), @@ -455,6 +468,7 @@ impl ViewFiles { files.active = Some(ActiveSegment { segment: Segment::create_new(&dir, end_ms, &header)?, texts: HashMap::new(), + labels_by_identity: no_labels, first_start_ms: start_ms, }); written.bytes += files.active.as_ref().expect("set").segment.len(); @@ -571,7 +585,13 @@ impl ViewFiles { let mut by_view = ViewIndex::new(); for (retention_ms, _, path) in paths { let Some((segment, heads)) = Segment::open(&path, &expected)? else { - set_aside(&path, "a segment of another plan, group or version")?; + set_aside( + &path, + &format!( + "a segment of another plan, group or format version (this data \ + plane reads version {FORMAT_VERSION})" + ), + )?; continue; }; for head in heads { @@ -1090,12 +1110,13 @@ mod tests { // docs/design/tiered-view-storage.md, tests V2, V3, V9, V12, V13, // V18, V19. - 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 { @@ -1299,6 +1320,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`. @@ -1317,13 +1391,13 @@ mod tests { !location.is_sealed(), "{what}: the newest segment is active" ); - let active = location.read(batch.schema(), ViewRead::Mmap).unwrap(); + let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; assert_same_rows(&batch, &active, &format!("{what}, active segment")); files.seal(0).unwrap(); assert!(location.is_sealed(), "{what}"); - let mapped = location.read(batch.schema(), ViewRead::Mmap).unwrap(); + let mapped = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; assert_same_rows(&batch, &mapped, &format!("{what}, mapped")); - let pread = location.read(batch.schema(), ViewRead::Pread).unwrap(); + let pread = location.read(batch.schema(), ViewRead::Pread).unwrap().0; assert_same_rows(&batch, &pread, &format!("{what}, pread")); } let _ = std::fs::remove_dir_all(&dir); @@ -1344,11 +1418,11 @@ mod tests { .unwrap(); let location = location_of(&written, 1); for how in [ViewRead::Pread, ViewRead::Mmap] { - assert_eq!(location.read(empty.schema(), how).unwrap().num_rows(), 0); + assert_eq!(location.read(empty.schema(), how).unwrap().0.num_rows(), 0); } files.seal(0).unwrap(); for how in [ViewRead::Pread, ViewRead::Mmap] { - assert_eq!(location.read(empty.schema(), how).unwrap().num_rows(), 0); + assert_eq!(location.read(empty.schema(), how).unwrap().0.num_rows(), 0); } let _ = std::fs::remove_dir_all(&dir); } @@ -1377,7 +1451,9 @@ mod tests { drop(file); for (i, batch) in batches.iter().enumerate() { let view = i as PhysicalASAPNodeId + 1; - let read = location_of(&written, view).read(batch.schema(), ViewRead::Mmap); + let read = location_of(&written, view) + .read(batch.schema(), ViewRead::Mmap) + .map(|(batch, _)| batch); if view == 2 { assert!(read.is_err(), "a damaged fragment must not decode"); } else { @@ -1387,25 +1463,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))]) @@ -1415,9 +1494,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(); - let r2 = l2.read(second.schema(), ViewRead::Mmap).unwrap(); + 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) @@ -1426,28 +1507,190 @@ 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(); + let (copied, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap(); assert_same_rows(&first, &copied, "pread"); - assert!(!l1.maps(identity(&copied).keys().values().as_ptr() as usize)); + // The rebuilt states' bytes, which the batch does not count, are + // reported for the window's charge, mapped or copied alike. + assert_eq!(copied_state_bytes, state_bytes); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A view of `series` series with the series identity, three label + /// columns and the value. `labels_match`: each label column holds its + /// series' label (`zone` is no label, so `""`); otherwise `job` holds + /// another text. Odd series are no input series (no `__name__`, as a + /// `rate` result): their identities are never interned. + fn labeled_window(end_ms: i64, series: usize, labels_match: bool) -> Batch { + let schema = Arc::new(Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain(PROMQL_SERIES_IDENTITY, DataType::Utf8, false), + Field::plain("job", DataType::Utf8, false), + Field::plain("region", DataType::Utf8, false), + Field::plain("zone", DataType::Utf8, false), + Field::plain("v", DataType::Float64, false), + ], + 0, + vec![], + )); + let rows = (0..series) + .map(|s| { + let mut labels: BTreeMap = [ + ("job".to_string(), format!("job-{}", s % 7)), + ("region".to_string(), format!("region-{}", s % 3)), + ("series".to_string(), format!("series-{s}")), + ] + .into(); + let identity: Arc = if s % 2 == 0 { + labels.insert("__name__".into(), "data".into()); + crate::series_ids::intern_pairs(&labels.iter().collect::>()) + .identity + .clone() + } else { + labels.insert("series".into(), format!("never-interned-{s}")); + serde_json::to_string(&labels).unwrap().into() + }; + let job = if labels_match { + labels["job"].clone() + } else { + format!("other-{}", s % 7) + }; + vec![ + Value::Timestamp(end_ms), + Value::Utf8(identity), + Value::Utf8(job.into()), + Value::Utf8(labels["region"].clone().into()), + Value::Utf8("".into()), + Value::Float64(s as f64), + ] + }) + .collect(); + Batch::try_new(schema, rows).unwrap() + } + + /// A text column holding its series' label is not stored: it reads + /// back, from the active segment and once sealed, from the series + /// identity, saving its 4-byte key per row; a text column that is not + /// its series' label is stored as before. + #[test] + fn label_columns_are_read_back_from_the_series_identity() { + let dir = segment_dir("identity-labels"); + let series = 300; + let (labeled, other) = ( + labeled_window(10, series, true), + labeled_window(10, series, false), + ); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append( + 0, + (0, 10), + &[ + (1, std::slice::from_ref(&labeled)), + (2, std::slice::from_ref(&other)), + ], + ) + .unwrap(); + let (l1, l2) = (location_of(&written, 1), location_of(&written, 2)); + // `job` (other) is stored in view 2 only; `region` and `zone` in + // neither. + // (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")); + } + // A later window with series new to the active segment: the label + // values built for the first read are extended by the new texts. + let later = labeled_window(20, series + 50, true); + let later_written = files + .append(0, (10, 20), &[(1, std::slice::from_ref(&later))]) + .unwrap(); + let l3 = location_of(&later_written, 1); + assert!(!l3.is_sealed()); + let read = l3.read(later.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(&later, &read, "labels, extended values"); + let read = l1.read(labeled.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(&labeled, &read, "labels, first window after the extension"); + files.seal(0).unwrap(); + for how in [ViewRead::Mmap, ViewRead::Pread] { + for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { + let read = location.read(batch.schema(), how).unwrap().0; + assert_same_rows(batch, &read, &format!("{what}, sealed, {how:?}")); + } + } + // After a restart: the segment indexed from its file. + drop((written, l1, l2)); + drop(files); + let view = |id: u64| -> MaterializedView { + serde_json::from_value(serde_json::json!({ + "node_id": id, + "refresh": "at_ingestion", + "coverage": {"definition_id": format!("v{id}"), "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap() + }; + let groups = vec![vec![ + (view(1), labeled.schema().clone()), + (view(2), other.schema().clone()), + ]]; + let index = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .index(&groups) + .unwrap(); + for (id, batch, what) in [(1, &labeled, "labels"), (2, &other, "other")] { + let location = &index[&id][0].1; + let read = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(batch, &read, &format!("{what}, indexed at startup")); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// A segment of an older format version is set aside at startup, not + /// read: its label columns are stored, not rebuilt. + #[test] + fn an_older_format_version_segment_is_set_aside() { + let dir = segment_dir("version"); + let batch = labeled_window(10, 3, true); + let view: MaterializedView = serde_json::from_value(serde_json::json!({ + "node_id": 1, + "refresh": "at_ingestion", + "coverage": {"definition_id": "v", "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap(); + let groups = vec![vec![(view, batch.schema().clone())]]; + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .unwrap(); + let path = location_of(&written, 1).segment_path().to_path_buf(); + drop(written); + drop(files); + // The header frame's payload ends with the version (a MessagePack + // fixint): rewrite it as the previous one. + let mut bytes = std::fs::read(&path).unwrap(); + let header_len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize; + assert_eq!(u32::from(bytes[8 + header_len - 1]), FORMAT_VERSION); + bytes[8 + header_len - 1] = (FORMAT_VERSION - 1) as u8; + std::fs::write(&path, bytes).unwrap(); + let index = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .index(&groups) + .unwrap(); + assert!(index.get(&1).is_none_or(Vec::is_empty)); + assert!(!path.exists()); + let mut stale = path.into_os_string(); + stale.push(".stale"); + assert!(PathBuf::from(stale).exists()); let _ = std::fs::remove_dir_all(&dir); } @@ -1464,9 +1707,9 @@ mod tests { .unwrap(); files.seal(0).unwrap(); let location = location_of(&written, 1); - let before = location.read(batch.schema(), ViewRead::Mmap).unwrap(); + let before = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; std::fs::remove_file(location.segment_path()).unwrap(); - let after = location.read(batch.schema(), ViewRead::Mmap).unwrap(); + let after = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; assert_same_rows(&before, &after, "after unlink"); let _ = std::fs::remove_dir_all(&dir); } @@ -1556,7 +1799,7 @@ mod tests { assert!(!oldest_short.segment_path().exists()); assert!(oldest_long.segment_path().exists()); assert!(files.bytes() < bytes_before); - let read = oldest_long.read(batch.schema(), ViewRead::Mmap).unwrap(); + let read = oldest_long.read(batch.schema(), ViewRead::Mmap).unwrap().0; assert_same_rows(&batch, &read, "the long-retention view's oldest window"); let left: Vec = segment_files(&dir); assert_eq!(left.len(), 5, "short: (60, 80]; long: four segments"); @@ -1600,7 +1843,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(); + 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); } @@ -1648,7 +1891,7 @@ mod tests { for (_, location) in &index[&1] { assert_same_rows( &batch, - &location.read(batch.schema(), ViewRead::Mmap).unwrap(), + &location.read(batch.schema(), ViewRead::Mmap).unwrap().0, "after the cut", ); } @@ -1690,7 +1933,7 @@ mod tests { for (_, location) in &recovered[&1] { assert_same_rows( &batch, - &location.read(batch.schema(), ViewRead::Mmap).unwrap(), + &location.read(batch.schema(), ViewRead::Mmap).unwrap().0, "recovered", ); } diff --git a/data_plane/src/prometheus.rs b/data_plane/src/prometheus.rs index 6bfb29aa..3cc788d7 100644 --- a/data_plane/src/prometheus.rs +++ b/data_plane/src/prometheus.rs @@ -21,31 +21,31 @@ pub struct InstantQuery { /// a time it cannot represent. Leaves room for any window offset. pub(crate) const MAX_TIME_MS: i64 = i64::MAX / 4; -/// Why an instant query's parameters are refused (400, `bad_data`). +/// Why a query's parameters are refused (400, `bad_data`): the error text. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("invalid parameter \"time\": {0}")] -pub(crate) struct BadTime(String); +#[error("{0}")] +pub(crate) struct BadParameter(pub(crate) String); impl InstantQuery { - /// Reads `query` and `time` (Unix seconds). `Ok(None)` if either is - /// missing or `time` is in another format, such as RFC 3339 (the query - /// is then forwarded); `Err` if `time` is a number that is not finite or - /// beyond [`MAX_TIME_MS`]. - pub(crate) fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadTime> { + /// Reads `query` and `time` ([`parse_time_ms`]; empty or missing: + /// now). `Ok(None)` if `query` is missing or `time` is Prometheus' min + /// or max time (the request is then forwarded, or refused without + /// forwarding); `Err` if `time` is not a parsable time or is beyond + /// [`MAX_TIME_MS`]. + pub(crate) fn parse( + url_query: Option<&str>, + form: &[u8], + ) -> Result, BadParameter> { let params: BTreeMap = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes()) .chain(form_urlencoded::parse(form)) .map(|(k, v)| (k.into_owned(), v.into_owned())) .collect(); - let time_ms = match params.get("time") { + let time_ms = match params.get("time").filter(|time| !time.is_empty()) { None => None, - Some(time) => match time.parse::() { - Err(_) => return Ok(None), - Ok(seconds) => Some(checked_seconds_to_ms(seconds).ok_or_else(|| { - BadTime(format!( - "{time} is not a time the data plane can evaluate at" - )) - })?), + Some(time) => match parse_time_ms("time", time)? { + Some(ms) => Some(ms), + None => return Ok(None), }, }; let Some(query) = params.get("query") else { @@ -71,20 +71,19 @@ pub struct RangeQuery { pub step_ms: i64, } -/// Why a range query's parameters are refused (400, `bad_data`). -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("{0}")] -pub(crate) struct BadRange(String); - impl RangeQuery { - /// Reads `query`, `start` and `end` (Unix seconds) and `step` (seconds - /// or a Prometheus duration such as `15s` or `1m30s`). `Ok(None)` if - /// one is missing or a time is in another format, such as RFC 3339 (the - /// query is then forwarded); `Err` if they cannot be evaluated: a time - /// beyond [`MAX_TIME_MS`], a step that is not positive or is beyond - /// [`MAX_TIME_MS`], an end before the start, or more than + /// Reads `query`, `start` and `end` ([`parse_time_ms`]) and `step` + /// (seconds or a Prometheus duration such as `15s` or `1m30s`). + /// `Ok(None)` if one is missing or a time is Prometheus' min or max + /// time (the request is then forwarded, or refused without + /// forwarding); `Err` if they cannot be evaluated: a time that is not + /// parsable or is beyond [`MAX_TIME_MS`], a step that is not positive or + /// is beyond [`MAX_TIME_MS`], an end before the start, or more than /// [`MAX_RANGE_STEPS`] steps. - pub(crate) fn parse(url_query: Option<&str>, form: &[u8]) -> Result, BadRange> { + pub(crate) fn parse( + url_query: Option<&str>, + form: &[u8], + ) -> Result, BadParameter> { let params: BTreeMap = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes()) .chain(form_urlencoded::parse(form)) @@ -98,34 +97,26 @@ impl RangeQuery { ) else { return Ok(None); }; - let time = |name: &str, text: &str| -> Result, BadRange> { - match text.parse::() { - Err(_) => Ok(None), - Ok(seconds) => checked_seconds_to_ms(seconds).map(Some).ok_or_else(|| { - BadRange(format!( - "invalid parameter \"{name}\": {text} is not a time the data plane can evaluate at" - )) - }), - } - }; - let (Some(start_ms), Some(end_ms)) = (time("start", start)?, time("end", end)?) else { + let (Some(start_ms), Some(end_ms)) = + (parse_time_ms("start", start)?, parse_time_ms("end", end)?) + else { return Ok(None); }; let step_ms = step_ms(step) .filter(|&ms| ms > 0 && ms <= MAX_TIME_MS) .ok_or_else(|| { - BadRange(format!( + BadParameter(format!( "invalid parameter \"step\": {step:?} is not a positive duration the data plane can evaluate" )) })?; if end_ms < start_ms { - return Err(BadRange( + return Err(BadParameter( "invalid parameter \"end\": end timestamp must not be before start time".into(), )); } // As Prometheus: refused when (end - start) / step exceeds it. if (end_ms - start_ms) / step_ms > MAX_RANGE_STEPS { - return Err(BadRange(format!( + return Err(BadParameter(format!( "exceeded maximum resolution of {MAX_RANGE_STEPS} points per timeseries. Try decreasing the query resolution (?step=XX)" ))); } @@ -177,10 +168,145 @@ fn step_ms(text: &str) -> Option { (!text.is_empty()).then_some(total) } +/// Prometheus' smallest and largest times, as its clients send them for +/// "no bound" (`v1.MinTime` and `v1.MaxTime` formatted as RFC 3339). +const PROMETHEUS_MIN_TIME: &str = "-292273086-05-16T16:47:06Z"; +const PROMETHEUS_MAX_TIME: &str = "292277025-08-17T07:12:55.999999999Z"; + +/// Query parameter `name`'s time `text` in milliseconds since the epoch, as +/// the Prometheus HTTP API reads it: Unix seconds with an optional fraction +/// (rounded to the millisecond), else RFC 3339 ([`rfc3339_ms`]). `Ok(None)` +/// for Prometheus' min or max time, which the data plane does not evaluate +/// at. `Err` is the 400 error text: Prometheus' for a value in neither +/// form, or a time beyond [`MAX_TIME_MS`]. +pub(crate) fn parse_time_ms(name: &str, text: &str) -> Result, BadParameter> { + if text == PROMETHEUS_MIN_TIME || text == PROMETHEUS_MAX_TIME { + return Ok(None); + } + match text.parse::() { + Ok(seconds) => checked_seconds_to_ms(seconds).map(Some).ok_or_else(|| { + BadParameter(format!( + "invalid parameter \"{name}\": {text} is not a time the data plane can evaluate at" + )) + }), + Err(_) => rfc3339_ms(text).map(Some).ok_or_else(|| { + BadParameter(format!( + "invalid parameter \"{name}\": cannot parse {text:?} to a valid timestamp" + )) + }), + } +} + +/// An RFC 3339 time (`2026-11-24T05:00:00Z`, `2026-11-24T05:00:00.25+01:00`) +/// in milliseconds since the epoch (fraction truncated, as Prometheus +/// truncates a parsed time), as Go's `time.Parse(time.RFC3339Nano, ..)` +/// accepts it: a four-digit year, `T`, a one- or two-digit hour, a fraction +/// of any length after `.` or `,`, and `Z` or a `±hh:mm` offset of at most +/// 24 hours and 60 minutes. +fn rfc3339_ms(text: &str) -> Option { + let bytes = text.as_bytes(); + let mut at = 0; + let year = digits(bytes, &mut at, 4, 4)?; + separator(bytes, &mut at, b'-')?; + let month = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b'-')?; + let day = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b'T')?; + let hour = digits(bytes, &mut at, 1, 2)?; + separator(bytes, &mut at, b':')?; + let minute = digits(bytes, &mut at, 2, 2)?; + separator(bytes, &mut at, b':')?; + let second = digits(bytes, &mut at, 2, 2)?; + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap => 29, + 2 => 28, + _ => return None, + }; + if !(1..=days_in_month).contains(&day) || hour > 23 || minute > 59 || second > 59 { + return None; + } + // Fractional seconds: `.` or `,` and one or more digits, the first + // three kept. + let mut fraction_ms = 0; + if matches!(bytes.get(at), Some(b'.' | b',')) { + let count = bytes[at + 1..] + .iter() + .take_while(|b| b.is_ascii_digit()) + .count(); + if count == 0 { + return None; + } + fraction_ms = bytes[at + 1..at + 1 + count.min(3)] + .iter() + .fold(0, |n, d| n * 10 + i64::from(d - b'0')) + * 10_i64.pow(3 - count.min(3) as u32); + at += 1 + count; + } + let offset_s = match &bytes[at..] { + b"Z" => 0, + [sign @ (b'+' | b'-'), h1, h2, b':', m1, m2] + if [h1, h2, m1, m2].iter().all(|b| b.is_ascii_digit()) => + { + let hours = i64::from((h1 - b'0') * 10 + (h2 - b'0')); + let minutes = i64::from((m1 - b'0') * 10 + (m2 - b'0')); + if hours > 24 || minutes > 60 { + return None; + } + let offset = hours * 3600 + minutes * 60; + if *sign == b'-' { + -offset + } else { + offset + } + } + _ => return None, + }; + // Days since the epoch of the civil date (H. Hinnant's algorithm). + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let year_of_era = y - era * 400; + let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + let days = era * 146_097 + day_of_era - 719_468; + let seconds = days * 86_400 + hour * 3600 + minute * 60 + second - offset_s; + Some(seconds * 1000 + fraction_ms) +} + +/// The number in `min..=max` digits at `*at` of `bytes`, moving `*at` past +/// them. +fn digits(bytes: &[u8], at: &mut usize, min: usize, max: usize) -> Option { + let count = bytes[*at..] + .iter() + .take(max) + .take_while(|b| b.is_ascii_digit()) + .count(); + if count < min { + return None; + } + let value = bytes[*at..*at + count] + .iter() + .fold(0, |n, d| n * 10 + i64::from(d - b'0')); + *at += count; + Some(value) +} + +/// Byte `c` at `*at` of `bytes`, moving `*at` past it. +fn separator(bytes: &[u8], at: &mut usize, c: u8) -> Option<()> { + (bytes.get(*at) == Some(&c)).then(|| *at += 1) +} + /// `seconds` in milliseconds, if finite and within [`MAX_TIME_MS`]. +/// As Prometheus: the whole seconds, plus the fraction rounded to the +/// millisecond (which keeps a sub-millisecond fraction exact at large +/// times, where `seconds * 1000` would not). fn checked_seconds_to_ms(seconds: f64) -> Option { - let ms = (seconds * 1000.0).round(); - (ms.is_finite() && ms.abs() <= MAX_TIME_MS as f64).then_some(ms as i64) + if !seconds.is_finite() || seconds.abs() > (MAX_TIME_MS / 1000) as f64 { + return None; + } + Some(seconds.trunc() as i64 * 1000 + (seconds.fract() * 1000.0).round() as i64) } /// A Prometheus `bad_data` error response body. @@ -406,7 +532,8 @@ mod tests { use super::*; use std::sync::Arc; - /// Parameters come from the URL or the form body; times are Unix seconds. + /// Parameters come from the URL or the form body; `time` is Unix + /// seconds or RFC 3339, an empty one is now. #[test] fn parses_instant_query_parameters() { let q = InstantQuery::parse(Some("query=up&time=1.5"), b"") @@ -418,11 +545,20 @@ mod tests { .unwrap(); assert_eq!((q.query.as_str(), q.time_ms), ("sum(x)", None)); assert!(InstantQuery::parse(Some("time=1"), b"").unwrap().is_none()); - assert!( - InstantQuery::parse(Some("query=up&time=2026-01-01T00:00:00Z"), b"") - .unwrap() - .is_none() - ); + let q = InstantQuery::parse(Some("query=up&time=2026-01-01T00:00:00Z"), b"") + .unwrap() + .unwrap(); + assert_eq!(q.time_ms, Some(1_767_225_600_000)); + assert!(InstantQuery::parse(Some("query=up&time=tomorrow"), b"").is_err()); + let q = InstantQuery::parse(Some("query=up&time="), b"") + .unwrap() + .unwrap(); + assert_eq!(q.time_ms, None); + // Prometheus' min and max times: forwarded. + for time in [PROMETHEUS_MIN_TIME, PROMETHEUS_MAX_TIME] { + let url = format!("query=up&time={time}"); + assert!(InstantQuery::parse(Some(&url), b"").unwrap().is_none()); + } for time in ["-1e300", "1e300", "NaN", "inf"] { let url = format!("query=up&time={time}"); assert!(InstantQuery::parse(Some(&url), b"").is_err(), "{time}"); @@ -455,12 +591,13 @@ mod tests { assert!(RangeQuery::parse(Some("query=up&start=0&end=60"), b"") .unwrap() .is_none()); - assert!(RangeQuery::parse( - Some("query=up&start=2026-01-01T00:00:00Z&end=1&step=1"), - b"" + let q = RangeQuery::parse( + Some("query=up&start=1970-01-01T00:00:01Z&end=2&step=1"), + b"", ) .unwrap() - .is_none()); + .unwrap(); + assert_eq!((q.start_ms, q.end_ms), (1_000, 2_000)); for bad in [ "query=up&start=0&end=60&step=0", "query=up&start=0&end=60&step=x", @@ -474,6 +611,59 @@ mod tests { } } + /// RFC 3339 times as Go's `time.Parse(time.RFC3339Nano, ..)` accepts + /// them, in milliseconds since the epoch (fractions truncated, as + /// Prometheus truncates a parsed time to the millisecond). + #[test] + fn parses_rfc3339_times() { + for (text, ms) in [ + ("1970-01-01T00:00:00Z", 0), + ("2026-11-24T05:00:00Z", 1_795_496_400_000), + ("2026-11-24T05:00:00.5Z", 1_795_496_400_500), + ("2026-11-24T05:00:00.123456789Z", 1_795_496_400_123), + ("2026-11-24T06:30:00+01:30", 1_795_496_400_000), + ("2026-11-24T00:00:00-05:00", 1_795_496_400_000), + ("2024-02-29T00:00:00Z", 1_709_164_800_000), + ("1969-12-31T23:59:59.999Z", -1), + ("0001-01-01T00:00:00Z", -62_135_596_800_000), + // Go's lenient forms: a long fraction, a comma, a one-digit + // hour, a 24-hour offset. + ("2026-11-24T05:00:00.1234567890123Z", 1_795_496_400_123), + ("2026-11-24T05:00:00,5Z", 1_795_496_400_500), + ("2026-11-24T5:00:00Z", 1_795_496_400_000), + ("2026-11-25T05:00:00+24:00", 1_795_496_400_000), + ] { + assert_eq!(rfc3339_ms(text), Some(ms), "{text}"); + } + for text in [ + "2026-11-24T05:00:00", + "2026-11-24t05:00:00Z", + "2026-11-24 05:00:00Z", + "2026-11-24T05:00:00.Z", + "2026-11-24T05:00Z", + "2023-02-29T00:00:00Z", + "2026-04-31T00:00:00Z", + "2026-11-24T05:00:60Z", + "2026-11-24T05:00:00+0100", + "2026-11-24T05:00:00+25:00", + "2026-11-24T05:00:00+01:61", + "+2026-11-24T05:00:00Z", + "2026-11-24T05:00:00Z ", + ] { + assert_eq!(rfc3339_ms(text), None, "{text}"); + } + assert_eq!( + parse_time_ms("time", "x").unwrap_err().0, + "invalid parameter \"time\": cannot parse \"x\" to a valid timestamp" + ); + assert_eq!(parse_time_ms("end", "1.0015"), Ok(Some(1_002))); + // The fraction rounded on its own, as Prometheus rounds it. + assert_eq!( + parse_time_ms("time", "1763408220.0665"), + Ok(Some(1_763_408_220_066)) + ); + } + /// Range results use Prometheus' matrix shape: one entry per series /// with its values in time order. #[test] diff --git a/data_plane/src/segment.rs b/data_plane/src/segment.rs index 1ab888c8..44682f5d 100644 --- a/data_plane/src/segment.rs +++ b/data_plane/src/segment.rs @@ -3,34 +3,39 @@ //! //! 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. - -use std::collections::HashMap; +//! 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; use std::path::{Path, PathBuf}; use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, RwLock}; +use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak}; use asap_executor::arrow::array::{ - Array, ArrayRef, DictionaryArray, PrimitiveArray, StringArray, UInt32Array, + Array, ArrayRef, DictionaryArray, PrimitiveArray, StringArray, StringBuilder, UInt32Array, }; use asap_executor::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, ScalarBuffer}; use asap_executor::arrow::datatypes::{ ArrowPrimitiveType, DataType as ArrowType, Float64Type, Int64Type, TimeUnit, TimestampMillisecondType, UInt32Type, }; -use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema}; +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, @@ -39,9 +44,13 @@ use asap_executor::Error; 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 = 2; +pub const FORMAT_VERSION: u32 = 4; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -51,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; @@ -59,20 +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, clap::ValueEnum)] 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. @@ -175,6 +196,12 @@ pub struct Segment { /// The texts as one Arrow array, shared by every window read from the /// segment; rebuilt when texts were added since. dictionary: Mutex>, + /// Every text dictionary built, the current one and those a window + /// read before a rebuild may still hold, to count each live one once. + dictionaries_built: Mutex>>, + /// What [`IDENTITY_LABEL`] columns read from the segment are built + /// from ([`Segment::label_values`]). + identity_label_values: Mutex, /// The newest window end of its records. max_end_ms: AtomicI64, } @@ -251,6 +278,8 @@ impl Segment { mapping: OnceLock::new(), texts: RwLock::new(Vec::new()), dictionary: Mutex::new(None), + dictionaries_built: Mutex::default(), + identity_label_values: Mutex::default(), max_end_ms: AtomicI64::new(i64::MIN), })) } @@ -348,6 +377,8 @@ impl Segment { mapping: OnceLock::new(), texts: RwLock::new(texts), dictionary: Mutex::new(None), + dictionaries_built: Mutex::default(), + identity_label_values: Mutex::default(), max_end_ms: AtomicI64::new(max_end_ms), }), heads, @@ -493,6 +524,24 @@ impl Segment { .map_err(|e| Error::Invalid(format!("mapping {}: {e}", self.path.display()))) } + /// Bytes of its text dictionaries still in memory (the texts, and the + /// label values of [`IDENTITY_LABEL`] columns): each is one array + /// shared by the windows read from the segment while it was current, + /// so it is counted once for the segment. Several of one kind only + /// while the active segment's texts grew under a window still held. + pub(crate) fn dictionary_bytes(&self) -> usize { + let mut built = self + .dictionaries_built + .lock() + .unwrap_or_else(|e| e.into_inner()); + built.retain(|dictionary| dictionary.strong_count() > 0); + built + .iter() + .filter_map(Weak::upgrade) + .map(|dictionary| dictionary.get_array_memory_size()) + .sum() + } + /// The texts with keys below `needed`, as one array shared by the /// windows read from the segment. fn dictionary(&self, needed: usize) -> Result { @@ -509,10 +558,97 @@ impl Segment { } let values: ArrayRef = Arc::new(StringArray::from_iter_values(texts.iter().map(|t| &**t))); *dictionary = Some(values.clone()); + self.dictionaries_built + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arc::downgrade(&values)); + Ok(values) + } +} + +/// Per label name, one value per segment text: that label of the text +/// taken as a series identity (`""` without it, or for a text that is no +/// identity). The dictionary of every [`IDENTITY_LABEL`] column of that +/// name, indexed by the rows' identity keys. +#[derive(Default)] +struct IdentityLabelValues { + values_by_label: HashMap, +} + +impl Segment { + /// The values of `label` for the texts with keys below `needed` taken + /// as series identities, as one array shared by the windows read from + /// the segment ([`IdentityLabelValues`]); extended by the texts added + /// since it was built, each parsed once per label. + fn label_values(&self, label: &str, needed: usize) -> Result { + let mut identity = self + .identity_label_values + .lock() + .unwrap_or_else(|e| e.into_inner()); + let built = identity.values_by_label.get(label).cloned(); + if let Some(values) = built.as_ref().filter(|v| v.len() >= needed) { + return Ok(values.clone()); + } + let built_len = built.as_ref().map_or(0, |values| values.len()); + // The texts added since, copied out so appends do not wait for + // their parsing. + let added: Vec> = { + let texts = self.texts.read().unwrap_or_else(|e| e.into_inner()); + if texts.len() < needed { + return Err(Error::Invalid(format!( + "{}: a text key past the segment's texts", + self.path.display() + ))); + } + texts[built_len..].to_vec() + }; + let built = built + .as_ref() + .map(|values| values.as_any().downcast_ref::()) + .unwrap_or_default(); + let added: Vec = added + .iter() + .map(|text| { + parse_identity(text) + .and_then(|labels| labels.get(label).cloned()) + .unwrap_or_default() + }) + .collect(); + let mut builder = StringBuilder::with_capacity( + built_len + added.len(), + built.map_or(0, |built| built.value_data().len()) + + added.iter().map(String::len).sum::(), + ); + for value in built.into_iter().flat_map(|built| built.iter()) { + builder.append_value(value.unwrap_or_default()); + } + for value in &added { + builder.append_value(value); + } + let values: ArrayRef = Arc::new(builder.finish()); + identity + .values_by_label + .insert(label.to_string(), values.clone()); + self.dictionaries_built + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arc::downgrade(&values)); Ok(values) } } +/// The labels of the series whose identity text is `text`: an interned +/// series' own, else parsed (and not kept); `None` for a text that is no +/// label set's JSON. The labels the writer's `labels_of_identity` gives, +/// without its process-wide cache (a segment's texts outlive no reader). +fn parse_identity(text: &str) -> Option>> { + match crate::series_ids::by_identity(text) { + Some(series) => Some(series.labels().clone()), + None if text.starts_with('{') => serde_json::from_str(text).ok().map(Arc::new), + None => None, + } +} + /// The head of a record frame's payload. fn record_head(payload: &[u8]) -> Option { let n = payload.len(); @@ -530,21 +666,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, } } } @@ -592,18 +724,6 @@ impl WindowLocation { self.segment.is_cold() } - /// Whether `address` lies inside its segment's mapping. - #[cfg(test)] - pub(crate) 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; @@ -633,19 +753,19 @@ 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`. - pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result { + /// 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() } else { @@ -660,8 +780,18 @@ 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. + pub(crate) fn segment(&self) -> &Arc { + &self.segment } /// The fragment's length, for counting bytes read. @@ -678,8 +808,15 @@ pub(crate) struct SegmentTexts<'a> { pub base: u32, pub new: Vec>, pub new_index: HashMap, u32>, + /// The labels of each series identity the segment's records held, by + /// identity text: looked up in the interner once per segment, not once + /// per row of every window. + pub labels_by_identity: &'a mut LabelsByIdentity, } +/// Per series identity text, its labels (`None`: no label set's JSON). +pub(crate) type LabelsByIdentity = HashMap, Option>>>; + impl SegmentTexts<'_> { fn key(&mut self, text: &Arc) -> u32 { if let Some(&key) = self.known.get(text).or_else(|| self.new_index.get(text)) { @@ -691,6 +828,18 @@ impl SegmentTexts<'_> { key } + /// The labels of the series whose identity text is `identity` + /// ([`labels_of_identity`]), cached for the segment. + fn identity_labels(&mut self, identity: &Arc) -> Option>> { + if let Some(labels) = self.labels_by_identity.get(identity) { + return labels.clone(); + } + let labels = labels_of_identity(identity); + self.labels_by_identity + .insert(identity.clone(), labels.clone()); + labels + } + /// Drops the new texts after the first `mark` (a fragment left out). pub fn forget_after(&mut self, mark: usize) { for text in self.new.drain(mark..) { @@ -721,8 +870,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], @@ -735,6 +884,7 @@ pub(crate) fn encode_fragment( out.extend_from_slice(&(columns as u32).to_le_bytes()); let descriptors_at = out.len(); out.resize(descriptors_at + columns * DESCRIPTOR_BYTES, 0); + let identity_labels = IdentityLabels::of(schema, rows, texts); for (column, field) in schema.fields.iter().enumerate() { let values = rows.iter().map(|row| &row[column]); let nulls: Vec = rows @@ -744,17 +894,46 @@ pub(crate) fn encode_fragment( // The second section: the validity bitmap, or a mapped state // column's states. let mut second: Option> = None; + // The identity column, when this column holds its series' label. + let label_of_identity_column = identity_labels + .as_ref() + .filter(|labels| { + field.dtype == FieldDataType::Plain(DataType::Utf8) + && labels.holds_label(rows, column, &field.name) + }) + .map(|labels| labels.column as u32); + // 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 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) + 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); @@ -799,8 +978,12 @@ pub(crate) fn encode_fragment( let values: Vec<&Value> = values.collect(); (GENERIC, 0, rmp_serde::to_vec(&values).ok()?) } - family if family_has_mapped_form(family) && mapped_states(rows, column).is_some() => { - let (offsets, states) = mapped_states(rows, column).expect("checked"); + _ 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) } @@ -825,7 +1008,7 @@ pub(crate) fn encode_fragment( 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), }; @@ -846,8 +1029,77 @@ 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 +/// telling which text columns are its labels ([`IDENTITY_LABEL`]). +struct IdentityLabels { + /// The series identity column's index. + column: usize, + /// Each row's labels; `None` when a row's identity is none. + by_row: Vec>>>, +} + +impl IdentityLabels { + /// `None` when there are no rows, or `schema` has no series identity + /// text column or no other text column. + fn of(schema: &Schema, rows: &[Vec], texts: &mut SegmentTexts) -> Option { + if rows.is_empty() { + return None; + } + let is_text = |dtype: &FieldDataType| *dtype == FieldDataType::Plain(DataType::Utf8); + let column = schema + .fields + .iter() + .position(|field| field.name == PROMQL_SERIES_IDENTITY && is_text(&field.dtype))?; + if !schema + .fields + .iter() + .enumerate() + .any(|(index, field)| index != column && is_text(&field.dtype)) + { + return None; + } + let by_row = rows + .iter() + .map(|row| match &row[column] { + Value::Utf8(identity) => texts.identity_labels(identity), + _ => None, + }) + .collect(); + Some(Self { column, by_row }) + } + + /// Whether every row's `column` is its series' label `name` (`""` + /// without it), so the column need not be stored. + fn holds_label(&self, rows: &[Vec], column: usize, name: &str) -> bool { + column != self.column + && rows + .iter() + .zip(&self.by_row) + .all(|(row, labels)| match (&row[column], labels) { + (Value::Utf8(text), Some(labels)) => { + **text == *labels.get(name).map_or("", String::as_str) + } + _ => false, + }) + } } /// Column `column` of `rows` in the executor's mapped state layout: the @@ -883,36 +1135,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, @@ -924,14 +1214,44 @@ fn primitive( PrimitiveArray::::try_new(values, nulls).map_err(|e| Error::Invalid(e.to_string())) } -/// The fragment in `source` as one batch of `schema`. +/// One column's descriptor in a fragment: its kind and flags, and its data +/// and second sections (offset and length, inside the fragment). +struct Descriptor { + kind: u32, + flags: u32, + data: (usize, usize), + valid: (usize, usize), +} + +/// Column `column`'s descriptor in fragment `bytes`; damaged when a +/// section lies past the fragment's end. +fn descriptor(bytes: &[u8], column: usize) -> Result { + let at = 8 + column * DESCRIPTOR_BYTES; + let kind_flags = word(bytes, at)?; + let section = |at: usize| -> Result<(usize, usize), Error> { + let (offset, len) = (word(bytes, at)? as usize, word(bytes, at + 8)? as usize); + if offset.checked_add(len).is_none_or(|end| end > bytes.len()) { + return Err(damaged()); + } + Ok((offset, len)) + }; + Ok(Descriptor { + kind: (kind_flags & 0xffff_ffff) as u32, + flags: (kind_flags >> 32) as u32, + data: section(at + 8)?, + valid: section(at + 24)?, + }) +} + +/// 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 { - let bytes = source.slice(); +) -> Result<(Batch, usize), Error> { + let mut state_bytes = 0; let header = word(bytes, 0)?; let rows = (header & 0xffff_ffff) as usize; let columns = (header >> 32) as usize; @@ -947,30 +1267,17 @@ 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); + // 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 at = 8 + column * DESCRIPTOR_BYTES; - let kind_flags = word(bytes, at)?; - let (kind, flags) = ((kind_flags & 0xffff_ffff) as u32, (kind_flags >> 32) as u32); - let data = ( - word(bytes, at + 8)? as usize, - word(bytes, at + 16)? as usize, - ); - let valid = ( - word(bytes, at + 24)? as usize, - word(bytes, at + 32)? as usize, - ); - if data - .0 - .checked_add(data.1) - .is_none_or(|end| end > bytes.len()) - || valid - .0 - .checked_add(valid.1) - .is_none_or(|end| end > bytes.len()) - { - return Err(damaged()); - } - let nulls = if valid.1 == 0 || kind == MAPPED_STATES { + let Descriptor { + kind, + flags, + data, + valid, + } = descriptor(bytes, column)?; + let nulls = if valid.1 == 0 || kind == MAPPED_STATES || kind == COMPACT_STATES { None } else { if valid.1 != rows.div_ceil(8) { @@ -982,16 +1289,57 @@ 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) .map_err(|e| Error::Invalid(e.to_string()))?, ) } - FLOAT64 => Arc::new(primitive::(source, data, rows, nulls)?), - INT64 => Arc::new(primitive::(source, data, rows, nulls)?), + IDENTITY_LABEL => { + // The identity column's keys, as this column's keys into + // the label's values by text. + let identity_column = flags as usize; + if identity_column >= columns { + return Err(damaged()); + } + let identity = descriptor(bytes, identity_column)?; + if identity.kind != TEXT || identity.valid.1 != 0 || data.1 != 0 || valid.1 != 0 { + return Err(damaged()); + } + // 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( + DictionaryArray::::try_new(keys, values) + .map_err(|e| Error::Invalid(e.to_string()))?, + ) + } + 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()); @@ -1003,7 +1351,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]) @@ -1013,15 +1361,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()); } - 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, @@ -1095,7 +1460,7 @@ fn decode_fragment( } out.push(BatchColumn::Plain(array)); } - Batch::try_from_columns(schema.clone(), out) + Ok((Batch::try_from_columns(schema.clone(), out)?, state_bytes)) } /// `rows` of one column `field` built by the executor: its array, and its @@ -1148,14 +1513,8 @@ mod tests { bytes.extend_from_slice(&word.to_le_bytes()); } bytes.extend_from_slice(&10i64.to_le_bytes()); - let len = bytes.len(); - let mut words = vec![0u64; len.div_ceil(8)]; - // SAFETY: `words` is at least `len` writable bytes. - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), words.as_mut_ptr().cast::(), len) - }; let segment = Segment::create_new(&dir, 20, &header).unwrap(); - assert!(decode_fragment(&Bytes::Owned(words, len), &schema, &segment, &[]).is_err()); + assert!(decode_fragment(&bytes, &schema, &segment, &[]).is_err()); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/data_plane/src/series_ids.rs b/data_plane/src/series_ids.rs index 0c221b71..ab7c0ae8 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -197,3 +197,13 @@ pub fn result_labels(identity: &str) -> Result { .or_insert(labels) .clone()) } + +/// The labels of the series whose identity text is `identity`: an +/// interned series' own (no parse), else parsed once ([`result_labels`]); +/// `None` when `identity` is not a label set's JSON. +pub fn labels_of_identity(identity: &str) -> Option>> { + match by_identity(identity) { + Some(series) => Some(series.labels().clone()), + None => result_labels(identity).ok(), + } +} 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 97e649ff..3b109952 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -757,9 +757,10 @@ enum SlotState { pub struct WindowSlot { key: WindowKey, schema: SchemaRef, - /// Its rows' bytes when decoded, counted when appended (a run that + /// Its charge when appended ([`window_batch_bytes`]: its buffers and + /// states, less the view's shared texts), kept although a run that /// later reads its states marks them held outside the run, after which - /// [`Batch::memory_bytes`] no longer counts them). + /// [`Batch::memory_bytes`] no longer counts them. bytes: u64, /// Its state, and whether the window left the store (past retention). state: Mutex<(SlotState, bool)>, @@ -826,14 +827,6 @@ impl WindowSlot { } } - /// Bytes held in memory outside the cache: `Pending` and `Pinned`. - fn heap_bytes(&self) -> u64 { - match self.lock().0 { - SlotState::Pending(_) | SlotState::Pinned(_) => self.bytes, - SlotState::Stored(_) => 0, - } - } - /// The window's batches: from memory, the cache, or its fragment. fn batches(&self) -> Result>, Error> { let location = match &self.lock().0 { @@ -850,17 +843,18 @@ impl WindowSlot { std::thread::sleep(tier.decode_delay); } let timer = Timer::start(); - let batch = location.read(&self.schema, tier.read).map_err(|error| { - Error::Invalid(format!( - "materialized view {} window ending {}: {error}", - self.key.view, self.key.end_ms - )) - })?; + let (batch, state_bytes) = + location.read(&self.schema, tier.read).map_err(|error| { + Error::Invalid(format!( + "materialized view {} window ending {}: {error}", + self.key.view, self.key.end_ms + )) + })?; tier.decode.record(timer); tier.cold_reads.fetch_add(1, Ordering::Relaxed); tier.cold_read_bytes .fetch_add(location.read_bytes(), Ordering::Relaxed); - let bytes = batch.memory_bytes() as u64; + let bytes = (window_batch_bytes(&batch) + state_bytes) as u64; Ok((Arc::new(vec![batch]), bytes)) }) } @@ -1235,9 +1229,12 @@ impl ViewStore { .map(|window| window.time_range_ms.1) } - /// Bytes of the stored rows: each window as counted when it was - /// appended (states included, whether or not a run has read them - /// since), plus each view's shared texts once. + /// Bytes of the stored rows: each window in memory as counted when it + /// was appended (states included, whether or not a run has read them + /// since), each cached window as the cache charges it, each view's + /// shared texts once, and each live text dictionary of the segments + /// holding stored windows once (built when one of their windows is read + /// back). pub fn bytes(&self) -> usize { let windows: usize = match &self.tier { None => self @@ -1247,13 +1244,22 @@ impl ViewStore { .map(|window| window.slot.bytes as usize) .sum(), Some(tier) => { - let heap: u64 = self - .by_view - .values() - .flatten() - .map(|window| window.slot.heap_bytes()) - .sum(); - (heap + tier.cache.stats().bytes) as usize + let mut pending_and_pinned_bytes = 0; + let mut dictionary_bytes = 0; + let mut segments_counted = BTreeSet::new(); + for window in self.by_view.values().flatten() { + match &window.slot.lock().0 { + SlotState::Pending(_) | SlotState::Pinned(_) => { + pending_and_pinned_bytes += window.slot.bytes as usize + } + SlotState::Stored(location) => { + if segments_counted.insert(Arc::as_ptr(location.segment())) { + dictionary_bytes += location.segment().dictionary_bytes(); + } + } + } + } + pending_and_pinned_bytes + dictionary_bytes + tier.cache.stats().bytes as usize } }; let texts: usize = self @@ -1338,9 +1344,13 @@ impl ViewStore { } } -/// A stored window batch's bytes apart from its shared texts: its own -/// buffers and states ([`Batch::memory_bytes`]) less each text column's -/// values array, which the view's [`SharedTexts`] counts once. +/// A window batch's bytes apart from its shared texts: its own buffers and +/// states ([`Batch::memory_bytes`]) less each text column's values array, +/// which is shared and counted once by its owner: the view's +/// [`SharedTexts`] for a window as appended, its segment's dictionary for +/// a window read back from its file. A window's cache charge both when +/// appended and when read back (plus, read back, its mapped state columns: +/// [`WindowLocation::read`]). fn window_batch_bytes(batch: &Batch) -> usize { let shared: usize = (0..batch.schema().fields.len()) .filter(|&index| batch.state_column(index).is_none()) diff --git a/data_plane/tests/time_params.rs b/data_plane/tests/time_params.rs new file mode 100644 index 00000000..8d4fb245 --- /dev/null +++ b/data_plane/tests/time_params.rs @@ -0,0 +1,253 @@ +//! Query times as the Prometheus HTTP API takes them: `time`, `start` and +//! `end` are Unix seconds (with an optional fraction) or RFC 3339 (with +//! optional fractional seconds and a zone offset), as vmalert sends them. +//! A planned query is answered from the plan in either form, with the same +//! answer; a time in neither form is refused with Prometheus' 400. + +mod common; + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use axum::Router; +use control_plane::plan_workload; +use data_plane::engine::EngineOptions; +use data_plane::ingestion::IngestionOptions; +use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; +use data_plane::{router, DataPlane, EXECUTION_HEADER}; +use http_body_util::BodyExt; +use serde_json::{json, Value}; +use tower::ServiceExt; + +const SUM: &str = "sum(sum_over_time(data[1m]))"; +const SERIES: usize = 5; + +/// The plan of `SUM` every 10 s over `SERIES` series of `data`; with +/// `no_forward`, a query the data plane does not answer from the plan is +/// refused instead of forwarded. +fn data_plane() -> Router { + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": SUM, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": SERIES as f64}}, + "sources": {"data": {"series_count": SERIES, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; + let options = EngineOptions { + no_forward: true, + view_dir: None, + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + }; + let state = DataPlane::with_options( + serde_json::to_string(&plan).unwrap(), + "http://127.0.0.1:1".into(), + options, + ) + .unwrap(); + router(Arc::new(state)) +} + +/// One sample per second in `(0, to_s]` for every series, then a barrier +/// closing every window through `to_s`. +async fn write(app: &Router, to_s: i64) { + let timeseries = (0..SERIES) + .map(|series| TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "data".into(), + }, + Label { + name: "instance".into(), + value: format!("i{series}"), + }, + ], + samples: (1..=to_s) + .map(|s| Sample { + timestamp: s * 1000, + value: (s + series as i64) as f64, + }) + .collect(), + }) + .collect(); + let written = app + .clone() + .oneshot( + Request::post("/api/v1/write") + .body(Body::from(encode(&WriteRequest { timeseries }))) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(written.status(), StatusCode::NO_CONTENT); + let barrier = app + .clone() + .oneshot( + Request::post(format!( + "/api/v1/precompute/watermark?time_ms={}", + to_s * 1000 + )) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(barrier.status(), StatusCode::OK); +} + +/// `endpoint`'s response to `SUM` with `params` (URL-encoded here): its +/// status, whether the plan answered it, and its body. +async fn get(app: &Router, endpoint: &str, params: &[(&str, &str)]) -> (StatusCode, bool, Value) { + let mut query = form_urlencoded::Serializer::new(String::new()); + query.append_pair("query", SUM); + for (name, value) in params { + query.append_pair(name, value); + } + let response = app + .clone() + .oneshot( + Request::get(format!("/api/v1/{endpoint}?{}", query.finish())) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let from_plan = response + .headers() + .get(EXECUTION_HEADER) + .is_some_and(|value| value == "plan"); + let body = response.into_body().collect().await.unwrap().to_bytes(); + (status, from_plan, serde_json::from_slice(&body).unwrap()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn rfc3339_times_are_answered_from_the_plan_like_unix_seconds() { + let app = data_plane(); + write(&app, 180).await; + + // Instant: 120 s after the epoch, in each form. + let (status, from_plan, expected) = get(&app, "query", &[("time", "120")]).await; + assert_eq!((status, from_plan), (StatusCode::OK, true), "{expected}"); + assert_eq!(expected["data"]["result"].as_array().unwrap().len(), 1); + for time in [ + "120.000", + "1970-01-01T00:02:00Z", + "1970-01-01T00:02:00.000Z", + "1970-01-01T00:02:00.000000000Z", + "1970-01-01T01:02:00+01:00", + "1969-12-31T23:32:00-00:30", + ] { + let (status, from_plan, served) = get(&app, "query", &[("time", time)]).await; + assert_eq!( + (status, from_plan), + (StatusCode::OK, true), + "{time}: {served}" + ); + assert_eq!(served, expected, "{time}"); + } + + // Range: 150 s to 180 s (inside the views' retention) every 10 s, in each form. + let (status, from_plan, expected) = get( + &app, + "query_range", + &[("start", "150"), ("end", "180"), ("step", "10")], + ) + .await; + assert_eq!((status, from_plan), (StatusCode::OK, true), "{expected}"); + for (start, end) in [ + ("1970-01-01T00:02:30Z", "1970-01-01T00:03:00Z"), + ("1970-01-01T00:02:30.0Z", "180"), + ("150", "1970-01-01T05:33:00+05:30"), + ] { + let (status, from_plan, served) = get( + &app, + "query_range", + &[("start", start), ("end", end), ("step", "10")], + ) + .await; + assert_eq!( + (status, from_plan), + (StatusCode::OK, true), + "{start}..{end}: {served}" + ); + assert_eq!(served, expected, "{start}..{end}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn times_in_neither_form_are_refused_as_prometheus_refuses_them() { + let app = data_plane(); + write(&app, 60).await; + for bad in [ + "yesterday", + "1970-01-01T00:02:00", + "1970-01-01 00:02:00Z", + "1970-13-01T00:00:00Z", + "1970-02-30T00:00:00Z", + "1970-01-01T24:00:00Z", + "1970-01-01T00:02:00+25:00", + "70-01-01T00:02:00Z", + "1970-01-01T00:02:00.Z", + ] { + let (status, _, body) = get(&app, "query", &[("time", bad)]).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{bad:?}: {body}"); + assert_eq!( + body, + json!({"status": "error", "errorType": "bad_data", + "error": format!("invalid parameter \"time\": cannot parse {bad:?} to a valid timestamp")}), + ); + for name in ["start", "end"] { + let mut params = vec![("start", "0"), ("end", "60"), ("step", "10")]; + params.retain(|(n, _)| *n != name); + params.push((name, bad)); + let (status, _, body) = get(&app, "query_range", ¶ms).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name}={bad:?}: {body}"); + assert_eq!( + body["error"], + format!("invalid parameter \"{name}\": cannot parse {bad:?} to a valid timestamp"), + ); + } + } + // An empty `start` or `end` is refused too; an empty `time` is now. + for name in ["start", "end"] { + let mut params = vec![("start", "0"), ("end", "60"), ("step", "10")]; + params.retain(|(n, _)| *n != name); + params.push((name, "")); + let (status, _, body) = get(&app, "query_range", ¶ms).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{name}=\"\": {body}"); + } + let (status, _, body) = get(&app, "query", &[("time", "")]).await; + assert_ne!(status, StatusCode::BAD_REQUEST, "time=\"\": {body}"); +} + +/// Prometheus' min and max times ("no bound") are valid times the plan +/// does not evaluate at: forwarded, so refused here without forwarding, +/// not rejected as unparsable. +#[tokio::test(flavor = "multi_thread")] +async fn prometheus_min_and_max_times_are_not_answered_from_the_plan() { + let app = data_plane(); + write(&app, 60).await; + for time in [ + "-292273086-05-16T16:47:06Z", + "292277025-08-17T07:12:55.999999999Z", + ] { + let (status, from_plan, body) = get(&app, "query", &[("time", time)]).await; + assert!( + status != StatusCode::BAD_REQUEST && !from_plan, + "{time}: {status} {body}" + ); + } +} diff --git a/data_plane/tests/view_cache_charge.rs b/data_plane/tests/view_cache_charge.rs new file mode 100644 index 00000000..556815a3 --- /dev/null +++ b/data_plane/tests/view_cache_charge.rs @@ -0,0 +1,247 @@ +//! A view window read back from its file is charged to the window cache +//! what it holds in memory, the same as when it was written: its own +//! columns and states, not the segment's text dictionary its text columns +//! share with every other window of the segment. That dictionary is +//! counted once per segment in the view bytes, as is each older one a +//! window still holds after the active segment's dictionary grew. +//! Measured with a counting global allocator (one test per binary, so no +//! other test allocates). + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use asap_executor::planner::ir::schema::{DataType, Field, Schema, PROMQL_SERIES_IDENTITY}; +use asap_executor::planner::plan::materialized_view::MaterializedView; +use asap_executor::values::{Batch, Value}; +use data_plane::persist::{ViewFiles, ViewRead}; +use data_plane::store::{ViewStore, ViewTier}; +use data_plane::window_cache::{WindowCache, WindowKey}; + +/// Counts the bytes allocated now. +struct Counting; + +static CURRENT: AtomicUsize = AtomicUsize::new(0); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let ptr = unsafe { System.alloc(layout) }; + if !ptr.is_null() { + CURRENT.fetch_add(layout.size(), Ordering::Relaxed); + } + ptr + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + CURRENT.fetch_sub(layout.size(), Ordering::Relaxed); + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + let new = unsafe { System.realloc(ptr, layout, new_size) }; + if !new.is_null() { + CURRENT.fetch_add(new_size, Ordering::Relaxed); + CURRENT.fetch_sub(layout.size(), Ordering::Relaxed); + } + new + } +} + +#[global_allocator] +static ALLOCATOR: Counting = Counting; + +const SERIES: usize = 2_000; +const WINDOWS: i64 = 8; +const WIDTH_MS: i64 = 1_000; +const VIEW: usize = 1; + +/// A per-series exact view of `data` carrying three labels, as the demo's +/// 1 s views: the series identity and `job`, `region`, `service` as text +/// columns, and the value. +fn schema() -> Arc { + Arc::new(Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain(PROMQL_SERIES_IDENTITY, DataType::Utf8, false), + Field::plain("job", DataType::Utf8, false), + Field::plain("region", DataType::Utf8, false), + Field::plain("service", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ], + 0, + vec![], + )) +} + +/// `series` series of the view's window ending `end_ms`. +fn window(end_ms: i64, series: usize) -> Batch { + let rows = (0..series) + .map(|s| { + let (job, region, service) = (s % 200, s % 4, s % 20); + vec![ + Value::Timestamp(end_ms), + Value::Utf8( + format!( + r#"{{"__name__":"data","job":"job-{job}","region":"region-{region}","series":"series-{s}","service":"service-{service}"}}"# + ) + .into(), + ), + Value::Utf8(format!("job-{job}").into()), + Value::Utf8(format!("region-{region}").into()), + Value::Utf8(format!("service-{service}").into()), + Value::Float64(s as f64 + end_ms as f64), + ] + }) + .collect(); + Batch::try_new(schema(), rows).unwrap() +} + +fn view() -> MaterializedView { + serde_json::from_value(serde_json::json!({ + "node_id": VIEW, + "refresh": "on_first_read", + "coverage": {"definition_id": "test-view", "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap() +} + +/// The heap bytes `read` leaves allocated, and how much the view bytes +/// grew over it. +fn held_by(views: &ViewStore, read: impl FnOnce()) -> (usize, usize) { + let view_bytes_before = views.bytes(); + let heap_before = CURRENT.load(Ordering::Relaxed); + read(); + let heap_held = CURRENT.load(Ordering::Relaxed).saturating_sub(heap_before); + (heap_held, views.bytes() - view_bytes_before) +} + +fn assert_close(what: &str, a: u64, b: u64) { + let ratio = a as f64 / b as f64; + assert!((0.8..=1.25).contains(&ratio), "{what}: {a} B vs {b} B"); +} + +/// Writes `WINDOWS` windows of `SERIES` series, seals the segment, drops +/// them from the cache and reads them back `how`; checks each read-back +/// window is charged what it was when written and, for `pread` (where +/// every byte read is on the heap), that the view bytes grow by what the +/// read holds. +fn sealed_windows_read_back(how: ViewRead) { + let dir = std::env::temp_dir().join(format!("view_cache_charge-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let view = view(); + let tier = Arc::new(ViewTier::new( + WindowCache::new(None, None), + how, + Duration::ZERO, + )); + let mut views = ViewStore::tiered(tier.clone()); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + for w in 1..=WINDOWS { + let range = ((w - 1) * WIDTH_MS, w * WIDTH_MS); + views + .append(&view, range, vec![window(range.1, SERIES)]) + .unwrap(); + let slot = views.slot(VIEW, range.1).unwrap(); + let batches = views.rows()[&VIEW].last().unwrap().1.clone(); + let written = files.append(0, range, &[(VIEW, &batches)]).unwrap(); + slot.stored(written.locations[0].1.clone()); + } + files.seal(0).unwrap(); + let written_charge = tier.cache.stats().bytes / WINDOWS as u64; + assert_eq!(tier.cache.stats().entries, WINDOWS as u64); + + // Every window leaves the cache, then is read back from the file. + tier.cache.set_target_bytes(Some(0)); + tier.cache.set_target_bytes(None); + assert_eq!(tier.cache.stats().bytes, 0); + let (heap_held, view_bytes_added) = held_by(&views, || { + assert_eq!(views.rows()[&VIEW].len(), WINDOWS as usize); + }); + let stats = tier.cache.stats(); + assert_eq!( + (stats.entries, tier.cold_reads.load(Ordering::Relaxed)), + (WINDOWS as u64, WINDOWS as u64) + ); + let read_back_charge = stats.bytes / WINDOWS as u64; + println!( + "{how:?}, sealed: per window, written charge {written_charge} B, read-back charge \ + {read_back_charge} B; {WINDOWS} windows read back: heap held {heap_held} B, view \ + bytes added {view_bytes_added} B" + ); + // The same rows, keys and values: its keys index a larger dictionary, + // the segment's, which is not the window's own. + assert_close( + &format!("{how:?}: read-back vs written charge per window"), + read_back_charge, + written_charge, + ); + // A mapped read borrows the fixed-width columns from the file's pages + // (charged, not on the heap). + if how == ViewRead::Pread { + assert_close( + "view bytes added vs heap held", + view_bytes_added as u64, + heap_held as u64, + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Reads back each window from the active segment right after writing it, +/// each with series new to the segment: each read rebuilds the segment's +/// dictionary, and the cached windows keep the older ones alive. The view +/// bytes count every dictionary still held, once. +fn active_windows_read_back_while_the_dictionary_grows() { + let dir = std::env::temp_dir().join(format!("view_cache_grow-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let view = view(); + let tier = Arc::new(ViewTier::new( + WindowCache::new(None, None), + ViewRead::Mmap, + Duration::ZERO, + )); + let mut views = ViewStore::tiered(tier.clone()); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let (mut heap_held, mut view_bytes_added) = (0, 0); + for w in 1..=WINDOWS { + let range = ((w - 1) * WIDTH_MS, w * WIDTH_MS); + let series = SERIES + w as usize * 100; + views + .append(&view, range, vec![window(range.1, series)]) + .unwrap(); + let slot = views.slot(VIEW, range.1).unwrap(); + let batches = views.rows()[&VIEW].last().unwrap().1.clone(); + let written = files.append(0, range, &[(VIEW, &batches)]).unwrap(); + slot.stored(written.locations[0].1.clone()); + tier.cache.remove(WindowKey { + view: VIEW, + end_ms: range.1, + }); + let (heap, added) = held_by(&views, || { + views.rows(); + }); + heap_held += heap; + view_bytes_added += added; + } + assert_eq!(tier.cold_reads.load(Ordering::Relaxed), WINDOWS as u64); + println!( + "active segment, growing: {WINDOWS} windows read back: heap held {heap_held} B, view \ + bytes added {view_bytes_added} B" + ); + assert_close( + "view bytes added vs heap held", + view_bytes_added as u64, + heap_held as u64, + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_read_back_window_is_charged_what_it_holds() { + sealed_windows_read_back(ViewRead::Pread); + sealed_windows_read_back(ViewRead::Mmap); + active_windows_read_back_while_the_dictionary_grows(); +} diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index 739a9f12..3f7f68fa 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 2**, +- 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,13 +216,16 @@ 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): ``` -Fragment = { rows: u32, columns: [(kind, offset, len)] } +Fragment = { rows: u32, columns: [(kind, flags, offset, len)] } text column u32 keys into the segment's dictionary (+ validity bitmap) + identity label nothing: a text column whose every row holds its series + identity's label of the column's name ("" without it); + read back from the identity column (its index in flags) timestamp column i64 per row, or one i64 when every row has the same value (the window end, today stored once per row) plain column f64 / i64 / u64 / bool per row (+ validity bitmap) @@ -245,6 +248,55 @@ segment, and a segment's first use of a text writes it again. Deleting an old segment then never strands a later one's keys. At 10k series and about 96 B per identity this costs about 1–2 MB per segment. +**Label columns from the series identity.** A text column whose every row +holds its series' label of the column's name (the `job`, `region`, … +columns a per-series view carries) is not written: the fragment marks it +`identity label`, and its label values are not added to the segment's +texts. A read takes the identity column's keys as its keys, into a +per-segment array per label name holding that label of each segment text +taken as a series identity (from the interned series, else parsed from the +identity's JSON once per label name per segment). At 10k series that array is about +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 @@ -283,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 @@ -308,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. @@ -346,6 +400,8 @@ levels: each level is its own view, tiered the same way. ### Zero-copy state views +*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 @@ -633,7 +689,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) | @@ -649,7 +705,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 2. +- **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`. - **Zero-copy revision:** states are used from the mapping @@ -686,10 +744,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`. | — |