diff --git a/Cargo.lock b/Cargo.lock index 982532021..c7fb056fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2775,6 +2775,7 @@ dependencies = [ name = "otlp" version = "0.1.0" dependencies = [ + "common", "flate2", "opentelemetry-proto", "prometheus_remote_write", @@ -2956,6 +2957,7 @@ version = "0.1.0" dependencies = [ "anyhow", "asap-executor", + "asap_sketchlib", "clap", "common", "control_plane", diff --git a/benchmarks/micro/view_read_bench.rs b/benchmarks/micro/view_read_bench.rs index 44d1601d6..1100981f9 100644 --- a/benchmarks/micro/view_read_bench.rs +++ b/benchmarks/micro/view_read_bench.rs @@ -133,7 +133,7 @@ fn main() { } let started = Instant::now(); for location in &locations { - std::hint::black_box(location.read(&schema, how).unwrap().0); + std::hint::black_box(location.read(&schema, how).unwrap()); } let ns = started.elapsed().as_nanos() as f64; println!( diff --git a/crates/adapters/ingest/otlp/Cargo.toml b/crates/adapters/ingest/otlp/Cargo.toml index d4de7928f..f4618417f 100644 --- a/crates/adapters/ingest/otlp/Cargo.toml +++ b/crates/adapters/ingest/otlp/Cargo.toml @@ -5,10 +5,12 @@ edition.workspace = true # OTLP (OpenTelemetry) metrics over HTTP: request decoding into the # caller's samples, and the replies. An adapter: it never sees an engine or -# a store. It depends on `prometheus-remote-write` alone, for the caller's +# a store. It depends on `prometheus-remote-write`, for the caller's # sample types (`SampleBuilder`), the in-place protobuf reader and the -# series cache its decoder shares. +# series cache its decoder shares, and on `common`, for the collector view +# states it decodes (`ViewStateBatch`). [dependencies] +common.workspace = true prometheus_remote_write.workspace = true # The OTLP protobuf messages, for senders, tests and the replies (no gRPC # server; the crate still builds tonic's codegen types and the diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs index dcac639e8..a29b1135e 100644 --- a/crates/adapters/ingest/otlp/src/lib.rs +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -55,6 +55,22 @@ //! - Points with a sketch payload attribute (`kll.`, `cms.` or //! `countsketch.sketch_payload`) are skipped, as ASAPQuery skips them. //! +//! # Collector view states +//! +//! A metric whose metadata names a view of the installed plan +//! (`asap.plan_id`, `asap.node_id`, `asap.view_state_key`) carries collector +//! view states, not samples (docs/design/collector-sketch-ingest.md, §4): +//! each data point is one series' state in the window `(start_time_unix_nano, +//! time_unix_nano]`, its ASAPv1 bytes in the `sketch.envelope` attribute and +//! its sample count in `count`. Resource, scope and the other point +//! attributes give the series' labels as for a sample, `__name__` being the +//! metric's name before `.asap_view.`. They are decoded into +//! [`Decoded::view_states`]; the state bytes are not read. A request whose +//! view identity is missing in part or does not parse, whose view metric is +//! not named `.asap_view.`, or that has a +//! `sketch.envelope` point outside such a metric, is refused +//! ([`OtlpError::ViewIdentity`]). +//! //! # Decoding //! //! As the Remote Write decoder, [`Decoder`] walks the protobuf in place, @@ -66,9 +82,14 @@ use std::borrow::Cow; use std::collections::btree_map::Entry; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::io::Read; +use common::view_identity::{ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, VIEW_STATE_KEY}; +use common::{ + CollectorSeriesStates, CollectorViewStates, LabelSet, ViewStateBatch, ViewStateKey, + ViewStateRecord, +}; use prometheus_remote_write::series_cache::SeriesCache; use prometheus_remote_write::wire::{Reader, Value}; use prometheus_remote_write::RemoteWriteError; @@ -108,6 +129,10 @@ pub enum OtlpError { Protobuf(String), #[error("request has more than {0} points")] TooManyPoints(usize), + /// A collector view's metric whose metadata lacks or misstates the view + /// identity, or a `sketch.envelope` point outside such a metric. + #[error("metric {metric}: view identity: {reason}")] + ViewIdentity { metric: String, reason: String }, } /// The protobuf reader's errors ([`RemoteWriteError::Protobuf`]). @@ -129,6 +154,8 @@ pub struct Decoded { /// Data points refused, which the reply reports as rejected: the points /// of sums with DELTA temporality. pub rejected_points: u64, + /// The collector view states, by view and series, in request order. + pub view_states: ViewStateBatch, } impl Decoded { @@ -217,11 +244,14 @@ fn walk( key_buffer, options, max_points: limits.max_points, + point_limit: limits.max_points, + series_of_state: HashMap::new(), decoded: Decoded { // Room for one sample per 50 encoded bytes, about one gauge // point with a few short attributes. samples: Vec::with_capacity(request.len() / 50), rejected_points: 0, + view_states: ViewStateBatch::default(), }, }; walk.request(request)?; @@ -355,6 +385,13 @@ struct Walk<'a, B: SampleBuilder> { key_buffer: &'a mut Vec, options: &'a LabelOptions, max_points: usize, + /// The request's point limit, for its error; `max_points` is what is + /// left of it for samples once the collector states decoded so far + /// took their share (so the samples' check stays one compare). + point_limit: usize, + /// Each series' place in `decoded.view_states`: by view index and + /// labels, its index in the view's series. + series_of_state: HashMap<(usize, LabelSet), usize>, decoded: Decoded, } @@ -396,17 +433,20 @@ impl Walk<'_, B> { Ok(()) } - /// An encoded `Metric`: its name (field 1) and its data, one of gauge + /// An encoded `Metric`: its name (field 1), its data, one of gauge /// (5), sum (7), histogram (9), exponential histogram (10) or summary - /// (11), whose points (field 1) each give samples. + /// (11), whose points (field 1) each give samples, and its metadata + /// (12): with a view identity, its points are collector states. fn metric(&mut self, resource: &ResourceLabels, bytes: &[u8]) -> Result<(), OtlpError> { let mut name = ""; let mut data = None; + let mut metadata = Vec::new(); let mut reader = Reader::new(bytes); while let Some((field, value)) = reader.field()? { match (field, value) { (1, Value::Bytes(text)) => name = utf8(text)?, (5 | 7 | 9 | 10 | 11, Value::Bytes(found)) => data = Some((field, found)), + (12, Value::Bytes(key_value)) => metadata.push(key_value), _ => {} } } @@ -422,6 +462,23 @@ impl Walk<'_, B> { 10 => PointKind::ExponentialHistogram, _ => PointKind::Summary, }; + let view = if metadata.is_empty() { + None + } else { + self.view_of(name, &metadata)? + }; + if let Some(view) = view { + let source_metric = name + .split_once(NAME_INFIX) + .map_or(name, |(source, _)| source); + let mut reader = Reader::new(data); + while let Some((field, value)) = reader.field()? { + if let (1, Value::Bytes(point)) = (field, value) { + self.state_point(resource, name, source_metric, view, kind, point)?; + } + } + return Ok(()); + } let delta_sum = field == 7 && { let mut temporality = 0; let mut reader = Reader::new(data); @@ -556,7 +613,7 @@ impl Walk<'_, B> { } }; if self.decoded.samples.len() >= self.max_points { - return Err(OtlpError::TooManyPoints(self.max_points)); + return Err(OtlpError::TooManyPoints(self.point_limit)); } self.decoded .samples @@ -594,10 +651,13 @@ impl Walk<'_, B> { pairs.push(key_value(attribute)?); } } - if pairs + if let Some((key, _)) = pairs .iter() - .any(|(key, value)| is_sketch_payload(key, value)) + .find(|(key, value)| is_sketch_payload(key, value)) { + if *key == ENVELOPE_ATTRIBUTE { + return Err(not_a_view(name)); + } return Ok(None); } let labels = series_labels(resource, &format!("{name}{suffix}"), &mut pairs); @@ -611,12 +671,163 @@ impl Walk<'_, B> { } } -/// Whether an attribute is a sketch payload: bytes under one of the -/// sketch payload keys. +impl Walk<'_, B> { + /// The index in `decoded.view_states` of the view metric `name`'s + /// `metadata` (encoded `KeyValue`s) names, added on first sight; `None` + /// for a metric whose metadata names no view (none of the identity + /// keys). + fn view_of(&mut self, name: &str, metadata: &[&[u8]]) -> Result, OtlpError> { + let (mut plan_id, mut node_id, mut key) = (None, None, None); + for entry in metadata { + let (entry_key, value) = key_value(entry)?; + match entry_key { + PLAN_ID => plan_id = Some(value.text().into_owned()), + NODE_ID => node_id = Some(value.text().into_owned()), + VIEW_STATE_KEY => key = Some(value.text().into_owned()), + _ => {} + } + } + if plan_id.is_none() && node_id.is_none() && key.is_none() { + return Ok(None); + } + let refused = |reason: String| OtlpError::ViewIdentity { + metric: name.to_string(), + reason, + }; + let missing = |key: &str| refused(format!("no {key} in the metric's metadata")); + let plan_id = plan_id + .filter(|id| !id.is_empty()) + .ok_or_else(|| missing(PLAN_ID))?; + let node_id: usize = node_id + .ok_or_else(|| missing(NODE_ID))? + .parse() + .map_err(|e| refused(format!("{NODE_ID}: {e}")))?; + let key: ViewStateKey = serde_json::from_str(&key.ok_or_else(|| missing(VIEW_STATE_KEY))?) + .map_err(|e| refused(format!("{VIEW_STATE_KEY}: {e}")))?; + if !name + .strip_suffix(&node_id.to_string()) + .is_some_and(|source| source.ends_with(NAME_INFIX) && source.len() > NAME_INFIX.len()) + { + return Err(refused(format!( + "the name is not {NAME_INFIX}{node_id}" + ))); + } + let views = &mut self.decoded.view_states.views; + if let Some(index) = views + .iter() + .position(|view| view.node_id == node_id && view.plan_id == plan_id && view.key == key) + { + return Ok(Some(index)); + } + views.push(CollectorViewStates { + plan_id, + node_id, + key, + series: Vec::new(), + }); + Ok(Some(views.len() - 1)) + } + + /// An encoded data point of `kind` of the view metric `name` (over + /// `source_metric`), view `view` of `decoded.view_states`: one series' + /// state in one window. + fn state_point( + &mut self, + resource: &ResourceLabels, + name: &str, + source_metric: &str, + view: usize, + kind: PointKind, + point: &[u8], + ) -> Result<(), OtlpError> { + let (attributes_field, flags_field) = kind.attributes_and_flags_fields(); + let (mut start_nanos, mut time_nanos, mut count, mut flags) = (0u64, 0u64, 0u64, 0u64); + let mut envelope = None; + let mut pairs = Vec::new(); + let mut reader = Reader::new(point); + while let Some((field, value)) = reader.field()? { + match (field, value) { + (field, Value::Bytes(attribute)) if field == attributes_field => { + match key_value(attribute)? { + (ENVELOPE_ATTRIBUTE, AttributeValue::Bytes(bytes)) => { + envelope = Some(bytes) + } + (ENVELOPE_ATTRIBUTE, AttributeValue::Text(_)) => { + return Err(OtlpError::ViewIdentity { + metric: name.to_string(), + reason: format!("{ENVELOPE_ATTRIBUTE} is not bytes"), + }) + } + pair => pairs.push(pair), + } + } + (2, Value::Fixed64(found)) => start_nanos = found, + (3, Value::Fixed64(found)) => time_nanos = found, + (4, Value::Fixed64(found)) if kind != PointKind::Number => count = found, + (field, Value::Varint(found)) if field == flags_field => flags = found, + _ => {} + } + } + // A view's window with no recorded value holds no state: nothing to + // stage (its window stays unstored unless another state comes). + if flags & FLAG_NO_RECORDED_VALUE != 0 { + return Ok(()); + } + let Some(envelope) = envelope else { + return Err(OtlpError::ViewIdentity { + metric: name.to_string(), + reason: format!("a point has no {ENVELOPE_ATTRIBUTE} bytes"), + }); + }; + if self.decoded.samples.len() >= self.max_points { + return Err(OtlpError::TooManyPoints(self.point_limit)); + } + self.max_points -= 1; + let labels: LabelSet = series_labels(resource, source_metric, &mut pairs) + .into_iter() + .map(|(name, value)| (name.into_owned(), value)) + .collect(); + let series = &mut self.decoded.view_states.views[view].series; + let index = *self + .series_of_state + .entry((view, labels)) + .or_insert_with_key(|(_, labels)| { + series.push(CollectorSeriesStates { + labels: labels.clone(), + records: Vec::new(), + }); + series.len() - 1 + }); + series[index].records.push(ViewStateRecord { + window_start_ms: (start_nanos / 1_000_000) as i64, + window_end_ms: (time_nanos / 1_000_000) as i64, + asapv1: envelope.to_vec(), + sample_count: count, + }); + Ok(()) + } +} + +/// The error of a `sketch.envelope` point under a metric naming no view. +#[cold] +fn not_a_view(name: &str) -> OtlpError { + OtlpError::ViewIdentity { + metric: name.to_string(), + reason: format!( + "a point has {ENVELOPE_ATTRIBUTE}, but the metric's metadata names no view" + ), + } +} + +/// Whether an attribute is a sketch payload (a collector state's +/// `sketch.envelope` included): bytes under one of the sketch payload keys. fn is_sketch_payload(key: &str, value: &AttributeValue) -> bool { matches!( key, - "kll.sketch_payload" | "cms.sketch_payload" | "countsketch.sketch_payload" + "kll.sketch_payload" + | "cms.sketch_payload" + | "countsketch.sketch_payload" + | ENVELOPE_ATTRIBUTE ) && matches!(value, AttributeValue::Bytes(_)) } diff --git a/crates/adapters/ingest/otlp/src/tests.rs b/crates/adapters/ingest/otlp/src/tests.rs index 2658614ac..b9d41e7d1 100644 --- a/crates/adapters/ingest/otlp/src/tests.rs +++ b/crates/adapters/ingest/otlp/src/tests.rs @@ -70,6 +70,7 @@ fn decode_with( }) .collect(), rejected_points: decoded.rejected_points, + view_states: decoded.view_states, }) } @@ -885,3 +886,200 @@ fn consecutive_points_share_their_series() { ] ); } + +// Collector view states (docs/design/collector-sketch-ingest.md, §4). + +const VIEW_KEY: &str = r#"{"definition_id":"5597d603bdf9f1a148d7c7e5344c1a97","window":{"tumbling":{"width_ms":5000}},"logical_properties":{"parameters":{"DDSketch":{"alpha":0.05}}}}"#; +const WINDOW_END_MS: u64 = 1_700_000_005_000; + +/// The metadata naming view `node` of plan `p1` with key `key`. +fn view_metadata(node: i64, key: &str) -> Vec { + vec![ + text("asap.plan_id", "p1"), + attribute("asap.node_id", any_value::Value::IntValue(node)), + text("asap.view_state_key", key), + ] +} + +/// A state point of the window ending at `WINDOW_END_MS`, as the collector +/// exports one: the series' attributes, then `sketch.envelope`. +fn state_point(attributes: Vec, envelope: &[u8], count: u64) -> SummaryDataPoint { + let mut attributes = attributes; + attributes.push(attribute( + "sketch.envelope", + any_value::Value::BytesValue(envelope.to_vec()), + )); + SummaryDataPoint { + attributes, + start_time_unix_nano: (WINDOW_END_MS - 5_000) * 1_000_000, + time_unix_nano: WINDOW_END_MS * 1_000_000, + count, + sum: 0.0, + ..Default::default() + } +} + +/// A collector view's metric: `.asap_view.` with `metadata`. +fn view_metric( + source: &str, + node: i64, + metadata: Vec, + data_points: Vec, +) -> Metric { + Metric { + metadata, + ..metric( + &format!("{source}.asap_view.{node}"), + Data::Summary(Summary { data_points }), + ) + } +} + +fn decoded(body: &[u8]) -> Result, OtlpError> { + decode_with(body, None, &LabelOptions::default(), &LIMITS) +} + +/// A view metric's points become states of their view, by series, with +/// the window from the point's times, the envelope's bytes and the count; +/// the series' labels are those a raw sample of the same attributes gets +/// (`job` from the resource, `__name__` the source metric), and a raw +/// gauge in the same request is still a sample. +#[test] +fn a_view_metrics_points_are_states_labeled_as_raw_samples() { + let series = vec![text("region", "r0"), text("label.0", "l0")]; + let body = encode(&request(vec![ + view_metric( + "data", + 1, + view_metadata(1, VIEW_KEY), + vec![state_point(series.clone(), &[1, 2, 3], 50)], + ), + gauge( + "data", + vec![number_point( + series, + WINDOW_END_MS * 1_000_000, + number_data_point::Value::AsDouble(2.5), + )], + ), + ])); + let decoded = decoded(&body).unwrap(); + let raw_labels = labels(&[ + ("__name__", "data"), + ("job", "api-gateway"), + ("label_0", "l0"), + ("region", "r0"), + ]); + assert_eq!( + decoded.samples, + vec![Point { + labels: raw_labels.clone(), + timestamp_ms: WINDOW_END_MS as i64, + value: 2.5, + }] + ); + let key: ViewStateKey = serde_json::from_str(VIEW_KEY).unwrap(); + assert_eq!( + decoded.view_states, + ViewStateBatch { + views: vec![CollectorViewStates { + plan_id: "p1".into(), + node_id: 1, + key, + series: vec![CollectorSeriesStates { + labels: raw_labels.into_iter().collect(), + records: vec![ViewStateRecord { + window_start_ms: WINDOW_END_MS as i64 - 5_000, + window_end_ms: WINDOW_END_MS as i64, + asapv1: vec![1, 2, 3], + sample_count: 50, + }], + }], + }], + } + ); +} + +/// Two views over one metric are two entries; one series' states of one +/// view are one series, its records in request order. +#[test] +fn states_group_by_view_then_series() { + let other_key = VIEW_KEY.replace("0.05", "0.01"); + let a = vec![text("region", "a")]; + let b = vec![text("region", "b")]; + let body = encode(&request(vec![ + view_metric( + "data", + 1, + view_metadata(1, VIEW_KEY), + vec![ + state_point(a.clone(), &[1], 1), + state_point(b, &[2], 1), + state_point(a.clone(), &[3], 1), + ], + ), + view_metric( + "data", + 2, + view_metadata(2, &other_key), + vec![state_point(a, &[4], 1)], + ), + ])); + let views = decoded(&body).unwrap().view_states.views; + let shape: Vec<(usize, Vec>>)> = views + .iter() + .map(|view| { + ( + view.node_id, + view.series + .iter() + .map(|s| s.records.iter().map(|r| r.asapv1.clone()).collect()) + .collect(), + ) + }) + .collect(); + assert_eq!( + shape, + vec![ + (1, vec![vec![vec![1], vec![3]], vec![vec![2]]]), + (2, vec![vec![vec![4]]]), + ] + ); +} + +/// A view identity missing in part or not parsing, a view point without +/// `sketch.envelope`, and a `sketch.envelope` point under a metric naming +/// no view refuse the whole request. +#[test] +fn a_bad_view_identity_refuses_the_request() { + let point = || vec![state_point(vec![text("region", "a")], &[1], 1)]; + let refused = |metric: Metric| match decoded(&encode(&request(vec![metric]))) { + Err(OtlpError::ViewIdentity { reason, .. }) => reason, + other => panic!("not refused: {other:?}"), + }; + let mut partial = view_metadata(1, VIEW_KEY); + partial.remove(0); + assert!(refused(view_metric("data", 1, partial, point())).contains("asap.plan_id")); + assert!( + refused(view_metric("data", 1, view_metadata(1, "{"), point())) + .contains("asap.view_state_key") + ); + let mut no_envelope = point(); + no_envelope[0].attributes.pop(); + assert!(refused(view_metric( + "data", + 1, + view_metadata(1, VIEW_KEY), + no_envelope + )) + .contains("sketch.envelope")); + let misnamed = view_metric("data", 2, view_metadata(1, VIEW_KEY), point()); + assert!(refused(misnamed).contains("asap_view.1")); + let unnamed = metric( + "data", + Data::Summary(Summary { + data_points: point(), + }), + ); + assert!(refused(unnamed).contains("names no view")); +} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 2591e4179..0eafe4f2c 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -13,6 +13,7 @@ mod plan; mod query_engine; mod query_request; mod query_result; +mod view_states; pub use fallback::{FallbackClient, FallbackError, FallbackResponse}; pub use plan::{InstallError, InstalledPlan, PlanId}; @@ -22,6 +23,10 @@ pub use query_result::{ Answer, InstantVector, InstantVectorElement, QueryResult, RangeVector, RangeVectorElement, ResultSample, Sample, Table, TableValue, }; +pub use view_states::{ + view_identity, CollectorSeriesStates, CollectorViewStates, ViewStateBatch, ViewStateKey, + ViewStateRecord, +}; /// The largest time, in milliseconds either side of the epoch, the data /// plane takes a sample at or answers a query at; beyond it a sample is diff --git a/crates/common/src/view_states.rs b/crates/common/src/view_states.rs new file mode 100644 index 000000000..e44b5fcc8 --- /dev/null +++ b/crates/common/src/view_states.rs @@ -0,0 +1,68 @@ +//! Collector view states: windowed summary states a collector built for a +//! materialized view of the installed plan, as the ingest adapter decoded +//! them (docs/design/collector-sketch-ingest.md, §4 and §6). Nested as the +//! OTAP tiers they travel in: view (Schema) → series (Dictionary) → state +//! (Record). + +pub use asap_types::plan::materialized_view::ViewStateKey; + +use crate::{LabelSet, PhysicalASAPNodeId}; + +/// The collector states of one request: what an ingest adapter hands the +/// precompute engine. Here because the adapter depends only on `common` +/// and builds it. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ViewStateBatch { + pub views: Vec, +} + +impl ViewStateBatch { + pub fn is_empty(&self) -> bool { + self.views.is_empty() + } +} + +/// One collector view's states (Schema tier): the view identity its +/// metric's metadata carries. +#[derive(Debug, Clone, PartialEq)] +pub struct CollectorViewStates { + /// `PhysicalASAPDAG::plan_id()` of the plan the collector loaded. + pub plan_id: String, + pub node_id: PhysicalASAPNodeId, + /// The view's `MaterializedView::view_state_key()`, as the collector + /// read it from its copy of the plan. + pub key: ViewStateKey, + pub series: Vec, +} + +/// One series' states (Dictionary tier). +#[derive(Debug, Clone, PartialEq)] +pub struct CollectorSeriesStates { + /// Built by the adapter's label function for raw samples; `__name__` + /// is the source metric (the metric's name before `.asap_view.`). + pub labels: LabelSet, + pub records: Vec, +} + +/// One state of one window `(window_start_ms, window_end_ms]` (Record tier). +#[derive(Debug, Clone, PartialEq)] +pub struct ViewStateRecord { + pub window_start_ms: i64, + pub window_end_ms: i64, + /// The full state, as `asap_sketchlib`'s ASAPv1 bytes. + pub asapv1: Vec, + /// Samples folded into the state, as the collector counted them. + pub sample_count: u64, +} + +/// The view identity's metric metadata keys and the reserved part of a +/// collector view's metric name. +pub mod view_identity { + pub const PLAN_ID: &str = "asap.plan_id"; + pub const NODE_ID: &str = "asap.node_id"; + pub const VIEW_STATE_KEY: &str = "asap.view_state_key"; + /// A collector view's metric is `.asap_view.`. + pub const NAME_INFIX: &str = ".asap_view."; + /// The data point attribute holding a state's ASAPv1 bytes. + pub const ENVELOPE_ATTRIBUTE: &str = "sketch.envelope"; +} diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 487955393..01c8449e3 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use common::{InstallablePlan, PhysicalASAPNodeId}; use internal_metrics::{Metrics, QueryMetrics}; +use precompute::collector::{CollectorStateIngestReport, CollectorViewOptions}; use precompute::engine::{ IngestError, InstalledPrecompute, PersistedViews, PrecomputeEngine, PrecomputeMode, PrecomputeOptions, SlowRefresh, @@ -142,6 +143,21 @@ pub struct EngineOptions { /// For tests: the wall clock ingestion reads, set by the test. #[doc(hidden)] pub clock: WallClock, + /// The plan's views a collector builds: their states arrive on + /// `/v1/metrics`, and the precompute engine does not build them. + pub collector: CollectorViewOptions, +} + +/// What names the view files of `plan_json` installed with `collector`'s +/// views built by a collector: the plan file's hash, with the collector +/// views mixed in when there are any (they change the refresh groups the +/// files are laid out by). +fn views_plan_hash(plan_json: &str, collector: &CollectorViewOptions) -> u64 { + if collector.views.is_empty() { + return plan_hash(plan_json.as_bytes()); + } + let views: Vec = collector.views.iter().map(ToString::to_string).collect(); + plan_hash(format!("{plan_json}\ncollector views: {}", views.join(",")).as_bytes()) } /// The default `view_cache_idle_ms`: a minute, four 15 s dashboard @@ -189,6 +205,7 @@ impl Default for EngineOptions { push_batching: precompute::push::MorselBatching::default(), panic_in_combine_of_window_end_ms: None, clock: WallClock::default(), + collector: CollectorViewOptions::default(), } } } @@ -220,7 +237,7 @@ impl EngineHandle { .zip(view_tier.clone()) .map(|(dir, tier)| PersistedViews { dir, - plan_hash: plan_hash(plan_json.as_bytes()), + plan_hash: views_plan_hash(&plan_json, &options.collector), sync_interval: std::time::Duration::from_millis(options.view_sync_interval_ms), segment_ms: options.view_segment_ms, persist: PersistOptions { @@ -254,6 +271,15 @@ impl EngineHandle { self.precompute.try_ingest(samples) } + /// Stages collector states; see + /// [`InstalledPrecompute::ingest_collector_states`]. + pub async fn ingest_collector_states( + &self, + batch: common::ViewStateBatch, + ) -> Result { + self.precompute.ingest_collector_states(batch).await + } + /// What the HTTP routes run queries through. pub(crate) fn dispatcher(&self) -> &QueryDispatcher { &self.dispatcher @@ -367,6 +393,7 @@ impl EngineOptions { precompute_memory_budget_bytes: self.precompute_memory_budget_bytes, panic_in_combine_of_window_end_ms: self.panic_in_combine_of_window_end_ms, clock: self.clock.clone(), + collector: self.collector.clone(), } } diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 81108e9d8..b658f083d 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -462,11 +462,13 @@ async fn write_victoriametrics(State(state): State>, body: Bytes) } /// `POST /v1/metrics`: an OTLP/HTTP metrics body (protobuf, gzip when its -/// `Content-Encoding` says so), each data point ingested as a sample -/// ([`otlp`]). Replies as OTLP/HTTP asks: 200 with an -/// `ExportMetricsServiceResponse` once the engine has the samples, its -/// `partial_success` counting the points rejected (sums with DELTA -/// temporality); 400 for a malformed body, 415 for OTLP/JSON, which is not +/// `Content-Encoding` says so), each data point ingested as a sample, or, +/// under a collector view's metric, staged as that view's state +/// ([`otlp`], [`precompute::collector`]). Replies as OTLP/HTTP asks: 200 with +/// an `ExportMetricsServiceResponse` once the engine has the samples and +/// states, its `partial_success` counting the points rejected (sums with +/// DELTA temporality, states failing a check); 400 for a malformed body or +/// view identity, 415 for OTLP/JSON, which is not /// decoded, and 503 or 500 as Remote Write, each with a `google.rpc.Status` /// body, encoded as the request was. Not served in forward mode (see /// [`router`]). @@ -503,15 +505,52 @@ async fn write_otlp( }; let metrics = state.engine.metrics(); metrics.otlp_decode.record(timer); - let reply = otlp::export_response_body( - decoded.rejected_points, - decoded.rejection_message().as_deref(), - ); + let mut rejected_points = decoded.rejected_points; + let mut message = decoded.rejection_message(); + // Before the samples: a request refused for them (503) is retried + // whole, and its states are then duplicates, which are ignored; the + // other way round, a request refused for its states would ingest its + // samples twice. + if !decoded.view_states.is_empty() { + match state + .engine + .ingest_collector_states(decoded.view_states) + .await + { + Ok(report) if report.rejected_total() > 0 => { + rejected_points += report.rejected_total(); + let states = format!( + "{} collector view states were rejected: {:?}", + report.rejected_total(), + report.rejected + ); + message = Some(match message { + Some(points) => format!("{points}; {states}"), + None => states, + }); + } + Ok(_) => {} + Err(IngestError::Busy) => { + return failed( + StatusCode::SERVICE_UNAVAILABLE, + &IngestError::Busy.to_string(), + ) + } + Err(IngestError::Stopped) => { + tracing::error!("OTLP collector states refused: the engine has stopped"); + return failed( + StatusCode::INTERNAL_SERVER_ERROR, + &IngestError::Stopped.to_string(), + ); + } + } + } if !decoded.samples.is_empty() { if let Some((status, message)) = ingest(&state, decoded.samples, "OTLP") { return failed(status, &message); } } + let reply = otlp::export_response_body(rejected_points, message.as_deref()); // Counted once the request is accepted, so a retried 503 counts once. metrics .otlp_rejected_points diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index a86061c5b..4cba53a13 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -496,6 +496,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { escape(&thread) ); } + metrics.collector_states.render(&mut out); out } diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs new file mode 100644 index 000000000..f0c05dc30 --- /dev/null +++ b/crates/data-plane/tests/collector_views.rs @@ -0,0 +1,775 @@ +//! Collector views (docs/design/collector-sketch-ingest.md): a view of the +//! plan a collector builds arrives as OTLP states on `/v1/metrics`, is +//! checked, staged, deduplicated and merged, committed when its request +//! ends (later states of a committed window merge into it), and answers +//! queries as the view the data plane builds from the same samples does. +//! +//! The OTLP bodies are built as the collector's OTAP codec writes a +//! summary point, with the view identity in the metric's metadata and the +//! state as `asap_sketchlib`'s ASAPv1 bytes of a `DdSketch` fed the samples +//! of one series and window, as the collector's processor builds it. + +mod common; + +use std::collections::BTreeSet; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use asap_planner::InstallablePlan; +use asap_sketchlib::DdSketch; +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::Value; +use tower::ServiceExt; + +const QUERY: &str = "quantile_over_time(0.99, data[5m])"; +const JOBS: [&str; 2] = ["a", "b"]; +const RANGE_MS: i64 = 300_000; + +/// The plan of [`QUERY`] (a DDSketch chain over `data`, the plan's one +/// view), with the chain's node id, width and DDSketch α. +fn plan() -> (InstallablePlan, usize, i64, f64) { + let (plan, node, width_ms, alpha) = plan_for(&common::inputs_without_levels(false)); + assert_eq!(plan.materialized_views().unwrap().len(), 1); + (plan, node, width_ms, alpha) +} + +/// The plan of [`QUERY`] for `inputs`, with its DDSketch chain's node id, +/// width and α. +fn plan_for(inputs: &control_plane::DeploymentInputs) -> (InstallablePlan, usize, i64, f64) { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/workloads/sketch-plan-quantile-single.json"); + let workload = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let plan = plan_workload(&workload, inputs).unwrap().0; + let chain = plan + .dag + .nodes + .iter() + .map(|node| serde_json::to_value(node).unwrap()) + .find(|node| !node["payload"]["ASAP"]["SummaryTumblingWindowChain"].is_null()) + .expect("the plan builds a chain"); + let payload = &chain["payload"]["ASAP"]["SummaryTumblingWindowChain"]; + assert_eq!( + payload["summary_type"], + serde_json::json!({"Sketch": "DDSketch"}) + ); + let width_ms = payload["tumbling_window_width_ms"].as_i64().unwrap(); + let alpha = chain["parameters"]["DDSketch"]["alpha"].as_f64().unwrap(); + ( + plan, + chain["id"].as_u64().unwrap() as usize, + width_ms, + alpha, + ) +} + +/// A sample value of `job` at second `s`: within the sketch's domain. +fn value(job: &str, s: i64) -> f64 { + (s % 97) as f64 + if job == "a" { 0.5 } else { 3.25 } +} + +/// 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 view `node`, with the server's +/// default push precompute (the data plane it is compared with builds by +/// window). +fn collector_data_plane(plan: &InstallablePlan, node: usize) -> (Router, Arc) { + let options = EngineOptions { + precompute_mode: PrecomputeMode::Push, + collector: CollectorViewOptions { + views: BTreeSet::from([node]), + ..CollectorViewOptions::default() + }, + ..no_forward(0) + }; + data_plane(plan, options) +} + +/// One second's samples of each 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 answer of [`QUERY`] at `time_ms` from a data plane that builds the +/// view itself from the samples in `(time_ms − 5 m, time_ms]`. +async fn built_here(plan: &InstallablePlan, time_ms: i64) -> Value { + built_here_without(plan, time_ms, (0, 0)).await +} + +/// [`built_here`] with no sample in `(gap.0, gap.1]`: the feed stopped. +async fn built_here_without(plan: &InstallablePlan, time_ms: i64, gap: (i64, i64)) -> Value { + 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() + .filter(|(timestamp, _)| !(gap.0 < *timestamp && *timestamp <= gap.1)) + .map(|(timestamp, value)| Sample { timestamp, value }) + .collect(), + }) + .collect(); + common::remote_write(&app, timeseries).await; + common::barrier(&app, time_ms).await; + let (status, _, body) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["data"]["result"].as_array().unwrap().len(), JOBS.len()); + body +} + +/// The ASAPv1 bytes of a DDSketch of α `alpha` fed `samples`. +fn sketch_state(alpha: f64, samples: &[(i64, f64)]) -> Vec { + let mut sketch = DdSketch::new(alpha); + for (_, value) in samples { + sketch.try_add(value).unwrap(); + } + sketch.to_asapv1().unwrap() +} + +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 `asapv1` of the window ending at `end_ms`. +struct State { + job: &'static str, + end_ms: i64, + asapv1: Vec, +} + +/// The OTLP body of `states` of view `node` of `plan`, with the view +/// identity as the collector reads it from its copy of the plan. +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 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()), + ]; + let data_points = states + .iter() + .map(|state| SummaryDataPoint { + attributes: vec![ + text("job", state.job), + KeyValue { + key: "sketch.envelope".into(), + value: Some(AnyValue { + value: Some(any_value::Value::BytesValue(state.asapv1.clone())), + }), + }, + ], + 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(); + let request = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: format!("data.asap_view.{node}"), + metadata, + data: Some(Data::Summary(Summary { data_points })), + ..Default::default() + }], + ..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() + ); +} + +/// Each job's state per window of `(time_ms − 5 m, time_ms]`. +fn states(alpha: f64, width_ms: i64, time_ms: i64) -> 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 { + states.push(State { + job, + end_ms, + asapv1: sketch_state(alpha, &samples(job, end_ms - width_ms, end_ms)), + }); + end_ms += width_ms; + } + } + states +} + +/// A view whose states come from the collector answers exactly as the +/// view the data plane builds from the same samples (DDSketch states of +/// equal α fed equal samples are equal); its metric's raw samples, read by +/// that view only, are not stored. +#[tokio::test(flavor = "multi_thread")] +async fn collector_states_answer_as_the_view_built_here() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let windows = (RANGE_MS / width_ms) as f64; + let committed = + format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}"); + wait_for(&state, &committed, windows).await; + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); + assert_eq!( + metric( + &state, + &format!("asap_collector_states_total{{view=\"{node}\",outcome=\"staged\"}}") + ), + states.len() as f64 + ); + + // Raw samples of `data` are not kept: only the collector view reads them. + 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); +} + +/// A view built here from a collector view (a wider level of the window +/// chain, merged from the collector's narrower windows) waits for the +/// collector view's windows, and answers as the levels built here from the +/// samples do. +#[tokio::test(flavor = "multi_thread")] +async fn a_view_reading_a_collector_view_is_built_from_its_states() { + let (plan, node, width_ms, alpha) = plan_for(&common::inputs(false)); + let views = plan.materialized_views().unwrap(); + assert!( + views + .iter() + .any(|view| view.inputs.materialized_views.contains(&node)), + "no view reads the chain" + ); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let committed = + format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}"); + wait_for(&state, &committed, (RANGE_MS / width_ms) as f64).await; + let mut answer = Value::Null; + for _ in 0..100 { + let (status, _, body) = + common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + answer = body; + if status == StatusCode::OK { + break; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + assert_eq!(answer, expected); +} + +/// A window's two partial states (a collector restarted inside it) are +/// merged into the window's state: it answers as the state of all its +/// samples does. A repeat of either partial, before or after the merge, +/// and after the window committed, is a duplicate; a state of a window +/// past its view's retention is dropped as late. +#[tokio::test(flavor = "multi_thread")] +async fn partials_merge_repeats_are_duplicates_late_states_drop() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let mut all = states(alpha, width_ms, time_ms); + // Job `a`'s newest window as two partials: its first and its second + // half of the samples. + let newest = all + .iter() + .position(|s| s.job == "a" && s.end_ms == time_ms) + .unwrap(); + let whole = samples("a", time_ms - width_ms, time_ms); + let (first, second) = whole.split_at(whole.len() / 2); + all[newest].asapv1 = sketch_state(alpha, first); + let second = State { + job: "a", + end_ms: time_ms, + asapv1: sketch_state(alpha, second), + }; + let first_again = State { + job: "a", + end_ms: time_ms, + asapv1: all[newest].asapv1.clone(), + }; + all.push(State { + job: "a", + end_ms: time_ms, + asapv1: all[newest].asapv1.clone(), + }); + let second_again = State { + job: "a", + end_ms: time_ms, + asapv1: second.asapv1.clone(), + }; + all.push(second); + all.push(first_again); + assert_eq!(post(&app, body(&plan, node, width_ms, &all)).await, 0); + let windows = (RANGE_MS / width_ms) as f64; + let line = |outcome: &str| { + format!("asap_collector_states_total{{view=\"{node}\",outcome=\"{outcome}\"}}") + }; + wait_for( + &state, + &format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}"), + windows, + ) + .await; + assert_eq!(metric(&state, &line("duplicate")), 2.0); + assert_eq!(metric(&state, &line("merged")), 1.0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); + + // After the commit: a repeat is still a duplicate; a state of a window + // an hour old, past the view's retention, is late. + let past_retention = State { + job: "b", + end_ms: time_ms - 3_600_000, + asapv1: sketch_state(alpha, &[(time_ms, 1.0)]), + }; + assert_eq!( + post( + &app, + body(&plan, node, width_ms, &[second_again, past_retention]) + ) + .await, + 0 + ); + assert_eq!(metric(&state, &line("duplicate")), 3.0); + assert_eq!(metric(&state, &line("late_merged")), 0.0); + assert_eq!(metric(&state, &line("late_dropped")), 1.0); + let (_, _, again) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(again, expected); +} + +/// A window's states may come in several requests (two collectors, each +/// with some series): the first commits the window, the next merge into +/// it, and it answers as one request with every state does. +#[tokio::test(flavor = "multi_thread")] +async fn states_of_one_window_in_two_requests_answer_as_one_request() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let (a, b): (Vec, Vec) = states(alpha, width_ms, time_ms) + .into_iter() + .partition(|s| s.job == "a"); + assert_eq!(post(&app, body(&plan, node, width_ms, &a)).await, 0); + assert_eq!(post(&app, body(&plan, node, width_ms, &b)).await, 0); + // The second request returned once its states were merged. + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected, "{}", state.engine.render_metrics()); + let line = format!("asap_collector_states_total{{view=\"{node}\",outcome=\"late_merged\"}}"); + assert_eq!(metric(&state, &line), b.len() as f64); +} + +/// A request sent twice (a retry after a lost reply) merges nothing +/// twice: every state of the second is a duplicate, and the answer is the +/// one request's. +#[tokio::test(flavor = "multi_thread")] +async fn a_request_sent_twice_counts_once() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let line = format!("asap_collector_states_total{{view=\"{node}\",outcome=\"duplicate\"}}"); + wait_for(&state, &line, states.len() as f64).await; + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// A window is committed when the request carrying its states returns, not +/// a grace later: a query right after the request answers from it. +#[tokio::test(flavor = "multi_thread")] +async fn a_window_answers_once_its_request_returns() { + let (plan, node, width_ms, alpha) = plan(); + let now = precompute::ingestion::wall_clock_ms(); + // The newest evaluation time, its windows ended less than 10 s ago. + let time_ms = now - now.rem_euclid(10_000); + let expected = built_here(&plan, time_ms).await; + + let (app, _state) = collector_data_plane(&plan, node); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// Two collectors, the second lagging more than a window behind: the first +/// sends every window but one, `(E − W, E]`, three windows before the +/// newest; the second's states of that window come after the later windows +/// committed. The window, stored empty meanwhile, takes the states, the +/// wider level built from it is computed again, and the answer equals one +/// data plane's that got every state on time: no window is lost. +#[tokio::test(flavor = "multi_thread")] +async fn a_window_whose_first_states_come_after_a_later_windows_is_stored() { + let (plan, node, width_ms, alpha) = plan_for(&common::inputs(false)); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let lagging_end = time_ms - 3 * width_ms; + let (lagging, on_time): (Vec, Vec) = states(alpha, width_ms, time_ms) + .into_iter() + .partition(|s| s.end_ms == lagging_end); + assert_eq!(post(&app, body(&plan, node, width_ms, &on_time)).await, 0); + // The lagging window is stored empty meanwhile: answered without it. + let (status, _, before) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{before}"); + assert_eq!(post(&app, body(&plan, node, width_ms, &lagging)).await, 0); + let line = |outcome: &str| { + format!("asap_collector_states_total{{view=\"{node}\",outcome=\"{outcome}\"}}") + }; + assert_eq!(metric(&state, &line("late_merged")), lagging.len() as f64); + assert_eq!(metric(&state, &line("late_dropped")), 0.0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// A collector that got late samples of a window it already emitted sends +/// a correction: a state of the late samples alone, for the same series +/// and window. It is a new state (other bytes), so it merges into the +/// committed window, which then answers as if every sample had come on +/// time; the correction sent again is a duplicate. +#[tokio::test(flavor = "multi_thread")] +async fn a_correction_state_merges_into_its_emitted_window() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let mut emitted = states(alpha, width_ms, time_ms); + let newest = emitted + .iter() + .position(|s| s.job == "a" && s.end_ms == time_ms) + .unwrap(); + let whole = samples("a", time_ms - width_ms, time_ms); + let (on_time, late) = whole.split_at(whole.len() * 2 / 3); + emitted[newest].asapv1 = sketch_state(alpha, on_time); + assert_eq!(post(&app, body(&plan, node, width_ms, &emitted)).await, 0); + let correction = || State { + job: "a", + end_ms: time_ms, + asapv1: sketch_state(alpha, late), + }; + assert_eq!( + post(&app, body(&plan, node, width_ms, &[correction()])).await, + 0 + ); + assert_eq!( + post(&app, body(&plan, node, width_ms, &[correction()])).await, + 0 + ); + let line = |outcome: &str| { + format!("asap_collector_states_total{{view=\"{node}\",outcome=\"{outcome}\"}}") + }; + assert_eq!(metric(&state, &line("late_merged")), 1.0); + assert_eq!(metric(&state, &line("duplicate")), 1.0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// A feed gap of 30 s (six 5 s windows with no state at all): the gap's +/// windows are stored empty, as the data plane stores the idle windows it +/// builds itself, so a query over the gap answers, and equals the answer +/// of a data plane that built the view from the same samples. +#[tokio::test(flavor = "multi_thread")] +async fn a_feed_gap_is_stored_empty_and_answered() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let gap = (time_ms - 120_000, time_ms - 120_000 + 6 * width_ms); + let expected = built_here_without(&plan, time_ms, gap).await; + + let (app, _state) = collector_data_plane(&plan, node); + let states: Vec = states(alpha, width_ms, time_ms) + .into_iter() + .filter(|s| !(gap.0 < s.end_ms && s.end_ms <= gap.1)) + .collect(); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// The collector's stream stops: no state comes for 30 s. Its windows close +/// on the engine's monotonic clock once they end plus the collector's close +/// delay and skew allowance (8 s) have passed, are stored empty, and a +/// query over the stop answers as ASAPQuery-backend alone answers from the +/// same samples (none in the stop). +#[tokio::test(flavor = "multi_thread")] +async fn windows_of_a_stopped_collector_close_by_the_clock() { + let (plan, node, width_ms, alpha) = plan(); + let stopped_at = query_time_ms() - 30_000; + let at = stopped_at + 30_000; + let expected = built_here_without(&plan, at, (stopped_at, at)).await; + + let clock = precompute::ingestion::WallClock::manual(stopped_at + 500); + let options = EngineOptions { + precompute_mode: PrecomputeMode::Push, + collector: CollectorViewOptions { + views: BTreeSet::from([node]), + ..CollectorViewOptions::default() + }, + clock: clock.clone(), + ..no_forward(0) + }; + let (app, _state) = data_plane(&plan, options); + let states: Vec = states(alpha, width_ms, at) + .into_iter() + .filter(|s| s.end_ms <= stopped_at) + .collect(); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let (status, _, _) = common::get(&app, &common::instant_uri(QUERY, at / 1000)).await; + assert_ne!(status, StatusCode::OK, "the stop's windows are still open"); + // The clock passes the stop's last window end by the 8 s allowance. + clock.set(stopped_at + 500 + 30_000 + 8_000); + common::barrier(&app, 0).await; + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, at / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// States failing a check are rejected with their reason and reported as +/// rejected points: another plan's, an unknown view's, another key's (θ), +/// a window not on the view's grid, and bytes that are not the view's +/// sketch. A window with no state is counted `empty` (and stored empty: +/// [`a_feed_gap_is_stored_empty_and_answered`]). +#[tokio::test(flavor = "multi_thread")] +async fn bad_states_are_rejected_and_a_window_without_states_is_counted() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let (app, state) = collector_data_plane(&plan, node); + let one = |end_ms: i64, asapv1: Vec| State { + job: "a", + end_ms, + asapv1, + }; + let good = sketch_state(alpha, &[(time_ms, 1.0)]); + let rejected = |reason: &str| { + metric( + &state, + &format!("asap_collector_states_rejected_total{{view=\"{node}\",reason=\"{reason}\"}}"), + ) + }; + + let good_body = || body(&plan, node, width_ms, &[one(time_ms, good.clone())]); + let other_plan = edited(good_body(), |metric| { + metric.metadata[0] = text("asap.plan_id", "another plan"); + }); + assert_eq!(post(&app, other_plan).await, 1); + assert_eq!(rejected("other_plan"), 1.0); + + let view = plan.materialized_views().unwrap().remove(0); + let mut key = serde_json::to_value(view.view_state_key()).unwrap(); + key["logical_properties"]["parameters"]["DDSketch"]["alpha"] = (alpha / 2.0).into(); + let other_key = edited(good_body(), |metric| { + metric.metadata[2] = text("asap.view_state_key", &key.to_string()); + }); + assert_eq!(post(&app, other_key).await, 1); + assert_eq!(rejected("key_mismatch"), 1.0); + + let other_name = edited(good_body(), |metric| { + metric.name = format!("other.asap_view.{node}") + }); + assert_eq!(post(&app, other_name).await, 1); + assert_eq!(rejected("name"), 1.0); + + assert_eq!( + post( + &app, + body(&plan, node, width_ms, &[one(time_ms - 1, good.clone())]) + ) + .await, + 1 + ); + assert_eq!(rejected("window"), 1.0); + + assert_eq!( + post( + &app, + body(&plan, node, width_ms, &[one(time_ms, vec![1, 2, 3])]) + ) + .await, + 1 + ); + assert_eq!(rejected("decode"), 1.0); + + let unknown = node + 1000; + let unknown_view = edited(good_body(), |metric| { + metric.name = format!("data.asap_view.{unknown}"); + metric.metadata[1].value = Some(AnyValue { + value: Some(any_value::Value::IntValue(unknown as i64)), + }); + }); + assert_eq!(post(&app, unknown_view).await, 1); + assert_eq!( + metric( + &state, + "asap_collector_states_rejected_total{view=\"unknown\",reason=\"unknown_view\"}" + ), + 1.0 + ); + + // Two windows apart: the one between them has no state. + let first = time_ms - 2 * width_ms; + let states = [one(first, good.clone()), one(time_ms, good)]; + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + wait_for( + &state, + &format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"empty\"}}"), + 1.0, + ) + .await; +} + +/// `body` with its one metric changed by `edit`. +fn edited(body: Vec, edit: impl FnOnce(&mut Metric)) -> Vec { + let mut request: ExportMetricsServiceRequest = prost::Message::decode(&body[..]).unwrap(); + edit(&mut request.resource_metrics[0].scope_metrics[0].metrics[0]); + prost::Message::encode_to_vec(&request) +} diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index b8a463e04..6954f16e4 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use std::fmt::Write; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; +use std::sync::Mutex; use std::time::Instant; /// CPU time this thread has used, in nanoseconds. @@ -283,6 +284,126 @@ impl PushMetrics { } } +/// Upper bounds of the collector state arrival delay histogram's buckets, +/// in seconds: states usually come within a second of their window's +/// end; later ones merge into a committed window. +const ARRIVAL_DELAY_BUCKETS_S: [f64; 9] = [0.5, 1.0, 2.0, 4.0, 6.0, 8.0, 12.0, 30.0, 60.0]; + +/// One collector view's states and windows. +#[derive(Default)] +struct CollectorViewCounts { + /// States by outcome: `staged`, `duplicate`, `merged`, `late_merged`, + /// `late_dropped`, `expired`. + outcomes: BTreeMap<&'static str, u64>, + /// States rejected, by reason. + rejected: BTreeMap<&'static str, u64>, + /// Windows by outcome: `committed`, `empty` (no state at commit). + windows: BTreeMap<&'static str, u64>, + /// From each decoded state's window end to its arrival, not cumulative + /// per bucket; the last bucket is beyond every bound. + delay_buckets: [u64; ARRIVAL_DELAY_BUCKETS_S.len() + 1], + delay_sum_ms: u64, +} + +/// What happened to collector view states, per view (by node id; `None`: +/// a view the installed plan has not, counted as `view="unknown"`); +/// rendered only once a state has arrived. +#[derive(Default)] +pub struct CollectorStateMetrics { + views: Mutex, CollectorViewCounts>>, +} + +impl CollectorStateMetrics { + fn with(&self, view: Option, update: impl FnOnce(&mut CollectorViewCounts)) { + let mut views = self.views.lock().unwrap_or_else(|e| e.into_inner()); + update(views.entry(view).or_default()); + } + + /// `count` states of `view` with `outcome`. + pub fn outcome(&self, view: usize, outcome: &'static str, count: u64) { + self.with(Some(view), |v| { + *v.outcomes.entry(outcome).or_default() += count + }); + } + + /// `count` states of `view` rejected for `reason`. + pub fn rejected(&self, view: Option, reason: &'static str, count: u64) { + self.with(view, |v| *v.rejected.entry(reason).or_default() += count); + } + + /// A window of `view` with `outcome`. + pub fn window(&self, view: usize, outcome: &'static str) { + self.with(Some(view), |v| *v.windows.entry(outcome).or_default() += 1); + } + + /// A state of `view` arrived `delay_ms` after its window's end. + pub fn arrived(&self, view: usize, delay_ms: i64) { + let seconds = delay_ms as f64 / 1e3; + let bucket = ARRIVAL_DELAY_BUCKETS_S + .iter() + .position(|bound| seconds <= *bound) + .unwrap_or(ARRIVAL_DELAY_BUCKETS_S.len()); + self.with(Some(view), |v| { + v.delay_buckets[bucket] += 1; + v.delay_sum_ms += delay_ms.max(0) as u64; + }); + } + + /// The `asap_collector_states_*` series in the Prometheus text format; + /// nothing before a state arrived. + pub fn render(&self, out: &mut String) { + let views = self.views.lock().unwrap_or_else(|e| e.into_inner()); + if views.is_empty() { + return; + } + let views: Vec<(String, &CollectorViewCounts)> = views + .iter() + .map(|(view, counts)| (view.map_or("unknown".into(), |id| id.to_string()), counts)) + .collect(); + let _ = writeln!(out, "# HELP asap_collector_states_total Collector view states by outcome: staged, duplicate (equal to one staged), merged (into the one staged), late_merged (into their closed window, or stored with it), late_dropped (their window past retention), expired (staged for a window skipped as past retention).\n# TYPE asap_collector_states_total counter"); + for (view, counts) in &views { + for (outcome, count) in &counts.outcomes { + let _ = writeln!( + out, + "asap_collector_states_total{{view=\"{view}\",outcome=\"{outcome}\"}} {count}" + ); + } + } + let _ = writeln!(out, "# HELP asap_collector_states_rejected_total Collector view states rejected, by reason.\n# TYPE asap_collector_states_rejected_total counter"); + for (view, counts) in &views { + for (reason, count) in &counts.rejected { + let _ = writeln!(out, "asap_collector_states_rejected_total{{view=\"{view}\",reason=\"{reason}\"}} {count}"); + } + } + let _ = writeln!(out, "# HELP asap_collector_states_windows_total Collector view windows at commit: committed, or empty (no state, not stored).\n# TYPE asap_collector_states_windows_total counter"); + for (view, counts) in &views { + for (outcome, count) in &counts.windows { + let _ = writeln!(out, "asap_collector_states_windows_total{{view=\"{view}\",outcome=\"{outcome}\"}} {count}"); + } + } + let name = "asap_collector_states_arrival_delay_seconds"; + let _ = writeln!(out, "# HELP {name} From a collector state's window end to its arrival.\n# TYPE {name} histogram"); + for (view, counts) in &views { + let mut cumulative = 0; + for (bound, bucket) in ARRIVAL_DELAY_BUCKETS_S.iter().zip(&counts.delay_buckets) { + cumulative += bucket; + let _ = writeln!( + out, + "{name}_bucket{{view=\"{view}\",le=\"{bound}\"}} {cumulative}" + ); + } + let count: u64 = counts.delay_buckets.iter().sum(); + let _ = writeln!(out, "{name}_bucket{{view=\"{view}\",le=\"+Inf\"}} {count}"); + let _ = writeln!( + out, + "{name}_sum{{view=\"{view}\"}} {}", + counts.delay_sum_ms as f64 / 1e3 + ); + let _ = writeln!(out, "{name}_count{{view=\"{view}\"}} {count}"); + } + } +} + /// Every measurement the engine's threads record. pub struct Metrics { /// Push precompute's measurements (push mode only). @@ -324,6 +445,8 @@ pub struct Metrics { pub view_file_bytes: AtomicU64, /// View segments whose pages were advised cold. pub view_segments_marked_cold: AtomicU64, + /// Collector view states, per view. + pub collector_states: CollectorStateMetrics, } impl Metrics { @@ -363,6 +486,7 @@ impl Metrics { view_persist_over_bound: AtomicU64::new(0), view_file_bytes: AtomicU64::new(0), view_segments_marked_cold: AtomicU64::new(0), + collector_states: CollectorStateMetrics::default(), } } } diff --git a/crates/precompute/Cargo.toml b/crates/precompute/Cargo.toml index 3821030a0..cca094326 100644 --- a/crates/precompute/Cargo.toml +++ b/crates/precompute/Cargo.toml @@ -22,4 +22,5 @@ tokio.workspace = true tracing.workspace = true [dev-dependencies] +asap_sketchlib.workspace = true control_plane = { workspace = true, features = ["test-support"] } diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs new file mode 100644 index 000000000..6542d0a7f --- /dev/null +++ b/crates/precompute/src/collector.rs @@ -0,0 +1,870 @@ +//! Collector views (docs/design/collector-sketch-ingest.md, §6): views of the +//! installed plan a collector builds, whose windowed states arrive over +//! OTLP ([`common::ViewStateBatch`]) instead of being computed here. +//! +//! A state goes through three steps: +//! +//! 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. +//! 2. [`Staging::stage`], on the ingest coordinator: a state of a window +//! not yet committed is staged per `(view, series, window)`, a repeat of +//! a state seen (equal bytes) is a duplicate, and a different state of +//! the same series and window is merged into the staged one. A state of +//! a committed window still kept is merged into it later +//! ([`crate::ingestion::Precompute::merge_late`]); one of a window past +//! retention, or of one never stored, is dropped as late. +//! 3. The windows a request staged close when the request ends +//! ([`crate::ingestion`]): their staged states become the window's rows +//! ([`CollectorViews::rows`]), committed by the precompute committer as +//! a computed window is, and the request is answered once they are. A +//! window with no state is not stored, so a query reading it is not +//! answered from the plan. + +use std::collections::hash_map::DefaultHasher; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::hash::{Hash, Hasher}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +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::summary_kernels::factory::create_planner_accumulator; +use asap_executor::values::{Batch, SchemaRef, Value}; +use asap_executor::AggregateCore; +use common::{ViewStateBatch, MAX_TIME_MS}; +use internal_metrics::Metrics; +use storage::persist::Asapv1Decoder; +use storage::series_ids::{intern_pairs, Series}; + +use crate::ingestion::{ClockReading, ClosedWindow, Computed, DagIndex, Ingestion, Precompute}; + +/// Which views of the installed plan a collector builds, and how long after +/// a window's end, with no state arriving, it closes on the clock. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CollectorViewOptions { + pub views: BTreeSet, + /// While no state arrives, a window closes once its end plus this has + /// passed on the monotonic clock, counted from the newest state's + /// window: the collector's window close delay and an allowance for + /// clock skew. States of it coming later merge in. + pub idle_close_ms: u64, +} + +impl Default for CollectorViewOptions { + /// No collector views; today's collector closes a window 6 s after its + /// end, and 2 s are allowed for clock skew. + fn default() -> Self { + Self { + views: BTreeSet::new(), + idle_close_ms: 8_000, + } + } +} + +/// Why a state was rejected, as `asap_collector_states_rejected_total`'s +/// `reason`. +pub mod reject { + /// Another plan's view. + pub const OTHER_PLAN: &str = "other_plan"; + /// No collector view of the installed plan has this node id. + pub const UNKNOWN_VIEW: &str = "unknown_view"; + /// The view's state key differs from the installed view's. + pub const KEY_MISMATCH: &str = "key_mismatch"; + /// The series' metric (`__name__`) is not the one the view's `Scan` + /// reads. + pub const NAME: &str = "name"; + /// The window is not one of the view's, or too far ahead of the clock. + pub const WINDOW: &str = "window"; + /// The bytes are not a state of the view's kernel. + pub const DECODE: &str = "decode"; + /// The state does not merge with the one staged for its series and + /// window. + pub const MERGE: &str = "merge"; +} + +/// What happened to a batch's states. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CollectorStateIngestReport { + /// Staged: the first state of its series and window. + pub staged: u64, + /// Ignored: equal to a state already staged for its series and window. + pub duplicate: u64, + /// Merged into the state staged for its series and window. + pub merged: u64, + /// Of a closed window still kept: merged into it, or stored with it + /// when it closed without states. + pub late_merged: u64, + /// Dropped: its window is past its view's retention. + pub late_dropped: u64, + /// Rejected, by reason ([`reject`]). + pub rejected: BTreeMap<&'static str, u64>, +} + +impl CollectorStateIngestReport { + /// States rejected for any reason. + pub fn rejected_total(&self) -> u64 { + self.rejected.values().sum() + } +} + +impl std::ops::AddAssign for CollectorStateIngestReport { + fn add_assign(&mut self, other: Self) { + self.staged += other.staged; + self.duplicate += other.duplicate; + self.merged += other.merged; + self.late_merged += other.late_merged; + self.late_dropped += other.late_dropped; + for (reason, count) in other.rejected { + *self.rejected.entry(reason).or_default() += count; + } + } +} + +/// What happened to a staged state or a window, as the +/// `asap_collector_states_*` series' `outcome`. +pub mod outcome { + pub const STAGED: &str = "staged"; + pub const DUPLICATE: &str = "duplicate"; + pub const MERGED: &str = "merged"; + /// Of a closed window still kept: merged into it (or stored with it). + pub const LATE_MERGED: &str = "late_merged"; + /// Its window was past its view's retention when it arrived. + pub const LATE_DROPPED: &str = "late_dropped"; + /// Staged for a window skipped as past the view's retention. + pub const EXPIRED: &str = "expired"; + /// A window committed with its staged states. + pub const COMMITTED: &str = "committed"; + /// A window with no state at commit: not stored. + pub const EMPTY: &str = "empty"; +} + +/// One state that passed the checks, for the coordinator to stage. +pub(crate) struct ArrivedState { + pub group: usize, + pub node_id: PhysicalASAPNodeId, + pub series: &'static Series, + pub end_ms: i64, + /// The hash of its ASAPv1 bytes, which tells a repeat from a partial. + pub hash: u64, + pub state: Arc, +} + +/// One installed collector view. +struct CollectorView { + group: usize, + key: ViewStateKey, + /// The metric its `Scan` reads: its rows' `__name__`. + source_metric: String, + width_ms: i64, + decoder: Asapv1Decoder, + /// Its rows' schema, and where the window end, the series identity + /// and the state are. + schema: SchemaRef, + window_end_column: Option, + identity_column: usize, + state_column: usize, +} + +/// The installed plan's collector views: what checks a state and turns +/// staged states into a window's rows. +pub(crate) struct CollectorViews { + /// `PhysicalASAPDAG::plan_id()` of the installed plan. + plan_id: String, + views: HashMap, + /// Each collector view's group's view. + view_of_group: HashMap, + max_future_ms: i64, + /// When each (view, reason) rejection was last logged. + logged: Mutex, &'static str), Instant>>, +} + +/// How often a rejection of one view and reason is logged. +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 + /// read exactly one metric, or whose rows hold more than a window end, + /// a series identity and a state. + pub fn new( + dag: &PhysicalASAPDAG, + ingestion: &Ingestion, + precompute: &Precompute, + max_future_ms: u64, + ) -> anyhow::Result { + let index = DagIndex::new(dag); + let groups = precompute.views(); + let mut installed = HashMap::new(); + for group in (0..groups.len()).filter(|&group| ingestion.is_collector(group)) { + let [(view, schema)] = groups[group].as_slice() else { + unreachable!("a collector view's group holds that view alone") + }; + let (id, schema) = (view.node_id, schema.clone()); + let fail = |why: String| anyhow::anyhow!("collector view {id}: {why}"); + let width_ms = precompute.width_ms(group); + let node = index.nodes[&id]; + let (summary_type, input) = match &node.payload { + Operator::ASAP( + ASAPOp::SummaryTumblingWindowChain { + summary_type, + input, + .. + } + | ASAPOp::SummaryAgg { + summary_type, + input, + .. + }, + ) => (summary_type, input), + other => return Err(fail(format!("builds no summary: {other:?}"))), + }; + let template = + 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 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")))?; + let mut identity_column = None; + let mut state_column = None; + // A chain's rows start with their window's end, its time index. + let window_end_column = schema.time_index; + for (column, field) in schema.fields.iter().enumerate() { + match &field.dtype { + _ if Some(column) == window_end_column => {} + _ if field.name == PROMQL_SERIES_IDENTITY => identity_column = Some(column), + FieldDataType::Plain(_) => { + return Err(fail(format!( + "its rows have column {}, which a collector state does not carry", + field.name + ))) + } + _ => state_column = Some(column), + } + } + let (Some(identity_column), Some(state_column)) = (identity_column, state_column) + else { + return Err(fail( + "its rows are not a series identity and a state".into(), + )); + }; + installed.insert( + id, + CollectorView { + group, + key: view.view_state_key().clone(), + source_metric, + width_ms, + decoder, + schema, + window_end_column, + identity_column, + state_column, + }, + ); + } + Ok(Self { + plan_id: dag.plan_id(), + view_of_group: installed + .iter() + .map(|(&id, view)| (view.group, id)) + .collect(), + views: installed, + max_future_ms: storage::store::millis(max_future_ms), + logged: Mutex::new(HashMap::new()), + }) + } + + /// The states of `batch` that pass every check, decoded, at wall-clock + /// time `now_ms`, and the report of those rejected (counted in + /// `metrics`, each view and reason logged at most once a minute). + pub fn check( + &self, + batch: ViewStateBatch, + now_ms: i64, + metrics: &Metrics, + ) -> (Vec, CollectorStateIngestReport) { + let mut report = CollectorStateIngestReport::default(); + let mut arrived = Vec::new(); + for states in batch.views { + let node_id = states.node_id; + let mut reject = |reason: &'static str, count: u64, detail: &dyn Fn() -> String| { + if count == 0 { + return; + } + *report.rejected.entry(reason).or_default() += count; + // A view the installed plan has not is counted and logged + // as one, whatever node id it names. + let view = self.views.contains_key(&node_id).then_some(node_id); + metrics.collector_states.rejected(view, reason, count); + self.log_rejection(view, reason, detail); + }; + let count = |series: &[common::CollectorSeriesStates]| -> u64 { + series.iter().map(|s| s.records.len() as u64).sum() + }; + let view = match self.views.get(&node_id) { + _ if states.plan_id != self.plan_id => { + reject(reject::OTHER_PLAN, count(&states.series), &|| { + format!("plan {} is not the installed plan", states.plan_id) + }); + continue; + } + None => { + reject(reject::UNKNOWN_VIEW, count(&states.series), &|| { + "no collector view of the installed plan has this node id".into() + }); + continue; + } + Some(view) if view.key != states.key => { + reject(reject::KEY_MISMATCH, count(&states.series), &|| { + format!( + "view state key {:?} differs from the installed view's", + states.key + ) + }); + continue; + } + Some(view) => view, + }; + for series in states.series { + if series.labels.get("__name__") != Some(&view.source_metric) { + reject(reject::NAME, series.records.len() as u64, &|| { + format!("a series' __name__ is not {}", view.source_metric) + }); + continue; + } + let labels: Vec<(&str, &str)> = series + .labels + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + let interned = intern_pairs(&labels); + for record in series.records { + let end_ms = record.window_end_ms; + if end_ms.rem_euclid(view.width_ms) != 0 + || record.window_start_ms != end_ms - view.width_ms + || end_ms > now_ms.saturating_add(self.max_future_ms).min(MAX_TIME_MS) + || end_ms < -MAX_TIME_MS + { + reject(reject::WINDOW, 1, &|| { + format!( + "window ({}, {end_ms}] is not one of its {} ms windows up to now", + record.window_start_ms, view.width_ms + ) + }); + continue; + } + 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() + }); + continue; + }; + metrics + .collector_states + .arrived(node_id, (now_ms - end_ms).max(0)); + let mut hasher = DefaultHasher::new(); + record.asapv1.hash(&mut hasher); + arrived.push(ArrivedState { + group: view.group, + node_id, + series: interned, + end_ms, + hash: hasher.finish(), + state, + }); + } + } + } + (arrived, report) + } + + fn log_rejection( + &self, + view: Option, + reason: &'static str, + detail: &dyn Fn() -> String, + ) { + let mut logged = self.logged.lock().unwrap_or_else(|e| e.into_inner()); + let now = Instant::now(); + if logged + .get(&(view, reason)) + .is_some_and(|last| now.duration_since(*last) < LOG_INTERVAL) + { + return; + } + logged.insert((view, reason), now); + tracing::warn!(?view, reason, detail = %detail(), "collector states rejected"); + } + + /// Whether group `group` is a collector view's. + pub fn builds(&self, group: usize) -> bool { + self.view_of_group.contains_key(&group) + } + + /// The view collector view group `group` builds. + pub fn view_of_group(&self, group: usize) -> PhysicalASAPNodeId { + self.view_of_group[&group] + } + + /// The rows of `window` of a collector view's group holding `states`, + /// one row per series, as the view's own run writes them: the states + /// in their view layout, as a computed window seals its states, so a + /// collector window takes the memory of a computed one. + pub fn rows(&self, window: ClosedWindow, states: Vec) -> Result { + let group = window.group; + let view = &self.views[&self.view_of_group(group)]; + let family = view.schema.fields[view.state_column].dtype.clone(); + let rows = states + .into_iter() + .map(|staged| { + let mut row = vec![Value::Null; view.schema.fields.len()]; + if let Some(column) = view.window_end_column { + row[column] = Value::Timestamp(window.end_ms); + } + row[view.identity_column] = Value::Utf8(staged.series.identity.clone()); + row[view.state_column] = Value::Summary { + family: family.clone(), + state: staged.state, + }; + row + }) + .collect(); + let batch = Batch::try_new(view.schema.clone(), rows) + .and_then(storage::segment::with_view_layout_states) + .map_err(|e| e.to_string())?; + Ok(Computed::Ran(vec![(0, vec![batch])])) + } +} + +/// One series' state of one window, staged until the window commits. +pub(crate) struct Staged { + series: &'static Series, + state: Arc, + /// The hashes of every state merged into it: a repeat of any is a + /// duplicate, even after a later partial was merged. + hashes: Vec, +} + +/// The collector states staged per window and series, on the ingest +/// coordinator, and the hashes of the states of each committed window +/// still kept. +#[derive(Default)] +pub(crate) struct Staging { + /// By `(group, window end)`, then by series id. + windows: BTreeMap<(usize, i64), BTreeMap>, + /// Per committed window still kept, by `(group, window end)`, the + /// hashes of every state merged into each series' state: a repeat of + /// one is a duplicate. + committed: BTreeMap<(usize, i64), HashMap>>, +} + +impl Staging { + /// Stages `states`, merging and deduplicating per series and window. A + /// state of a closed window still kept that is no duplicate is + /// returned, by window, to merge into it (or to store it with, when it + /// closed without states); one of a window past retention is late. A view's group + /// starts at the oldest window of its first states, and each group + /// with staged windows is to close through its newest. Counts each + /// state's outcome in `metrics`. + pub fn stage( + &mut self, + states: Vec, + ingestion: &mut Ingestion, + now: ClockReading, + metrics: &Metrics, + ) -> ( + CollectorStateIngestReport, + BTreeMap>, + ) { + let mut report = CollectorStateIngestReport::default(); + let mut late: BTreeMap> = BTreeMap::new(); + let mut oldest: BTreeMap = BTreeMap::new(); + for state in &states { + let end = oldest.entry(state.group).or_insert(state.end_ms); + *end = (*end).min(state.end_ms); + } + for (group, end_ms) in oldest { + ingestion.start_collector_group(group, end_ms); + } + // Committed windows no longer kept take no more states. + let kept_after = ingestion.kept_after_ms(); + self.committed + .retain(|&(group, end), _| kept_after[group].is_none_or(|kept_after| end > kept_after)); + let mut newest: BTreeMap = BTreeMap::new(); + for arrived in states { + let view = arrived.node_id; + let key = (arrived.group, arrived.end_ms); + if ingestion + .closed_through(arrived.group) + .is_some_and(|through| arrived.end_ms <= through) + { + // A window closed without states (its first come after a + // later window's) is stored with them, if still kept. + let kept = + kept_after[arrived.group].is_none_or(|kept_after| arrived.end_ms > kept_after); + if !kept { + report.late_dropped += 1; + metrics + .collector_states + .outcome(view, outcome::LATE_DROPPED, 1); + continue; + } + let series = self.committed.entry(key).or_default(); + let hashes = series.entry(arrived.series.id).or_default(); + if hashes.contains(&arrived.hash) { + report.duplicate += 1; + metrics + .collector_states + .outcome(view, outcome::DUPLICATE, 1); + continue; + } + hashes.push(arrived.hash); + report.late_merged += 1; + metrics + .collector_states + .outcome(view, outcome::LATE_MERGED, 1); + let window = ClosedWindow { + group: arrived.group, + end_ms: arrived.end_ms, + }; + late.entry(window).or_default().push(Staged { + series: arrived.series, + state: arrived.state, + hashes: vec![arrived.hash], + }); + continue; + } + let newest = newest.entry(arrived.group).or_insert(arrived.end_ms); + *newest = (*newest).max(arrived.end_ms); + let window = self.windows.entry(key).or_default(); + let Some(staged) = window.get_mut(&arrived.series.id) else { + window.insert( + arrived.series.id, + Staged { + series: arrived.series, + state: arrived.state, + hashes: vec![arrived.hash], + }, + ); + report.staged += 1; + metrics.collector_states.outcome(view, outcome::STAGED, 1); + continue; + }; + if staged.hashes.contains(&arrived.hash) { + report.duplicate += 1; + metrics + .collector_states + .outcome(view, outcome::DUPLICATE, 1); + continue; + } + match staged.state.merge_with(&*arrived.state) { + Ok(merged) => { + staged.state = Arc::from(merged); + staged.hashes.push(arrived.hash); + report.merged += 1; + metrics.collector_states.outcome(view, outcome::MERGED, 1); + } + Err(error) => { + *report.rejected.entry(reject::MERGE).or_default() += 1; + metrics + .collector_states + .rejected(Some(view), reject::MERGE, 1); + tracing::warn!(view, %error, "a collector state does not merge with the staged one"); + } + } + } + for (group, end_ms) in newest { + ingestion.collector_arrived(group, end_ms, now); + } + (report, late) + } + + /// The states staged for `window`, removed, for it to commit; empty + /// when none is (it is then not stored). Their hashes are kept while + /// the window is, so a repeat is a duplicate. + pub fn take(&mut self, window: ClosedWindow) -> Vec { + let key = (window.group, window.end_ms); + let staged: Vec = self + .windows + .remove(&key) + .map(|series| series.into_values().collect()) + .unwrap_or_default(); + if !staged.is_empty() { + let hashes = self.committed.entry(key).or_default(); + for state in &staged { + hashes + .entry(state.series.id) + .or_default() + .extend(&state.hashes); + } + } + staged + } + + /// Drops the states staged for windows of `group` ending at or before + /// `through` (windows skipped as expired), returning how many. + pub fn drop_through(&mut self, group: usize, through: i64) -> u64 { + let expired: Vec<(usize, i64)> = self + .windows + .range((group, i64::MIN)..=(group, through)) + .map(|(&window, _)| window) + .collect(); + expired + .into_iter() + .filter_map(|window| self.windows.remove(&window)) + .map(|series| series.len() as u64) + .sum() + } +} + +#[cfg(test)] +mod tests { + use asap_executor::arrow::array::UInt32Array; + use asap_executor::planner::summary_type::{SketchAlgorithm, SketchParams}; + use asap_executor::summary_kernels::DDSketchAccumulator; + use asap_executor::values::BatchColumn; + use asap_executor::StateColumnUpdater; + use asap_sketchlib::DdSketch; + use control_plane::test_support::one_query_plan; + use storage::store::ViewStore; + + use super::*; + use crate::ingestion::IngestionOptions; + + /// The ingestion of a one-chain plan whose chain a collector builds, + /// and the chain's window width. + fn ingestion() -> (Ingestion, i64) { + let plan = one_query_plan("sum_over_time(data[1m])", false); + let views = plan.materialized_views().unwrap(); + let chain = views[0].node_id; + let collector = CollectorViewOptions { + 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 }, + &collector, + ) + .unwrap(); + assert!(ingestion.is_collector(0)); + (ingestion, precompute.width_ms(0)) + } + + /// The plan of `quantile_over_time(0.99, data[1m])` within 5% over many + /// series and no raw data: one DDSketch chain, one level. + fn quantile_sketch_plan() -> common::InstallablePlan { + let workload = serde_json::from_value(serde_json::json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": "quantile_over_time(0.99, data[1m])", + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {"accuracy": {"max_error": 0.05, "failure_probability": 0.3, + "accuracy_scope": "whole_result"}}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 100000.0}}, + "sources": {"data": {"series_count": 10000, "sample_interval": 100, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let mut inputs = control_plane::DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = false; + inputs.deployment_capabilities.excluded_candidates = serde_json::from_value( + serde_json::json!([{"operator": "SummaryMergeWindows"}, {"operator": "TimeRangeCover"}]), + ) + .unwrap(); + control_plane::plan_workload(&workload, &inputs).unwrap().0 + } + + /// A window built from a collector's states holds them as the window + /// the view's own run computes from the same samples does (sealed, in + /// the sketch's view layout), so the view store charges both alike. + #[test] + fn a_collector_window_is_charged_as_the_computed_window_of_its_samples() { + let plan = quantile_sketch_plan(); + let views = plan.materialized_views().unwrap(); + let chain = views[0].node_id; + let options = CollectorViewOptions { + 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 family = view.schema.fields[view.state_column].dtype.clone(); + assert_eq!(family, FieldDataType::Sketch(SketchAlgorithm::DDSketch)); + let parameters = DagIndex::new(&plan.dag).nodes[&chain].parameters.clone(); + let Some(SketchParams::DDSketch { alpha }) = parameters else { + panic!("a DDSketch chain has its alpha"); + }; + let end_ms = 100 * view.width_ms; + // Each series' samples, into the state the view's run builds and + // into the collector's sketch, whose ASAPv1 bytes are decoded as + // `check` decodes them. + let series_count = 50; + let mut updater = StateColumnUpdater::new(&family, parameters.as_ref()).unwrap(); + let mut staged = Vec::new(); + for series in 0..series_count { + let group = updater.add_group().unwrap(); + let mut sketch = DdSketch::new(alpha); + for s in 0..60 { + let value = ((series * 31 + s * 17) % 997) as f64 + 0.5; + updater + .update(group, value, end_ms - view.width_ms + s * 1000 + 1) + .unwrap(); + sketch.try_add(&value).unwrap(); + } + let job = format!("job-{series}"); + staged.push(Staged { + series: intern_pairs(&[("__name__", "data"), ("job", &job)]), + state: view.decoder.decode(&sketch.to_asapv1().unwrap()).unwrap(), + hashes: Vec::new(), + }); + } + let window = ClosedWindow { + group: view.group, + end_ms, + }; + let Computed::Ran(mut ran) = collector.rows(window, staged).unwrap() else { + unreachable!("a collector window is run"); + }; + let collected = ran.remove(0).1.remove(0); + // The computed window: the same rows, with the states the run seals. + let mut sealed = Some(updater.seal()); + let columns = (0..view.schema.fields.len()) + .map( + |column| match sealed.take_if(|_| column == view.state_column) { + Some(states) => BatchColumn::States { + indices: UInt32Array::from_iter_values(0..series_count as u32), + states: Arc::new(states), + }, + None => BatchColumn::Plain(collected.column(column).clone()), + }, + ) + .collect(); + let computed = Batch::try_from_columns(view.schema.clone(), columns).unwrap(); + let charge = |batch: Batch| { + let mut store = ViewStore::default(); + store + .append(&views[0], (end_ms - view.width_ms, end_ms), vec![batch]) + .unwrap(); + store.bytes() + }; + assert_eq!(charge(collected), charge(computed)); + } + + fn state(group: usize, end_ms: i64, hash: u64) -> ArrivedState { + ArrivedState { + group, + node_id: 0, + series: intern_pairs(&[("__name__", "data"), ("job", "collector-unit")]), + end_ms, + hash, + state: Arc::new(DDSketchAccumulator::new(0.05)), + } + } + + /// A request's windows close through its newest when it ends, in any + /// order within it. A later state of a closed window still kept is + /// returned to merge into it (or to store it with) unless it repeats + /// one seen; a state of a window past retention is late. + #[test] + fn windows_close_through_the_newest_staged_and_later_states_merge() { + let (mut ingestion, width) = ingestion(); + let metrics = Metrics::new(&[]); + let mut staging = Staging::default(); + let earlier = 100 * width; + let newest = earlier + width; + // The newest window first, then the earlier one, and a partial and + // a repeat of the newest. + let (report, late) = staging.stage( + vec![ + state(0, newest, 1), + state(0, earlier, 2), + state(0, newest, 4), + state(0, newest, 1), + ], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!((report.staged, report.merged, report.duplicate), (2, 1, 1)); + assert!(late.is_empty()); + let closed = ingestion.close(); + assert_eq!( + closed.iter().map(|w| w.end_ms).collect::>(), + [earlier, newest] + ); + for window in &closed { + assert_eq!(staging.take(*window).len(), 1); + } + // Later states of the committed windows: new ones merge, repeats + // (of a state committed, or merged later) are duplicates. + let (report, late) = staging.stage( + vec![ + state(0, earlier, 3), + state(0, earlier, 3), + state(0, earlier, 2), + state(0, newest, 4), + ], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!((report.late_merged, report.duplicate), (1, 3)); + let windows: Vec = late.keys().map(|w| w.end_ms).collect(); + assert_eq!(windows, [earlier]); + // A request two windows on: the window between closes with no + // state; its states coming later are to store it with, and a + // repeat of one is a duplicate. + let latest = newest + 2 * width; + staging.stage( + vec![state(0, latest, 5)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + let closed = ingestion.close(); + assert_eq!(closed.len(), 2); + for window in &closed { + staging.take(*window); + } + let between = newest + width; + let (report, late) = staging.stage( + vec![state(0, between, 6), state(0, between, 6)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!((report.late_merged, report.duplicate), (1, 1)); + assert_eq!(late.keys().map(|w| w.end_ms).collect::>(), [between]); + // One past the view's retention is late. + let (report, late) = staging.stage( + vec![state(0, earlier - 100 * width, 7)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!(report.late_dropped, 1); + assert!(late.is_empty()); + } +} diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 9e78ae664..acac19334 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -15,6 +15,10 @@ //! order to its copy of the views and publishes them, then queues them //! for the `persist-N` threads ([`storage::persist_pool`]). //! +//! A collector view's states ([`crate::collector`]) are checked and +//! decoded on the HTTP side, staged by the ingest coordinator, and handed to +//! the committer as a computed window when the view's window closes. +//! //! Windows closed and not yet refreshed (the precompute backlog) are //! bounded by `max_precompute_backlog`: when it is full, the ingest //! coordinator waits, the shards' queues fill and Remote Write gets 503 @@ -23,7 +27,7 @@ //! Each thread records the thread CPU and wall time of its phases in //! [`Metrics`], exported on `/metrics`. -use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, RwLock}; @@ -32,7 +36,7 @@ use std::time::Instant; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::runtime::Limits; use asap_executor::values::Batch; -use common::{InstallError, InstallablePlan, InstalledPlan}; +use common::{InstallError, InstallablePlan, InstalledPlan, ViewStateBatch}; use internal_metrics::{Metrics, PushMetrics, Timer}; use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; @@ -43,6 +47,10 @@ use storage::store::{ }; use tokio::sync::oneshot; +use crate::collector::{ + outcome, ArrivedState, CollectorStateIngestReport, CollectorViewOptions, CollectorViews, + Staged, Staging, +}; use crate::ingestion::{ ClockReading, ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, RefreshTaskGraph, Refreshed, Routing, WallClock, @@ -104,9 +112,25 @@ enum Command { barrier_ms: i64, reply: oneshot::Sender, }, + /// Collector states to stage, checked and decoded: `reply` gets what + /// staging did, `committed` answers once the windows they close are + /// committed. + CollectorStates { + states: Vec, + reply: oneshot::Sender, + committed: oneshot::Sender, + }, Stop, } +/// A collector request the coordinator took: its states, and where to +/// answer what staging did and when their windows are committed. +type CollectorRequest = ( + Vec, + oneshot::Sender, + oneshot::Sender, +); + /// A shard's state after its last message. struct ShardReport { shard: usize, @@ -162,12 +186,20 @@ enum PrecomputeJob { closed_at: Instant, }, /// Late samples of a closed window (one or more ingest shards' worth), - /// to merge into it once committed. + /// or late collector states of a collector view's window, to merge + /// into it once committed. Late { window: ClosedWindow, raw_data: RawShards, + states: Vec, samples: u64, }, + /// A collector view's window, with the states staged for it. + Collector { + window: ClosedWindow, + states: Vec, + closed_at: Instant, + }, /// Answers `barrier_ms` once every window queued before is refreshed. Barrier { barrier_ms: i64, @@ -271,6 +303,9 @@ pub struct PrecomputeOptions { /// The wall clock the precompute engine reads (the system clock but in /// tests). pub clock: WallClock, + /// The views a collector builds, whose states arrive by + /// [`InstalledPrecompute::ingest_collector_states`]. + pub collector: CollectorViewOptions, } /// Where the views are persisted, when they are: the view files' @@ -334,12 +369,25 @@ impl PrecomputeEngine { let limits = Limits { max_bytes: self.options.run_memory_limit_bytes, }; - let (ingestion, precompute) = - Ingestion::new(&plan.dag, &views, groups, self.options.ingestion, limits)?; + let (ingestion, precompute) = Ingestion::new( + &plan.dag, + &views, + groups, + self.options.ingestion, + limits, + &self.options.collector, + )?; tracing::info!(pane_width_ms = ingestion.pane_width_ms(), "raw data panes"); + let collector = CollectorViews::new( + &plan.dag, + &ingestion, + &precompute, + self.options.ingestion.max_future_ms, + )?; InstalledPrecompute::start( ingestion, precompute, + collector, &self.options, self.persisted.clone(), self.published.clone(), @@ -373,6 +421,11 @@ pub struct InstalledPrecompute { shards: Vec>, shared: Arc, max_queued_samples: u64, + /// Closed windows not yet refreshed beyond which collector states are + /// refused as `Busy`, as samples are once the queues fill behind them. + max_precompute_backlog: u64, + /// The installed plan's collector views. + collector: Arc, } impl InstalledPrecompute { @@ -383,6 +436,7 @@ impl InstalledPrecompute { fn start( mut ingestion: Ingestion, precompute: Precompute, + collector: CollectorViews, options: &PrecomputeOptions, persisted: Option, published: Arc, @@ -565,6 +619,8 @@ impl InstalledPrecompute { let ingest_guard = RunningGuard(running.clone()); let ingest_shared = shared.clone(); let coordinator_shards = shards.clone(); + let collector = Arc::new(collector); + let coordinator_collector = collector.clone(); std::thread::Builder::new() .name("ingest".into()) .spawn(move || { @@ -577,6 +633,7 @@ impl InstalledPrecompute { jobs, &ingest_shared, &pushed, + &coordinator_collector, ); })?; let views = Arc::new(views); @@ -621,6 +678,7 @@ impl InstalledPrecompute { check_task_inputs: options.check_task_inputs, push_parts: shard_count as u32, panic_in_combine_of_window_end_ms: options.panic_in_combine_of_window_end_ms, + collector: collector.clone(), }, RunningGuard(running), &shared, @@ -630,9 +688,45 @@ impl InstalledPrecompute { shards, shared, max_queued_samples: options.max_queued_samples, + max_precompute_backlog: options.max_precompute_backlog as u64, + collector, }) } + /// Checks, decodes and stages `batch`'s collector states + /// ([`crate::collector`]), once the ingest coordinator has run the + /// commands queued before, and returns once the windows they close are + /// committed (and written, with persisted views). `Busy` while the + /// precompute backlog is full; `Stopped` when the engine has exited. + pub async fn ingest_collector_states( + &self, + batch: ViewStateBatch, + ) -> Result { + if !self.is_running() { + return Err(IngestError::Stopped); + } + if self.precompute_backlog() >= self.max_precompute_backlog { + return Err(IngestError::Busy); + } + let now_ms = self.shared.clock.now_ms(); + let (states, mut report) = self.collector.check(batch, now_ms, &self.shared.metrics); + if states.is_empty() { + return Ok(report); + } + let (reply, done) = oneshot::channel(); + let (committed, windows_committed) = oneshot::channel(); + self.commands + .send(Command::CollectorStates { + states, + reply, + committed, + }) + .map_err(|_| IngestError::Stopped)?; + report += done.await.map_err(|_| IngestError::Stopped)?; + windows_committed.await.map_err(|_| IngestError::Stopped)?; + Ok(report) + } + /// Queues `samples` for ingestion. `Busy` when the queue would hold /// more than `max_queued_samples`; `Stopped` when the engine has exited. pub fn try_ingest(&self, samples: Vec) -> Result<(), IngestError> { @@ -1005,6 +1099,7 @@ fn serve_shard( /// never hold the watermark; the coordinator also wakes every tick, and /// flushes when the idle watermark would close a window /// ([`Ingestion::idle_closes_at`]). +#[allow(clippy::too_many_arguments)] fn serve_ingest( mut ingestion: Ingestion, mut raw_shards: Vec>, @@ -1013,6 +1108,7 @@ fn serve_ingest( jobs: SyncSender, shared: &Shared, pushed: &[bool], + collector: &CollectorViews, ) { const TICK: std::time::Duration = std::time::Duration::from_millis(100); let mut newest: Vec> = vec![None; shards.len()]; @@ -1046,6 +1142,12 @@ fn serve_ingest( // append, and windows would close without them. let mut held: Vec = Vec::new(); let queries_read_raw_data = ingestion.queries_read_raw_data(); + // Collector states staged until their window closes, at the end of + // the pass that took them. + let mut staging = Staging::default(); + // Collector requests taken this pass: their states, and where to + // answer what staging did and when their windows are committed. + let mut collector_requests: Vec = Vec::new(); // Published in place of the raw data when no query reads it. let no_raw_data: RawShards = Arc::new( (0..shards.len()) @@ -1074,6 +1176,14 @@ fn serve_ingest( barriers.push((barrier_ms, reply)); moved = true; } + Ok(Command::CollectorStates { + states, + reply, + committed, + }) => { + collector_requests.push((states, reply, committed)); + moved = true; + } Ok(Command::Stop) => break, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, @@ -1093,6 +1203,14 @@ fn serve_ingest( barriers.push((barrier_ms, reply)); moved = true; } + Command::CollectorStates { + states, + reply, + committed, + } => { + collector_requests.push((states, reply, committed)); + moved = true; + } Command::Stop => break 'serve, } } @@ -1125,6 +1243,12 @@ fn serve_ingest( Ok(Command::AdvanceWatermark { barrier_ms, reply }) => { deferred.push_back((barrier_ms, reply)) } + // This pass closes their windows: it is moving. + Ok(Command::CollectorStates { + states, + reply, + committed, + }) => collector_requests.push((states, reply, committed)), Ok(Command::Stop) => break 'serve, // A shard that died never answers: stop, failing the // barriers waiting. @@ -1150,6 +1274,18 @@ fn serve_ingest( if let Some(flushed) = flushed_at { ingestion.advance_idle(flushed.monotonic_ms); } + // The collector states this pass took: their windows close below. + let mut collector_late: BTreeMap> = BTreeMap::new(); + let mut collector_committed = Vec::new(); + for (states, reply, committed) in collector_requests.drain(..) { + let (report, late) = + staging.stage(states, &mut ingestion, shared.clock.read(), &shared.metrics); + let _ = reply.send(report); + for (window, states) in late { + collector_late.entry(window).or_default().extend(states); + } + collector_committed.push(committed); + } // The barriers first, so a window one of them closes is not // counted as closed by wall-clock time. let mut closed = Vec::new(); @@ -1176,7 +1312,41 @@ fn serve_ingest( }); } } - if !queue_refreshes(&closed, &snapshot, &jobs, shared, pushed) { + // Each closed collector view window's staged states, for the + // committer to make its rows. A window with none (a feed gap) is + // stored empty, as an idle window built here is; states coming + // later merge into it. + let mut collector_states = HashMap::new(); + let collector_states_metrics = &shared.metrics.collector_states; + for &window in closed.iter().filter(|w| ingestion.is_collector(w.group)) { + let states = staging.take(window); + let view = collector.view_of_group(window.group); + let outcome = if states.is_empty() { + outcome::EMPTY + } else { + outcome::COMMITTED + }; + collector_states_metrics.window(view, outcome); + collector_states.insert(window, states); + } + // States of windows skipped as past their view's retention. + for group in (0..pushed.len()).filter(|&g| ingestion.is_collector(g)) { + if let Some(through) = ingestion.closed_through(group) { + let expired = staging.drop_through(group, through); + if expired > 0 { + let view = collector.view_of_group(group); + collector_states_metrics.outcome(view, outcome::EXPIRED, expired); + } + } + } + if !queue_refreshes( + &closed, + &snapshot, + &jobs, + shared, + pushed, + &mut collector_states, + ) { break; } for (window, samples) in std::mem::take(&mut late) { @@ -1192,12 +1362,35 @@ fn serve_ingest( let job = PrecomputeJob::Late { window, raw_data, + states: Vec::new(), samples: samples.len() as u64, }; if jobs.send(job).is_err() { break 'serve; } } + for (window, states) in collector_late { + let job = PrecomputeJob::Late { + window, + raw_data: Arc::new(vec![Arc::new(ingestion.late_raw_data())]), + states, + samples: 0, + }; + if jobs.send(job).is_err() { + break 'serve; + } + } + // Each collector request is answered once the windows its states + // closed, and the merges queued before, are committed. + for committed in collector_committed { + let job = PrecomputeJob::Barrier { + barrier_ms: 0, + reply: committed, + }; + if jobs.send(job).is_err() { + break 'serve; + } + } let routing = Arc::new(ingestion.routing()); *shared.routing.write().unwrap_or_else(|e| e.into_inner()) = routing.clone(); let watermark_ms = ingestion.watermark_ms(); @@ -1263,7 +1456,8 @@ fn serve_ingest( tracing::warn!("ingest stopped"); } -/// Queues a refresh of each of `closed` over `raw_data`, waiting while the +/// Queues a refresh of each of `closed` over `raw_data` (a collector view's +/// window with its states, from `collector_states`), waiting while the /// backlog is full; `false` once the precompute thread has exited. fn queue_refreshes( closed: &[ClosedWindow], @@ -1271,10 +1465,17 @@ fn queue_refreshes( jobs: &SyncSender, shared: &Shared, pushed: &[bool], + collector_states: &mut HashMap>, ) -> bool { for &window in closed { shared.precompute_backlog.fetch_add(1, Ordering::SeqCst); - let job = if pushed.get(window.group).copied().unwrap_or(false) { + let job = if let Some(states) = collector_states.remove(&window) { + PrecomputeJob::Collector { + window, + states, + closed_at: Instant::now(), + } + } else if pushed.get(window.group).copied().unwrap_or(false) { PrecomputeJob::Push { window, closed_at: Instant::now(), @@ -1302,6 +1503,8 @@ struct PoolOptions { /// The partials a pushed window combines: one per ingest shard. push_parts: u32, panic_in_combine_of_window_end_ms: Option, + /// What makes a collector view window's rows from its staged states. + collector: Arc, } /// What the precompute committer waits for. @@ -1427,7 +1630,9 @@ fn spawn_precompute( for job in jobs { if matches!( job, - PrecomputeJob::Refresh { .. } | PrecomputeJob::Push { .. } + PrecomputeJob::Refresh { .. } + | PrecomputeJob::Push { .. } + | PrecomputeJob::Collector { .. } ) && !slots.acquire(&shared.running) { break; @@ -1640,9 +1845,9 @@ fn serve_precompute( 1 }; let mut tasks = WindowTasks::new(precompute.tasks().clone(), parts as u32); - // Late samples by window, merged once it and the windows built from it - // are committed: each window's raw data parts and sample count. - let mut late: BTreeMap>, u64)> = BTreeMap::new(); + // Late samples and collector states by window, merged once it and the + // windows built from it are committed. + let mut late: BTreeMap = BTreeMap::new(); // Per group, the end of the newest window whose job came: the windows // closed so far (jobs come in the order windows close). let mut closed_through: Vec> = vec![None; precompute.groups().len()]; @@ -1672,21 +1877,33 @@ fn serve_precompute( closed_through[window.group].max(Some(window.end_ms)); tasks.push_window(window, closed_at, options.push_parts) } + PoolEvent::Job(PrecomputeJob::Collector { + window, + states, + closed_at, + }) => { + closed_through[window.group] = + closed_through[window.group].max(Some(window.end_ms)); + let rows = options.collector.rows(window, states); + tasks.collector_window(window, rows, closed_at) + } PoolEvent::Partial(partial) => tasks.partial(partial), PoolEvent::Job(PrecomputeJob::Late { window, raw_data, + states, samples, }) => { - let (parts, count) = late.entry(window).or_default(); + let pending = late.entry(window).or_default(); if precompute.recomputes(window.group) { // The raw data whole, as of the newest pass: it // holds the late samples of the earlier ones. - *parts = raw_data.iter().cloned().collect(); + pending.raw_data = raw_data.iter().cloned().collect(); } else { - parts.extend(raw_data.iter().cloned()); + pending.raw_data.extend(raw_data.iter().cloned()); } - *count += samples; + pending.states.extend(states); + pending.samples += samples; } PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { tasks.barrier(barrier_ms, reply) @@ -1754,14 +1971,15 @@ fn serve_precompute( .filter(|&window| precompute.late_ready(window, |w| tasks.pending(w))) .collect(); for window in ready { - let (parts, samples) = late.remove(&window).expect("listed"); + let pending = late.remove(&window).expect("listed"); merge_late( precompute, window, - (Arc::new(parts), samples), + pending, &mut views, &closed_through, &mut to_persist, + options, shared, ); committed = true; @@ -1795,6 +2013,15 @@ fn serve_precompute( tracing::warn!("precompute stopped"); } +/// Late samples or collector states of one window, waiting on the +/// committer until it may merge them ([`Precompute::late_ready`]). +#[derive(Default)] +struct PendingLate { + raw_data: Vec>, + states: Vec, + samples: u64, +} + /// A window persisted after the views are published: its group, range, /// revision, each view's rows, and each view's stored window as committed /// (told where it was written; a later merge in the same pass replaces it @@ -1812,16 +2039,44 @@ type ToPersist = ( /// it, and queues the changed windows to be written again. Samples whose /// window is no longer stored, or whose merge fails, are dropped and /// counted. +#[allow(clippy::too_many_arguments)] fn merge_late( precompute: &Precompute, window: ClosedWindow, - (raw_data, samples): (RawShards, u64), + pending: PendingLate, views: &mut Arc, closed_through: &[Option], to_persist: &mut Vec, + options: &PoolOptions, shared: &Shared, ) { - let merged = precompute.merge_late(window, raw_data, views, false, closed_through); + let PendingLate { + raw_data, + states, + samples, + } = pending; + // A collector view's late states are its rows' change; its window + // closed without states (they came after a later window's) is stored + // with them. + let rows = if states.is_empty() { + Ok(Vec::new()) + } else { + match options.collector.rows(window, states) { + Ok(Computed::Ran(mut rows)) => Ok(rows.pop().map(|(_, rows)| rows).unwrap_or_default()), + Ok(Computed::AlreadyStored) => Ok(Vec::new()), + Err(error) => Err(asap_executor::Error::Invalid(error)), + } + }; + let merged = rows.and_then(|rows| { + precompute.merge_late( + window, + Arc::new(raw_data), + rows, + views, + options.collector.builds(window.group), + closed_through, + ) + }); let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); match merged { Ok(changed) => { @@ -1869,7 +2124,7 @@ fn commit_window( .lock() .unwrap_or_else(|e| e.into_inner()); let combine = |parts: Vec| -> Result { - if task.pushed { + if task.built == BuiltBy::Push { let delay_ms: u64 = options .slow_refreshes .iter() @@ -1882,7 +2137,9 @@ fn commit_window( } let timer = Timer::start(); let combined = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - if task.pushed && options.panic_in_combine_of_window_end_ms == Some(window.end_ms) { + if task.built == BuiltBy::Push + && options.panic_in_combine_of_window_end_ms == Some(window.end_ms) + { panic!( "combine of the window ending at {} panicked (test hook)", window.end_ms @@ -1895,10 +2152,12 @@ fn commit_window( } })) .unwrap_or_else(|_| Err("the combine panicked".to_string()))?; - if let (true, Some(push)) = (task.pushed, &shared.metrics.push) { + if let (BuiltBy::Push, Some(push)) = (task.built, &shared.metrics.push) { push.combine[window.group].record(timer); } - Ok(if task.pushed { + // Views loaded from the files at startup may already store a + // pushed or collector window. + Ok(if task.built != BuiltBy::Run { precompute.missing_only(window, combined, views) } else { combined @@ -1910,7 +2169,7 @@ fn commit_window( .commit(window, computed, views) .map_err(|e| e.to_string()) }); - if let (true, Some(push)) = (task.pushed, &shared.metrics.push) { + if let (BuiltBy::Push, Some(push)) = (task.built, &shared.metrics.push) { push.commit.record(timer); push.commit_lag_ms.store( (shared.clock.now_ms() - window.end_ms).max(0), @@ -1948,12 +2207,22 @@ fn commit_window( shared.precompute_backlog.fetch_sub(1, Ordering::SeqCst); } +/// How a window's rows were built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BuiltBy { + /// Its group's ingestion run, over the raw data (or its parts' runs). + Run, + /// Push: its parts are the shards' partials. + Push, + /// A collector: its rows are the states staged for it. + Collector, +} + /// A computed window ready to commit: its run, or its parts' runs by /// part. struct CommitTask { window: ClosedWindow, - /// Built by push: its parts are the shards' partials. - pushed: bool, + built: BuiltBy, result: Result, String>, closed_at: Instant, times: TaskTimes, @@ -1978,7 +2247,7 @@ enum TaskState { struct WindowTask { window: ClosedWindow, - pushed: bool, + built: BuiltBy, closed_at: Instant, state: TaskState, } @@ -2030,7 +2299,7 @@ impl WindowTasks { self.next_seq, WindowTask { window, - pushed: false, + built: BuiltBy::Run, closed_at, state: TaskState::Waiting(raw_data), }, @@ -2045,7 +2314,7 @@ impl WindowTasks { seq, WindowTask { window, - pushed: true, + built: BuiltBy::Push, closed_at, state: TaskState::Running { parts, @@ -2061,12 +2330,37 @@ impl WindowTasks { } } + /// A collector view's window, computed: `rows` are its staged states. + fn collector_window( + &mut self, + window: ClosedWindow, + rows: Result, + closed_at: Instant, + ) { + let now = Instant::now(); + self.tasks.insert( + self.next_seq, + WindowTask { + window, + built: BuiltBy::Collector, + closed_at, + state: TaskState::Computed { + result: rows.map(|rows| vec![rows]), + times: TaskTimes { + started: now, + computed: now, + }, + }, + }, + ); + self.next_seq += 1; + } + /// A shard's partial of a pushed window. fn partial(&mut self, partial: Partial) { - let seq = self - .tasks - .iter() - .find_map(|(&seq, task)| (task.pushed && task.window == partial.window).then_some(seq)); + let seq = self.tasks.iter().find_map(|(&seq, task)| { + (task.built == BuiltBy::Push && task.window == partial.window).then_some(seq) + }); match seq { Some(seq) => self.computed( seq, @@ -2176,7 +2470,7 @@ impl WindowTasks { }; Some(CommitTask { window: task.window, - pushed: task.pushed, + built: task.built, result, closed_at: task.closed_at, times, @@ -2408,8 +2702,15 @@ mod tests { let views = plan.materialized_views().unwrap(); let groups = plan.ingestion_refresh_groups().unwrap(); let limits = asap_executor::runtime::Limits { max_bytes: 4 << 30 }; - let (mut ingestion, _) = - Ingestion::new(&plan.dag, &views, groups, options, limits).unwrap(); + let (mut ingestion, _) = Ingestion::new( + &plan.dag, + &views, + groups, + options, + limits, + &Default::default(), + ) + .unwrap(); let widths: Vec = ingestion.group_windows().iter().map(|w| w.0).collect(); assert_eq!(widths, [60_000, 10_000]); ingestion.set_push_groups(vec![true, false]); @@ -2453,6 +2754,7 @@ mod tests { precompute_memory_budget_bytes: None, panic_in_combine_of_window_end_ms: None, clock: WallClock::stopped(), + collector: CollectorViewOptions::default(), }; PrecomputeEngine::new(options, None, Arc::new(PublishedStore::new(Arc::default()))) } diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 1b2d3b6df..9b07e8d99 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -26,6 +26,14 @@ //! Raw samples are kept while a window still to be closed or a query-time //! `Scan` (back to its `retention_ms`) reads them. //! +//! A view a collector builds ([`CollectorViewOptions`]) is a refresh group +//! of its own that no run computes: its windows close through the newest +//! one a collector request staged states of, when that request ends, and +//! its rows are the states the collector sent for it +//! ([`crate::collector`]). Its `Scan`s keep no raw +//! samples unless another reader needs them, and a group reading it closes +//! a window only once that view's window has closed. +//! //! [`Ingestion`] (the ingest coordinator) keeps the watermark and closes //! windows, and the ingest shards store the samples ([`Routing`]); each //! closed window is refreshed by [`Precompute`] (the precompute pool) over @@ -55,6 +63,8 @@ use storage::store::{ use common::MAX_TIME_MS; +use crate::collector::CollectorViewOptions; + /// How ingestion treats sample times. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct IngestionOptions { @@ -144,7 +154,7 @@ const IDLE_GRACE_MS: i64 = 1_000; /// A refresh group's window `(end_ms - W, end_ms]` that the watermark has /// passed, to refresh; `group` indexes the plan's ingestion refresh groups. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub(crate) struct ClosedWindow { pub group: usize, pub end_ms: i64, @@ -199,8 +209,27 @@ struct RefreshGroup { /// The longest retention of its views. retention_ms: i64, /// End of the newest window closed or skipped; `None` before the - /// first sample of a metric it scans. + /// first sample of a metric it scans (a collector view's group: before + /// its first state). refreshed_through: Option, + /// A collector view's group: its windows close as states arrive. + collector: bool, + /// A collector view's group: the end of the newest window states were + /// staged for; its windows close through it. + collector_arrived_through: Option, + /// A collector view's group: when its newest states arrived (with the + /// end of their newest window, capped at that wall-clock time), for + /// closing its windows on the clock while none arrive. + collector_arrived: Option<(i64, ClockReading)>, + /// A collector view's group: the end its windows close through on the + /// clock ([`Ingestion::advance_idle`]); it never goes back. + collector_idle_through: Option, + /// It reads a collector view's group, directly or through other + /// groups: its windows close only once those groups closed them. + reads_collector: bool, + /// A collector view's group, or one reading it: the end of the window + /// before its first, once it started. + collector_start: Option, } impl RefreshGroupRun { @@ -243,20 +272,27 @@ pub(crate) struct Ingestion { /// Groups whose windows the ingest shards build by push: they read no /// raw data, so they keep none. push_groups: Vec, + /// How long after a collector view's window end, with no state + /// arriving, it closes on the clock ([`CollectorViewOptions`]). + collector_idle_close_ms: i64, pub stats: IngestionStats, } impl Ingestion { /// Compiles one ingestion run per refresh group of `dag`'s `views`, - /// for the [`Precompute`] returned with the ingestion. Refuses views - /// refreshed on first read, which the data plane does not refresh yet, - /// and groups without a bounded window. + /// for the [`Precompute`] returned with the ingestion; each of + /// `collector`'s views is a group of its own, compiled only for its + /// output schema. Refuses views refreshed on first read, which the data + /// plane does not refresh yet, groups without a bounded window, and a + /// collector view that is not refreshed at ingestion on windows that + /// end on multiples of their width. pub fn new( dag: &PhysicalASAPDAG, views: &[MaterializedView], groups: Vec, options: IngestionOptions, limits: Limits, + collector: &CollectorViewOptions, ) -> Result<(Self, Precompute), IngestionError> { if let Some(view) = views .iter() @@ -269,28 +305,30 @@ impl Ingestion { } let index = DagIndex::new(dag); let groups = split_order_sensitive_views(dag, views, groups)?; + let groups = split_collector_views(groups, &collector.views)?; let group_of: HashMap = groups .iter() .enumerate() - .flat_map(|(index, group)| group.views.iter().map(move |v| (v.node_id, index))) + .flat_map(|(index, (group, _))| group.views.iter().map(move |v| (v.node_id, index))) .collect(); let mut runs = Vec::new(); let mut clocks = Vec::new(); let mut tasks = RefreshTaskGraph::default(); - for group in groups { + for (group, from_collector) in groups { let ids: Vec = group.views.iter().map(|v| v.node_id).collect(); let Some(window) = group.refresh_window else { return Err(IngestionError::Unsupported(format!( "views {ids:?} are refreshed over an unbounded window" ))); }; - // The views of other groups it reads are view slots. + // The views of other groups it reads are view slots. A + // collector view reads none: its inputs are on the collector. let in_group: HashSet = ids.iter().copied().collect(); let read: BTreeSet = group .views .iter() .flat_map(|v| v.inputs.materialized_views.iter().copied()) - .filter(|id| !in_group.contains(id)) + .filter(|id| !in_group.contains(id) && !from_collector) .collect(); let read_views: Vec = views .iter() @@ -309,7 +347,8 @@ impl Ingestion { .iter() .any(|id| carries_state_across_windows(&index.nodes[id].payload)), ); - let by_series = read.is_empty() + let by_series = !from_collector + && read.is_empty() && below .iter() .all(|id| computes_each_series_alone(&index.nodes[id].payload)); @@ -330,8 +369,17 @@ impl Ingestion { views: ids.clone(), error, })?; - let metrics = index.metrics_below(&ids, &read); - let started_by = index.metrics_below(&ids, &BTreeSet::new()); + // A collector view's group scans nothing here and starts with + // its first state; a group reading one is not started by the + // metrics scanned below it. + let (metrics, started_by) = if from_collector { + (BTreeSet::new(), BTreeSet::new()) + } else { + ( + index.metrics_below(&ids, &read), + index.metrics_below(&ids, &collector.views), + ) + }; let margin_ms = options.view_retention_margin_ms; let views = group .views @@ -363,9 +411,18 @@ impl Ingestion { recomputes, metrics, reads: tasks.reads.last().cloned().unwrap_or_default(), + reads_collector: tasks.reads.last().into_iter().flatten().any(|&read| { + let read: &RefreshGroup = &clocks[read]; + read.collector || read.reads_collector + }), started_by, retention_ms, refreshed_through: None, + collector: from_collector, + collector_arrived_through: None, + collector_arrived: None, + collector_idle_through: None, + collector_start: None, }); } let pane_width_ms = clocks @@ -374,6 +431,7 @@ impl Ingestion { .fold(MAX_PANE_WIDTH_MS, gcd); // The `Scan`s the query run reads: below the roots, outside views. let view_ids: HashSet = views.iter().map(|v| v.node_id).collect(); + let scanned_metrics = index.scanned_metrics_here(dag, &collector.views); let mut query_time_lookback_ms: HashMap> = HashMap::new(); for scan in index.below(&dag.roots, &view_ids) { let node = index.nodes[&scan]; @@ -397,7 +455,7 @@ impl Ingestion { } let mut ingestion = Self { groups: clocks, - scanned_metrics: Arc::new(storage::store::scanned_metrics(&dag.nodes)), + scanned_metrics: Arc::new(scanned_metrics), pane_width_ms, query_time_lookback_ms, options, @@ -407,6 +465,7 @@ impl Ingestion { arrived: None, idle_watermark_ms: None, push_groups: Vec::new(), + collector_idle_close_ms: millis(collector.idle_close_ms), stats: IngestionStats::default(), }; // Each view's readers: the groups whose runs read it. @@ -593,16 +652,33 @@ impl Ingestion { /// at that flush ([`Self::advance_idle`]), so samples still queued /// count first. pub(crate) fn idle_closes_at(&self, now_monotonic_ms: i64) -> bool { - let Some(idle) = self.idle_watermark_at(now_monotonic_ms) else { - return false; - }; + let idle = self.idle_watermark_at(now_monotonic_ms); self.groups.iter().any(|group| { - group - .refreshed_through - .is_some_and(|through| through.saturating_add(group.width_ms) <= idle) + let idle = if group.collector { + self.collector_idle_at(group, now_monotonic_ms) + } else { + idle + }; + match (group.refreshed_through, idle) { + (Some(through), Some(idle)) => through.saturating_add(group.width_ms) <= idle, + _ => false, + } }) } + /// Collector view group `group`'s idle watermark at monotonic + /// `now_monotonic_ms`: as [`Self::idle_watermark_at`], from the newest + /// state's window end and when it arrived, less the collector's close + /// delay and skew allowance. `None` before its first states. + fn collector_idle_at(&self, group: &RefreshGroup, now_monotonic_ms: i64) -> Option { + let (end, arrived) = group.collector_arrived?; + Some( + end.min(arrived.wall_ms) + .saturating_add(now_monotonic_ms.saturating_sub(arrived.monotonic_ms)) + .saturating_sub(self.collector_idle_close_ms), + ) + } + /// Notes that the flush sent at `flushed` ran a sample. pub(crate) fn sample_arrived(&mut self, flushed: ClockReading) { self.arrived = Some(flushed); @@ -615,6 +691,11 @@ impl Ingestion { self.idle_watermark_ms = self .idle_watermark_ms .max(self.idle_watermark_at(flushed_monotonic_ms)); + for index in 0..self.groups.len() { + let idle = self.collector_idle_at(&self.groups[index], flushed_monotonic_ms); + let group = &mut self.groups[index]; + group.collector_idle_through = group.collector_idle_through.max(idle); + } } /// What the ingest shards need to route samples now: the metrics a @@ -679,7 +760,10 @@ impl Ingestion { cutoffs, compress_through, late_through, - groups_waiting: self.groups.iter().any(|g| g.refreshed_through.is_none()), + groups_waiting: self + .groups + .iter() + .any(|g| g.refreshed_through.is_none() && !g.collector), committed: self .scanned_metrics .iter() @@ -712,7 +796,7 @@ impl Ingestion { /// newest closed one, and the groups reading them (transitively) keep /// theirs, which the change reaches though the group's own window is /// gone. `None` before the group's first window. - fn kept_after_ms(&self) -> Vec> { + pub(crate) fn kept_after_ms(&self) -> Vec> { let mut kept: Vec> = self .groups .iter() @@ -751,13 +835,19 @@ impl Ingestion { self.newest_sample_ms = self.newest_sample_ms.max(newest_ms); } - /// Closes and returns every window the watermark has passed, oldest - /// first within each group, groups in plan order (a group may read the - /// views of an earlier one). + /// Closes and returns every window the watermark has passed (a + /// collector view's: through the newest its states were staged for), + /// oldest first within each group, groups in plan order (a group may + /// read the views of an earlier one). pub(crate) fn close(&mut self) -> Vec { self.close_windows() } + /// Whether group `group` is a collector view's. + pub(crate) fn is_collector(&self, group: usize) -> bool { + self.groups[group].collector + } + /// An event-time barrier: the producer states that every sample at or /// before `barrier_ms` has been written, so every window ending at or /// before it closes without a later sample. Capped at `now_ms`; a @@ -782,7 +872,8 @@ impl Ingestion { /// window is skipped unless it starts at or after the declared stream /// start. fn start_groups(&mut self, metric: &str, timestamp_ms: i64) { - for group in &mut self.groups { + for index in 0..self.groups.len() { + let group = &mut self.groups[index]; if group.refreshed_through.is_some() || !group.started_by.contains(metric) { continue; } @@ -798,6 +889,7 @@ impl Ingestion { first_end } }); + self.align_to_collector_reads(index); } } @@ -853,12 +945,93 @@ impl Ingestion { cutoff } - /// Closes every window the watermark has passed and compacts the - /// panes it has passed. - fn close_windows(&mut self) -> Vec { - let Some(watermark) = self.watermark_ms() else { - return Vec::new(); + /// Starts collector view group `group` at its first states, the oldest + /// of the window ending at `end_ms`: that window is its first. Then + /// aligns the groups reading it ([`Self::align_to_collector_reads`]), + /// in plan order. + pub(crate) fn start_collector_group(&mut self, group: usize, end_ms: i64) { + let started = &mut self.groups[group]; + if started.refreshed_through.is_some() { + return; + } + let start = end_ms - started.width_ms; + started.refreshed_through = Some(start); + started.collector_start = Some(start); + for reader in group + 1..self.groups.len() { + self.align_to_collector_reads(reader); + } + } + + /// For group `reader`, reading collector views' groups (directly or + /// through other groups): once each of those started, its windows start + /// at its first boundary after all of them; it starts there if no + /// metric starts it, and skips there if it started earlier (its windows + /// before would read collector windows that never come). + fn align_to_collector_reads(&mut self, reader: usize) { + let waiting = &self.groups[reader]; + if !waiting.reads_collector { + return; + } + let starts: Option> = waiting + .reads + .iter() + .filter(|&&read| self.groups[read].reads_collector || self.groups[read].collector) + .map(|&read| self.groups[read].collector_start) + .collect(); + let Some(first) = starts.and_then(|starts| starts.into_iter().max()) else { + return; }; + let waiting = &mut self.groups[reader]; + let first = waiting.window_end(first); + match waiting.refreshed_through { + None if waiting.started_by.is_empty() => waiting.refreshed_through = Some(first), + Some(through) if through < first => { + self.stats.windows_skipped_first += ((first - through) / waiting.width_ms) as u64; + waiting.refreshed_through = Some(first); + } + _ => {} + } + if waiting.collector_start.is_none() { + waiting.collector_start = waiting.refreshed_through; + } + } + + /// Collector view group `group` staged states of its window ending + /// `end_ms` at `now`: its windows close through it at the next close, + /// and on the clock from then while no state arrives. + pub(crate) fn collector_arrived(&mut self, group: usize, end_ms: i64, now: ClockReading) { + let group = &mut self.groups[group]; + group.collector_arrived_through = group.collector_arrived_through.max(Some(end_ms)); + let newest = group.collector_arrived_through.expect("set above"); + group.collector_arrived = Some((newest, now)); + } + + /// End of group `group`'s newest window closed or skipped. + pub(crate) fn closed_through(&self, group: usize) -> Option { + self.groups[group].refreshed_through + } + + /// Closes every window the watermark has passed, and every collector + /// view's window through the newest its states were staged for. + pub(crate) fn close_windows(&mut self) -> Vec { + let watermark = self.watermark_ms(); + // Per group, the time its windows close through. + let closes_through: Vec> = self + .groups + .iter() + .map(|group| { + if group.collector { + group + .collector_arrived_through + .max(group.collector_idle_through) + } else { + watermark + } + }) + .collect(); + if closes_through.iter().all(Option::is_none) { + return Vec::new(); + } // Windows ending after this close only by the idle watermark. let event_watermark = self.event_watermark_ms(); // Per group, the windows ending at or before this would already be @@ -871,11 +1044,23 @@ impl Ingestion { let mut expired: Vec = self .groups .iter() - .map(|group| { - group.window_end(watermark.saturating_sub(group.retention_ms)) - group.width_ms + .zip(&closes_through) + .map(|(group, through)| match through { + Some(through) => { + group.window_end(through.saturating_sub(group.retention_ms)) - group.width_ms + } + None => i64::MIN, }) .collect(); for reader in (0..self.groups.len()).rev() { + if expired[reader] == i64::MIN { + // A reader that closes nothing yet keeps every window it + // reads. + for &read in &self.groups[reader].reads { + expired[read] = i64::MIN; + } + continue; + } for &read in &self.groups[reader].reads { let group = &self.groups[read]; // The latest boundary of `group` at or before the reader's. @@ -886,8 +1071,24 @@ impl Ingestion { let mut closed = Vec::new(); // Per group, how far this pass skipped its expired windows. let mut skipped_to: Vec> = vec![None; self.groups.len()]; - for (index, group) in self.groups.iter_mut().enumerate() { - let Some(mut through) = group.refreshed_through else { + for index in 0..self.groups.len() { + // A group reading a collector view's group closes a window only + // once every group it reads closed it: they close by different + // clocks. One that scans no raw data itself follows them alone. + let mut closes_through = closes_through[index]; + let group = &self.groups[index]; + if group.reads_collector { + if group.metrics.is_empty() { + closes_through = Some(i64::MAX); + } + for &read in &group.reads { + closes_through = closes_through.min(self.groups[read].refreshed_through); + } + } + let group = &mut self.groups[index]; + let (Some(mut through), Some(closes_through)) = + (group.refreshed_through, closes_through) + else { continue; }; let mut expired_through = expired[index]; @@ -907,9 +1108,9 @@ impl Ingestion { } while let Some(end) = through .checked_add(group.width_ms) - .filter(|e| *e <= watermark) + .filter(|e| *e <= closes_through) { - if event_watermark.is_none_or(|w| end > w) { + if !group.collector && event_watermark.is_none_or(|w| end > w) { self.stats.windows_closed_by_wall_clock += 1; } closed.push(ClosedWindow { @@ -1501,8 +1702,11 @@ impl Precompute { /// included), replacing the window ([`ViewStore::replace_window`]). /// /// A reader's window not closed yet (past `closed_through`, by group) - /// takes no change: it reads the changed window when it closes. With - /// `insert`, a window not stored is stored with the change. Returns + /// takes no change: it reads the changed window when it closes. A + /// collector view's group runs nothing: its change is `late_rows`, the + /// rows of its late states. With `insert`, a window not stored is + /// stored with the change (a collector view's whose first states came + /// after a later window's, and the windows read from it). Returns /// each changed window, to write again; a view whose window is no /// longer stored takes no change (a merged change still reaches its /// readers). @@ -1510,6 +1714,7 @@ impl Precompute { &self, window: ClosedWindow, raw_data: RawShards, + late_rows: Vec, views: &mut Arc, insert: bool, closed_through: &[Option], @@ -1576,21 +1781,25 @@ impl Precompute { window_start = window_end; } } - let raw = if source { - raw_data.clone() + if source && !late_rows.is_empty() { + vec![(run.views[0].node_id, late_rows.clone())] } else { - empty_raw.clone() - }; - let outputs = self.run(group, end, raw, Arc::new(read), None)?; - let Computed::Ran(rows) = - self.computed(group, (0..run.views.len()).collect(), outputs) - else { - continue; - }; - rows.into_iter() - .map(|(index, batches)| (run.views[index].node_id, batches)) - .filter(|(_, batches)| batches.iter().any(|b| b.num_rows() > 0)) - .collect() + let raw = if source { + raw_data.clone() + } else { + empty_raw.clone() + }; + let outputs = self.run(group, end, raw, Arc::new(read), None)?; + let Computed::Ran(rows) = + self.computed(group, (0..run.views.len()).collect(), outputs) + else { + continue; + }; + rows.into_iter() + .map(|(index, batches)| (run.views[index].node_id, batches)) + .filter(|(_, batches)| batches.iter().any(|b| b.num_rows() > 0)) + .collect() + } }; if late.is_empty() { continue; @@ -1682,8 +1891,8 @@ impl Precompute { } /// The DAG's nodes by id and each node's inputs. -struct DagIndex<'a> { - nodes: HashMap< +pub(crate) struct DagIndex<'a> { + pub nodes: HashMap< PhysicalASAPNodeId, &'a asap_executor::planner::plan::physical_asap_dag::PhysicalASAPDAGNode, >, @@ -1691,7 +1900,7 @@ struct DagIndex<'a> { } impl<'a> DagIndex<'a> { - fn new(dag: &'a PhysicalASAPDAG) -> Self { + pub fn new(dag: &'a PhysicalASAPDAG) -> Self { let mut inputs: HashMap> = HashMap::new(); for edge in &dag.edges { inputs.entry(edge.consumer).or_default().push(edge.producer); @@ -1721,8 +1930,33 @@ impl<'a> DagIndex<'a> { seen } + /// The metrics a `Scan` of `dag` reads that a node not built by a + /// collector reads: not those only `collector_views` (and the nodes + /// below them) read. + fn scanned_metrics_here( + &self, + dag: &PhysicalASAPDAG, + collector_views: &BTreeSet, + ) -> BTreeSet { + if collector_views.is_empty() { + return storage::store::scanned_metrics(&dag.nodes); + } + let on_collector = self.below( + &collector_views.iter().copied().collect::>(), + &HashSet::new(), + ); + let here: Vec = dag + .nodes + .iter() + .map(|node| node.id) + .filter(|id| !on_collector.contains(id)) + .collect(); + let stop: HashSet = collector_views.iter().copied().collect(); + storage::store::scanned_metrics(self.below(&here, &stop).iter().map(|id| self.nodes[id])) + } + /// The metrics scanned below `views`, not reading through `read_views`. - fn metrics_below( + pub fn metrics_below( &self, views: &[PhysicalASAPNodeId], read_views: &BTreeSet, @@ -1822,6 +2056,62 @@ fn split_order_sensitive_views( Ok(split) } +/// `groups` with each of `collector`'s views taken out as a group of its +/// own, before the rest of its group (which may read it). Errs for a +/// collector view that is not in a group, or whose windows do not end on +/// multiples of their width (a collector state's window does). +fn split_collector_views( + groups: Vec, + collector: &BTreeSet, +) -> Result, IngestionError> { + if collector.is_empty() { + return Ok(groups.into_iter().map(|group| (group, false)).collect()); + } + let mut split = Vec::with_capacity(groups.len() + collector.len()); + let mut found = BTreeSet::new(); + for group in groups { + let (on_collector, here): (Vec, Vec) = group + .views + .into_iter() + .partition(|view| collector.contains(&view.node_id)); + for view in on_collector { + if group + .refresh_window + .is_none_or(|window| window.phase_ms != 0) + { + return Err(IngestionError::Unsupported(format!( + "collector view {}: its windows do not end on multiples of their width", + view.node_id + ))); + } + found.insert(view.node_id); + let views = vec![view]; + split.push(( + IngestionRefreshGroup { + refresh_window: group.refresh_window, + views, + }, + true, + )); + } + if !here.is_empty() { + split.push(( + IngestionRefreshGroup { + refresh_window: group.refresh_window, + views: here, + }, + false, + )); + } + } + if let Some(missing) = collector.iter().find(|id| !found.contains(id)) { + return Err(IngestionError::Unsupported(format!( + "collector view {missing} is not a materialized view refreshed at ingestion" + ))); + } + Ok(split) +} + fn gcd(a: i64, b: i64) -> i64 { if b == 0 { a.abs() @@ -1831,7 +2121,7 @@ fn gcd(a: i64, b: i64) -> i64 { } /// One reading of both clocks of a [`WallClock`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub(crate) struct ClockReading { pub wall_ms: i64, pub monotonic_ms: i64, diff --git a/crates/precompute/src/lib.rs b/crates/precompute/src/lib.rs index 9d647e05c..3d82b56da 100644 --- a/crates/precompute/src/lib.rs +++ b/crates/precompute/src/lib.rs @@ -1,7 +1,9 @@ //! The data plane's ingest side: routing samples to the plan's raw data and //! closing windows ([`ingestion`]), building views by push pipelines -//! ([`push`]), and the threads that run them ([`engine`]). +//! ([`push`]), taking in the views a collector builds ([`collector`]), and +//! the threads that run them ([`engine`]). +pub mod collector; pub mod engine; pub mod ingestion; pub mod push; diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index 2d0fe406d..851a3813e 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -851,6 +851,30 @@ pub(crate) fn encode_state(state: &dyn AggregateCore, grids: &mut Grids) -> Opti } } +/// Rebuilds sketch states of one kernel from ASAPv1 bytes, as the view +/// files rebuild a stored state: for states built elsewhere (a collector's) +/// into the kernel the executor builds for their view. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Asapv1Decoder(SketchKernel); + +impl Asapv1Decoder { + /// The decoder of `template`'s kernel (an empty state the executor + /// built); `None` for a state not stored as ASAPv1 bytes (an exact + /// state, a Hydra-Count-Min group). + pub fn of_state(template: &dyn AggregateCore) -> Option { + match encode_state(template, &mut Grids::default())? { + StoredValue::Sketch { kernel, .. } => Some(Self(kernel)), + _ => None, + } + } + + /// The state `asapv1` encodes; `None` when the bytes are not this + /// kernel's. + pub fn decode(&self, asapv1: &[u8]) -> Option> { + decode_sketch(self.0, asapv1) + } +} + /// The kernel state `kernel` rebuilds from `asapv1`. pub(crate) fn decode_sketch(kernel: SketchKernel, asapv1: &[u8]) -> Option> { Some(match kernel { @@ -1438,13 +1462,13 @@ mod tests { !location.is_sealed(), "{what}: the newest segment is active" ); - let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let active = location.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&batch, &active, &format!("{what}, active segment")); files.seal(0).unwrap(); assert!(location.is_sealed(), "{what}"); - let mapped = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let mapped = location.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&batch, &mapped, &format!("{what}, mapped")); - let pread = location.read(batch.schema(), ViewRead::Pread).unwrap().0; + let pread = location.read(batch.schema(), ViewRead::Pread).unwrap(); assert_same_rows(&batch, &pread, &format!("{what}, pread")); } let _ = std::fs::remove_dir_all(&dir); @@ -1465,11 +1489,11 @@ mod tests { .unwrap(); let location = location_of(&written, 1); for how in [ViewRead::Pread, ViewRead::Mmap] { - assert_eq!(location.read(empty.schema(), how).unwrap().0.num_rows(), 0); + assert_eq!(location.read(empty.schema(), how).unwrap().num_rows(), 0); } files.seal(0).unwrap(); for how in [ViewRead::Pread, ViewRead::Mmap] { - assert_eq!(location.read(empty.schema(), how).unwrap().0.num_rows(), 0); + assert_eq!(location.read(empty.schema(), how).unwrap().num_rows(), 0); } let _ = std::fs::remove_dir_all(&dir); } @@ -1498,9 +1522,7 @@ mod tests { drop(file); for (i, batch) in batches.iter().enumerate() { let view = i as PhysicalASAPNodeId + 1; - let read = location_of(&written, view) - .read(batch.schema(), ViewRead::Mmap) - .map(|(batch, _)| batch); + let read = location_of(&written, view).read(batch.schema(), ViewRead::Mmap); if view == 2 { assert!(read.is_err(), "a damaged fragment must not decode"); } else { @@ -1511,11 +1533,11 @@ mod tests { } /// A cold read rebuilds a KLL column (no compact form) in the mapped - /// layout in buffers of its own and reports their bytes, which the - /// batch's own memory count leaves out; every window of a segment + /// layout in buffers of its own, which the batch's stored bytes count + /// and its run memory count leaves out; every window of a segment /// shares one dictionary of texts; `ViewRead::Pread` reads the same rows. #[test] - fn cold_reads_report_state_bytes_and_share_one_dictionary() { + fn cold_reads_count_state_bytes_and_share_one_dictionary() { let dir = segment_dir("cold-read"); let (_, a, b) = states().remove(1); let (a, b): (Arc, Arc) = (Arc::from(a), Arc::from(b)); @@ -1546,10 +1568,9 @@ mod tests { .unwrap(); files.seal(0).unwrap(); let (l1, l2) = (location_of(&w1, 1), location_of(&w2, 1)); - let (r1, state_bytes) = l1.read(first.schema(), ViewRead::Mmap).unwrap(); - let (r2, _) = l2.read(second.schema(), ViewRead::Mmap).unwrap(); + let r1 = l1.read(first.schema(), ViewRead::Mmap).unwrap(); + let r2 = l2.read(second.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&first, &r1, "mapped"); - assert_eq!(state_bytes, held); // The column reports the bytes its views span, but a run reading // it is charged none of them: they are the store's. assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), held); @@ -1566,11 +1587,11 @@ mod tests { Arc::ptr_eq(identity(&r1).values(), identity(&r2).values()), "one dictionary per segment" ); - let (copied, copied_state_bytes) = l1.read(first.schema(), ViewRead::Pread).unwrap(); + let copied = l1.read(first.schema(), ViewRead::Pread).unwrap(); assert_same_rows(&first, &copied, "pread"); - // The rebuilt states' bytes, which the batch does not count, are - // reported for the window's charge, mapped or copied alike. - assert_eq!(copied_state_bytes, state_bytes); + // The window's charge counts the rebuilt states, mapped or copied + // alike. + assert_eq!(copied.stored_bytes(), r1.stored_bytes()); let _ = std::fs::remove_dir_all(&dir); } @@ -1658,7 +1679,7 @@ mod tests { // fixed.) assert!(l2.len() > l1.len()); for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { - let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let active = location.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(batch, &active, &format!("{what}, active segment")); } // A later window with series new to the active segment: the label @@ -1669,14 +1690,14 @@ mod tests { .unwrap(); let l3 = location_of(&later_written, 1); assert!(!l3.is_sealed()); - let read = l3.read(later.schema(), ViewRead::Mmap).unwrap().0; + let read = l3.read(later.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&later, &read, "labels, extended values"); - let read = l1.read(labeled.schema(), ViewRead::Mmap).unwrap().0; + let read = l1.read(labeled.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&labeled, &read, "labels, first window after the extension"); files.seal(0).unwrap(); for how in [ViewRead::Mmap, ViewRead::Pread] { for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { - let read = location.read(batch.schema(), how).unwrap().0; + let read = location.read(batch.schema(), how).unwrap(); assert_same_rows(batch, &read, &format!("{what}, sealed, {how:?}")); } } @@ -1706,7 +1727,7 @@ mod tests { .unwrap(); for (id, batch, what) in [(1, &labeled, "labels"), (2, &other, "other")] { let location = &index[&id][0].1; - let read = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let read = location.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(batch, &read, &format!("{what}, indexed at startup")); } let _ = std::fs::remove_dir_all(&dir); @@ -1769,9 +1790,9 @@ mod tests { .unwrap(); files.seal(0).unwrap(); let location = location_of(&written, 1); - let before = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let before = location.read(batch.schema(), ViewRead::Mmap).unwrap(); std::fs::remove_file(location.segment_path()).unwrap(); - let after = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let after = location.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&before, &after, "after unlink"); let _ = std::fs::remove_dir_all(&dir); } @@ -1862,7 +1883,7 @@ mod tests { assert!(!oldest_short.segment_path().exists()); assert!(oldest_long.segment_path().exists()); assert!(files.bytes() < bytes_before); - let read = oldest_long.read(batch.schema(), ViewRead::Mmap).unwrap().0; + let read = oldest_long.read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&batch, &read, "the long-retention view's oldest window"); let left: Vec = segment_files(&dir); assert_eq!(left.len(), 5, "short: (60, 80]; long: four segments"); @@ -1906,7 +1927,7 @@ mod tests { files.seal(0).unwrap(); assert!(locations[4].is_cold(), "sealing (60, 80] cools (40, 60]"); assert!(!locations[6].is_cold()); - let (read, _) = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap(); + let read = locations[0].read(batch.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&batch, &read, "a cold segment"); let _ = std::fs::remove_dir_all(&dir); } @@ -1967,8 +1988,7 @@ mod tests { &index[&1][0] .1 .read(second.schema(), ViewRead::Mmap) - .unwrap() - .0, + .unwrap(), "revision 1", ); @@ -2039,7 +2059,7 @@ mod tests { for (_, location) in &index[&1] { assert_same_rows( &batch, - &location.read(batch.schema(), ViewRead::Mmap).unwrap().0, + &location.read(batch.schema(), ViewRead::Mmap).unwrap(), "after the cut", ); } @@ -2084,7 +2104,7 @@ mod tests { for (_, location) in &recovered[&1] { assert_same_rows( &batch, - &location.read(batch.schema(), ViewRead::Mmap).unwrap().0, + &location.read(batch.schema(), ViewRead::Mmap).unwrap(), "recovered", ); } diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index 45586b1a8..c04a90b44 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -783,11 +783,10 @@ impl WindowLocation { Ok(Bytes::Owned(bytes)) } - /// The fragment's rows as one batch of `schema`, and the bytes its - /// state columns hold: they are rebuilt in the view layout, which - /// [`Batch::memory_bytes`] counts as held outside the run, so a cache - /// holding the batch charges them itself. - pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result<(Batch, usize), Error> { + /// The fragment's rows as one batch of `schema`. Its state columns are + /// rebuilt in the view layout, which [`Batch::memory_bytes`] counts as + /// held outside the run and [`Batch::stored_bytes`] counts in full. + pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result { let grids: Vec>> = if self.grids.1 == 0 { Vec::new() } else { @@ -1166,6 +1165,53 @@ fn view_column_of(views: Vec>) -> Option<(Vec, Vec)> { Some((offsets, states)) } +/// `batch` with each state column of a family with a view layout +/// (DDSketch, KLL, Count-Min, exact records) in that layout, in one buffer +/// per column, as a window read back from its fragment holds it; other +/// columns as they are. A window built from states decoded one by one (a +/// collector view's) is so held as a computed window seals its states, +/// and charged alike ([`Batch::stored_bytes`]). +pub fn with_view_layout_states(batch: Batch) -> Result { + let schema = batch.schema().clone(); + let rows = batch.num_rows(); + let sources: Vec> = (0..rows).map(|row| (&batch, row)).collect(); + let columns = schema + .fields + .iter() + .enumerate() + .map(|(index, field)| { + let Some(states) = batch.state_column(index) else { + return Ok(BatchColumn::Plain(batch.column(index).clone())); + }; + let indices = batch + .column(index) + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Invalid("state indices are not u32".into()))?; + let Some((offsets, views)) = + view_bytes(&field.dtype, &sources, index).and_then(view_column_of) + else { + return Ok(BatchColumn::States { + indices: indices.clone(), + states: states.clone(), + }); + }; + let offsets = + ScalarBuffer::::new(buffer(&offsets, 0, offsets.len())?, 0, rows + 1); + let views = buffer(&views, 0, views.len())?; + Ok(BatchColumn::States { + indices: UInt32Array::from_iter_values(0..rows as u32), + states: Arc::new(StateColumn::from_views( + field.dtype.clone(), + views, + offsets, + )?), + }) + }) + .collect::, Error>>()?; + Batch::try_from_columns(schema, columns) +} + /// A little-endian `u64` at `at` of `bytes`. fn word(bytes: &[u8], at: usize) -> Result { Ok(u64::from_le_bytes( @@ -1289,15 +1335,13 @@ fn descriptor(bytes: &[u8], column: usize) -> Result { }) } -/// The columnar fragment `bytes` as one batch of `schema`, and the bytes -/// its state columns hold. +/// The columnar fragment `bytes` as one batch of `schema`. fn decode_fragment( bytes: &[u8], schema: &SchemaRef, segment: &Segment, grids: &[Option>], -) -> Result<(Batch, usize), Error> { - let mut state_bytes = 0; +) -> Result { let header = word(bytes, 0)?; let rows = (header & 0xffff_ffff) as usize; let columns = (header >> 32) as usize; @@ -1414,7 +1458,6 @@ fn decode_fragment( let (states, offsets) = decode_states(compact, &bytes[data.0..data.0 + data.1], rows) .ok_or_else(damaged)?; - state_bytes += states.len() * 8 + offsets.len() * 4; let column = StateColumn::from_views( field.dtype.clone(), Buffer::from(states), @@ -1430,7 +1473,6 @@ fn decode_fragment( if data.1 != (rows + 1) * 4 { return Err(damaged()); } - state_bytes += data.1 + valid.1; let offsets = ScalarBuffer::::new(buffer(bytes, data.0, data.1)?, 0, rows + 1); let states = buffer(bytes, valid.0, valid.1)?; let column = StateColumn::from_views(field.dtype.clone(), states, offsets)?; @@ -1502,7 +1544,7 @@ fn decode_fragment( } out.push(BatchColumn::Plain(array)); } - Ok((Batch::try_from_columns(schema.clone(), out)?, state_bytes)) + Batch::try_from_columns(schema.clone(), out) } /// `rows` of one column `field` built by the executor: its array, and its diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 9c392050d..7d3cedb72 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1303,18 +1303,17 @@ impl WindowSlot { std::thread::sleep(tier.decode_delay); } let timer = Timer::start(); - let (batch, state_bytes) = - location.read(&self.schema, tier.read).map_err(|error| { - Error::Invalid(format!( - "materialized view {} window ending {}: {error}", - self.key.view, self.key.end_ms - )) - })?; + let batch = location.read(&self.schema, tier.read).map_err(|error| { + Error::Invalid(format!( + "materialized view {} window ending {}: {error}", + self.key.view, self.key.end_ms + )) + })?; tier.decode.record(timer); tier.cold_reads.fetch_add(1, Ordering::Relaxed); tier.cold_read_bytes .fetch_add(location.read_bytes(), Ordering::Relaxed); - let bytes = (window_batch_bytes(&batch) + state_bytes) as u64; + let bytes = window_batch_bytes(&batch) as u64; Ok((Arc::new(vec![batch]), bytes)) }) } @@ -2018,12 +2017,12 @@ fn merged_rows<'a>(batches: impl Iterator) -> Result usize { let shared: usize = (0..batch.schema().fields.len()) .filter(|&index| batch.state_column(index).is_none()) @@ -2035,7 +2034,7 @@ fn window_batch_bytes(batch: &Batch) -> usize { .map(|dictionary| dictionary.values().get_array_memory_size()) }) .sum(); - batch.memory_bytes().saturating_sub(shared) + batch.stored_bytes().saturating_sub(shared) } /// The newest published snapshot of the store, which every query run reads. diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 2f9932af0..091d1e6ed 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -115,13 +115,14 @@ data-plane common, precompute, storage, query, internal-metrics, every adapt This is #935's decision 1. - Adapters never see an engine or a store. In ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); a separate `common` crate - closes that here. The ingest adapters need not even `common`: each - decodes into the caller's types (below), so `prometheus-remote-write` - depends on nothing in the workspace, `victoriametrics-remote-write` only - on `prometheus-remote-write`, whose protobuf it reads (zstd-compressed - instead of snappy), and `otlp` only on `prometheus-remote-write`, whose + closes that here. The ingest adapters decode samples into the caller's + types (below), so `prometheus-remote-write` depends on nothing in the + workspace, `victoriametrics-remote-write` only on + `prometheus-remote-write`, whose protobuf it reads (zstd-compressed + instead of snappy), and `otlp` on `prometheus-remote-write`, whose `SampleBuilder`, in-place protobuf reader and series cache its decoder - uses. + uses, and on `common`, for the collector view states it decodes + (`ViewStateBatch`, docs/design/collector-sketch-ingest.md). - `control-plane` is a dev-dependency of `data-plane`, `precompute` and `query` only: their tests plan workloads with it. - `precompute` and `query` do not depend on each other. Both depend on