diff --git a/crates/executor/src/sources/data_store.rs b/crates/executor/src/sources/data_store.rs index 873915f95..fa6a49854 100644 --- a/crates/executor/src/sources/data_store.rs +++ b/crates/executor/src/sources/data_store.rs @@ -32,10 +32,11 @@ pub trait DataStore { /// `request.time_range_ms` exactly, in `request.schema` (a /// `SummaryTumblingWindowChain`'s windows, each `(window_end, keys, /// state)`; any other view's group columns and one state column). Exact: the executor never re-filters them, - /// so the store never counts an observation twice, never returns - /// another definition's state, and never treats missing state as - /// empty; it returns an error instead. The states are the store's: a - /// run is not charged for them. + /// so the store never counts an observation twice, never returns the + /// state of another view state key (`MaterializedView::view_state_key`) + /// or concrete selection, and never treats missing state as empty; it returns + /// an error instead. The states are the store's: a run is not charged + /// for them. fn read_materialized_view( &self, view: &MaterializedView, diff --git a/crates/integration-tests/tests/kll_tumbling_window_execution.rs b/crates/integration-tests/tests/kll_tumbling_window_execution.rs index 3ea642551..3f13b9179 100644 --- a/crates/integration-tests/tests/kll_tumbling_window_execution.rs +++ b/crates/integration-tests/tests/kll_tumbling_window_execution.rs @@ -15,7 +15,7 @@ use asap_types::ir::operator::{GroupKeys, Reduction, Source}; use asap_types::ir::scalar::ColumnRef; use asap_types::ir::schema::{DataType, Field, FieldDataType, Schema}; use asap_types::ir::{ASAPOp, NonASAPOp, OperatorNode, QueryRoot, TimeRangeKind}; -use asap_types::plan::materialized_view::MaterializedView; +use asap_types::plan::materialized_view::{MaterializedView, ViewStateKey}; use asap_types::plan::physical_asap_dag::PhysicalASAPDAG; use asap_types::plan::physical_asap_dag::ViewCoverage; use asap_types::stages::{Lifetime, StorageMedium}; @@ -63,6 +63,10 @@ struct Fixture { p99: u64, } fn fixture() -> Fixture { + fixture_with(200) +} +/// [`fixture`] with KLL `k` in place of 200. +fn fixture_with(k: u32) -> Fixture { let new = |operator| OperatorNode::new_shared(operator).unwrap(); let scan = new(asap_types::ir::Operator::NonASAP(NonASAPOp::Scan { source: Source::Table { @@ -113,7 +117,7 @@ fn fixture() -> Fixture { .unwrap(); asap_executor::physical_planner::test_support::set_build_parameters( &mut dag.nodes, - Some(&asap_types::summary_type::SketchParams::Kll { k: 200 }), + Some(&asap_types::summary_type::SketchParams::Kll { k }), ); let mut tumbling_window_ids = vec![0; 5]; let (mut merge, mut p50, mut p99) = (0, 0, 0); @@ -428,13 +432,13 @@ fn tumbling_windows_reject_parameters_schema_and_missing_binding() { ); } -/// Finds a view's states only by its definition id and the requested time -/// range, as a deployment's summary store does; never by node id. -struct DefinitionStore { - states: std::collections::BTreeMap<(String, (i64, i64)), Batch>, - requested: std::sync::Mutex>, +/// Finds a view's states only by its view state key and the requested +/// time range, as a deployment's summary store does; never by node id. +struct ViewStateStore { + states: std::collections::HashMap<(ViewStateKey, (i64, i64)), Batch>, + requested: std::sync::Mutex>, } -impl asap_executor::sources::DataStore for DefinitionStore { +impl asap_executor::sources::DataStore for ViewStateStore { fn read_raw_data( &self, source: &Source, @@ -449,10 +453,7 @@ impl asap_executor::sources::DataStore for DefinitionStore { request: &asap_executor::sources::MaterializedViewRequest, _: RunContext, ) -> Result, Error> { - let key = ( - view.coverage().definition_id().to_owned(), - request.time_range_ms, - ); + let key = (view.view_state_key().clone(), request.time_range_ms); self.requested.lock().unwrap().push(key.clone()); let state = self .states @@ -463,28 +464,20 @@ impl asap_executor::sources::DataStore for DefinitionStore { } } -/// A store keyed only by `(definition_id, time range)` answers the five-tumbling-window -/// query: the five tumbling windows share one definition and request the five -/// one-minute ranges that tile the window, and the answers equal those of -/// binding each tumbling window's state to its node. -#[test] -fn a_store_keyed_by_definition_and_time_range_answers_the_tumbling_windows() { - let fixture = fixture(); +/// The states of the tumbling windows of minutes 0..5 (`(m, m + 1]` +/// minutes), built by `fixture`'s newest tumbling window, in a store keyed +/// by that fixture's view state key and each minute's range. +fn view_state_store(fixture: &Fixture) -> (Arc, Vec) { let maintenance = compile(&fixture.dag, &[], &[fixture.tumbling_windows[0]]).unwrap(); - // The state of the tumbling window of minute `m`, `(m, m + 1]` minutes. let tumbling_windows: Vec = (0..5) .map(|m| tumbling_window_state(&maintenance, m)) .collect(); - let definition = fixture.views[0].coverage().definition_id().to_owned(); - assert!(fixture - .views - .iter() - .all(|view| view.coverage().definition_id() == definition)); + let key = fixture.views[0].view_state_key().clone(); let states = (0..5) .map(|m| { ( ( - definition.clone(), + key.clone(), ( m * TUMBLING_WINDOW_WIDTH_MS, (m + 1) * TUMBLING_WINDOW_WIDTH_MS, @@ -494,30 +487,56 @@ fn a_store_keyed_by_definition_and_time_range_answers_the_tumbling_windows() { ) }) .collect(); - let store = Arc::new(DefinitionStore { + let store = Arc::new(ViewStateStore { states, requested: Default::default(), }); + (store, tumbling_windows) +} + +/// Runs `fixture`'s p50 and p99 against `store` at the query scope: the +/// rows of each root, or the first error. +fn run_quantiles( + fixture: &Fixture, + store: Arc, +) -> Result>>, Error> { let compiled = compile(&fixture.dag, &fixture.views, &[fixture.p50, fixture.p99]).unwrap(); - let scope = query_scope(); - let by_definition = block_on(async { - let dag = compiled.instantiate(store.clone()).unwrap(); - let streams = dag - .execute( - compiled.roots(), - RunContext::new(scope.clone(), Limits::default()).unwrap(), - ) - .unwrap(); + block_on(async { + let dag = compiled.instantiate(store)?; + let streams = dag.execute( + compiled.roots(), + RunContext::new(query_scope(), Limits::default())?, + )?; let mut outputs = Vec::new(); for mut stream in streams { let mut rows = Vec::new(); while let Some(batch) = stream.next().await { - rows.extend(batch.unwrap().to_rows()); + rows.extend(batch?.to_rows()); } outputs.push(rows); } - outputs - }); + Ok(outputs) + }) +} + +/// A store keyed only by `(view_state_key, time range)` answers the +/// five-tumbling-window query: the five tumbling windows differ only in +/// the `TimeShift` below them, which is selection, so they share one key and +/// request the five one-minute ranges that tile the window, and the +/// answers equal those of binding each tumbling window's state to its node. +#[test] +fn a_store_keyed_by_view_state_key_and_time_range_answers_the_tumbling_windows() { + let fixture = fixture(); + let nodes: std::collections::BTreeSet<_> = + fixture.views.iter().map(|view| view.node_id).collect(); + assert_eq!(nodes.len(), 5, "five views, five nodes"); + let key = fixture.views[0].view_state_key(); + assert!(fixture + .views + .iter() + .all(|view| view.view_state_key() == key)); + let (store, tumbling_windows) = view_state_store(&fixture); + let by_key = run_quantiles(&fixture, store.clone()).unwrap(); let mut requested: Vec<(i64, i64)> = store .requested .lock() @@ -536,10 +555,38 @@ fn a_store_keyed_by_definition_and_time_range_answers_the_tumbling_windows() { .collect::>() ); // View `i` holds the tumbling window ending `i` minutes before the evaluation time. + let compiled = compile(&fixture.dag, &fixture.views, &[fixture.p50, fixture.p99]).unwrap(); let by_node = store_at(&fixture.views, 300_000, |i| tumbling_windows[4 - i].clone()); - let by_node: Vec>> = physical_common::execute(&compiled, by_node, scope) + let by_node: Vec>> = physical_common::execute(&compiled, by_node, query_scope()) .iter() .map(|batches| batches.iter().flat_map(Batch::to_rows).collect()) .collect(); - assert_eq!(format!("{by_definition:?}"), format!("{by_node:?}")); + assert_eq!(format!("{by_key:?}"), format!("{by_node:?}")); +} + +/// The bug a key of the coverage alone has: KLL views with `k = 200` and +/// `k = 400` share their coverage, so a store keyed by `definition_id` +/// would hand the `k = 200` states to the `k = 400` query. Keyed by the +/// view state key, the `k = 400` query finds no state and fails instead. +#[test] +fn a_store_keyed_by_view_state_key_misses_states_of_another_sketch_parameter() { + let k200 = fixture_with(200); + let k400 = fixture_with(400); + assert_eq!(k200.views[0].coverage(), k400.views[0].coverage()); + let (store, _) = view_state_store(&k200); + let error = run_quantiles(&k400, store).unwrap_err(); + assert!(error.to_string().contains("no state for"), "{error}"); +} + +/// KLL views that differ only in θ (`k = 200` vs `k = 400`) have one +/// coverage, so a logical key cannot tell their states apart, and +/// different view state keys. +#[test] +fn views_differing_only_in_sketch_parameters_have_different_view_state_keys() { + let k200 = fixture_with(200); + let k400 = fixture_with(400); + for (view200, view400) in k200.views.iter().zip(&k400.views) { + assert_eq!(view200.coverage(), view400.coverage()); + assert_ne!(view200.view_state_key(), view400.view_state_key()); + } } diff --git a/crates/integration-tests/tests/main.rs b/crates/integration-tests/tests/main.rs index b7ef0a2e7..c88c27873 100644 --- a/crates/integration-tests/tests/main.rs +++ b/crates/integration-tests/tests/main.rs @@ -46,3 +46,4 @@ mod sql_to_post_asap; mod stage3_objective; mod storage_costs; mod time_range; +mod view_state_key; diff --git a/crates/integration-tests/tests/materialized_views.rs b/crates/integration-tests/tests/materialized_views.rs index 9d1ccb925..d0bbd7111 100644 --- a/crates/integration-tests/tests/materialized_views.rs +++ b/crates/integration-tests/tests/materialized_views.rs @@ -36,3 +36,19 @@ fn a_plan_file_of_an_older_wire_version_is_refused_by_version() { let read = InstallablePlan::from_json(&serde_json::to_string(¤t).unwrap()).unwrap(); assert_eq!(read, current); } + +/// The plan id of the DAG in a committed plan file, written by another +/// process: a deployment that keyed states by `(plan_id, node_id)` finds +/// them again only while this stays the same. +#[test] +fn the_plan_id_of_a_committed_plan_file_is_pinned() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/materialized_view_fixtures/plan_wire_version_10.json"); + let file: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let dag: asap_types::plan::physical_asap_dag::PhysicalASAPDAG = + serde_json::from_value(file["dag"]["dag"].clone()).unwrap(); + assert_eq!(dag.plan_id(), PINNED_PLAN_ID); +} + +/// `the_plan_id_of_a_committed_plan_file_is_pinned`'s plan id. +const PINNED_PLAN_ID: &str = "90231c1c36f2b1660ed23d24725d635f"; diff --git a/crates/integration-tests/tests/view_state_key.rs b/crates/integration-tests/tests/view_state_key.rs new file mode 100644 index 000000000..65cfe9ccd --- /dev/null +++ b/crates/integration-tests/tests/view_state_key.rs @@ -0,0 +1,471 @@ +//! What a materialized view's stored state is, in any plan +//! (`MaterializedView::view_state_key`): the view's definition, its own +//! window and its θ. Refresh mode, retention and storage medium do not +//! enter, and neither do the nodes below the view. The plan id +//! (`PhysicalASAPDAG::plan_id`) names one installed plan. +use std::rc::Rc; + +use asap_executor::physical_planner::test_support::{set_build_parameters, views_at}; +use asap_planner::{ + plan_installable, CostInputs, DeploymentCapabilities, FrontendInput, InstallablePlan, + PlanningModels, PlanningWorkload, UserInput, +}; +use asap_types::ir::operator::{GroupKeys, Reduction, Source}; +use asap_types::ir::scalar::ColumnRef; +use asap_types::ir::schema::{DataType, Field, FieldDataType, Schema}; +use asap_types::ir::{ASAPOp, NonASAPOp, Operator, OperatorNode, TimeRangeKind}; +use asap_types::plan::materialized_view::{ + MaterializedView, MaterializedViewRefresh, ViewStateKey, +}; +use asap_types::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPDAGNode, ViewCoverage}; +use asap_types::stages::{Lifetime, StorageMedium}; +use asap_types::summary_type::{SketchAlgorithm, SketchParams, SketchStatistic, SummaryUpdate}; + +const MINUTE_MS: u64 = 60_000; + +/// `p50(SummaryMerge(TimeRange(5m, Chain[width_ms](Scan(t)))))` over +/// `t(ts, value)`, every node at query time, the chain KLL `k = 200` (and +/// the merge, which reads its states); with the chain's node id and the +/// merge's. +fn chain_dag(width_ms: u64) -> (PhysicalASAPDAG, usize, usize) { + let new = |operator| OperatorNode::new_shared(operator).unwrap(); + let scan = new(Operator::NonASAP(NonASAPOp::Scan { + source: Source::Table { + table_ref: "t".into(), + }, + predicates: vec![], + schema: Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("value", DataType::Float64, false), + ], + 0, + vec![], + ), + })); + let chain: Rc = new(Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: scan, + summary_type: FieldDataType::Sketch(SketchAlgorithm::Kll), + input: SummaryUpdate::column(ColumnRef::Named("value".into())), + reduction: Reduction::Reduce(GroupKeys::default()), + filter: None, + tumbling_window_width_ms: width_ms, + })); + let range = new(Operator::NonASAP(NonASAPOp::TimeRange { + range: std::time::Duration::from_millis(5 * MINUTE_MS), + kind: TimeRangeKind::Range, + child: chain, + })); + let merge = new(Operator::ASAP(ASAPOp::SummaryMerge { + children: vec![range], + group_by: None, + })); + let p50 = new(Operator::ASAP(ASAPOp::SummaryEstimate { + summary_input: merge, + query: SketchStatistic::Quantile { q: 0.5 }, + })); + let mut dag = + asap_types::test_support::forwarders::physical_asap_dag_at_query_time(&p50).unwrap(); + set_build_parameters(&mut dag.nodes, Some(&SketchParams::Kll { k: 200 })); + let id_of = |dag: &PhysicalASAPDAG, f: &dyn Fn(&Operator) -> bool| { + dag.nodes.iter().find(|node| f(&node.payload)).unwrap().id + }; + let chain = id_of(&dag, &|operator| { + matches!( + operator, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { .. }) + ) + }); + let merge = id_of(&dag, &|operator| { + matches!(operator, Operator::ASAP(ASAPOp::SummaryMerge { .. })) + }); + node_mut(&mut dag, merge).parameters = Some(SketchParams::Kll { k: 200 }); + (dag, chain, merge) +} + +fn node_mut(dag: &mut PhysicalASAPDAG, id: usize) -> &mut PhysicalASAPDAGNode { + dag.nodes.iter_mut().find(|node| node.id == id).unwrap() +} + +/// The view at node `id` of `dag`, with the coverage every view of these +/// tests shares (one definition, an empty selection): materialized at +/// ingestion time, unless its lifetime already keeps it across evaluations +/// (then refreshed on first read). +fn view_at(dag: &mut PhysicalASAPDAG, id: usize) -> MaterializedView { + node_mut(dag, id).view_coverage = Some(ViewCoverage::new("kll of t.value".into(), vec![])); + views_at(dag, &[id as u64]).unwrap().remove(0) +} + +/// The node of `chain_dag(width_ms)` whose operator `is_view` picks, as a +/// view refreshed on first read (θ `k = 200`, the coverage these tests +/// share), over its chain kept as a view refreshed at ingestion. +fn view_over_chain(width_ms: u64, is_view: fn(&Operator) -> bool) -> MaterializedView { + let (mut dag, chain, _) = chain_dag(width_ms); + let view = dag + .nodes + .iter() + .find(|node| is_view(&node.payload)) + .unwrap() + .id; + let node = node_mut(&mut dag, view); + node.lifetime = Lifetime::AcrossEvaluations(StorageMedium::Memory); + node.retention_ms = Some(5 * MINUTE_MS); + node.parameters = Some(SketchParams::Kll { k: 200 }); + node.view_coverage = Some(ViewCoverage::new("kll of t.value".into(), vec![])); + views_at(&mut dag, &[chain as u64, view as u64]) + .unwrap() + .into_iter() + .find(|materialized| materialized.node_id == view) + .unwrap() +} + +fn is_merge(operator: &Operator) -> bool { + matches!(operator, Operator::ASAP(ASAPOp::SummaryMerge { .. })) +} + +fn is_time_range(operator: &Operator) -> bool { + matches!(operator, Operator::NonASAP(NonASAPOp::TimeRange { .. })) +} + +/// Chains of 1-minute and of 5-minute windows that differ in nothing else +/// have one coverage and different keys: the view node's own window +/// differs. +#[test] +fn chain_views_differing_only_in_window_width_have_different_view_state_keys() { + let (mut one_minute, chain, _) = chain_dag(MINUTE_MS); + let one_minute = view_at(&mut one_minute, chain); + let (mut five_minutes, chain, _) = chain_dag(5 * MINUTE_MS); + let five_minutes = view_at(&mut five_minutes, chain); + assert_eq!(one_minute.coverage(), five_minutes.coverage()); + assert_ne!(one_minute.view_state_key(), five_minutes.view_state_key()); +} + +/// The last 5 minutes of a 1-minute chain are five window rows, of a +/// 5-minute chain one: a `TimeRange` view over a chain keeps the chain's +/// windows, so the two have different keys. +#[test] +fn time_range_views_over_chains_of_different_widths_have_different_view_state_keys() { + let over_one_minute = view_over_chain(MINUTE_MS, is_time_range); + let over_five_minutes = view_over_chain(5 * MINUTE_MS, is_time_range); + assert_eq!(over_one_minute.coverage(), over_five_minutes.coverage()); + assert_ne!( + over_one_minute.view_state_key(), + over_five_minutes.view_state_key() + ); +} + +/// A `TimeRangeCover` of the last 10 minutes over a 5-minute and a 1-minute +/// chain of one scan of `t`, as a view refreshed on first read (KLL +/// `k = 200`), over its chains kept as views refreshed at ingestion. +fn cover_view() -> MaterializedView { + let new = |operator| OperatorNode::new_shared(operator).unwrap(); + let scan = new(Operator::NonASAP(NonASAPOp::Scan { + source: Source::Table { + table_ref: "t".into(), + }, + predicates: vec![], + schema: Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("value", DataType::Float64, false), + ], + 0, + vec![], + ), + })); + let chain = |width_ms: u64| { + new(Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: scan.clone(), + summary_type: FieldDataType::Sketch(SketchAlgorithm::Kll), + input: SummaryUpdate::column(ColumnRef::Named("value".into())), + reduction: Reduction::Reduce(GroupKeys::default()), + filter: None, + tumbling_window_width_ms: width_ms, + })) + }; + let cover = new(Operator::NonASAP(NonASAPOp::TimeRangeCover { + range: std::time::Duration::from_millis(10 * MINUTE_MS), + offset_ms: 0, + levels: vec![chain(5 * MINUTE_MS), chain(MINUTE_MS)], + })); + let merge = new(Operator::ASAP(ASAPOp::SummaryMerge { + children: vec![cover], + group_by: None, + })); + let p50 = new(Operator::ASAP(ASAPOp::SummaryEstimate { + summary_input: merge, + query: SketchStatistic::Quantile { q: 0.5 }, + })); + let mut dag = + asap_types::test_support::forwarders::physical_asap_dag_at_query_time(&p50).unwrap(); + set_build_parameters(&mut dag.nodes, Some(&SketchParams::Kll { k: 200 })); + let chains: Vec = dag + .nodes + .iter() + .filter(|node| { + matches!( + node.payload, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { .. }) + ) + }) + .map(|node| node.id as u64) + .collect(); + let cover = dag + .nodes + .iter() + .find(|node| { + matches!( + node.payload, + Operator::NonASAP(NonASAPOp::TimeRangeCover { .. }) + ) + }) + .unwrap() + .id; + let node = node_mut(&mut dag, cover); + node.lifetime = Lifetime::AcrossEvaluations(StorageMedium::Memory); + node.retention_ms = Some(10 * MINUTE_MS); + node.parameters = Some(SketchParams::Kll { k: 200 }); + node.view_coverage = Some(ViewCoverage::new("kll of t.value".into(), vec![])); + let mut ids = chains; + ids.push(cover as u64); + views_at(&mut dag, &ids) + .unwrap() + .into_iter() + .find(|view| view.node_id == cover) + .unwrap() +} + +/// A `TimeRangeCover` view's rows are windows of each of its levels: its +/// key's window lists the levels' widths, widest first. +#[test] +fn a_time_range_cover_view_keys_its_levels_widths() { + let view = cover_view(); + assert_eq!( + serde_json::to_value(&view.view_state_key().window).unwrap(), + serde_json::json!({"tumbling_levels": {"widths_ms": [300000, 60000]}}) + ); +} + +/// A merge of the last 5 minutes from a 1-minute chain and one from a +/// 5-minute chain hold one state, computed two ways: one key. The chain +/// below the view says how the state is computed, not what it is. +#[test] +fn merges_of_one_range_over_chains_of_different_widths_share_a_view_state_key() { + let over_one_minute = view_over_chain(MINUTE_MS, is_merge); + let over_five_minutes = view_over_chain(5 * MINUTE_MS, is_merge); + assert_eq!(over_one_minute.coverage(), over_five_minutes.coverage()); + assert_eq!( + over_one_minute.view_state_key(), + over_five_minutes.view_state_key() + ); +} + +/// One chain view refreshed at ingestion and kept in memory for ever, and +/// the same view refreshed on first read and kept on disk for an hour: +/// one stored state, so one key; two plans, so two plan ids. +#[test] +fn views_differing_only_in_refresh_retention_or_medium_have_equal_view_state_keys() { + let (mut at_ingestion, chain, _) = chain_dag(MINUTE_MS); + let at_ingestion_view = view_at(&mut at_ingestion, chain); + let (mut on_first_read, chain, _) = chain_dag(MINUTE_MS); + let node = node_mut(&mut on_first_read, chain); + node.lifetime = Lifetime::AcrossEvaluations(StorageMedium::Disk); + node.retention_ms = Some(60 * MINUTE_MS); + let on_first_read_view = view_at(&mut on_first_read, chain); + assert_eq!( + at_ingestion_view.refresh(), + MaterializedViewRefresh::AtIngestion + ); + assert_eq!( + on_first_read_view.refresh(), + MaterializedViewRefresh::OnFirstRead + ); + assert_ne!( + at_ingestion_view.retention_ms(), + on_first_read_view.retention_ms() + ); + assert_eq!( + at_ingestion_view.view_state_key(), + on_first_read_view.view_state_key() + ); + assert_ne!(at_ingestion.plan_id(), on_first_read.plan_id()); + assert_eq!(at_ingestion_view.plan_id(), at_ingestion.plan_id()); +} + +/// The committed sketch workload `chains-10m-5m-3m-10s` (quantiles over +/// `data` with `[10m]`, `[5m]` and `[3m]` ranges, the last every 10 s), +/// planned as its `mvp` snapshot is: raw data not retained, the snapshot's +/// cost inputs. +async fn chains_plan() -> InstallablePlan { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let read = |path: &str| std::fs::read_to_string(root.join(path)).unwrap(); + let workload: PlanningWorkload = serde_json::from_str(&read( + "crates/planner-cli/tests/sketch_plan_snapshots/workloads/chains-10m-5m-3m-10s.json", + )) + .unwrap(); + let capabilities: DeploymentCapabilities = serde_json::from_str(&read( + "crates/planner-cli/tests/sketch_plan_snapshots/deployments/mvp.capabilities.json", + )) + .unwrap(); + let cost_inputs: CostInputs = serde_json::from_str(&read( + "tools/dag-viewer/cost-inputs/aws-fargate-us-east-1.json", + )) + .unwrap(); + let models = PlanningModels::builtin() + .with_deployment_capabilities(&capabilities) + .with_cost_inputs(&cost_inputs); + plan_installable(UserInput::new(&workload, FrontendInput::Promql, models)) + .await + .unwrap() + .0 +} + +/// Main's snapshot of this workload has three views of one coverage: a +/// 5-minute chain, a 10-second chain and 60-second windows merged from it. +/// Their keys differ pairwise. +#[tokio::test] +async fn planned_views_of_one_coverage_get_distinct_view_state_keys() { + let views = chains_plan().await.materialized_views().unwrap(); + let coverage = views[0].coverage(); + let same_coverage: Vec<&MaterializedView> = views + .iter() + .filter(|view| view.coverage() == coverage) + .collect(); + assert_eq!(same_coverage.len(), 3, "{views:#?}"); + for (i, first) in same_coverage.iter().enumerate() { + for second in &same_coverage[i + 1..] { + assert_ne!( + first.view_state_key(), + second.view_state_key(), + "views {} and {}", + first.node_id, + second.node_id + ); + } + } +} + +/// The key of the planned 5-minute chain, written out as its JSON: what a +/// durable store recovers states by, so a change to it is a change to what +/// a deployment has stored. The JSON reads back as the same key. +#[tokio::test] +async fn the_view_state_key_of_a_planned_chain_is_pinned_and_round_trips_through_json() { + let plan = chains_plan().await; + let views = plan.materialized_views().unwrap(); + let five_minute_chain = views + .iter() + .find(|view| { + plan.dag.nodes.iter().any(|node| { + node.id == view.node_id + && matches!( + node.payload, + Operator::ASAP(ASAPOp::SummaryTumblingWindowChain { + tumbling_window_width_ms: 300_000, + .. + }) + ) + }) + }) + .expect("a 5-minute chain view"); + let key = five_minute_chain.view_state_key(); + assert_eq!( + serde_json::to_value(key).unwrap(), + serde_json::json!({ + "definition_id": "bfbffb8f01ab202d585c3e18c9f78080", + "window": {"tumbling": {"width_ms": 300000}}, + "logical_properties": {"parameters": {"Kll": {"k": 2863}}} + }) + ); + let json = serde_json::to_string(key).unwrap(); + assert_eq!(&serde_json::from_str::(&json).unwrap(), key); +} + +/// `quantile_over_time(0.99, data[5m])` every minute, alone and next to a +/// query over another metric: two plans, one key for the quantile's view. +#[tokio::test] +async fn a_view_planned_in_two_workloads_keeps_its_view_state_key() { + let workload = |queries: &[&str]| -> PlanningWorkload { + let repeating: Vec = queries + .iter() + .map(|query| { + serde_json::json!({ + "demand": {"fixed_interval_at": {"evaluation_phase": 0, "interval": 60000}}, + "predictability": {"predictable": {"known_at": null}}, + "query": query, + "requirements": {"accuracy": {"failure_probability": 0.01, "max_error": 0.01}} + }) + }) + .collect(); + serde_json::from_value(serde_json::json!({ + "data_workload": { + "arrival": {"ingesting": {"rows_per_second": 2000.0}}, + "sources": { + "data": {"metric_type": "gauge", "sample_interval": 15000, "series_count": 10000}, + "other": {"metric_type": "gauge", "sample_interval": 15000, "series_count": 10000} + } + }, + "query_workload": {"language": "promql", "query_batch": null, "repeating_queries": repeating} + })) + .unwrap() + }; + let capabilities = DeploymentCapabilities { + raw_data_retained: false, + query_time_results_retained: false, + ..Default::default() + }; + let plan = |workload: PlanningWorkload| { + let capabilities = capabilities.clone(); + async move { + let models = PlanningModels::builtin().with_deployment_capabilities(&capabilities); + plan_installable(UserInput::new(&workload, FrontendInput::Promql, models)) + .await + .unwrap() + .0 + } + }; + let alone = plan(workload(&["quantile_over_time(0.99, data[5m])"])).await; + let beside = plan(workload(&[ + "quantile_over_time(0.99, data[5m])", + "sum_over_time(other[1m])", + ])) + .await; + let alone_views = alone.materialized_views().unwrap(); + let beside_views = beside.materialized_views().unwrap(); + assert!(!alone_views.is_empty()); + assert_ne!(alone.dag.plan_id(), beside.dag.plan_id()); + // A view's operator, as the plan file writes it (its inputs' node ids + // removed): the quantile's views are found in the second plan by it. + let operator_of = |plan: &InstallablePlan, view: &MaterializedView| { + let node = plan + .dag + .nodes + .iter() + .find(|node| node.id == view.node_id) + .unwrap(); + let mut payload = serde_json::to_value(&node.payload).unwrap(); + strip_node_ids(&mut payload); + payload + }; + for view in &alone_views { + let same_operator: Vec<&MaterializedView> = beside_views + .iter() + .filter(|other| operator_of(&beside, other) == operator_of(&alone, view)) + .collect(); + assert_eq!(same_operator.len(), 1, "{:?}", view.view_state_key()); + assert_eq!(same_operator[0].view_state_key(), view.view_state_key()); + } +} + +/// `value` without the node ids its operator's inputs are written as. +fn strip_node_ids(value: &mut serde_json::Value) { + match value { + serde_json::Value::Object(fields) => { + for key in ["child", "children", "summary_input", "levels"] { + fields.remove(key); + } + fields.values_mut().for_each(strip_node_ids); + } + serde_json::Value::Array(items) => items.iter_mut().for_each(strip_node_ids), + _ => {} + } +} diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json index e407fe010..8f8b81587 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "3b3f67a1f3c9d5b2763c9de99557f43e", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "4979322924750ccd229ed30e06b692a0", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "query": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{job=\"order-service\"}[5m])) by (le))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json index 95e0bbf53..fb2dd3b6d 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "782b58d5b5663e0807064a09f1d9b98e", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -68,8 +80,20 @@ "materialized_views": [] }, "node_id": 7, + "plan_id": "782b58d5b5663e0807064a09f1d9b98e", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "planner_executor_error": "the executor cannot compile the plan's query run: invalid DAG: node 13: invalid DAG: value operation has no native implementation", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json index 33116b37e..ccf75dc61 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "9b8f7e452816f875449016c748516f92", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "4979322924750ccd229ed30e06b692a0", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "planner_executor_error": "the executor cannot compile the plan's query run: invalid DAG: node 7: invalid DAG: value operation has no native implementation", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json index 7ef1a033a..c0bb9d7bc 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -70,8 +82,20 @@ ] }, "node_id": 2, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -107,8 +131,20 @@ ] }, "node_id": 3, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } }, { "coverage": { @@ -142,8 +178,20 @@ "materialized_views": [] }, "node_id": 9, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -179,8 +227,20 @@ ] }, "node_id": 10, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -216,8 +276,20 @@ ] }, "node_id": 11, + "plan_id": "4f1e762604bbf979289dc017b44a331c", "refresh": "at_ingestion", - "retention_ms": 28800000 + "retention_ms": 28800000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } } ], "query": "sum(increase(http_requests_total{job=\"payment-service\",status=~\"5..\"}[1h] offset 6h)) / sum(increase(http_requests_total{job=\"payment-service\"}[1h] offset 6h))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json index 7e1a352f5..e81f62fab 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -70,8 +82,20 @@ ] }, "node_id": 2, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -107,8 +131,20 @@ ] }, "node_id": 3, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "e2a484ba8499e6304dc20ec7f22439f1", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } }, { "coverage": { @@ -142,8 +178,20 @@ "materialized_views": [] }, "node_id": 9, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -179,8 +227,20 @@ ] }, "node_id": 10, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -216,8 +276,20 @@ ] }, "node_id": 11, + "plan_id": "6ce757cd533b9cd3e525a35bee1ce088", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } } ], "query": "sum(increase(http_requests_total{job=\"payment-service\",status=~\"5..\"}[1h])) / sum(increase(http_requests_total{job=\"payment-service\"}[1h]))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json index c1d2c5bcb..5814bb777 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "16936ea2ddee5a4d02b813c938c1d581", "refresh": "at_ingestion", - "retention_ms": 7500000 + "retention_ms": 7500000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "query": "sum(rate(http_requests_total{job=\"order-service\"}[5m] offset 1h))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json index 849b3117c..c61a0763f 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json @@ -33,8 +33,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "18cb4ce5ea6faeb4cd53939f67c8f61d", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "f59063d026a5d754ce7f409ff9b0b9d7", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "query": "sum(rate(http_requests_total{job=\"order-service\"}[5m]))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json index 993a24d05..0080493be 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json @@ -14,8 +14,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "caf2808753629aef042a4137c52532cf", "refresh": "at_ingestion", - "retention_ms": 3900000 + "retention_ms": 3900000, + "view_state_key": { + "definition_id": "39b753519c8eabf9fe5af63fcfb59e19", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "query": "sum(rate(http_requests_total{job=~\"user-service|order-service|payment-service\"}[5m]))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json index c4fc716b6..97ee9285b 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json @@ -14,8 +14,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "904aa65a5adbf0e8b33be1f3b7f0ba37", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -32,8 +44,20 @@ ] }, "node_id": 2, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "904aa65a5adbf0e8b33be1f3b7f0ba37", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -50,8 +74,20 @@ ] }, "node_id": 3, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "904aa65a5adbf0e8b33be1f3b7f0ba37", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } }, { "coverage": { @@ -66,8 +102,20 @@ "materialized_views": [] }, "node_id": 9, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "39b753519c8eabf9fe5af63fcfb59e19", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -84,8 +132,20 @@ ] }, "node_id": 10, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "39b753519c8eabf9fe5af63fcfb59e19", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -102,8 +162,20 @@ ] }, "node_id": 11, + "plan_id": "ef77cd5303dccd877907b5305d10a2a5", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "39b753519c8eabf9fe5af63fcfb59e19", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } } ], "query": "sum(rate(http_requests_total{status=~\"5..\",job=~\"user-service|order-service|payment-service\"}[1h])) / sum(rate(http_requests_total{job=~\"user-service|order-service|payment-service\"}[1h]))", diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q26.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q26.json index da0108cf0..30b8d60b6 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q26.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q26.json @@ -14,8 +14,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "f413ac4f80b9ec7adf5ccc28716cc089", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "466f50917756802af016b8b6f1e0cd5e", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -32,8 +44,20 @@ ] }, "node_id": 2, + "plan_id": "f413ac4f80b9ec7adf5ccc28716cc089", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "466f50917756802af016b8b6f1e0cd5e", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -50,8 +74,20 @@ ] }, "node_id": 3, + "plan_id": "f413ac4f80b9ec7adf5ccc28716cc089", "refresh": "at_ingestion", - "retention_ms": 7200000 + "retention_ms": 7200000, + "view_state_key": { + "definition_id": "466f50917756802af016b8b6f1e0cd5e", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 900000 + } + } + } } ], "query": "sum(rate(process_cpu_seconds_total[1h]))", diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json index 7e54e7ab8..6a09150af 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "f6f31722b12fc85f69ff48e068761870", "refresh": "at_ingestion", - "retention_ms": 600000 + "retention_ms": 600000, + "view_state_key": { + "definition_id": "bfbffb8f01ab202d585c3e18c9f78080", + "logical_properties": { + "parameters": { + "Kll": { + "k": 2863 + } + } + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } }, { "coverage": { @@ -30,8 +46,24 @@ "materialized_views": [] }, "node_id": 10, + "plan_id": "f6f31722b12fc85f69ff48e068761870", "refresh": "at_ingestion", - "retention_ms": 180000 + "retention_ms": 180000, + "view_state_key": { + "definition_id": "bfbffb8f01ab202d585c3e18c9f78080", + "logical_properties": { + "parameters": { + "Kll": { + "k": 1404 + } + } + }, + "window": { + "tumbling": { + "width_ms": 10000 + } + } + } }, { "coverage": { @@ -48,8 +80,24 @@ ] }, "node_id": 11, + "plan_id": "f6f31722b12fc85f69ff48e068761870", "refresh": "at_ingestion", - "retention_ms": 180000 + "retention_ms": 180000, + "view_state_key": { + "definition_id": "bfbffb8f01ab202d585c3e18c9f78080", + "logical_properties": { + "parameters": { + "Kll": { + "k": 1404 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ @@ -1199,7 +1247,7 @@ }, "parameters": { "Kll": { - "k": 1404 + "k": 2863 } }, "payload": { @@ -1273,7 +1321,7 @@ }, "parameters": { "Kll": { - "k": 1404 + "k": 2863 } }, "payload": { @@ -1333,7 +1381,7 @@ }, "parameters": { "Kll": { - "k": 1404 + "k": 2863 } }, "payload": { @@ -1509,7 +1557,7 @@ }, "parameters": { "Kll": { - "k": 1404 + "k": 2863 } }, "payload": { @@ -1569,7 +1617,7 @@ }, "parameters": { "Kll": { - "k": 1404 + "k": 2863 } }, "payload": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/nested-windows-15m-1h-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/nested-windows-15m-1h-mvp.json index 00f651241..254a48e74 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/nested-windows-15m-1h-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/nested-windows-15m-1h-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "64ca7f25b93e6c8c4c8feff333df1a23", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "64ca7f25b93e6c8c4c8feff333df1a23", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/quantile-grouped-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/quantile-grouped-mvp.json index 3695faaac..7445a5d6f 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/quantile-grouped-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/quantile-grouped-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "f7dc3dbf9f6c995d655257d30264a96a", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 10000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "f7dc3dbf9f6c995d655257d30264a96a", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/quantile-single-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/quantile-single-mvp.json index 18a8198e1..1e3b9ed0d 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/quantile-single-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/quantile-single-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "c5a429f13d5fe0d638487a1f29fb6de1", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 10000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "c5a429f13d5fe0d638487a1f29fb6de1", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json index 390c1d8b7..777b24251 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "af364d44eccce9e553faf9caf2443cd5", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 1000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "af364d44eccce9e553faf9caf2443cd5", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json index 9f1bd5418..7062c108f 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "8c2bbba375df73032544bda8ce858852", "refresh": "at_ingestion", - "retention_ms": 100000 + "retention_ms": 100000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 1000 + } + } + } }, { "coverage": { @@ -30,8 +46,20 @@ "materialized_views": [] }, "node_id": 8, + "plan_id": "8c2bbba375df73032544bda8ce858852", "refresh": "at_ingestion", - "retention_ms": 1200000 + "retention_ms": 1200000, + "view_state_key": { + "definition_id": "87fb3a2af6a1c70dca832c73960f21b2", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 30000 + } + } + } }, { "coverage": { @@ -48,8 +76,20 @@ ] }, "node_id": 9, + "plan_id": "8c2bbba375df73032544bda8ce858852", "refresh": "at_ingestion", - "retention_ms": 1200000 + "retention_ms": 1200000, + "view_state_key": { + "definition_id": "87fb3a2af6a1c70dca832c73960f21b2", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -66,8 +106,20 @@ ] }, "node_id": 10, + "plan_id": "8c2bbba375df73032544bda8ce858852", "refresh": "at_ingestion", - "retention_ms": 1200000 + "retention_ms": 1200000, + "view_state_key": { + "definition_id": "87fb3a2af6a1c70dca832c73960f21b2", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json index 89c748eb5..925859288 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "c045967dec81e9d78136e1163a395e6f", "refresh": "at_ingestion", - "retention_ms": 100000 + "retention_ms": 100000, + "view_state_key": { + "definition_id": "0c7f962d8fde713c1de7a58752019151", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 1000 + } + } + } }, { "coverage": { @@ -30,8 +46,20 @@ "materialized_views": [] }, "node_id": 8, + "plan_id": "c045967dec81e9d78136e1163a395e6f", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "87fb3a2af6a1c70dca832c73960f21b2", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 5000 + } + } + } }, { "coverage": { @@ -48,8 +76,20 @@ ] }, "node_id": 9, + "plan_id": "c045967dec81e9d78136e1163a395e6f", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "87fb3a2af6a1c70dca832c73960f21b2", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/ratio-of-quantiles-1h-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/ratio-of-quantiles-1h-mvp.json index e1f9c0e73..e351ddc87 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/ratio-of-quantiles-1h-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/ratio-of-quantiles-1h-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "18fa0355977198a88b4f05910987e4d1", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.02 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "18fa0355977198a88b4f05910987e4d1", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.02 + } + } + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/shared-quantiles-1h-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/shared-quantiles-1h-mvp.json index cf32a34db..5c930e67e 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/shared-quantiles-1h-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/shared-quantiles-1h-mvp.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "ae7fcf6e1ea97f76ca21b30b49411252", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } }, { "coverage": { @@ -32,8 +48,24 @@ ] }, "node_id": 2, + "plan_id": "ae7fcf6e1ea97f76ca21b30b49411252", "refresh": "at_ingestion", - "retention_ms": 3600000 + "retention_ms": 3600000, + "view_state_key": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "logical_properties": { + "parameters": { + "DDSketch": { + "alpha": 0.05 + } + } + }, + "window": { + "tumbling": { + "width_ms": 300000 + } + } + } } ], "queries": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-different-windows-raw-retained.json b/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-different-windows-raw-retained.json index 40127549d..88bc5cd2e 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-different-windows-raw-retained.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-different-windows-raw-retained.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 5, + "plan_id": "6d7351cc3cf7ce07c425fd0b394d9508", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "a446d509bf79a41e64d4c7dc4e541037", + "logical_properties": { + "parameters": { + "Kll": { + "k": 547 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "planner_executor_error": "the executor cannot refresh materialized view 5 from its inputs: invalid DAG: summary time column must be a timestamp", diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-same-window-raw-retained.json b/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-same-window-raw-retained.json index 8ce23df1f..d24ff8824 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-same-window-raw-retained.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/sql-rollup-quantile-same-window-raw-retained.json @@ -14,8 +14,24 @@ "materialized_views": [] }, "node_id": 5, + "plan_id": "89012c8e68fdc98e4a2444c794e86277", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "a446d509bf79a41e64d4c7dc4e541037", + "logical_properties": { + "parameters": { + "Kll": { + "k": 547 + } + } + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "planner_executor_error": "the executor cannot refresh materialized view 5 from its inputs: invalid DAG: summary time column must be a timestamp", @@ -183,10 +199,10 @@ "timing": "query_time" }, "9": { - "cost_per_second": 1.8740000046e-15, + "cost_per_second": 1.87400004601e-15, "cost_source": "analytical", "cpu_core_seconds_per_second": 1.66666666667e-10, - "detail": "operator: pass 10 rows; x 0.0167/s; holds 24 bytes for 0.000 ms", + "detail": "operator: pass 10 rows; x 0.0167/s; holds 240 bytes for 0.000 ms", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "Project", @@ -199,7 +215,7 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 995666.351778, + "average_memory_bytes": 995666.351779, "cpu_ops_per_second": 1343987.1, "disk_bytes": 9600000, "latency_per_query": [ @@ -221,7 +237,7 @@ } ], "peak_cpu_cores": 3, - "peak_memory_bytes": 3255584, + "peak_memory_bytes": 3255800, "precompute_load": 4.16666666667e-7, "recommended_configuration": { "ingest": { @@ -1230,7 +1246,9 @@ }, { "id": 9, - "lifetime": "None", + "lifetime": { + "OneEvaluation": "Memory" + }, "output_schema": { "closed": true, "fields": [ diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/topk-rate-guarantees-ignored-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/topk-rate-guarantees-ignored-mvp.json index 408e45a42..4b705279d 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/topk-rate-guarantees-ignored-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/topk-rate-guarantees-ignored-mvp.json @@ -14,8 +14,20 @@ "materialized_views": [] }, "node_id": 1, + "plan_id": "6656cdf755430662cfeaee0364ac65c2", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "d4ef697d67fefe4d32e35729d739c47f", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 10000 + } + } + } }, { "coverage": { @@ -32,8 +44,20 @@ ] }, "node_id": 2, + "plan_id": "6656cdf755430662cfeaee0364ac65c2", "refresh": "at_ingestion", - "retention_ms": 300000 + "retention_ms": 300000, + "view_state_key": { + "definition_id": "d4ef697d67fefe4d32e35729d739c47f", + "logical_properties": { + "parameters": null + }, + "window": { + "tumbling": { + "width_ms": 60000 + } + } + } } ], "queries": [ diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index ac00cf2f9..dff018f8f 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -13,7 +13,9 @@ edition = "2021" # this feature flag. A shared Rc still (de)serializes as an ordinary inline # value, once per reference, exactly like the old Box. serde = { version = "1", features = ["derive", "rc"] } -serde_json = "1" +# float_roundtrip: a plan file read back has the floats it was written +# with, so `PhysicalASAPDAG::plan_id` survives the round trip. +serde_json = { version = "1", features = ["float_roundtrip"] } thiserror = "2" # The sketch rows of the family-capability table (`SketchFamily::capability`). asap_sketchlib = { workspace = true } diff --git a/crates/types/src/plan/content_id.rs b/crates/types/src/plan/content_id.rs new file mode 100644 index 000000000..35632f9cc --- /dev/null +++ b/crates/types/src/plan/content_id.rs @@ -0,0 +1,24 @@ +//! Content ids of plan parts: a part's JSON, hashed with 128-bit FNV-1a, so +//! two processes that hold the same part give the same id +//! ([`ViewCoverage::definition_id`](super::physical_asap_dag::ViewCoverage), +//! [`PhysicalASAPDAG::plan_id`](super::physical_asap_dag::PhysicalASAPDAG::plan_id)). + +use serde::Serialize; + +/// The 128-bit FNV-1a hash, in hex, of `value`'s JSON (non-finite floats +/// serialized by `serde_f64`): stable across processes and Rust versions, +/// equal for equal serializations. +pub(crate) fn content_id(value: &impl Serialize) -> String { + let text = serde_json::to_string(value).expect("a plan part serializes"); + fnv1a_128_hex(&text) +} + +/// The 128-bit FNV-1a hash of `text`, in hex. +fn fnv1a_128_hex(text: &str) -> String { + const OFFSET: u128 = 0x6c62272e07bb014262b821756295c58d; + const PRIME: u128 = 0x0000000001000000000000000000013b; + let hash = text.bytes().fold(OFFSET, |hash, byte| { + (hash ^ u128::from(byte)).wrapping_mul(PRIME) + }); + format!("{hash:032x}") +} diff --git a/crates/types/src/plan/materialized_view/mod.rs b/crates/types/src/plan/materialized_view/mod.rs index 53476da6d..528f1a86b 100644 --- a/crates/types/src/plan/materialized_view/mod.rs +++ b/crates/types/src/plan/materialized_view/mod.rs @@ -64,12 +64,16 @@ //! once. Stage 3's cost assumes this grouping; a runtime that splits a group //! computes the same states at a higher cost than priced. //! -//! Each view's `coverage` says what its stored state is: a stable id of its -//! definition (what it computes) and its selection (which rows went in, -//! with time relative to the evaluation time). Two views with the same -//! definition id and the same concrete selection (relative time made -//! absolute at an evaluation) hold the same state, so a runtime may store -//! it once. +//! ## Identifying a view +//! +//! Within one installed plan a view is `(plan_id, node_id)` +//! ([`MaterializedView::plan_id`]). What its stored state is, in any plan, +//! is its [`ViewStateKey`] ([`MaterializedView::view_state_key`]): what it +//! computes, the view node's own window and its θ. Its `coverage` adds which +//! rows went in (the selection, with time relative to the evaluation time). +//! Two views with the same key and the same concrete selection (relative +//! time made absolute at an evaluation) hold the same state, so a runtime +//! may store it once. use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -86,9 +90,15 @@ use crate::stages::EvaluationGrid; pub struct MaterializedView { /// The node whose output is materialized. pub node_id: PhysicalASAPNodeId, + /// The plan it belongs to (`PhysicalASAPDAG::plan_id`): with + /// `node_id`, its address in one installed plan. + pub(crate) plan_id: String, + /// What its stored state is, in any plan: from the view node alone. + pub(crate) view_state_key: ViewStateKey, /// Which run refreshes it. pub(crate) refresh: MaterializedViewRefresh, - /// What the stored state is: the node's aggregate coverage. + /// What it computes and which rows went in: the node's logical + /// aggregate coverage. pub(crate) coverage: ViewCoverage, /// What its refresh reads. pub inputs: MaterializedViewInputs, @@ -109,11 +119,20 @@ impl MaterializedView { pub fn retention_ms(&self) -> u64 { self.retention_ms } -} -#[cfg(any(test, feature = "test-support"))] -impl MaterializedView { - /// What the stored state is. + /// The plan the view belongs to (`PhysicalASAPDAG::plan_id`): with + /// `node_id`, its address in one installed plan. + pub fn plan_id(&self) -> &str { + &self.plan_id + } + + /// What its stored state is, in any plan: a store keys states by it + /// and the concrete selection. + pub fn view_state_key(&self) -> &ViewStateKey { + &self.view_state_key + } + + /// What it computes and which rows went in. pub fn coverage(&self) -> &ViewCoverage { &self.coverage } @@ -324,4 +343,7 @@ pub enum InstallableDagError { } mod raw_data; +mod view_state_key; mod views; + +pub use view_state_key::{ViewStateKey, ViewWindow}; diff --git a/crates/types/src/plan/materialized_view/view_state_key.rs b/crates/types/src/plan/materialized_view/view_state_key.rs new file mode 100644 index 000000000..e372db7e6 --- /dev/null +++ b/crates/types/src/plan/materialized_view/view_state_key.rs @@ -0,0 +1,121 @@ +//! What a materialized view's stored state is, in any plan +//! ([`ViewStateKey`]): logical-layer information carried on the view's +//! physical node, like its coverage. + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use crate::ir::operator::asap::ASAPOp; +use crate::ir::operator::node::Operator; +use crate::ir::operator::non_asap::NonASAPOp; +use crate::plan::physical_asap_dag::{PhysicalASAPDAGNode, PhysicalASAPNodeId, ViewCoverage}; +use crate::stages::LogicalProperties; + +/// What a view's stored state is, in any plan and process, from the view +/// node alone: what it computes (`definition_id`), the windows its rows +/// are (`window`) and its candidate's logical properties (θ). Two views with +/// equal keys and one concrete selection hold interchangeable states, so a +/// store keys states by `(ViewStateKey, concrete selection)`. The nodes +/// below the view say how the state is computed, not what it is, and do not +/// enter: equivalent implementations in one memo group with equal θ share a +/// key. Physical properties (timing, lifetime, retention, storage medium) +/// do not enter either. +/// +/// Example: a KLL chain view of 1-minute windows with `k = 200` is +/// `{ definition_id: "…", window: Some(Tumbling { width_ms: 60000 }), +/// logical_properties: { parameters: Kll { k: 200 } } }`; the same chain +/// with `k = 400` or 5-minute windows has another key. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ViewStateKey { + /// What is computed: the memo group's coverage definition + /// ([`ViewCoverage::definition_id`](crate::plan::physical_asap_dag::ViewCoverage)). + pub definition_id: String, + /// The windows the view's rows are, from its own operator + /// ([`ViewWindow`]); `None` for one state per group, whose window is in + /// its selection. + pub window: Option, + /// The view node's candidate's logical properties (θ). + pub logical_properties: LogicalProperties, +} + +impl ViewStateKey { + /// The key of the view at `node` with `coverage`, from the node alone: + /// its definition, the windows its rows are ([`ViewWindow::of_node`] + /// over `nodes`, the DAG's nodes by id) and its θ. + pub(super) fn of_view( + node: &PhysicalASAPDAGNode, + coverage: &ViewCoverage, + nodes: &HashMap, + ) -> Self { + ViewStateKey { + definition_id: coverage.definition_id().to_owned(), + window: ViewWindow::of_node(node, nodes), + logical_properties: LogicalProperties::of_parameters(node.parameters.clone()), + } + } +} + +/// The windows a view's rows are, from its operator: `None` in a key for a +/// view that is one state per group, whose window is in its selection. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum ViewWindow { + /// Tumbling windows `width_ms` wide, on a grid anchored at the epoch: a + /// `SummaryTumblingWindowChain`'s or a `SummaryMergeWindows`' rows, or + /// those a `TimeRange` or `TimeShift` over one selects. + Tumbling { width_ms: u64 }, + /// The windows a `TimeRangeCover` selects from its levels, one width + /// per level in its level order (widest first). + TumblingLevels { widths_ms: Vec }, +} + +impl ViewWindow { + /// The windows `node`'s rows are: a chain's or `SummaryMergeWindows`' + /// width; through a `TimeRange` or `TimeShift`, those of the node it + /// selects from; a `TimeRangeCover`'s levels' widths; `None` for any + /// other node (one state per group). + /// + /// Example: `TimeRange(5m, Chain[1m])` is `Tumbling { width_ms: 60000 }`; + /// `SummaryMerge(TimeRange(5m, Chain[1m]))` is `None`. + fn of_node( + node: &PhysicalASAPDAGNode, + nodes: &HashMap, + ) -> Option { + match &node.payload { + Operator::ASAP( + ASAPOp::SummaryTumblingWindowChain { + tumbling_window_width_ms, + .. + } + | ASAPOp::SummaryMergeWindows { + tumbling_window_width_ms, + .. + }, + ) => Some(ViewWindow::Tumbling { + width_ms: *tumbling_window_width_ms, + }), + Operator::NonASAP( + NonASAPOp::TimeRange { child, .. } | NonASAPOp::TimeShift { child, .. }, + ) => Self::of_node(nodes[child], nodes), + Operator::NonASAP(NonASAPOp::TimeRangeCover { levels, .. }) => { + let widths_ms = levels + .iter() + .map(|level| match Self::of_node(nodes[level], nodes) { + Some(ViewWindow::Tumbling { width_ms }) => Some(width_ms), + _ => None, + }) + .collect::>>(); + // Every level of a cover is a chain of one build: a planner bug + // otherwise, which a key without the window would hide. + debug_assert!(widths_ms.is_some(), "a TimeRangeCover level is no chain"); + Some(ViewWindow::TumblingLevels { + widths_ms: widths_ms?, + }) + } + _ => None, + } + } +} diff --git a/crates/types/src/plan/materialized_view/views.rs b/crates/types/src/plan/materialized_view/views.rs index c61281258..74cf19dd6 100644 --- a/crates/types/src/plan/materialized_view/views.rs +++ b/crates/types/src/plan/materialized_view/views.rs @@ -8,7 +8,7 @@ use std::collections::{HashMap, HashSet}; use super::{ IngestionRefreshGroup, InstallableDagError, MaterializedView, MaterializedViewInputs, - MaterializedViewRefresh, RefreshWindow, + MaterializedViewRefresh, RefreshWindow, ViewStateKey, }; use crate::ir::operator::asap::ASAPOp; use crate::ir::operator::node::Operator; @@ -256,6 +256,7 @@ impl<'a> ViewIndex<'a> { .filter(|node| node.is_view()) .map(|node| node.id) .collect(); + let plan_id = self.dag.plan_id(); let mut derived = Vec::new(); for &id in self.children_first.iter().filter(|id| views.contains(id)) { let node = self.nodes[&id]; @@ -287,8 +288,11 @@ impl<'a> ViewIndex<'a> { reason: "the plan node carries no view_coverage".into(), } })?; + let view_state_key = ViewStateKey::of_view(node, &coverage, &self.nodes); derived.push(MaterializedView { node_id: id, + plan_id: plan_id.clone(), + view_state_key, refresh: if refreshed_at_ingestion { MaterializedViewRefresh::AtIngestion } else { diff --git a/crates/types/src/plan/mod.rs b/crates/types/src/plan/mod.rs index d9359f465..85f3acfc3 100644 --- a/crates/types/src/plan/mod.rs +++ b/crates/types/src/plan/mod.rs @@ -2,6 +2,7 @@ //! ([`physical_asap_dag`]), and the materialized views it installs //! ([`materialized_view`]); the time windows its nodes read //! ([`time_window`]). +mod content_id; pub mod materialized_view; pub mod physical_asap_dag; pub mod time_window; diff --git a/crates/types/src/plan/physical_asap_dag.rs b/crates/types/src/plan/physical_asap_dag.rs index 1e714ba01..daa0003f4 100644 --- a/crates/types/src/plan/physical_asap_dag.rs +++ b/crates/types/src/plan/physical_asap_dag.rs @@ -101,7 +101,8 @@ pub struct PhysicalASAPDAGNode { #[serde(skip)] pub selected_physical_candidate: Option, /// For a materialized view (lifetime `AcrossEvaluations`), what it - /// stores: its memo group's aggregate coverage, carried into the plan + /// computes and which rows went in: its memo group's aggregate + /// coverage, logical-layer information carried into the plan /// as a [`ViewCoverage`] (the selection, and the plan-scope content id /// of the definition, [`ViewCoverage::definition_id`]). Set when the /// plan is built from the memo, where the node's group is known; `None` @@ -156,8 +157,12 @@ impl ViewCoverage { selection, } } +} - /// The plan-scope content id of what the view computes. +impl ViewCoverage { + /// The content id of what the view computes, logically: equal for two + /// views of different θ or tumbling-window widths, so not a store key + /// on its own (see `MaterializedView::view_state_key`). pub fn definition_id(&self) -> &str { &self.definition_id } @@ -301,6 +306,18 @@ pub enum PhysicalASAPDAGValidationError { SummaryTypeSchemaMismatch { node: PhysicalASAPNodeId }, } +impl PhysicalASAPDAG { + /// The content id of this plan: the 128-bit FNV-1a hash, in hex, of its + /// JSON as the plan file holds it (every serialized field of its nodes, + /// edges and roots; not `selected_physical_candidate`). Equal for equal + /// plans across processes and plan-file round trips; different when any + /// of those fields differ. With a node id, it names one view of one + /// installed plan. O(plan size). + pub fn plan_id(&self) -> String { + super::content_id::content_id(self) + } +} + impl PhysicalASAPDAG { /// Each query's root in node ids, in workload order: query `i` is the /// scalar root keyed `i` when there is one, and otherwise the next entry diff --git a/crates/types/src/plan/view_coverage.rs b/crates/types/src/plan/view_coverage.rs index f640ff1fa..7d0268d8e 100644 --- a/crates/types/src/plan/view_coverage.rs +++ b/crates/types/src/plan/view_coverage.rs @@ -7,6 +7,7 @@ use serde::Serialize; +use super::content_id::content_id; use crate::ir::Operator; use crate::plan::physical_asap_dag::ViewCoverage; use crate::stages::{Memo, MemoGroupId}; @@ -16,9 +17,8 @@ use crate::stages::{Memo, MemoGroupId}; /// coverage. The definition's input groups are expanded to their /// expressions recursively, down to the `Scan`s, so the id names no memo /// group: two memos (or processes) that compute the same thing give the -/// same id, and different computations different ids. It is the 128-bit -/// FNV-1a hash, in hex, of the expanded definition's JSON (non-finite -/// floats serialized by `serde_f64`). Stage 3 sets it on a materialized +/// same id, and different computations different ids. It is the content id +/// (`plan::content_id`) of the expanded definition. Stage 3 sets it on a materialized /// view's plan node (`PhysicalASAPDAGNode::view_coverage`). pub fn view_coverage(memo: &Memo, group: MemoGroupId) -> Option { let coverage = memo.groups()[group.0 as usize] @@ -34,10 +34,8 @@ pub fn view_coverage(memo: &Memo, group: MemoGroupId) -> Option { .map(|operator| operator.map_children(|input| input.map(|input| expanded(memo, input)))) .collect(), }; - let serialized = - serde_json::to_string(&expanded_definition).expect("an expanded definition serializes"); Some(ViewCoverage { - definition_id: fnv1a_128_hex(&serialized), + definition_id: content_id(&expanded_definition), selection: coverage.selection.clone(), }) } @@ -65,14 +63,3 @@ fn expanded(memo: &Memo, group: MemoGroupId) -> ExpandedExpression { .map_children(|&input| expanded(memo, input)), )) } - -/// The 128-bit FNV-1a hash of `text`, in hex: stable across processes and -/// Rust versions. -fn fnv1a_128_hex(text: &str) -> String { - const OFFSET: u128 = 0x6c62272e07bb014262b821756295c58d; - const PRIME: u128 = 0x0000000001000000000000000000013b; - let hash = text.bytes().fold(OFFSET, |hash, byte| { - (hash ^ u128::from(byte)).wrapping_mul(PRIME) - }); - format!("{hash:032x}") -} diff --git a/crates/types/src/stages/logical/candidate/mod.rs b/crates/types/src/stages/logical/candidate/mod.rs index 9450c2eda..b49c27703 100644 --- a/crates/types/src/stages/logical/candidate/mod.rs +++ b/crates/types/src/stages/logical/candidate/mod.rs @@ -52,7 +52,7 @@ impl CandidateForMemoGroup { let input_requirements = vec![LogicalRequirements::default(); operator.children().len()]; Self { expression: CandidateExpression { operator }, - logical_properties: LogicalProperties { parameters }, + logical_properties: LogicalProperties::of_parameters(parameters), input_requirements, fused_groups, origin, @@ -142,7 +142,8 @@ pub enum CandidateError { /// states) carries the θ of the states it reads. /// [`Memo::add_candidate`](crate::stages::Memo::add_candidate) checks θ /// against the candidate's group's output ([`parameters_fit`]). -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] pub struct LogicalProperties { /// $\boldsymbol\theta_v$, from the algorithm's predefined list; `None` for /// an exact operator. @@ -150,6 +151,12 @@ pub struct LogicalProperties { } impl LogicalProperties { + /// The logical properties with θ `parameters`, as a plan node carries + /// them (`PhysicalASAPDAGNode::parameters`). + pub(crate) fn of_parameters(parameters: Option) -> Self { + Self { parameters } + } + /// $\boldsymbol\theta_v$. pub fn parameters(&self) -> Option<&SketchParams> { self.parameters.as_ref() diff --git a/crates/types/src/summary_type/parameters.rs b/crates/types/src/summary_type/parameters.rs index dd727787b..b25c63bf0 100644 --- a/crates/types/src/summary_type/parameters.rs +++ b/crates/types/src/summary_type/parameters.rs @@ -184,6 +184,22 @@ pub enum SketchParams { Hydra(HydraParams), } +// θ compares and hashes as a value so it can key a stored view +// (`ViewStateKey`). Its only float, DDSketch `alpha`, lies in (0, 1) in every +// θ the planner builds (`parameters_fit` checks it against the algorithm's +// list), so `==` is an equivalence there; the hash is that of its JSON text, +// which equal values share. The hash allocates a string: fine for a store's +// keys, not for a hot map keyed by θ. +impl Eq for SketchParams {} + +impl std::hash::Hash for SketchParams { + fn hash(&self, state: &mut H) { + serde_json::to_string(self) + .expect("sketch parameters serialize") + .hash(state); + } +} + /// A sampling summary family — retains an actual (weighted) subset of input /// rows rather than a compressed sketch. The retained rows are its summary /// sample ([`FieldDataType::SummarySample`](crate::ir::schema::FieldDataType::SummarySample)), diff --git a/crates/types/tests/coverage_finalize.rs b/crates/types/tests/coverage_finalize.rs index cc320ed7b..cb61654f6 100644 --- a/crates/types/tests/coverage_finalize.rs +++ b/crates/types/tests/coverage_finalize.rs @@ -58,6 +58,11 @@ fn a_finalized_rate_covers_what_the_rate_covers() { let finalized = add(&mut memo, finalize(counter, Some(CounterReadout::Rate))); assert!(coverage(&memo, rate).is_some()); assert_eq!(coverage(&memo, finalized), coverage(&memo, rate)); + // So a view of either form has one view coverage, and one view state key. + assert_eq!( + asap_types::plan::view_coverage(&memo, finalized), + asap_types::plan::view_coverage(&memo, rate) + ); } /// Each exact kind's finalize covers what its aggregate over the same rows diff --git a/crates/types/tests/memo_aggregate_coverage.rs b/crates/types/tests/memo_aggregate_coverage.rs index 5929e6d58..d91cf8d3c 100644 --- a/crates/types/tests/memo_aggregate_coverage.rs +++ b/crates/types/tests/memo_aggregate_coverage.rs @@ -683,3 +683,59 @@ fn a_cover_under_an_offset_covers_its_range_that_much_earlier() { let direct = kll_over_last_5m_of(&mut memo, shift(HOUR_MS, None, g1)); assert_eq!(coverage(&memo, an_hour_back), coverage(&memo, direct)); } + +/// Known limitation (#1494): `sum(rate(latency{job="api"}[5m]))` from the +/// scan (the matcher below `rate`, never lifted) and from +/// `sum by (job) (rate(latency[5m]))` filtered to `job = "api"` (the +/// filter lifted) aggregate the same rows but get different coverages, so +/// one stored state gets two keys. +#[test] +#[ignore = "known limitation: #1494"] +fn known_limitation_1494_coverage_does_not_depend_on_where_the_filter_sits() { + use asap_types::test_support::memo_fixtures::aggregate; + let mut memo = Memo::new(&DataWorkload::default()); + let sum_of = |memo: &mut Memo, input: MemoGroupId| { + memo.find_or_add_group(aggregate( + Reduction::by(vec![]), + AggIntent::Sum { col: Some(1) }, + input, + )) + .unwrap() + }; + let rate_of = |memo: &mut Memo, predicates: Vec>| { + let series = memo.find_or_add_group(latency(predicates)).unwrap(); + let window = memo + .find_or_add_group(range(5 * MINUTE_MS, series)) + .unwrap(); + memo.find_or_add_group(aggregate(Reduction::PerEntity, AggIntent::Rate, window)) + .unwrap() + }; + // From the scan: the matcher sits below `rate`. + let api_rate = rate_of(&mut memo, vec![job_is("api")]); + let from_scan = sum_of(&mut memo, api_rate); + // From `sum by (job)`: keep job "api" (column 0 of `[job, sum]`), then sum. + let rate = rate_of(&mut memo, vec![]); + let by_job = memo + .find_or_add_group(aggregate( + Reduction::by(vec![JOB]), + AggIntent::Sum { col: Some(1) }, + rate, + )) + .unwrap(); + let api_row = memo + .find_or_add_group(filter( + ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(0)), + op: CompareOpKind::Eq, + right: Box::new(ScalarExpr::Literal(ScalarValue::Utf8("api".into()))), + semantics: ExprSemantics::Promql, + }, + by_job, + )) + .unwrap(); + let from_rollup = sum_of(&mut memo, api_row); + let from_scan = view_coverage(&memo, from_scan).unwrap(); + let from_rollup = view_coverage(&memo, from_rollup).unwrap(); + assert_eq!(from_scan.definition_id(), from_rollup.definition_id()); + assert_eq!(from_scan.selection(), from_rollup.selection()); +} diff --git a/crates/types/tests/physical_asap_dag.rs b/crates/types/tests/physical_asap_dag.rs index 39691b4cd..25e738eb3 100644 --- a/crates/types/tests/physical_asap_dag.rs +++ b/crates/types/tests/physical_asap_dag.rs @@ -349,3 +349,89 @@ fn high_fan_in_edges_preserve_multiplicity_without_order_dependence() { Err(PhysicalASAPDAGValidationError::EdgeRoleMismatch { .. }) )); } + +/// `plan()` with its `Scan` keeping `value > threshold`, exported at query +/// time with each node's id; a float literal enters the plan's JSON. +fn plan_with_threshold(threshold: f64) -> PhysicalASAPDAG { + use asap_types::ir::scalar::expr_ir::{CompareOpKind, ScalarValue}; + use asap_types::ir::{ExprSemantics, Predicate, ScalarExpr}; + let scan = OperatorNode::new_shared(Operator::NonASAP(NonASAPOp::Scan { + source: Source::Table { + table_ref: "t".into(), + }, + predicates: vec![Predicate(ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(1)), + op: CompareOpKind::Gt, + right: Box::new(ScalarExpr::Literal(ScalarValue::Float64(threshold))), + semantics: ExprSemantics::Sql, + })], + schema: Schema::new(vec![ + Field::plain("key", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ]), + })) + .unwrap(); + let state = OperatorNode::new_shared(Operator::ASAP(ASAPOp::SummaryAgg { + child: scan, + summary_type: FieldDataType::ExactAggregate(ExactKind::Sum, ExactParams::Sum), + input: SummaryUpdate::column(ColumnRef::Named("value".into())), + reduction: Reduction::by(vec![0]), + filter: None, + })) + .unwrap(); + let root = OperatorNode::new_shared(Operator::ASAP(ASAPOp::FinalizeExactAccumulator { + child: state, + counter_readout: None, + })) + .unwrap(); + asap_types::test_support::forwarders::physical_asap_dag_at_query_time(&root).unwrap() +} + +/// A plan file read back has the plan id it was written with, with a float +/// literal whose bits `serde_json`'s default float parsing does not +/// restore (`1.0715660391465826e-75`): the planner and a runtime that reads +/// its plan file name the plan alike. +#[test] +fn the_plan_id_survives_a_plan_file_round_trip() { + let dag = plan_with_threshold(1.0715660391465826e-75); + let read: PhysicalASAPDAG = + serde_json::from_str(&serde_json::to_string(&dag).unwrap()).unwrap(); + assert_eq!(read, dag); + assert_eq!(read.plan_id(), dag.plan_id()); +} + +/// The plan id changes with every field of the plan file and with nothing +/// else: a node's retention, θ, lifetime or operator; not the in-memory +/// `selected_physical_candidate`. +#[test] +fn the_plan_id_changes_with_the_plan_and_only_with_it() { + let dag = plan_with_threshold(10.0); + let plan_id = dag.plan_id(); + assert_eq!(plan_id.len(), 32, "{plan_id}"); + assert!(plan_id.bytes().all(|byte| byte.is_ascii_hexdigit())); + let changed = |change: &dyn Fn(&mut PhysicalASAPDAG)| { + let mut changed = dag.clone(); + change(&mut changed); + changed.plan_id() + }; + assert_ne!( + changed(&|dag| dag.nodes[0].retention_ms = Some(60_000)), + plan_id + ); + assert_ne!( + changed(&|dag| { + dag.nodes[0].parameters = Some(asap_types::summary_type::SketchParams::Kll { k: 200 }) + }), + plan_id + ); + assert_ne!( + changed(&|dag| dag.nodes[0].lifetime = Lifetime::AcrossEvaluations(StorageMedium::Memory)), + plan_id + ); + assert_ne!(changed(&|dag| *dag = plan_with_threshold(20.0)), plan_id); + assert_eq!( + changed(&|dag| dag.nodes[0].selected_physical_candidate = + Some(asap_types::stages::PhysicalCandidateId(7))), + plan_id + ); +} diff --git a/docs/design_docs/physical-planning-and-deployment.md b/docs/design_docs/physical-planning-and-deployment.md index c3a1a3e66..5bb5c8206 100644 --- a/docs/design_docs/physical-planning-and-deployment.md +++ b/docs/design_docs/physical-planning-and-deployment.md @@ -24,8 +24,8 @@ flowchart LR | **Deployment** | Selected candidate, concrete data/state bindings and operational lifecycle | ASAPPlanner owns the first three layers and the shared physical operator -implementation library. Deployment systems such as ASAPQuery and asap-fusion -own deployment compilation and operation. Materialization is a planning contract +implementation library. Deployment runtimes own deployment compilation and +operation. Materialization is a planning contract associated with the logical DAG, not a separate computation IR. > **Status:** Stage 2 (physical ASAP-aware optimization) decides, per summary @@ -432,7 +432,7 @@ executor, and a deployment runtime. | **Executor: operator library** | `PhysicalOperator` and the native operators | `asap-executor` | DataFusion's `ExecutionPlan` nodes | | **Executor: compiled plan** | `compile(dag, views, roots)` → `CompiledPhysicalDAG` with raw data and materialized view slots | `asap-executor` | DataFusion's physical planner, which resolves tables while planning; ours leaves them as slots | | **Executor: deployment interface** | `DataStore` (`read_raw_data`, `read_materialized_view`), `RawDataRequest`, `MaterializedViewRequest`, `instantiate` | `asap-executor` defines it; the deployment implements it | DataFusion's `TableProvider` and catalog | -| **Deployment** | raw-data storage, the summary store (what a stored state is, where it lives, readiness, revisions), run scheduling, retention, transport | ASAPQuery, asap-fusion | catalog and runtime | +| **Deployment** | raw-data storage, the summary store (what a stored state is, where it lives, readiness, revisions), run scheduling, retention, transport | a deployment runtime | catalog and runtime | ### The plan file @@ -445,8 +445,9 @@ pub struct InstallablePlan { impl InstallablePlan { /// Reads `wire_version` before the rest, so an older file is refused by version. pub fn from_json(text: &str) -> Result; - /// Every materialized view, in dependency order: its node, refresh mode - /// (at ingestion, or on first read and kept), coverage, inputs and retention. + /// Every materialized view, in dependency order: its node, plan id, view + /// state key, refresh mode (at ingestion, or on first read and kept), + /// coverage, inputs and retention. pub fn materialized_views(&self) -> Result, InstallablePlanError>; /// The views refreshed at ingestion, by refresh group (one refresh window /// each), each group after the groups it reads. @@ -466,6 +467,31 @@ pub struct RefreshWindow { pub width_ms: u64, // width of each window pub phase_ms: u64, // where each window ends, modulo width_ms } +impl PhysicalASAPDAG { + /// The plan's content id: 128-bit FNV-1a, in hex, of the DAG's JSON. + pub fn plan_id(&self) -> String; +} +pub struct MaterializedView { + pub node_id: PhysicalASAPNodeId, // the view's node + pub inputs: MaterializedViewInputs, // the views its refresh reads + /* plan id, view state key, refresh, coverage, retention: read by the methods */ +} +impl MaterializedView { + pub fn plan_id(&self) -> &str; // with node_id: the view in one installed plan + pub fn view_state_key(&self) -> &ViewStateKey; // what its stored state is, in any plan + pub fn coverage(&self) -> &ViewCoverage; // definition_id and selection (logical) + pub fn refresh(&self) -> MaterializedViewRefresh; + pub fn retention_ms(&self) -> u64; +} +pub struct ViewStateKey { + pub definition_id: String, // what is computed (the memo group's coverage definition) + pub window: Option, // the view node's own windows + pub logical_properties: LogicalProperties, // the view node's candidate's θ +} +pub enum ViewWindow { // non_exhaustive + Tumbling { width_ms: u64 }, // a chain's or SummaryMergeWindows' rows, also through TimeRange / TimeShift + TumblingLevels { widths_ms: Vec }, // a TimeRangeCover's levels +} ``` These derivations are methods on `PhysicalASAPDAG` in `asap-types`, so a @@ -511,6 +537,55 @@ state is stamped with that end, so the same `TimeRange` selects them. A `TimeShift { at }` evaluates its input once per request, at the request's end (`@ end()`), start (`@ start()`) or the given time. +### Identifying a materialized view + +A view has two identities, in two scopes: + +- **In one installed plan:** `(plan_id, node_id)`. `plan_id` is the content + id of the plan's DAG: the 128-bit FNV-1a hash, in hex, of its JSON (every + serialized field of its nodes, edges and roots; not + `selected_physical_candidate`, which the plan file does not hold, nor the + query texts or wire version). Equal serializations have equal ids + across processes and plan-file round trips; a change to any serialized + field of the DAG changes it. +- **In any plan:** the store key `(ViewStateKey, concrete selection)`: two + views with equal keys and one concrete selection (the request's time + range and the selection's other constraints) hold interchangeable + states, so a runtime keeps one copy, also across replanning. A runtime + that wants a short id hashes the key's JSON itself. + +`ViewStateKey` is logical-layer information carried on the physical node, +like `view_coverage`, and it is taken from the view node alone: + +| Layer | What | On the node | In the key | +| --- | --- | --- | --- | +| Logical, memo group | what is computed | `view_coverage.definition_id` | `definition_id` | +| Logical, memo group | which rows went in | `view_coverage.selection` | no: the store key's second half | +| Logical, candidate | θ | `parameters` (the candidate's `LogicalProperties::parameters`) | `logical_properties` | +| The view node's operator | the windows its rows are | a `SummaryTumblingWindowChain`'s or `SummaryMergeWindows`' `tumbling_window_width_ms`, also through a `TimeRange` or `TimeShift` over one; a `TimeRangeCover`'s levels' widths | `window` (`None` for one state per group, whose window is in its selection) | +| Physical | refresh (timing), lifetime (medium), retention | node fields | no | +| Below the view node | how the state is computed | the sub-DAG | no | + +`definition_id` alone is not a store key: coverage leaves out θ and the +tumbling-window width. Two KLL views of one minute of `t.value` with +`k = 200` and `k = 400` have one coverage, and so do the three views of +the planned `chains-10m-5m-3m-10s` workload (a 5-minute chain, a 10-second +chain and 60-second windows merged from it); their keys differ in +`logical_properties` and in `window`. Equivalent implementations in one +memo group with equal θ share a key: +`SummaryMerge(TimeRange(5m, Chain[1m]))` and +`SummaryMerge(TimeRange(5m, Chain[5m]))` hold one state. This relies on the +planner's rule that a chain serves only readers evaluated on its grid (a +multiple of its width), so both read the same interval. Views that differ +only in refresh mode, retention or storage medium share a key too. Five +views `SummaryAgg(TimeRange(1m, TimeShift(i·1m, Scan)))`, `i = 0..4`, +share one key, and each minute's state is filed once under it and its +absolute interval. + +Known limitation: the key is only as good as the coverage it carries. A +coverage depends on where a filter sits, not only on which rows are +aggregated (#1494), so one stored state can get two keys. + ### Input slots and compilation An **input slot** is a position in a compiled DAG where data is read at run @@ -562,7 +637,7 @@ pub struct MaterializedViewRequest<'a> { | | `read_raw_data` | `read_materialized_view` | | --- | --- | --- | -| Keyed by | `Source` | `MaterializedView` (its coverage: the content id `definition_id` and selection) | +| Keyed by | `Source` | `MaterializedView` (its `view_state_key` and concrete selection; in one installed plan, `(plan_id, node_id)`) | | Time range | optional, a hint | always given, exact | | Predicates | a hint | none | | Executor re-filters | yes | no | @@ -570,10 +645,10 @@ pub struct MaterializedViewRequest<'a> { - A **time series** is a table `(ts, value, *labels)`, as `Source::TimeSeries` declares. - A **SQL table** is a table with a time index. -- A **materialized view** read returns exactly the states whose intervals tile the requested range. The store never counts an observation twice, never returns another definition's state, and never treats missing state as empty; it returns an error instead. +- A **materialized view** read returns exactly the states whose intervals tile the requested range. The store never counts an observation twice, never returns the state of another `view_state_key` or concrete selection, and never treats missing state as empty; it returns an error instead. Only the definition side of the deployment's summary store crosses the -interface (the view's coverage and schema). Instances (their interval, group +interface (the view's `view_state_key`, coverage and schema). Instances (their interval, group values, placement, status) stay inside the store, which resolves a read to them. @@ -677,7 +752,7 @@ dd_tumbling_window_0; the older tumbling windows were stored by earlier runs): refresh.instantiate(store) Scan calls read_raw_data(TimeSeries { latency }, time_range_ms = (12:04, 12:05]) once; both builds read its rows - store the KllState and the DDSketchState in the summary store, each under its view's coverage and interval + store the KllState and the DDSketchState in the summary store, each under its view's view_state_key and interval Query at T = 12:05 over (12:00, 12:05]: the installed DAG has the chain expanded: five tumbling window views, tumbling window i under TimeShift(i·1m) @@ -689,11 +764,11 @@ Query at T = 12:05 over (12:00, 12:05]: NativeKllMerge executes once for both readouts → p50, p99 ``` -The deployment matches a view to stored states by its coverage -(`definition_id` and selection). Identity has two scopes: the memo compares -coverages by `AggregateDefinition` `==` (its definitions hold memo group ids) -and needs no id; the plan carries the view's content id on its node -(`PhysicalASAPDAGNode::view_coverage`), defined at +The deployment matches a view to stored states by its `view_state_key` and +selection ([Identifying a materialized view](#identifying-a-materialized-view)). +The memo compares coverages by `AggregateDefinition` `==` (its definitions +hold memo group ids) and needs no id; the plan carries the view's content +id on its node (`PhysicalASAPDAGNode::view_coverage`), defined at [`ViewCoverage::definition_id`](../../crates/types/src/plan/physical_asap_dag.rs). At execution time it checks their actual coverage, revisions and readiness. A compiled plan cannot establish future @@ -714,9 +789,9 @@ sketch, or maintain different windows: such changes require replanning. | Where does retention live? | On the materialized-view node of the exported DAG | — | Mapping the materialized-views extension's terms: its `query()` is the sub-DAG -under the view's node, and `coverage.definition_id` (the content id, -[`ViewCoverage::definition_id`](../../crates/types/src/plan/physical_asap_dag.rs)) -identifies it. +under the view's node, and its stored state is identified by +`MaterializedView::view_state_key` with the selection (in one installed +plan, by `(plan_id, node_id)`). Its readiness is the summary store's status, which the deployment owns. Its `mv_dependencies` build graph is `MaterializedView.inputs`. @@ -775,7 +850,8 @@ operator/runtime fixtures: | Test | Contract exercised | | --- | --- | | `kll_tumbling_window_execution::five_tumbling_windows_roundtrip_and_shared_merge_runs_once` | One-minute tumbling window refreshes from raw data → five materialized view slots → shared native merge → p50/p99; counts every sample once, checks adjacent aligned windows and instruments one merge start per run | -| `kll_tumbling_window_execution::a_store_keyed_by_definition_and_time_range_answers_the_tumbling_windows` | A store that finds states only by `(definition_id, time range)` (the content id is an opaque string to the store) answers the five-tumbling-window query: the tumbling windows share one definition and request the five ranges that tile the window | +| `kll_tumbling_window_execution::a_store_keyed_by_view_state_key_and_time_range_answers_the_tumbling_windows` | A store that finds states only by `(view_state_key, time range)` answers the five-tumbling-window query: the tumbling windows share one key and request the five ranges that tile the window; with `k = 400` views over `k = 200` states, the read fails instead of answering (`…_misses_states_of_another_sketch_parameter`) | +| `view_state_key::*` (and `kll_tumbling_window_execution::views_differing_only_in_sketch_parameters_have_different_view_state_keys` for θ) | view-node-width-only differences give different keys; refresh, retention and medium do not; equivalent merges over 1-minute and 5-minute chains share a key; the three planned views of one coverage in `chains-10m-5m-3m-10s` get distinct keys; a view keeps its key across two workloads; the key is pinned and round-trips through JSON | | `runtime_install::tumbling_windows_of_one_refresh_window_read_each_raw_window_once` | A KLL chain and a DDSketch chain of 10 s tumbling windows over one `Scan` are one refresh group: each tumbling window window is read from raw data once, in one ingestion run that builds both tumbling windows; each state equals that of a run of its view alone, and both queries answer as the query-time reference | | `kll_tumbling_window_execution::tumbling_windows_reject_parameters_schema_and_missing_binding` | Parameter relabelling, incompatible schemas and missing views fail explicitly | | `precompute_candidates::grouped_rate_can_be_materialized_before_or_after_grouped_sum` | Stored counter state and stored Sum state answer like query time; summing counters before Rate does not | diff --git a/docs/design_docs/proposals/asap-primitive-schema.md b/docs/design_docs/proposals/asap-primitive-schema.md index 6924ef76e..a7606147e 100644 --- a/docs/design_docs/proposals/asap-primitive-schema.md +++ b/docs/design_docs/proposals/asap-primitive-schema.md @@ -321,7 +321,7 @@ Its definition differs from G4's, so G10 cannot merge with G4, even though both - `input`: the group the definition reads, below everything the walk passed (`None` when the walk lifted a predicate out of a `Scan`). - `unlifted_operators`: what the state computes over `input`, top down from the `SummaryAgg` or `Aggregate`, each operator with only the conditions that stayed. Each operator's main input is `None`; any other group it reads, such as the group of a scalar subquery in a `Filter`'s condition, is `Some(group)`. - `selection`: which output rows of that computation the state took, as a union of boxes. -- Identity, in two scopes. In the memo, coverages compare by `AggregateDefinition` `==` (it holds `MemoGroupId`s); nothing in the memo needs an id. The plan carries the view's content id, [`ViewCoverage::definition_id`](../../../crates/types/src/plan/physical_asap_dag.rs) (defined there), on the view's plan node (`PhysicalASAPDAGNode::view_coverage`), made by `view_coverage(memo, group)`, which expands the memo's coverage (each input group to its expression, down to the `Scan`s) rather than re-deriving it; a summary store files states under it together with a concrete selection. +- Identity, in two scopes. In the memo, coverages compare by `AggregateDefinition` `==` (it holds `MemoGroupId`s); nothing in the memo needs an id. The plan carries the view's content id, [`ViewCoverage::definition_id`](../../../crates/types/src/plan/physical_asap_dag.rs) (defined there), on the view's plan node (`PhysicalASAPDAGNode::view_coverage`), made by `view_coverage(memo, group)`, which expands the memo's coverage (each input group to its expression, down to the `Scan`s) rather than re-deriving it; it is not a store key on its own (it leaves out θ and the tumbling-window width): a summary store files states under the view's `ViewStateKey` (`MaterializedView::view_state_key`: this id, the view node's window and its θ) together with a concrete selection. ##### The definition diff --git a/tools/dag-viewer/README.md b/tools/dag-viewer/README.md index 24f79c8c8..892575e1a 100644 --- a/tools/dag-viewer/README.md +++ b/tools/dag-viewer/README.md @@ -150,7 +150,9 @@ whole document): `multiplier` and `detail`), `accepted_accuracy_per_query` (`summary`), `pruned_candidates` (as Stage 2's), `milp_variables`, `milp_constraints`, `materialized_views` (`node_id`, a plan node, `refresh`, - `coverage.definition_id`, `inputs` and `retention_ms`), + `plan_id`, `view_state_key` (`definition_id`, `window`, + `logical_properties`), `coverage.definition_id`, `inputs` and + `retention_ms`), `materialized_views_error` (the plan is invalid: its views cannot be derived), `planner_executor_can_run` (whether the Planner's executor compiles the plan) with `planner_executor_error` when