diff --git a/Cargo.lock b/Cargo.lock index ad40a02a6..8a46138d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -339,7 +339,7 @@ dependencies = [ [[package]] name = "asap-accuracy" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", "asap_sketchlib", @@ -350,7 +350,7 @@ dependencies = [ [[package]] name = "asap-cost" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", "asap_sketchlib", @@ -362,7 +362,7 @@ dependencies = [ [[package]] name = "asap-executor" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "ahash", "arrow", @@ -380,7 +380,7 @@ dependencies = [ [[package]] name = "asap-frontend-common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", "serde", @@ -390,7 +390,7 @@ dependencies = [ [[package]] name = "asap-frontend-metricsql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-frontend-common", "asap-types", @@ -401,7 +401,7 @@ dependencies = [ [[package]] name = "asap-frontend-promql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-frontend-common", "asap-types", @@ -411,7 +411,7 @@ dependencies = [ [[package]] name = "asap-frontend-sql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-frontend-common", "asap-sql-function-catalog", @@ -423,7 +423,7 @@ dependencies = [ [[package]] name = "asap-planner" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-accuracy", "asap-cost", @@ -445,12 +445,12 @@ dependencies = [ [[package]] name = "asap-sql-function-catalog" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" [[package]] name = "asap-stage0-memo" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", ] @@ -458,7 +458,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass1-per-computation-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", "thiserror 2.0.20", @@ -467,7 +467,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass2-reuse-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-accuracy", "asap-types", @@ -477,7 +477,7 @@ dependencies = [ [[package]] name = "asap-stage2-physical-optimization" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-types", ] @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "asap-stage3-plan-selection" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap-accuracy", "asap-cost", @@ -500,7 +500,7 @@ dependencies = [ [[package]] name = "asap-types" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "asap_sketchlib", "serde", @@ -511,7 +511,7 @@ dependencies = [ [[package]] name = "asap_sketchlib" version = "0.4.0" -source = "git+https://www.github.com/ProjectASAP/asap_sketchlib?rev=355093f48f2649df1b86f2d390c2faa145a5f0a0#355093f48f2649df1b86f2d390c2faa145a5f0a0" +source = "git+https://github.com/ProjectASAP/asap_sketchlib?rev=d050037bb127d425cb4160ea9b5960856ef3188c#d050037bb127d425cb4160ea9b5960856ef3188c" dependencies = [ "rand 0.9.5", "rmp-serde", @@ -2551,7 +2551,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metricsql_common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "chrono", ] @@ -2559,7 +2559,7 @@ dependencies = [ [[package]] name = "metricsql_parser" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=566b35ca771e2283b1e93385105cd0401a9a67e6#566b35ca771e2283b1e93385105cd0401a9a67e6" dependencies = [ "ahash", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 1c533a992..04153eee4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,13 +25,13 @@ version = "0.1.0" # `asap-planner` to plan, `asap-executor` to execute, and `asap-types` for # the plan types `common`'s boundary names (such as `QueryLanguage`). # Elsewhere, Planner IR types are reached through `asap_executor::planner`. -asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } -asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } -asap-types = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } +asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "566b35ca771e2283b1e93385105cd0401a9a67e6" } +asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "566b35ca771e2283b1e93385105cd0401a9a67e6" } +asap-types = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "566b35ca771e2283b1e93385105cd0401a9a67e6" } # The sketch library the Planner's executor pins, for the byte encodings of -# the sketch states the data plane persists; keep it at the Planner's rev -# (here overridden below for the executor too). -asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = "389530ce23b121520f0218a4471e376db2c35945" } +# the sketch states the data plane persists; keep it at exactly the Planner's +# rev, so cargo builds one copy for both. +asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = "d050037bb127d425cb4160ea9b5960856ef3188c" } serde = { version = "1.0", features = ["derive"] } # `float_roundtrip`: a plan file reloads to the plan it was written from @@ -58,10 +58,3 @@ prometheus_remote_write = { path = "crates/adapters/ingest/prometheus-remote-wri query = { path = "crates/query" } storage = { path = "crates/storage" } victoriametrics_remote_write = { path = "crates/adapters/ingest/victoriametrics-remote-write" } - -# asap_sketchlib#271's head, ahead of the Planner's pin (389530c): DDSketch -# view merges in place, with width-specialized loops (a 1 h quantile over -# cold windows 3x faster). Drop when the Planner's pin moves past it. The -# `www.` URL is a distinct source, so it may patch the one the Planner names. -[patch."https://github.com/ProjectASAP/asap_sketchlib"] -asap_sketchlib = { git = "https://www.github.com/ProjectASAP/asap_sketchlib", rev = "355093f48f2649df1b86f2d390c2faa145a5f0a0" } diff --git a/README.md b/README.md index 300266b77..64e15e533 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,6 @@ cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked ``` -The Planner revision is pinned in `Cargo.toml` (ASAPPlanner `1d527bc` for -`asap-planner`, `asap-executor` and `asap-types`; `asap_sketchlib` patched to -`355093f`); see +The Planner revision is pinned in `Cargo.toml` (ASAPPlanner `566b35c`; `asap_sketchlib` at +the Planner's own pin, `d050037`); see [scripts/ci/README.md](scripts/ci/README.md). diff --git a/benchmarks/micro/tier_bench.rs b/benchmarks/micro/tier_bench.rs index 474c3927a..6a78ad94d 100644 --- a/benchmarks/micro/tier_bench.rs +++ b/benchmarks/micro/tier_bench.rs @@ -100,8 +100,15 @@ async fn main() { let plan_text = serde_json::to_string(&plan).unwrap(); println!( "plan states (mentions): {:?}", - ["DDSketch", "\"Kll\"", "Hll", "Cms", "Counter", "Max"] - .map(|k| (k, plan_text.matches(k).count())) + [ + "DDSketch", + "\"KLL\"", + "\"HLL\"", + "CountMinSketch", + "Counter", + "Max" + ] + .map(|k| (k, plan_text.matches(k).count())) ); let now_ms = std::time::SystemTime::now() diff --git a/benchmarks/micro/view_read_bench.rs b/benchmarks/micro/view_read_bench.rs index 498be9441..e5f87f57a 100644 --- a/benchmarks/micro/view_read_bench.rs +++ b/benchmarks/micro/view_read_bench.rs @@ -35,7 +35,7 @@ fn main() { let _ = std::fs::remove_dir_all(&dir); let family = match family_name { - "kll" => FieldDataType::Sketch(SketchAlgorithm::Kll), + "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"), diff --git a/crates/data-plane/tests/planner_executor_parity.rs b/crates/data-plane/tests/planner_executor_parity.rs index 532739a64..cc3778454 100644 --- a/crates/data-plane/tests/planner_executor_parity.rs +++ b/crates/data-plane/tests/planner_executor_parity.rs @@ -711,7 +711,7 @@ fn same_within(a: &[Answer], b: &[Answer], relative: f64) -> bool { fn tolerance(plan: &InstallablePlan) -> f64 { let randomized = serde_json::to_string(&plan.dag) .unwrap() - .contains("\"Kll\""); + .contains("\"KLL\""); if randomized { 0.05 } else { @@ -1055,26 +1055,41 @@ fn shapes(views: &BTreeMap>) -> BTreeMap>, - expected: &BTreeMap>, +/// Each view's windows within its retention of its newest window: those +/// ending less than `retention_ms` before it, and the newest itself (the +/// windows the store keeps by retention, `storage::store`'s +/// `oldest_kept_end`). Both data planes must hold exactly these: no window +/// that recent is skipped as expired or evicted. Older windows leave the +/// store lazily (at the view's next append), and a narrower level is held +/// until its readers commit, so how many such windows linger at the end of +/// a run depends on the order windows were committed in and on when each +/// shard reported, which differ between push and the window path and from +/// run to run; and no query reads them. +fn within_retention( + views: BTreeMap>, + plan: &InstallablePlan, ) -> BTreeMap> { - served + let retention_ms: BTreeMap = plan + .ingestion_refresh_groups() + .unwrap() + .iter() + .flat_map(|group| &group.views) + .map(|view| { + let retention = i64::try_from(view.retention_ms()).unwrap_or(i64::MAX); + (format!("{}", view.node_id), retention) + }) + .collect(); + views .into_iter() .map(|(view, windows)| { - let oldest = expected - .get(&view) - .and_then(|w| w.first()) - .map_or(i64::MIN, |w| w.0 .1); - let windows = windows.into_iter().filter(|w| w.0 .1 >= oldest).collect(); + let newest_end = windows.last().map_or(i64::MIN, |w| w.0 .1); + // A view of no refresh group keeps every window. + let retention = retention_ms.get(&view).copied().unwrap_or(i64::MAX); + let oldest_kept_end = newest_end.saturating_sub(retention); + let windows = windows + .into_iter() + .filter(|w| w.0 .1 > oldest_kept_end || w.0 .1 == newest_end) + .collect(); (view, windows) }) .collect() @@ -1120,8 +1135,9 @@ fn first_difference( "shapes differ".into() } -/// T2. Push precompute stores the same view rows as the window path: per -/// (view, window), the same keys and the same states (exact values, or +/// T2. Push precompute stores the same view rows as the window path: the +/// same windows within each view's retention, and per (view, window) the +/// same keys and the same states (exact values, or /// sketch bytes). KLL plans store the same windows and keys; their states /// may differ within the target, which T1 checks through the answers. #[tokio::test(flavor = "multi_thread")] @@ -1148,8 +1164,8 @@ async fn push_precompute_stores_the_window_paths_view_rows() { data_plane_over(&plan, &points, start_ms, false, window, Views::InMemory).await; let (_, by_push) = data_plane_over(&plan, &points, start_ms, false, push, Views::InMemory).await; - let expected = stored_views(&by_window); - let served = from_oldest_of(stored_views(&by_push), &expected); + let expected = within_retention(stored_views(&by_window), &plan); + let served = within_retention(stored_views(&by_push), &plan); compared_views += expected.len(); let equal = if tolerance(&plan) > 1e-9 { shapes(&expected) == shapes(&served) diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index 5ce063d70..e0d9ad661 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -463,7 +463,7 @@ async fn per_series_breakers_are_concatenated() { } let randomized = serde_json::to_string(&plan.dag) .unwrap() - .contains("\"Kll\""); + .contains("\"KLL\""); if randomized { // KLL compacts at random: same windows and keys, answers within 5% // (T1); here only the shape. diff --git a/crates/data-plane/tests/view_persistence.rs b/crates/data-plane/tests/view_persistence.rs index 037edb4dd..a99f091f7 100644 --- a/crates/data-plane/tests/view_persistence.rs +++ b/crates/data-plane/tests/view_persistence.rs @@ -140,7 +140,7 @@ async fn kll_views_answer_alike_after_a_restart() { .unwrap(); let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; let plan = serde_json::to_string(&plan).unwrap(); - assert!(plan.contains("Kll"), "the plan builds no KLL"); + assert!(plan.contains("\"KLL\""), "the plan builds no KLL"); answers_alike_after_a_restart("kll", query, &plan).await; } diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index af9c903fa..df46270bc 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -130,8 +130,11 @@ impl CompiledQueries { BTreeSet::new() }; let mut slots: Vec = views.to_vec(); - for &node in &shared { - slots.push(query_time_slot(node)?); + if !shared.is_empty() { + let plan_id = dag.plan_id(); + for &node in &shared { + slots.push(query_time_slot(&plan_id, node)?); + } } let mut compiled: BTreeMap> = BTreeMap::new(); for &node in shared.iter().chain(&dag.roots) { @@ -471,11 +474,16 @@ fn scans_below( } /// The view slot a shared node is bound as: its whole output at the run's -/// evaluation time, refreshed on first read and kept for that evaluation. -fn query_time_slot(node: PhysicalASAPNodeId) -> anyhow::Result { +/// evaluation time, refreshed on first read and kept for that evaluation; +/// a view of plan `plan_id` (`PhysicalASAPDAG::plan_id`) whose state key +/// names only that node. +fn query_time_slot(plan_id: &str, node: PhysicalASAPNodeId) -> anyhow::Result { Ok(serde_json::from_value(serde_json::json!({ "node_id": node, "refresh": "on_first_read", + "plan_id": plan_id, + "view_state_key": {"definition_id": format!("query-time-result-{node}"), "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": format!("query-time-result-{node}"), "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 0, diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index 1a9037826..e49fdafee 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -452,8 +452,8 @@ impl ViewFiles { for (view, batches) in views { let (mark, grids_mark) = (texts.new.len(), grids.bytes.len()); let encoded = batches.first().and_then(|first| { - let rows = window_rows(batches)?; - encode_fragment(first.schema(), &rows, &mut texts, &mut grids) + let (rows, sources) = window_rows(batches)?; + encode_fragment(first.schema(), &rows, &sources, &mut texts, &mut grids) }); match encoded { Some(fragment) => fragments.push((*view, fragment)), @@ -636,10 +636,20 @@ impl ViewFiles { /// The rows of a window's `batches`. A window split by series is kept as /// one batch per part; its rows are written in the order one run over /// every series emits them (by their plain columns' values), so a window's -/// fragment is the same whichever way its run was split. `None` when a -/// plain value has no order. -fn window_rows(batches: &[Batch]) -> Option>> { - let mut rows: Vec> = batches.iter().flat_map(Batch::to_rows).collect(); +/// fragment is the same whichever way its run was split. With each row, +/// the batch and row it came from ([`crate::segment::RowSource`]). `None` +/// when a plain value has no order. +fn window_rows(batches: &[Batch]) -> Option<(Vec>, Vec>)> { + let mut rows: Vec<(Vec, crate::segment::RowSource<'_>)> = batches + .iter() + .flat_map(|batch| { + batch + .to_rows() + .into_iter() + .enumerate() + .map(move |(row, values)| (values, (batch, row))) + }) + .collect(); if batches.len() > 1 { let plain: Vec = batches[0] .schema() @@ -659,7 +669,7 @@ fn window_rows(batches: &[Batch]) -> Option>> { .map(|row| { let key = plain .iter() - .map(|&column| row[column].key()) + .map(|&column| row.0[column].key()) .collect::, _>>() .ok()?; Some((key, row)) @@ -668,7 +678,7 @@ fn window_rows(batches: &[Batch]) -> Option>> { keyed.sort_by(|a, b| a.0.cmp(&b.0)); rows = keyed.into_iter().map(|(_, row)| row).collect(); } - Some(rows) + Some(rows.into_iter().unzip()) } /// The state `value` stores, with the record's rebuilt `grids`. @@ -1121,7 +1131,11 @@ mod tests { DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY, }; use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm}; - use asap_executor::values::state_view_bytes; + + /// Each row of `batch` as a fragment row's source. + fn sources_of(batch: &Batch) -> Vec> { + (0..batch.num_rows()).map(|row| (batch, row)).collect() + } /// A fresh directory for one test's segments. fn segment_dir(test: &str) -> PathBuf { @@ -1136,11 +1150,11 @@ mod tests { use SketchAlgorithm as A; Some(FieldDataType::Sketch(match kernel { SketchKernel::DDSketch => A::DDSketch, - SketchKernel::Kll => A::Kll, - SketchKernel::CountMin => A::Cms, - SketchKernel::Kmv => A::Kmv, - SketchKernel::Hll(_) => A::Hll, - SketchKernel::WeightedFrequency(FrequencyKind::CmsHeap) => A::CmsWithHeap, + SketchKernel::Kll => A::KLL, + SketchKernel::CountMin => A::CountMinSketch, + SketchKernel::Kmv => A::KMV, + SketchKernel::Hll(_) => A::HLL, + SketchKernel::WeightedFrequency(FrequencyKind::CmsHeap) => A::CountMinSketchWithHeap, SketchKernel::WeightedFrequency(FrequencyKind::CountSketchHeap) => { A::CountSketchWithHeap } @@ -1320,7 +1334,11 @@ mod tests { .collect(); out.push(( "HydraCms".into(), - window_batch(10, FieldDataType::Sketch(SketchAlgorithm::HydraCms), groups), + window_batch( + 10, + FieldDataType::Sketch(SketchAlgorithm::HydraCountMinSketch), + groups, + ), )); out } @@ -1354,9 +1372,9 @@ mod tests { ) } - /// 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). + /// The window of [`ten_sample_ddsketch_window`] takes 8.3 kB on disk + /// (8 B a series), not the 82 kB its DDSketch views alone take in the + /// view layout. #[test] fn a_ten_sample_ddsketch_window_is_stored_compact() { let dir = segment_dir("dd-bytes"); @@ -1365,16 +1383,14 @@ mod tests { 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 views: usize = + crate::segment::view_bytes(&batch.schema().fields[4].dtype, &sources_of(&batch), 4) + .unwrap() + .iter() + .map(|view| view.len()) + .sum(); + assert_eq!(views, 82_176); + assert_eq!(location_of(&written, 1).len(), 8_309); let _ = std::fs::remove_dir_all(&dir); } @@ -1477,15 +1493,20 @@ mod tests { 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 kll = FieldDataType::Sketch(SketchAlgorithm::KLL); 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::(); + + crate::segment::view_bytes( + &kll, + &sources_of(&window_batch(10, kll.clone(), states.clone())), + 4, + ) + .unwrap() + .iter() + .map(|view| view.len().div_ceil(8) * 8) + .sum::(); let (first, second) = ( window_batch(10, kll.clone(), states.clone()), window_batch(20, kll, states), @@ -1503,7 +1524,10 @@ mod tests { 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); + // The column reports the bytes its views span, but a run reading + // it is charged none of them: they are the store's. + assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), held); + assert_eq!(r1.memory_bytes() + held, r1.stored_bytes()); let identity = |batch: &Batch| { batch .column(1) @@ -1636,6 +1660,9 @@ mod tests { serde_json::from_value(serde_json::json!({ "node_id": id, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": format!("v{id}"), "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": format!("v{id}"), "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1667,6 +1694,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1863,6 +1893,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1914,6 +1947,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1961,6 +1997,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -2003,6 +2042,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index 13d34a4e5..29a2bf368 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -12,10 +12,11 @@ //! 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 +//! ([`crate::state_codec`]) and rebuilt in the executor's view //! 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::borrow::Cow; use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::fs::File; @@ -38,7 +39,7 @@ 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, + family_has_view_layout, Batch, BatchColumn, SchemaRef, StateColumn, Value, }; use asap_executor::Error; use serde::{Deserialize, Serialize}; @@ -50,7 +51,11 @@ use crate::state_codec::{ }; /// The view file format version these segments are. -pub(crate) const FORMAT_VERSION: u32 = 4; +/// +/// 5: DDSketch states without `sum`, `min` and `max` (`asap_sketchlib` +/// ASAPv1 kind `0x05 0x01`; a 64-byte view head). A version 4 segment is +/// set aside on open, never read. +pub(crate) const FORMAT_VERSION: u32 = 5; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -69,16 +74,16 @@ const TIMESTAMP: u32 = 4; /// Any other plain column: MessagePack of its values. const GENERIC: u32 = 5; const STATES: u32 = 6; -/// A state column in the executor's mapped layout: `u32` offsets in the +/// A state column in the executor's view layout: `u32` offsets in the /// 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; +/// For a family with a view layout but no compact form (KLL, Count-Min). +const VIEW_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. +/// the [`CompactKind`] code. Read back into the view layout. const COMPACT_STATES: u32 = 9; /// Flag: a timestamp column whose rows all hold one value, stored once. const CONSTANT: u32 = 1; @@ -762,7 +767,7 @@ impl WindowLocation { } /// The fragment's rows as one batch of `schema`, and the bytes its - /// state columns hold: they are rebuilt in the mapped layout, which + /// state columns hold: they are rebuilt in the view 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> { @@ -870,11 +875,15 @@ fn validity(nulls: &[bool]) -> Option> { Some(bits) } -/// `rows` (of `schema`) as one compressed columnar fragment; `None` when a -/// state has no byte encoding. +/// Where a fragment row came from: a window's batch and its row there. +pub(crate) type RowSource<'a> = (&'a Batch, usize); + +/// `rows` (of `schema`) as one compressed columnar fragment, row `i` read +/// from `sources[i]`; `None` when a state has no byte encoding. pub(crate) fn encode_fragment( schema: &Schema, rows: &[Vec], + sources: &[RowSource<'_>], texts: &mut SegmentTexts, grids: &mut Grids, ) -> Option> { @@ -891,7 +900,7 @@ pub(crate) fn encode_fragment( .iter() .map(|row| matches!(row[column], Value::Null)) .collect(); - // The second section: the validity bitmap, or a mapped state + // The second section: the validity bitmap, or a view-layout state // column's states. let mut second: Option> = None; // The identity column, when this column holds its series' label. @@ -902,24 +911,17 @@ pub(crate) fn encode_fragment( && labels.holds_label(rows, column, &field.name) }) .map(|labels| labels.column as u32); + // Each state in its view layout (`None` when a state has none, e.g. + // a keyed exact state, or the family has no view layout). + let views = view_bytes(&field.dtype, sources, column); // 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), + // the views (`None` when the column has no compact form). + let mut compact = compact_kind(&field.dtype) + .zip(views.as_ref()) + .and_then(|(kind, views)| Some((kind, encode_states(kind, views.iter())?))); + // Otherwise the column in the view layout, when it has one. + let mut view_column = match views { + Some(views) if compact.is_none() => view_column_of(views), _ => None, }; let (kind, mut flags, data): (u32, u32, Vec) = match &field.dtype { @@ -982,10 +984,10 @@ pub(crate) fn encode_fragment( 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"); + _ if view_column.is_some() => { + let (offsets, states) = view_column.take().expect("checked"); second = Some(states); - (MAPPED_STATES, 0, offsets) + (VIEW_STATES, 0, offsets) } _ => { // States: u32 offsets[rows + 1], then each state's stored bytes. @@ -1007,7 +1009,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")), + (VIEW_STATES, _) => section(&mut out, &second.take().expect("states")), (STATES | GENERIC | COMPACT_STATES, _) => (0, 0), (_, Some(bits)) => section(&mut out, &bits), (_, None) => (0, 0), @@ -1102,18 +1104,45 @@ impl IdentityLabels { } } -/// Column `column` of `rows` in the executor's mapped state layout: the -/// `u32` offsets (`rows + 1`) and the states back to back, each padded to 8 -/// bytes; `None` when a state has no mapped form. -fn mapped_states(rows: &[Vec], column: usize) -> Option<(Vec, Vec)> { - let mut offsets = Vec::with_capacity((rows.len() + 1) * 4); - let mut states = Vec::new(); +/// Each source row's state in column `column` (of `family`) in the +/// executor's view layout, read from its batch's state column +/// ([`StateColumn::view_bytes`]: borrowed where that column holds views); +/// `None` when a row holds no state, the family has no view layout, or a +/// state has none (a keyed exact state). +pub(crate) fn view_bytes<'a>( + family: &FieldDataType, + sources: &[RowSource<'a>], + column: usize, +) -> Option>> { + if !family_has_view_layout(family) { + return None; + } + sources + .iter() + .map(|&(batch, row)| { + let states = batch.state_column(column)?; + let indices = batch + .column(column) + .as_any() + .downcast_ref::()?; + if indices.is_null(row) { + return None; + } + states.view_bytes(indices.value(row) as usize) + }) + .collect() +} + +/// State `views` in the executor's view layout as one column: the `u32` +/// offsets (`rows + 1`) and the states back to back, each padded to 8 +/// bytes. Each view is dropped once copied, so the column and the views +/// are not both held whole. +fn view_column_of(views: Vec>) -> Option<(Vec, Vec)> { + let mut offsets = Vec::with_capacity((views.len() + 1) * 4); + let mut states = Vec::with_capacity(views.iter().map(|view| padded(view.len())).sum()); offsets.extend_from_slice(&0u32.to_le_bytes()); - for row in rows { - let Value::Summary { state, .. } = &row[column] else { - return None; - }; - states.extend(state_view_bytes(state.as_ref())?); + for view in views { + states.extend_from_slice(&view); states.resize(padded(states.len()), 0); offsets.extend_from_slice(&u32::try_from(states.len()).ok()?.to_le_bytes()); } @@ -1277,7 +1306,7 @@ fn decode_fragment( data, valid, } = descriptor(bytes, column)?; - let nulls = if valid.1 == 0 || kind == MAPPED_STATES || kind == COMPACT_STATES { + let nulls = if valid.1 == 0 || kind == VIEW_STATES || kind == COMPACT_STATES { None } else { if valid.1 != rows.div_ceil(8) { @@ -1369,7 +1398,7 @@ fn decode_fragment( 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( + let column = StateColumn::from_views( field.dtype.clone(), Buffer::from(states), ScalarBuffer::from(offsets), @@ -1380,18 +1409,14 @@ fn decode_fragment( }); continue; } - MAPPED_STATES => { + VIEW_STATES => { if data.1 != (rows + 1) * 4 { return Err(damaged()); } 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, - offsets, - )?; + let column = StateColumn::from_views(field.dtype.clone(), states, offsets)?; out.push(BatchColumn::States { indices: UInt32Array::from_iter_values(0..rows as u32), states: Arc::new(column), diff --git a/crates/storage/src/state_codec.rs b/crates/storage/src/state_codec.rs index 147170fdc..a9f276687 100644 --- a/crates/storage/src/state_codec.rs +++ b/crates/storage/src/state_codec.rs @@ -1,12 +1,12 @@ //! 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 +//! A state column is written in the executor's view layout +//! ([`asap_executor::values::StateColumn::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 a 64-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, +//! stores the same states in a compact form and rebuilds the view layout, //! byte for byte, when a window is read cold: //! //! - DDSketch: only non-empty buckets, as a varint gap from the previous @@ -19,12 +19,12 @@ //! - 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 +//! Everything here is lossless: decoding gives the bytes the view 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 +//! the view-layout 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 +/// The state families with a compact form, as the view layout names /// them: which fixed-size exact record, or which sketch. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum CompactKind { @@ -68,7 +68,7 @@ impl CompactKind { }) } - /// The bytes of one record in the mapped layout, for an exact kind. + /// The bytes of one record in the view layout, for an exact kind. fn record_bytes(self) -> Option { Some(match self { Self::DDSketch => return None, @@ -138,9 +138,18 @@ fn padded(n: usize) -> usize { 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 +/// Bytes of a DDSketch view before its arrays: magic and version, four /// 8-byte fields, six 4-byte fields. -const DD_HEAD_BYTES: usize = 88; +const DD_HEAD_BYTES: usize = 64; +/// Where a DDSketch view's 4-byte fields lie in its head: the count width, +/// the store form (1 sparse), and each store's first bucket index and +/// entry count. +const DD_WIDTH_AT: usize = 40; +const DD_SPARSE_AT: usize = 44; +const DD_POSITIVE_OFFSET_AT: usize = 48; +const DD_POSITIVE_ENTRIES_AT: usize = 52; +const DD_NEGATIVE_OFFSET_AT: usize = 56; +const DD_NEGATIVE_ENTRIES_AT: usize = 60; /// 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; @@ -152,9 +161,6 @@ type Buckets = Vec<(i32, u64)>; #[derive(Debug, Default, Clone, PartialEq)] struct DdContents { alpha: u64, - sum: u64, - min: u64, - max: u64, zero_count: u64, admission_rate: u64, positive: Buckets, @@ -194,13 +200,10 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { 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)? { + let width = u32_at(view, DD_WIDTH_AT)? as usize; + let sparse = match u32_at(view, DD_SPARSE_AT)? { 0 => false, 1 => true, _ => return None, @@ -245,21 +248,16 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { } 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, - )?; + let positive_offset = u32_at(view, DD_POSITIVE_OFFSET_AT)? as i32; + let positive_entries = u32_at(view, DD_POSITIVE_ENTRIES_AT)? as usize; + let negative_offset = u32_at(view, DD_NEGATIVE_OFFSET_AT)? as i32; + let negative_entries = u32_at(view, DD_NEGATIVE_ENTRIES_AT)? as usize; + store(positive_offset, positive_entries, &mut dd.positive)?; + store(negative_offset, negative_entries, &mut dd.negative)?; if at != view.len() { return None; } - (dd.alpha, dd.sum, dd.min, dd.max) = (alpha, sum, min, max); + dd.alpha = alpha; (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 @@ -276,16 +274,8 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { && 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, - ); + && trimmed(&contents.positive, positive_offset, positive_entries) + && trimmed(&contents.negative, negative_offset, negative_entries); (canonical && contents.count()? == count).then_some(()) } @@ -330,9 +320,6 @@ impl DdContents { for word in [ self.alpha, self.count()?, - self.sum, - self.min, - self.max, self.zero_count, self.admission_rate, ] { @@ -585,10 +572,10 @@ fn buckets(reader: &mut StreamReader, previous_first: &mut i32, out: &mut Bucket // ------------------------------------------------------------ the columns -/// The tag of an exact record kept whole, in its mapped layout. +/// The tag of an exact record kept whole, in its view layout. const RAW: u8 = 0xff; -/// A column of `states` (each the mapped-layout bytes of one state of +/// A column of `states` (each the view-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). @@ -614,9 +601,6 @@ pub(crate) fn encode_states( 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); } @@ -716,7 +700,7 @@ fn put_record( true } -/// Decodes `rows` states of `kind` from their compact form into the mapped +/// Decodes `rows` states of `kind` from their compact form into the view /// 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. @@ -749,8 +733,6 @@ pub(crate) fn decode_states( 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>(); @@ -774,7 +756,7 @@ pub(crate) fn decode_states( reader.finished().then_some((words, offsets)) } -/// One exact record of `kind`, appended to `view` in its mapped layout. +/// One exact record of `kind`, appended to `view` in its view layout. fn record( kind: CompactKind, reader: &mut StreamReader, @@ -919,28 +901,28 @@ mod tests { } /// 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. + /// finest DDSketch view): the view layout takes 96 bytes a state (a + /// 64-byte head and a dense run of 1-byte counts, half of them empty), + /// the compact column 23 before compression. #[test] - fn a_ten_sample_ddsketch_state_takes_47_compact_bytes() { + fn a_ten_sample_ddsketch_state_takes_23_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); + assert_eq!(view.len(), 96); 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); + // first bucket's delta from the previous row's, 9 gaps, 10 counts); + // per column, alpha and the admission rate (16), the stream lengths + // (6: the int stream's, and the three empty float streams'), and one + // more byte for the first row's first bucket (no previous row). + assert_eq!(compact.len(), rows * 23 + 16 + 6 + 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: + /// Decoding gives the view layout's bytes exactly, so every answer + /// read from a compact column is the answer read from the view-layout one: /// empty sketches, zeros, negative samples, counts past one byte, /// dense and sparse stores. #[test] @@ -957,7 +939,10 @@ mod tests { 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"); + assert_ne!( + states[4][DD_SPARSE_AT], states[5][DD_SPARSE_AT], + "both store forms are covered" + ); let back = round_trip(CompactKind::DDSketch, &states); assert_eq!(back, states); for (a, b) in states.iter().zip(&back) { @@ -970,7 +955,7 @@ mod tests { } /// Sketches of different index mappings have no shared column head: - /// the column keeps its mapped layout. + /// the column keeps its view layout. #[test] fn ddsketches_of_two_alphas_have_no_compact_column() { let states = [dd(0.02, &[1.0]), dd(0.05, &[1.0])]; @@ -978,13 +963,13 @@ mod tests { } /// Views the writer never writes (keys out of order, non-zero padding) - /// have no compact form: their column keeps the mapped layout rather + /// have no compact form: their column keeps the view 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_eq!(view[DD_SPARSE_AT], 1, "a sparse store"); assert!(dd_contents(&view).is_some()); let mut swapped = view.clone(); // Swap the second and third sparse keys. @@ -1048,7 +1033,7 @@ mod tests { } } - /// A counter takes 56 bytes in the mapped layout and 20 in a compact + /// A counter takes 56 bytes in the view 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. diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 4ed237f08..4800d4cf7 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1819,6 +1819,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1885,6 +1888,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1975,6 +1981,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/crates/storage/tests/view_cache_charge.rs b/crates/storage/tests/view_cache_charge.rs index 6c457e6b7..922fc4d2e 100644 --- a/crates/storage/tests/view_cache_charge.rs +++ b/crates/storage/tests/view_cache_charge.rs @@ -101,6 +101,9 @@ fn view() -> MaterializedView { serde_json::from_value(serde_json::json!({ "node_id": VIEW, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index 095796b7d..fb03b8df8 100644 --- a/docs/design/tiered-view-storage.md +++ b/docs/design/tiered-view-storage.md @@ -217,7 +217,7 @@ it is deleted whole. A segment holds the existing framing (a little-endian 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 4**, +- a header frame (MessagePack): plan hash, group, **format version 5**, and the segment start; - one record frame per refreshed window. Its head is a small MessagePack map, followed by the parts it points at: @@ -275,7 +275,7 @@ 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 +row on disk (an 88-byte head, 64 bytes from format 5, 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): @@ -330,6 +330,12 @@ finish. Disk use is then retention plus one segment, not unbounded. A file in the old format (`group-.log`, version 1) is renamed `*.stale` and not loaded, as a file of another plan is today. +**Format version 5.** The same layout as format 4, over the sketch library +version in which a DDSketch keeps no sum, minimum or maximum (`asap_sketchlib` +ASAPv1 kind `0x05 0x01`): its view head is 64 bytes, and a compact DDSketch +column has no float streams. The data plane sets a format 4 segment aside +(renamed `.stale`) when it opens it, and does not migrate it. + ### Read path `RunStore::read_materialized_view` returns a stream of the windows @@ -718,9 +724,10 @@ 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, format version 4: label columns are +- **Fragment encoding:** columnar, format version 5: 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). + and text columns, zstd level 1 per fragment (format 4); DDSketch states + without sum, minimum or maximum (format 5). - **No cgroup limit:** no budget, plus idle eviction. - **Old view files:** renamed `*.stale`. - **Zero-copy revision:** states are used from the mapping