From 14473416f25712e8f3ea5c7599ef62c3d20ff2e7 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 15:44:09 +0000 Subject: [PATCH 1/2] feat(control plane): place exact accumulator chains on the collector The planner's DeploymentCapabilities lists no exact family: each is supported unless an exclusion its fields expand into rules it out. The collector rule read sketches only, so `sum_over_time(data[1m])` (an exact Sum chain) stayed in the backend and `data` was read raw although the collector's capabilities exclude only the counter states. Rule (a) now accepts an exact accumulator build over the sample value when no exclusion of `executor` matches the node. The capabilities version goes to 2: the same JSON now means exact families are built. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/control-plane/src/collector_views.rs | 67 +++++++++++++++-- crates/control-plane/tests/collector_views.rs | 71 +++++++++++++++---- .../tests/data/collector-capabilities.json | 2 +- 3 files changed, 119 insertions(+), 21 deletions(-) diff --git a/crates/control-plane/src/collector_views.rs b/crates/control-plane/src/collector_views.rs index aaa8314ec..c069e5d63 100644 --- a/crates/control-plane/src/collector_views.rs +++ b/crates/control-plane/src/collector_views.rs @@ -20,18 +20,22 @@ use asap_planner::{ DeploymentCapabilities, ExecutionTiming, InstallablePlan, InstallablePlanError, PhysicalASAPDAG, PhysicalASAPNodeId, SupportedSummary, INSTALLABLE_PLAN_WIRE_VERSION, }; +use asap_types::deployment_capabilities::CandidateDescription; use asap_types::ir::operator::arguments::{Reduction, Source}; use asap_types::ir::operator::kind::OperatorKind; use asap_types::ir::scalar::{ColumnRef, CompareOpKind, ScalarValue}; use asap_types::ir::schema::FieldDataType; use asap_types::ir::{ASAPOp, NonASAPOp, Operator, ScalarExpr}; use asap_types::plan::physical_asap_dag::PhysicalASAPDAGNode; +use asap_types::stages::PhysicalProperties; use asap_types::summary_type::{SketchAlgorithm, SummaryInputExpr, SummaryUpdate}; use common::CollectorViewsFile; use serde::Deserialize; -/// The `capabilities_version` this control plane reads. -const CAPABILITIES_VERSION: u32 = 1; +/// The `capabilities_version` this control plane reads. Version 2 reads +/// `executor` with the planner's semantics in full, exact accumulators +/// included; version 1 meant sketches only, with the same JSON. +const CAPABILITIES_VERSION: u32 = 2; /// What `asap_sketches --print-capabilities` prints: what the collector can /// run, in the planner's vocabulary, each capability stated once. @@ -56,7 +60,7 @@ pub struct CollectorExecutor { pub supported_summaries: Vec, /// Every other field, with the planner's serde (unknown fields /// refused); its own `supported_summaries` is `None`. The rule reads - /// none of them yet. + /// the exclusions they expand into for exact accumulator builds. pub rest: DeploymentCapabilities, } @@ -502,8 +506,10 @@ impl<'a> Index<'a> { } /// Rule (a): `node`'s operator is listed, with its arguments within that -/// entry's limits and `predicate_ops`, and any summary it builds or reads -/// within `executor.supported_summaries`. `Err` names what is not. +/// entry's limits and `predicate_ops`, any sketch it builds or reads +/// within `executor.supported_summaries`, and any exact accumulator it +/// builds not excluded by `executor` ([`within_exact`]). `Err` names what +/// is not. fn within_capabilities( node: &PhysicalASAPDAGNode, index: &Index, @@ -608,8 +614,12 @@ fn within_summaries( node: &PhysicalASAPDAGNode, capabilities: &CollectorCapabilities, ) -> Result<(), String> { - let FieldDataType::Sketch(algorithm) = summary_type else { - return Err(format!("summary {summary_type:?}")); + let algorithm = match summary_type { + FieldDataType::Sketch(algorithm) => algorithm, + FieldDataType::ExactAggregate(..) => { + return within_exact(summary_type, input, node, capabilities) + } + _ => return Err(format!("summary {summary_type:?}")), }; let entry = summary_entry(*algorithm, capabilities)?; let input_kind = match (&input.item, &input.weight) { @@ -640,6 +650,49 @@ fn within_summaries( Ok(()) } +/// An exact accumulator build (`Sum`, `Count`, `Min`, ...) within the +/// capabilities. The planner's `DeploymentCapabilities` lists no exact +/// family: every one is supported unless an exclusion its fields expand +/// into rules it out (`counter_semantics` rules out the counter states, +/// `state_not_mergeable_across_windows` a family's chains, and +/// `excluded_candidates` anything). So the build is within them when none +/// of those exclusions matches the node, and it reads each sample's value, +/// the one input the collector folds into an exact state. +fn within_exact( + summary_type: &FieldDataType, + input: &SummaryUpdate, + node: &PhysicalASAPDAGNode, + capabilities: &CollectorCapabilities, +) -> Result<(), String> { + let sample_value = SummaryUpdate { + item: None, + weight: SummaryInputExpr::Column(ColumnRef::SampleValue), + }; + if *input != sample_value { + return Err(format!("input {input:?} of {summary_type:?}")); + } + let candidate = CandidateDescription { + operator: &node.payload, + parameters: node.parameters.as_ref(), + physical_properties: PhysicalProperties::new(node.output_state.timing, node.lifetime) + .map_err(|e| e.to_string())?, + read_summary_type: None, + }; + match capabilities + .executor + .rest + .exclusions() + .into_iter() + .find(|excluded| excluded.exclusion.matches(&candidate)) + { + Some(excluded) => Err(format!( + "summary {summary_type:?}, excluded by {}", + excluded.source + )), + None => Ok(()), + } +} + /// A predicate the collector evaluates: a conjunction of comparisons of a /// column with a `Utf8` literal (a label matcher), each with an op of /// `ops`. diff --git a/crates/control-plane/tests/collector_views.rs b/crates/control-plane/tests/collector_views.rs index 4eb5eed9b..47c136f46 100644 --- a/crates/control-plane/tests/collector_views.rs +++ b/crates/control-plane/tests/collector_views.rs @@ -124,26 +124,71 @@ fn a_leaf_sketch_chain_is_the_collector_view() { } } -/// With an exact view over the same metric (not in the capabilities), the -/// quantile's chain is still the one collector view, and `data` is still -/// read raw by the backend. +/// `sum_over_time` is an exact `Sum` chain. The planner's capabilities +/// list no exact family: each is supported unless an exclusion rules it +/// out, and the collector's exclude only the counter states. So the chain +/// is the collector view, and the backend no longer reads `data` raw. #[test] -fn a_metric_another_view_reads_stays_raw() { +fn a_leaf_exact_chain_is_the_collector_view() { + let plan = plan(&["sum_over_time(data[1m])"], false); + let (file, _) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + let chain = chain(&plan); + let summary_type = serde_json::to_value( + &plan + .dag + .nodes + .iter() + .find(|node| node.id == chain) + .unwrap() + .payload, + ) + .unwrap()["ASAP"]["SummaryTumblingWindowChain"]["summary_type"] + .clone(); + assert_eq!(summary_type, json!({"ExactAggregate": ["Sum", "Sum"]})); + assert_eq!(file.outputs, [chain]); + assert_eq!(file.backend_reads_raw, [("data".to_string(), false)].into()); +} + +/// `sum`, `count`, `avg`, `min` and `max` over time, and a quantile, over +/// one metric: every chain (`avg` reads the `Sum` and `Count` ones) is a +/// collector view, and `data` is no longer read raw. +#[test] +fn exact_and_sketch_views_of_one_metric_all_go_to_the_collector() { let plan = plan( &[ - "quantile_over_time(0.99, data[5m])", - "sum_over_time(data[5m])", + "quantile_over_time(0.99, data[1m])", + "sum_over_time(data[1m])", + "count_over_time(data[1m])", + "avg_over_time(data[1m])", + "min_over_time(data[1m])", + "max_over_time(data[1m])", ], false, ); let (file, reasons) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); - let chains = nodes_of(&plan, "SummaryTumblingWindowChain"); - assert_eq!(chains.len(), 2); - assert_eq!(file.outputs.len(), 1); - let exact = chains.iter().find(|c| !file.outputs.contains(c)).unwrap(); + let mut chains = nodes_of(&plan, "SummaryTumblingWindowChain"); + chains.sort(); + assert_eq!(chains.len(), 5, "DDSketch, Sum, Count, Min, Max"); + let mut outputs = file.outputs.clone(); + outputs.sort(); + assert_eq!(outputs, chains, "{reasons:?}"); + assert_eq!(file.backend_reads_raw, [("data".to_string(), false)].into()); +} + +/// An exact family an exclusion of the capabilities rules out stays in +/// the backend, with the exclusion as the reason, and its metric is read +/// raw. +#[test] +fn an_excluded_exact_family_stays_in_the_backend() { + let plan = plan(&["sum_over_time(data[1m])"], false); + let mut no_sum = capabilities(); + no_sum["executor"]["excluded_candidates"] = json!([{"summary_family": {"exact": "Sum"}}]); + let (file, reasons) = collector_sub_dag(&plan, &parse(&no_sum)).unwrap(); + assert!(file.outputs.is_empty()); assert!(matches!( - reason(&reasons, *exact), - Some(NotOnCollector::NotInCapabilities(what)) if what.contains("ExactAggregate") + reason(&reasons, chain(&plan)), + Some(NotOnCollector::NotInCapabilities(what)) + if what.contains("ExactAggregate") && what.contains("excluded_candidates[0]") )); assert_eq!(file.backend_reads_raw, [("data".to_string(), true)].into()); } @@ -305,7 +350,7 @@ fn the_file_reads_back_and_its_views_keep_their_keys() { #[test] fn unknown_capabilities_are_refused() { let mut newer = capabilities(); - newer["capabilities_version"] = json!(2); + newer["capabilities_version"] = json!(3); assert!(CollectorCapabilities::from_json(&newer.to_string()).is_err()); let mut unknown = capabilities(); unknown["operators"][0]["reductions_typo"] = json!([]); diff --git a/crates/control-plane/tests/data/collector-capabilities.json b/crates/control-plane/tests/data/collector-capabilities.json index 22a010392..0050366a9 100644 --- a/crates/control-plane/tests/data/collector-capabilities.json +++ b/crates/control-plane/tests/data/collector-capabilities.json @@ -1,4 +1,4 @@ -{"capabilities_version": 1, +{"capabilities_version": 2, "executor": { "supported_summaries": [ {"summary": {"summary_type": "DDSketch", "readouts": []}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, From 3ff92a0520c17f2e48d52aca043d712d5d457c7d Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:02:18 +0000 Subject: [PATCH 2/2] feat(collector views): ingest exact Sum, Count, Min and Max states A collector sends an exact accumulator's state as the executor's view layout of it (StateColumn::view_bytes), the record this data plane stores the state as, behind the lineage frame; there is no ASAPv1 encoding of an exact state, so CollectorViews::new refused every exact view. The view's decoder is now a StateDecoder: ASAPv1 for a sketch, and for Sum/Count/Min/Max the one record read back with StateColumn::from_views (a record of another size or a bad presence word is a decode reject). Counter and IRate views are refused (their states depend on sample order). Lineages, the reorder buffer, merging, commit on arrival and late merges are unchanged: they hold the decoded kernel state. Two corrections with equal bytes are distinct records of their lineage and both merge (collector_exact_views tests). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- .../data-plane/tests/collector_exact_views.rs | 600 ++++++++++++++++++ crates/precompute/src/collector.rs | 119 +++- 2 files changed, 711 insertions(+), 8 deletions(-) create mode 100644 crates/data-plane/tests/collector_exact_views.rs diff --git a/crates/data-plane/tests/collector_exact_views.rs b/crates/data-plane/tests/collector_exact_views.rs new file mode 100644 index 000000000..058b29682 --- /dev/null +++ b/crates/data-plane/tests/collector_exact_views.rs @@ -0,0 +1,600 @@ +//! Collector views of exact accumulators (`sum`, `count`, `avg`, `min` and +//! `max_over_time`): their states arrive over OTLP as the executor's view +//! layout of each state (`StateColumn::view_bytes`, the fixed-width record +//! this data plane stores the state as) behind the collector's lineage +//! frame, are checked, staged, deduplicated by lineage and merged, +//! committed when their request ends, and answer every query as the views +//! the data plane builds from the same samples do. A correction of a +//! committed window (a delta of its lineage) merges into it; its repeat is +//! a duplicate, and a later correction with the same bytes is not. + +mod common; + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::time::Duration; + +use asap_planner::InstallablePlan; +use axum::body::Body; +use axum::http::{header, Request, StatusCode}; +use axum::Router; +use control_plane::plan_workload; +use data_plane::engine::EngineOptions; +use data_plane::{router, DataPlane}; +use http_body_util::BodyExt; +use otlp::proto::collector::metrics::v1::{ + ExportMetricsServiceRequest, ExportMetricsServiceResponse, +}; +use otlp::proto::common::v1::{any_value, AnyValue, KeyValue}; +use otlp::proto::metrics::v1::{ + metric::Data, Metric, ResourceMetrics, ScopeMetrics, Summary, SummaryDataPoint, +}; +use precompute::collector::CollectorViewOptions; +use precompute::engine::PrecomputeMode; +use precompute::ingestion::IngestionOptions; +use prometheus_remote_write::{Label, Sample, TimeSeries}; +use serde_json::{json, Value}; +use tower::ServiceExt; + +const QUERIES: [&str; 5] = [ + "sum_over_time(data[5m])", + "count_over_time(data[5m])", + "avg_over_time(data[5m])", + "min_over_time(data[5m])", + "max_over_time(data[5m])", +]; +const JOBS: [&str; 2] = ["a", "b"]; +const RANGE_MS: i64 = 300_000; + +/// An exact family a chain of the plan builds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Kind { + Sum, + Count, + Min, + Max, +} + +/// The plan of [`QUERIES`] with no raw data kept and one level per chain, +/// and its chains: node id and family; all of one width, returned too. +fn plan() -> (InstallablePlan, BTreeMap, i64) { + let entries: Vec = QUERIES + .iter() + .map(|query| { + json!({ + "query": query, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }) + }) + .collect(); + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": entries}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 100000.0}}, + "sources": {"data": {"series_count": 10000, "sample_interval": 100, + "metric_type": "gauge"}}}, + })) + .unwrap(); + let plan = plan_workload(&workload, &common::inputs_without_levels(false)) + .unwrap() + .0; + let mut chains = BTreeMap::new(); + let mut widths = BTreeSet::new(); + for node in &plan.dag.nodes { + let node = serde_json::to_value(node).unwrap(); + let chain = &node["payload"]["ASAP"]["SummaryTumblingWindowChain"]; + if chain.is_null() { + continue; + } + let kind = match chain["summary_type"]["ExactAggregate"][0].as_str() { + Some("Sum") => Kind::Sum, + Some("Count") => Kind::Count, + Some("Min") => Kind::Min, + Some("Max") => Kind::Max, + other => panic!("not an exact chain: {other:?}"), + }; + widths.insert(chain["tumbling_window_width_ms"].as_i64().unwrap()); + chains.insert(node["id"].as_u64().unwrap() as usize, kind); + } + let mut kinds: Vec = chains.values().copied().collect(); + kinds.sort(); + assert_eq!(kinds, [Kind::Sum, Kind::Count, Kind::Min, Kind::Max]); + let [width_ms] = widths.into_iter().collect::>()[..] else { + panic!("chains of several widths") + }; + (plan, chains, width_ms) +} + +/// A sample value of `job` at second `s`, exact in binary, so every sum is +/// exact in any order. +fn value(job: &str, s: i64) -> f64 { + (s % 97) as f64 + if job == "a" { 0.5 } else { -3.25 } +} + +/// One second's samples of `job` in `(from_ms, to_ms]`. +fn samples(job: &str, from_ms: i64, to_ms: i64) -> Vec<(i64, f64)> { + (from_ms / 1000 + 1..=to_ms / 1000) + .map(|s| (s * 1000, value(job, s))) + .collect() +} + +/// The state of `kind` over `samples` in the executor's view layout: +/// little-endian 8-byte words. `Sum`: sum, compensation, seen; `Count`: +/// count; `Min`/`Max`: present, value. +fn record(kind: Kind, samples: &[(i64, f64)]) -> Vec { + let values = samples.iter().map(|(_, v)| *v); + let present = u64::from(!samples.is_empty()); + let words: Vec = match kind { + Kind::Sum => vec![values.sum::().to_bits(), 0, present], + Kind::Count => vec![samples.len() as u64], + Kind::Min => vec![present, values.fold(f64::INFINITY, f64::min).to_bits()], + Kind::Max => vec![present, values.fold(f64::NEG_INFINITY, f64::max).to_bits()], + }; + words.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +/// The query time: a multiple of the 10 s evaluation interval, 20 s ago, +/// so every window it reads has ended. +fn query_time_ms() -> i64 { + let now = precompute::ingestion::wall_clock_ms(); + now - now.rem_euclid(10_000) - 20_000 +} + +fn no_forward(stream_start_ms: i64) -> EngineOptions { + EngineOptions { + no_forward: true, + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(stream_start_ms), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + } +} + +fn data_plane(plan: &InstallablePlan, options: EngineOptions) -> (Router, Arc) { + let plan = serde_json::to_string(plan).unwrap(); + let state = + Arc::new(DataPlane::with_options(plan, "http://127.0.0.1:1".into(), options).unwrap()); + (router(state.clone()), state) +} + +/// A data plane whose collector builds every chain of `chains`. +fn collector_data_plane( + plan: &InstallablePlan, + chains: &BTreeMap, +) -> (Router, Arc) { + let options = EngineOptions { + precompute_mode: PrecomputeMode::Push, + collector: CollectorViewOptions { + plan_id: Some(plan.dag.plan_id()), + views: chains.keys().copied().collect(), + ..CollectorViewOptions::default() + }, + ..no_forward(0) + }; + data_plane(plan, options) +} + +/// Each query's answer at `time_ms` from a data plane that builds the +/// views itself from the samples in `(time_ms − 5 m, time_ms]`. +async fn built_here(plan: &InstallablePlan, time_ms: i64) -> Vec { + let (app, _state) = data_plane(plan, no_forward(time_ms - RANGE_MS)); + let timeseries = JOBS + .iter() + .map(|job| TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "data".into(), + }, + Label { + name: "job".into(), + value: (*job).into(), + }, + ], + samples: samples(job, time_ms - RANGE_MS, time_ms) + .into_iter() + .map(|(timestamp, value)| Sample { timestamp, value }) + .collect(), + }) + .collect(); + common::remote_write(&app, timeseries).await; + common::barrier(&app, time_ms).await; + answers(&app, time_ms).await +} + +/// Each query's answer at `time_ms`. +async fn answers(app: &Router, time_ms: i64) -> Vec { + let mut out = Vec::new(); + for query in QUERIES { + let (status, _, body) = common::get(app, &common::instant_uri(query, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{query}: {body}"); + assert_eq!( + body["data"]["result"].as_array().unwrap().len(), + JOBS.len(), + "{query}: {body}" + ); + out.push(body); + } + out +} + +fn text(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.into())), + }), + } +} + +/// One state: `job`'s state `bytes` of the window ending at `end_ms`, +/// record `sequence` of its lineage from collector instance `epoch`: a +/// full when 0, else a delta on the record before. +struct State { + job: &'static str, + end_ms: i64, + bytes: Vec, + epoch: u64, + sequence: u64, +} + +/// The OTLP body of `states` of view `node`, as the collector's codec +/// writes it: one metric per collector instance (the epoch is metric +/// metadata), each state behind its lineage frame. +fn body(plan: &InstallablePlan, node: usize, width_ms: i64, states: &[State]) -> Vec { + let view = plan + .materialized_views() + .unwrap() + .into_iter() + .find(|view| view.node_id == node) + .unwrap(); + let key = serde_json::to_value(view.view_state_key()).unwrap(); + let epochs: BTreeSet = states.iter().map(|state| state.epoch).collect(); + let metrics = epochs + .into_iter() + .map(|epoch| { + let metadata = vec![ + text("asap.plan_id", view.plan_id()), + KeyValue { + key: "asap.node_id".into(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(node as i64)), + }), + }, + text("asap.view_state_key", &key.to_string()), + text("asap.producer_epoch", &epoch.to_string()), + ]; + let data_points = states + .iter() + .filter(|state| state.epoch == epoch) + .map(|state| SummaryDataPoint { + attributes: vec![ + text("job", state.job), + KeyValue { + key: "sketch.envelope".into(), + value: Some(AnyValue { + value: Some(any_value::Value::BytesValue(::common::frame_lineage( + state.sequence, + &state.bytes, + ))), + }), + }, + ], + start_time_unix_nano: ((state.end_ms - width_ms) * 1_000_000) as u64, + time_unix_nano: (state.end_ms * 1_000_000) as u64, + count: 1, + ..Default::default() + }) + .collect(); + Metric { + name: format!("data.asap_view.{node}"), + metadata, + data: Some(Data::Summary(Summary { data_points })), + ..Default::default() + } + }) + .collect(); + let request = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics, + ..Default::default() + }], + ..Default::default() + }], + }; + prost::Message::encode_to_vec(&request) +} + +/// Posts an OTLP body; returns the reply's rejected points. +async fn post(app: &Router, body: Vec) -> i64 { + let response = app + .clone() + .oneshot( + Request::post("/v1/metrics") + .header(header::CONTENT_TYPE, "application/x-protobuf") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + let reply: ExportMetricsServiceResponse = prost::Message::decode(&bytes[..]).unwrap(); + reply.partial_success.map_or(0, |p| p.rejected_data_points) +} + +/// The value of `/metrics` line `line` (exactly that series), 0 if absent. +fn metric(state: &DataPlane, line: &str) -> f64 { + state + .engine + .render_metrics() + .lines() + .find_map(|l| l.strip_prefix(line)?.strip_prefix(' ')?.parse().ok()) + .unwrap_or(0.0) +} + +/// Waits until `/metrics` line `line` reaches `at_least`. +async fn wait_for(state: &DataPlane, line: &str, at_least: f64) { + for _ in 0..200 { + if metric(state, line) >= at_least { + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!( + "{line} stayed below {at_least}:\n{}", + state.engine.render_metrics() + ); +} + +fn outcome(node: usize, outcome: &str) -> String { + format!("asap_collector_states_total{{view=\"{node}\",outcome=\"{outcome}\"}}") +} + +fn committed(node: usize) -> String { + format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}") +} + +/// Each job's state of `kind` per window of `(time_ms − 5 m, time_ms]`; +/// job `a`'s newest window holds only the samples `keep` keeps of it. +fn states( + kind: Kind, + width_ms: i64, + time_ms: i64, + keep: impl Fn(&[(i64, f64)]) -> Vec<(i64, f64)>, +) -> Vec { + let mut states = Vec::new(); + for job in JOBS { + let mut end_ms = time_ms - RANGE_MS + width_ms; + while end_ms <= time_ms { + let mut window = samples(job, end_ms - width_ms, end_ms); + if job == "a" && end_ms == time_ms { + window = keep(&window); + } + states.push(State { + job, + end_ms, + bytes: record(kind, &window), + epoch: 1, + sequence: 0, + }); + end_ms += width_ms; + } + } + states +} + +/// The views the collector builds answer every query exactly as the views +/// the data plane builds from the same samples; `data`'s raw samples, read +/// by those views only, are not stored. +#[tokio::test(flavor = "multi_thread")] +async fn exact_collector_states_answer_as_the_views_built_here() { + let (plan, chains, width_ms) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, &chains); + for (&node, &kind) in &chains { + let states = states(kind, width_ms, time_ms, <[_]>::to_vec); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + wait_for(&state, &committed(node), (RANGE_MS / width_ms) as f64).await; + assert_eq!( + metric(&state, &outcome(node, "staged")), + states.len() as f64 + ); + } + assert_eq!(answers(&app, time_ms).await, expected); + + let timeseries = vec![TimeSeries { + labels: vec![Label { + name: "__name__".into(), + value: "data".into(), + }], + samples: vec![Sample { + timestamp: time_ms, + value: 1.0, + }], + }]; + common::remote_write(&app, timeseries).await; + for _ in 0..100 { + if state.engine.stats().samples_unrouted == 1 { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(state.engine.stats().samples_unrouted, 1); +} + +/// Job `a`'s newest window arrives in one request as two partials, the +/// full of collector instance 1 and the full of instance 2 (merged at +/// staging), with a repeat of the first (a duplicate); after the windows +/// commit, a correction of the window before it (instance 1's delta of its +/// late samples) merges into it, and the correction sent again is a +/// duplicate. Every query then answers as if every sample had come on +/// time. +#[tokio::test(flavor = "multi_thread")] +async fn exact_partials_and_corrections_merge_and_repeats_are_duplicates() { + let (plan, chains, width_ms) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, &chains); + let newest = samples("a", time_ms - width_ms, time_ms); + let (first, second) = newest.split_at(2); + let before = time_ms - width_ms; + let older = samples("a", before - width_ms, before); + let (on_time, late) = older.split_at(older.len() - 1); + for (&node, &kind) in &chains { + let mut all = states(kind, width_ms, time_ms, |_| first.to_vec()); + all.iter_mut() + .find(|s| s.job == "a" && s.end_ms == before) + .unwrap() + .bytes = record(kind, on_time); + let full = |epoch: u64, samples: &[(i64, f64)]| State { + job: "a", + end_ms: time_ms, + bytes: record(kind, samples), + epoch, + sequence: 0, + }; + all.push(full(2, second)); + all.push(full(1, first)); + assert_eq!(post(&app, body(&plan, node, width_ms, &all)).await, 0); + wait_for(&state, &committed(node), (RANGE_MS / width_ms) as f64).await; + assert_eq!(metric(&state, &outcome(node, "merged")), 1.0, "{kind:?}"); + assert_eq!(metric(&state, &outcome(node, "duplicate")), 1.0, "{kind:?}"); + let correction = || State { + job: "a", + end_ms: before, + bytes: record(kind, late), + epoch: 1, + sequence: 1, + }; + for _ in 0..2 { + assert_eq!( + post(&app, body(&plan, node, width_ms, &[correction()])).await, + 0 + ); + } + assert_eq!( + metric(&state, &outcome(node, "late_merged")), + 1.0, + "{kind:?}" + ); + assert_eq!(metric(&state, &outcome(node, "duplicate")), 2.0, "{kind:?}"); + } + assert_eq!(answers(&app, time_ms).await, expected); +} + +/// Two corrections of one window with the same bytes (two late samples of +/// equal value, each sent alone: two `Count` 1 records, two `Sum`s of the +/// same value) are two records of their lineage, sequences 1 and 2: both +/// merge, so the window counts both samples. Telling a repeat by its bytes +/// would drop the second. +#[tokio::test(flavor = "multi_thread")] +async fn equal_bytes_corrections_with_distinct_sequences_both_merge() { + let (plan, chains, width_ms) = plan(); + let time_ms = query_time_ms(); + let (app, state) = collector_data_plane(&plan, &chains); + let before = time_ms - width_ms; + let window = samples("a", before - width_ms, before); + // The last two samples late, given the same value. + let (on_time, _) = window.split_at(window.len() - 2); + let late_value = 42.5; + let mut all_samples = on_time.to_vec(); + all_samples.extend( + window[window.len() - 2..] + .iter() + .map(|(t, _)| (*t, late_value)), + ); + for (&node, &kind) in &chains { + let mut all = states(kind, width_ms, time_ms, <[_]>::to_vec); + all.iter_mut() + .find(|s| s.job == "a" && s.end_ms == before) + .unwrap() + .bytes = record(kind, on_time); + assert_eq!(post(&app, body(&plan, node, width_ms, &all)).await, 0); + wait_for(&state, &committed(node), (RANGE_MS / width_ms) as f64).await; + let correction = |sequence: u64| State { + job: "a", + end_ms: before, + bytes: record(kind, &[(before, late_value)]), + epoch: 1, + sequence, + }; + assert_eq!(correction(1).bytes, correction(2).bytes); + for sequence in [1, 2] { + assert_eq!( + post(&app, body(&plan, node, width_ms, &[correction(sequence)])).await, + 0 + ); + } + assert_eq!( + metric(&state, &outcome(node, "late_merged")), + 2.0, + "{kind:?}" + ); + assert_eq!(metric(&state, &outcome(node, "duplicate")), 0.0, "{kind:?}"); + } + // Job `a`'s samples over the range, the two late ones at their value: + // the count and the sum include both. + let mut range: Vec = samples("a", time_ms - RANGE_MS, time_ms) + .into_iter() + .filter(|(t, _)| *t <= before - width_ms || *t > before) + .map(|(_, v)| v) + .collect(); + range.extend(all_samples.iter().map(|(_, v)| *v)); + let job_a = |body: &Value| -> f64 { + body["data"]["result"] + .as_array() + .unwrap() + .iter() + .find(|r| r["metric"]["job"] == "a") + .unwrap()["value"][1] + .as_str() + .unwrap() + .parse() + .unwrap() + }; + let answers = answers(&app, time_ms).await; + assert_eq!(job_a(&answers[1]), range.len() as f64, "count_over_time"); + assert_eq!( + job_a(&answers[0]), + range.iter().sum::(), + "sum_over_time" + ); +} + +/// Bytes that are not a record of the view's family (a `Min` record sent +/// to the `Sum` view, or three bytes) are rejected as `decode`. +#[tokio::test(flavor = "multi_thread")] +async fn bytes_that_are_not_the_views_record_are_rejected() { + let (plan, chains, width_ms) = plan(); + let time_ms = query_time_ms(); + let (app, state) = collector_data_plane(&plan, &chains); + let sum = *chains.iter().find(|(_, k)| **k == Kind::Sum).unwrap().0; + for (epoch, bytes) in [ + (1, record(Kind::Min, &[(time_ms, 1.0)])), + (2, vec![1, 2, 3]), + ] { + let one = State { + job: "a", + end_ms: time_ms, + bytes, + epoch, + sequence: 0, + }; + assert_eq!(post(&app, body(&plan, sum, width_ms, &[one])).await, 1); + } + assert_eq!( + metric( + &state, + &format!("asap_collector_states_rejected_total{{view=\"{sum}\",reason=\"decode\"}}") + ), + 2.0 + ); +} diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 41b465681..0751d8786 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -6,8 +6,10 @@ //! //! 1. [`CollectorViews::check`], on the HTTP thread: finds the view by //! `(plan_id, node_id)`, checks its key, metric name and window, interns -//! the series as a raw sample's, and decodes the ASAPv1 bytes into the -//! view's kernel. A state failing a check is rejected with a reason. +//! the series as a raw sample's, and decodes the state bytes into the +//! view's kernel: a sketch's ASAPv1 bytes, or an exact accumulator's +//! record in the executor's view layout ([`StateDecoder`]). A state +//! failing a check is rejected with a reason. //! 2. [`Staging::stage`], on the ingest coordinator: each record is //! checked against its `(view, series, window)` lineages (§8): a full //! of a new producer epoch starts a lineage, a delta onto its lineage's @@ -35,12 +37,14 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use asap_executor::arrow::buffer::{Buffer, ScalarBuffer}; use asap_executor::planner::ir::schema::{FieldDataType, PROMQL_SERIES_IDENTITY}; use asap_executor::planner::ir::{ASAPOp, Operator}; use asap_executor::planner::plan::materialized_view::ViewStateKey; use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; +use asap_executor::planner::summary_type::ExactKind; use asap_executor::summary_kernels::factory::create_planner_accumulator; -use asap_executor::values::{Batch, SchemaRef, Value}; +use asap_executor::values::{Batch, SchemaRef, StateColumn, Value}; use asap_executor::AggregateCore; use common::{StateKind, ViewStateBatch, MAX_TIME_MS}; use internal_metrics::Metrics; @@ -284,7 +288,7 @@ struct CollectorView { /// The metric its `Scan` reads: its rows' `__name__`. source_metric: String, width_ms: i64, - decoder: Asapv1Decoder, + decoder: StateDecoder, /// Its rows' schema, and where the window end, the series identity /// and the state are. schema: SchemaRef, @@ -293,6 +297,38 @@ struct CollectorView { state_column: usize, } +/// How a collector view's state bytes are read into its kernel. +enum StateDecoder { + /// A sketch: `asap_sketchlib`'s ASAPv1 bytes. + Asapv1(Asapv1Decoder), + /// An exact accumulator (`Sum`, `Count`, `Min`, `Max`) of this family: + /// its one record in the executor's view layout + /// (`StateColumn::view_bytes`), the bytes this data plane stores the + /// state as. + ViewLayout(FieldDataType), +} + +impl StateDecoder { + /// The state `bytes` encode; `None` when they are not one state of the + /// view's kernel (another sketch, a record of another size, a presence + /// word other than 0 or 1). + fn decode(&self, bytes: &[u8]) -> Option> { + match self { + Self::Asapv1(decoder) => decoder.decode(bytes), + Self::ViewLayout(family) => { + let end = u32::try_from(bytes.len()).ok()?; + let column = StateColumn::from_views( + family.clone(), + Buffer::from(bytes.to_vec()), + ScalarBuffer::from(vec![0, end]), + ) + .ok()?; + (column.len() == 1).then(|| column.state(0)) + } + } + } +} + /// The installed plan's collector views: what checks a state and turns /// staged states into a window's rows. pub(crate) struct CollectorViews { @@ -312,7 +348,8 @@ const LOG_INTERVAL: Duration = Duration::from_secs(60); impl CollectorViews { /// The collector views of `dag`: the views of `ingestion`'s collector /// view groups (one view each, in `precompute`'s groups). Errs for a - /// view that builds no sketch with an ASAPv1 encoding, that does not + /// view that builds neither an exact accumulator nor a sketch with an + /// ASAPv1 encoding, that does not /// read exactly one metric, or whose rows hold more than a window end, /// a series identity and a state. pub fn new( @@ -351,8 +388,21 @@ impl CollectorViews { create_planner_accumulator(summary_type, node.parameters.as_ref(), input) .map_err(fail)? .snapshot_accumulator(); - let decoder = Asapv1Decoder::of_state(&*template) - .ok_or_else(|| fail("its state has no ASAPv1 encoding".into()))?; + let decoder = match summary_type { + // An order-sensitive state (a counter's, an instant + // rate's) is not merged from collector partials. + FieldDataType::ExactAggregate( + ExactKind::Sum | ExactKind::Count | ExactKind::Min | ExactKind::Max, + _, + ) => StateDecoder::ViewLayout(summary_type.clone()), + FieldDataType::ExactAggregate(kind, _) => { + return Err(fail(format!("its {kind:?} state depends on sample order"))) + } + _ => StateDecoder::Asapv1( + Asapv1Decoder::of_state(&*template) + .ok_or_else(|| fail("its state has no ASAPv1 encoding".into()))?, + ), + }; let metrics = index.metrics_below(&[id], &BTreeSet::new()); let [source_metric] = <[String; 1]>::try_from(metrics.into_iter().collect::>()) .map_err(|metrics| fail(format!("reads metrics {metrics:?}, not one")))?; @@ -488,7 +538,7 @@ impl CollectorViews { } let Some(state) = view.decoder.decode(&record.asapv1) else { reject(reject::DECODE, 1, &|| { - "the bytes are not a state of the view's sketch".into() + "the bytes are not a state of the view's summary".into() }); continue; }; @@ -1399,4 +1449,57 @@ mod tests { (8_000, 8_000) ); } + + /// An exact collector view (`sum_over_time`'s `Sum` chain) is + /// installed; its states are decoded from the executor's view layout + /// (sum, compensation, seen as little-endian words), merge by addition, + /// and commit as the same record. Bytes of another size are no state. + #[test] + fn an_exact_collector_view_decodes_its_view_layout_records() { + let plan = one_query_plan("sum_over_time(data[1m])", false); + let views = plan.materialized_views().unwrap(); + let chain = views[0].node_id; + let options = CollectorViewOptions { + plan_id: None, + views: BTreeSet::from([chain]), + ..CollectorViewOptions::default() + }; + let (ingestion, precompute) = Ingestion::new( + &plan.dag, + &views, + plan.ingestion_refresh_groups().unwrap(), + IngestionOptions::default(), + asap_executor::runtime::Limits { max_bytes: 1 << 30 }, + &options, + ) + .unwrap(); + let collector = CollectorViews::new(&plan.dag, &ingestion, &precompute, 0).unwrap(); + let view = &collector.views[&chain]; + let sum = |value: f64| -> Vec { + [value.to_bits(), 0, 1] + .iter() + .flat_map(|w: &u64| w.to_le_bytes()) + .collect() + }; + let first = view.decoder.decode(&sum(7.5)).expect("a Sum record"); + let second = view.decoder.decode(&sum(2.5)).expect("a Sum record"); + assert!(view.decoder.decode(&sum(1.0)[..16]).is_none()); + assert!(view.decoder.decode(&[1, 2, 3]).is_none()); + let merged: Arc = Arc::from(first.merge_with(&*second).unwrap()); + let staged = vec![Staged { + series: intern_pairs(&[("__name__", "data"), ("job", "exact-unit")]), + state: merged, + lineages: Vec::new(), + }]; + let window = ClosedWindow { + group: view.group, + end_ms: 100 * view.width_ms, + }; + let Computed::Ran(mut ran) = collector.rows(window, staged).unwrap() else { + unreachable!("a collector window is run"); + }; + let batch = ran.remove(0).1.remove(0); + let states = batch.state_column(view.state_column).unwrap(); + assert_eq!(states.view_bytes(0).unwrap().as_ref(), sum(10.0).as_slice()); + } }