From 55e040b97c0eecce9075bfbf25f3ee188c1d14d5 Mon Sep 17 00:00:00 2001 From: Zeying Zhu <50204836+zzylol@users.noreply.github.com> Date: Mon, 30 Nov 2026 04:57:12 +0000 Subject: [PATCH] collector_views: sequence numbers and delta emission (full, then deltas per window) Every collector view state now carries its lineage, the records one collector instance sends for one (view, series, window): - asap.producer_epoch (Metric metadata, decimal text of a u64): the instance, a random number drawn when the executor starts; states of two epochs are two Metric entries. - asap.sequence (int), asap.state_kind ("full" | "delta") and asap.base_sequence (int, deltas only) on each point: record 0 is a full, record n >= 1 a delta on n - 1. Each emission of a window is the state of the samples taken since the previous one: the window's run is sealed and the next sample starts a new run. So corrections of late samples are deltas, and the new optional processor setting open_window_emit_interval_ms (default off: a window is emitted at its close, as before) also emits open windows, as a full and then deltas, so ASAPQuery-backend answers them with fresh partial states. For DDSketch a delta is exactly the new samples' bucket counts; for KLL it is a KLL of the new samples, which merges within the sketch's rank error. Sequences are kept per run group, window and series (by a hash of the series key, since series ids are reused) while the window is within retention; the views of a group filter by labels only, so this is each view's lineage. Two corrections with equal bytes now get sequences 1 and 2 instead of looking like one retry. A new counter states.delta counts the deltas sent. collector-views.json may carry window_close_delay_ms (copied by the control plane for ASAPQuery-backend's idle close); the loader accepts and ignores it, and still refuses unknown fields. The golden on-time states file is unchanged: its test now strips the lineage (epoch metadata, sequence 0, kind full) from the emitted messages and compares them with the file's. The q01 wire example tests/fixtures/collector-views/q01/otlp-body.pb is regenerated with a fixed epoch (9241337045811906213) and the full's lineage attributes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- asap-precompute-rs/src/answers.rs | 1 + .../src/bin/stream_bench/model.rs | 1 + asap-precompute-rs/src/envelope.rs | 29 ++ asap-precompute-rs/src/kll_windows.rs | 1 + asap-precompute-rs/src/otap/codec.rs | 197 ++++++++++- .../src/otap/collector_views.rs | 60 +++- asap-precompute-rs/src/otap/planner_views.rs | 13 + asap-precompute-rs/src/otap/schema.rs | 13 + asap-precompute-rs/src/otap/view_executor.rs | 313 +++++++++++++++++- asap-precompute-rs/src/precompute.rs | 2 + .../tests/collector_views_e2e.rs | 104 +++++- .../fixtures/collector-views/q01/otlp-body.pb | Bin 669 -> 781 bytes asap-precompute-rs/tests/otap_pipeline_e2e.rs | 1 + docs/data_model.md | 13 +- 14 files changed, 713 insertions(+), 35 deletions(-) diff --git a/asap-precompute-rs/src/answers.rs b/asap-precompute-rs/src/answers.rs index 8c3c057..9f9cc67 100644 --- a/asap-precompute-rs/src/answers.rs +++ b/asap-precompute-rs/src/answers.rs @@ -64,6 +64,7 @@ pub fn gauge( count: template.count, aggregation_temporality: 0, value, + lineage: None, } } diff --git a/asap-precompute-rs/src/bin/stream_bench/model.rs b/asap-precompute-rs/src/bin/stream_bench/model.rs index 37dc6c7..173d4e7 100644 --- a/asap-precompute-rs/src/bin/stream_bench/model.rs +++ b/asap-precompute-rs/src/bin/stream_bench/model.rs @@ -76,6 +76,7 @@ impl Meta { count: 0, aggregation_temporality: 0, value, + lineage: None, } } } diff --git a/asap-precompute-rs/src/envelope.rs b/asap-precompute-rs/src/envelope.rs index d80ccae..b51a585 100644 --- a/asap-precompute-rs/src/envelope.rs +++ b/asap-precompute-rs/src/envelope.rs @@ -85,6 +85,28 @@ impl SketchType { } } +/// A collector view state's place in its lineage: the records one collector +/// instance (`producer_epoch`) sends for one (view, series, window), numbered +/// from 0. Record 0 is a full state (the samples folded into the window when +/// it was sent); record `n ≥ 1` is a delta on record `n − 1` (the state of the +/// samples folded since). The OTAP codec writes the epoch as the metric's +/// `asap.producer_epoch` metadata and the rest as the point's +/// `asap.sequence`, `asap.state_kind` and `asap.base_sequence` attributes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct Lineage { + /// The collector instance: a random number drawn at start. + pub producer_epoch: u64, + /// 0 for a full; a delta's base is `sequence − 1`. + pub sequence: u64, +} + +impl Lineage { + /// A delta's base sequence; `None` for a full. + pub fn base_sequence(&self) -> Option { + self.sequence.checked_sub(1) + } +} + /// One emitted sketch (or scalar estimate) plus its runtime metadata. /// /// `payload` is the sketch's ASAPv1 envelope bytes and is what @@ -153,6 +175,9 @@ pub struct SketchEnvelope { /// Encode writes it to the `value` column. #[serde(default)] pub value: f64, + /// A collector view state's lineage; `None` outside `planner_views`. + #[serde(default)] + pub lineage: Option, } #[cfg(test)] @@ -183,6 +208,10 @@ mod tests { count: 100, aggregation_temporality: 1, value: 88.0, + lineage: Some(Lineage { + producer_epoch: 9, + sequence: 2, + }), }; let json = serde_json::to_string(&env).expect("serialize"); let decoded: SketchEnvelope = serde_json::from_str(&json).expect("deserialize"); diff --git a/asap-precompute-rs/src/kll_windows.rs b/asap-precompute-rs/src/kll_windows.rs index 7b5020a..a57d4bb 100644 --- a/asap-precompute-rs/src/kll_windows.rs +++ b/asap-precompute-rs/src/kll_windows.rs @@ -296,6 +296,7 @@ impl KllWindowStore { count: entry.count, aggregation_temporality: 1, value: 0.0, + lineage: None, }) }) .collect() diff --git a/asap-precompute-rs/src/otap/codec.rs b/asap-precompute-rs/src/otap/codec.rs index ec078c4..7621986 100644 --- a/asap-precompute-rs/src/otap/codec.rs +++ b/asap-precompute-rs/src/otap/codec.rs @@ -71,9 +71,13 @@ use otel_arrow_dfe_pdata_views::views::metrics::{ use otel_arrow_dfe_pdata_views::views::resource::ResourceView; use crate::config::{sketch_size_string, SketchParams}; -use crate::envelope::{SketchEnvelope, SketchType, ViewIdentity}; +use crate::envelope::{Lineage, SketchEnvelope, SketchType, ViewIdentity}; use crate::observation::{KeyValue, Observation, ObservationValue, SourceDescriptor}; +use super::schema::{ + ATTR_BASE_SEQUENCE, ATTR_SEQUENCE, ATTR_STATE_KIND, META_PRODUCER_EPOCH, STATE_KIND_DELTA, + STATE_KIND_FULL, +}; use super::schema::{ ATTR_ENVELOPE, ATTR_SCHEMA_VERSION, ATTR_SERIES_ID, ATTR_SKETCH_SIZE, ATTR_SKETCH_TYPE, ATTR_WINDOW_END_MS, ATTR_WINDOW_START_MS, META_NODE_ID, META_PLAN_ID, META_VIEW_STATE_KEY, @@ -241,6 +245,7 @@ fn same_view_scope(left: &SketchEnvelope, right: &SketchEnvelope) -> bool { fn same_view_metric(left: &SketchEnvelope, right: &SketchEnvelope) -> bool { left.view == right.view + && left.lineage.map(|l| l.producer_epoch) == right.lineage.map(|l| l.producer_epoch) && left.metric_name == right.metric_name && left.source.unit == right.source.unit && left.source.description == right.source.description @@ -260,6 +265,8 @@ fn same_view_metric(left: &SketchEnvelope, right: &SketchEnvelope) -> bool { struct AsapMetricsView<'a> { envelopes: &'a [SketchEnvelope], resources: Vec, + /// Each producer epoch's `asap.producer_epoch` text. + epochs: HashMap, } struct AsapResourceGroup { @@ -323,9 +330,15 @@ impl<'a> AsapMetricsView<'a> { }); metrics[metric_pos].push(row); } + let epochs = envelopes + .iter() + .filter_map(|env| env.lineage) + .map(|lineage| (lineage.producer_epoch, lineage.producer_epoch.to_string())) + .collect(); Self { envelopes, resources, + epochs, } } @@ -335,7 +348,8 @@ impl<'a> AsapMetricsView<'a> { fn attributes_for_row(&self, row: usize) -> Vec> { let env = &self.envelopes[row]; if env.view.is_some() { - // The received point attributes, then the state. + // The received point attributes, then the state and its place + // in its lineage. let mut attrs = string_attributes(&env.labels); if !env.payload.is_empty() { attrs.push(AsapAttribute { @@ -343,6 +357,28 @@ impl<'a> AsapMetricsView<'a> { value: AsapAnyValue::Bytes(&env.payload), }); } + if let Some(lineage) = env.lineage { + attrs.push(AsapAttribute { + key: ATTR_SEQUENCE, + value: AsapAnyValue::Int(lineage.sequence), + }); + match lineage.base_sequence() { + None => attrs.push(AsapAttribute { + key: ATTR_STATE_KIND, + value: AsapAnyValue::Str(STATE_KIND_FULL), + }), + Some(base) => attrs.extend([ + AsapAttribute { + key: ATTR_STATE_KIND, + value: AsapAnyValue::Str(STATE_KIND_DELTA), + }, + AsapAttribute { + key: ATTR_BASE_SEQUENCE, + value: AsapAnyValue::Int(base), + }, + ]), + } + } return attrs; } let mut attrs = Vec::with_capacity(3); @@ -511,11 +547,17 @@ impl<'v, 'a> MetricView for AsapMetricView<'v, 'a> { } /// A collector view's identity (`asap.plan_id`, `asap.node_id`, - /// `asap.view_state_key`); none for a hand-configured sketch. + /// `asap.view_state_key`) and producer epoch (`asap.producer_epoch`, when + /// its states have a lineage); none for a hand-configured sketch. fn metadata(&self) -> Self::AttributeIter<'_> { - let Some(view) = &self.view.envelopes[self.rows[0]].view else { + let row = &self.view.envelopes[self.rows[0]]; + let Some(view) = &row.view else { return Vec::new().into_iter(); }; + let epoch = row.lineage.map(|lineage| AsapAttribute { + key: META_PRODUCER_EPOCH, + value: AsapAnyValue::Str(&self.view.epochs[&lineage.producer_epoch]), + }); vec![ AsapAttribute { key: META_PLAN_ID, @@ -531,6 +573,9 @@ impl<'v, 'a> MetricView for AsapMetricView<'v, 'a> { }, ] .into_iter() + .chain(epoch) + .collect::>() + .into_iter() } } @@ -1520,6 +1565,7 @@ fn decode_view(view: &V, f: impl FnMut(&Observation)) -> Result< }; let name = DecodeMetric { view: view_identity(&metric, &name)?, + producer_epoch: producer_epoch(&metric, &name)?, source: Arc::new(SourceDescriptor { unit: String::from_utf8_lossy(metric.unit()).into_owned(), description: String::from_utf8_lossy(metric.description()).into_owned(), @@ -1634,6 +1680,8 @@ struct DecodeSchema { struct DecodeMetric { name: String, view: Option>, + /// `asap.producer_epoch` of a collector view's states, when present. + producer_epoch: Option, source: Arc, } @@ -1707,6 +1755,66 @@ fn view_identity( } } +/// A Metric's `asap.producer_epoch` metadata (decimal text), if any. +fn producer_epoch(metric: &M, name: &str) -> Result, CodecError> { + for attr in metric.metadata() { + if attr.key() != META_PRODUCER_EPOCH.as_bytes() { + continue; + } + let text = attr.value().and_then(|v| { + v.as_string() + .map(|s| String::from_utf8_lossy(s).into_owned()) + }); + return text.and_then(|t| t.parse().ok()).map(Some).ok_or_else(|| { + CodecError::Decode(format!( + "metric {name}: {META_PRODUCER_EPOCH} is not a u64 as decimal text" + )) + }); + } + Ok(None) +} + +/// A state's lineage from its metric's epoch and its point's `asap.sequence`, +/// `asap.state_kind` and `asap.base_sequence`: `None` when the point has none +/// of them; an error when they are partial or disagree (a full is sequence 0 +/// without a base, a delta `n ≥ 1` on base `n − 1`). +fn decode_lineage( + epoch: Option, + sequence: Option, + kind: Option<&str>, + base: Option, +) -> Result, CodecError> { + if sequence.is_none() && kind.is_none() && base.is_none() { + return Ok(None); + } + // OTAP Arrow's sparse attribute encoding may leave out an int attribute + // whose value is 0 (OTLP keeps it): a full's sequence is then absent. + let sequence = sequence.or((kind == Some(STATE_KIND_FULL)).then_some(0)); + let lineage = match (epoch, sequence, kind, base) { + (Some(producer_epoch), Some(0), Some(STATE_KIND_FULL), None) => Lineage { + producer_epoch, + sequence: 0, + }, + (Some(producer_epoch), Some(n), Some(STATE_KIND_DELTA), Some(b)) + if n >= 1 && b == n - 1 => + { + Lineage { + producer_epoch, + sequence: n as u64, + } + } + _ => { + return Err(CodecError::Decode(format!( + "a state's lineage needs {META_PRODUCER_EPOCH}, {ATTR_SEQUENCE} and \ + {ATTR_STATE_KIND} \"{STATE_KIND_FULL}\" at 0, or \"{STATE_KIND_DELTA}\" at n ≥ 1 \ + with {ATTR_BASE_SEQUENCE} n − 1; got epoch {epoch:?}, sequence {sequence:?}, \ + kind {kind:?}, base {base:?}" + ))) + } + }; + Ok(Some(lineage)) +} + impl DecodeAccumulator { fn push_summary_data_point( &mut self, @@ -1719,6 +1827,7 @@ impl DecodeAccumulator { let mut envelope_bytes: Option> = None; let mut window_start_ms = None; let mut window_end_ms = None; + let (mut sequence, mut kind, mut base) = (None, None, None); let mut labels = series_labels.to_vec(); for attr in dp.attributes() { @@ -1726,6 +1835,13 @@ impl DecodeAccumulator { let key = String::from_utf8_lossy(attr.key()).into_owned(); match key.as_str() { ATTR_ENVELOPE => envelope_bytes = value.as_bytes().map(<[u8]>::to_vec), + ATTR_SEQUENCE => sequence = value.as_int64(), + ATTR_STATE_KIND => { + kind = value + .as_string() + .map(|s| String::from_utf8_lossy(s).into_owned()) + } + ATTR_BASE_SEQUENCE => base = value.as_int64(), ATTR_WINDOW_START_MS => { window_start_ms = value.as_int64().filter(|v| *v >= 0).map(|v| v as u64) } @@ -1766,6 +1882,7 @@ impl DecodeAccumulator { count: dp.count(), aggregation_temporality: 0, value: dp.sum(), + lineage: decode_lineage(metric.producer_epoch, sequence, kind.as_deref(), base)?, }; let mut observation = Observation::new( timestamp_ms, @@ -1872,6 +1989,7 @@ impl DecodeAccumulator { count: 0, aggregation_temporality: 0, value, + lineage: None, }) } None => ObservationValue::float(value), @@ -1920,6 +2038,7 @@ mod tests { count: 0, aggregation_temporality: 0, value, + lineage: None, } } @@ -2261,9 +2380,16 @@ mod tests { count: 50, aggregation_temporality: 1, value: 0.0, + lineage: Some(Lineage { + producer_epoch: Q01_EPOCH, + sequence: 0, + }), } } + /// The producer epoch of [`q01_state`] (and of the q01 wire fixture). + const Q01_EPOCH: u64 = 9_241_337_045_811_906_213; + /// `pdata` as the OTLP `ExportMetricsServiceRequest` an OTLP exporter sends. fn otlp_request( pdata: OtapPdata, @@ -2373,6 +2499,7 @@ mod tests { ("asap.plan_id", view.plan_id.as_str()), ("asap.node_id", "1"), ("asap.view_state_key", Q01_KEY), + ("asap.producer_epoch", &Q01_EPOCH.to_string()), ]) ); let Some(Data::Summary(summary)) = &metric.data else { @@ -2391,6 +2518,8 @@ mod tests { "sketch.envelope", &format!("<{} bytes>", state.payload.len()) ), + ("asap.sequence", "0"), + ("asap.state_kind", "full"), ]) ); assert_eq!(point.start_time_unix_nano, 1_767_225_595_000_000_000); @@ -2405,6 +2534,66 @@ mod tests { let env = decoded.observations[0].value.envelope.as_ref().unwrap(); assert_eq!(env.view, state.view); assert_eq!(env.payload, state.payload); + assert_eq!(env.lineage, state.lineage); + assert_eq!(env.labels, state.labels, "the lineage is not a label"); + } + + /// A delta carries `asap.base_sequence` and decodes back to its lineage; + /// states of two epochs are two Metric entries (one epoch each). + #[test] + fn a_delta_round_trips_and_epochs_are_separate_metrics() { + let full = q01_state(1_767_225_600_000); + let mut delta = full.clone(); + delta.lineage = Some(Lineage { + producer_epoch: Q01_EPOCH, + sequence: 3, + }); + let mut other_epoch = full.clone(); + other_epoch.lineage = Some(Lineage { + producer_epoch: 1, + sequence: 0, + }); + let pdata = encode_envelopes_to_pdata(&[full.clone(), delta.clone(), other_epoch.clone()]) + .expect("encode"); + let (_, data) = otlp_request(pdata.clone()); + let metrics = &data.resource_metrics[0].scope_metrics[0].metrics; + assert_eq!(metrics.len(), 2, "one metric per epoch"); + let decoded = decode_pdata_to_observations(pdata).expect("decode"); + let lineages: Vec<_> = decoded + .observations + .iter() + .map(|o| o.value.envelope.as_ref().unwrap().lineage) + .collect(); + assert_eq!(lineages, [full.lineage, delta.lineage, other_epoch.lineage]); + } + + /// A lineage whose kind does not match its sequence and base is refused. + #[test] + fn an_inconsistent_lineage_is_refused_on_decode() { + use otel_arrow_dfe_pdata::proto::opentelemetry::common::v1::{ + any_value, AnyValue, KeyValue, + }; + use otel_arrow_dfe_pdata::proto::opentelemetry::metrics::v1::metric::Data; + use otel_arrow_dfe_pdata::proto::OtlpProtoMessage; + let pdata = encode_envelopes_to_pdata(&[q01_state(1_767_225_600_000)]).expect("encode"); + let (_, mut data) = otlp_request(pdata); + let Some(Data::Summary(summary)) = + &mut data.resource_metrics[0].scope_metrics[0].metrics[0].data + else { + panic!("a Summary"); + }; + // A "full" of sequence 0 with a base. + summary.data_points[0].attributes.push(KeyValue { + key: "asap.base_sequence".into(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(0)), + }), + }); + let pdata = OtapPdata::new_todo_context( + OtapPayload::try_from(OtlpProtoMessage::Metrics(data)).expect("from OTLP"), + ); + let error = decode_pdata_to_observations(pdata).expect_err("refused"); + assert!(error.to_string().contains("asap.sequence"), "{error}"); } /// Two views over one source metric are two Metric entries, each with its diff --git a/asap-precompute-rs/src/otap/collector_views.rs b/asap-precompute-rs/src/otap/collector_views.rs index 05093e8..b461446 100644 --- a/asap-precompute-rs/src/otap/collector_views.rs +++ b/asap-precompute-rs/src/otap/collector_views.rs @@ -17,16 +17,33 @@ //! shutdown) as the window's own state is; ASAPQuery-backend merges it into //! the committed window. //! +//! With `open_window_emit_interval_ms`, every interval (checked on the idle +//! timer) each open window's samples since its last emission are also sent, +//! so ASAPQuery-backend answers the open window with a fresh partial state. +//! +//! Every state carries its lineage (ASAPQuery-backend's +//! `docs/design/collector-sketch-ingest.md`, section 8): the processor's +//! producer epoch, drawn at start, as the metric's `asap.producer_epoch` +//! metadata, and the point's `asap.sequence`, `asap.state_kind` and +//! `asap.base_sequence`. A window's first emission for a series is a full +//! (sequence 0); every later one (an open-window emission, the close, a +//! correction) is a delta on the one before: the state of the samples since, +//! which the backend merges. A restarted collector has a new epoch, so its +//! lineages start again with a full. +//! //! Per view (registration attribute `view`, its output metric) it reports //! the counters of metric set `processor.collector_views`: samples folded //! into the view's windows or corrections, samples dropped late beyond the //! view's retention and rejected (a value the sketch refuses), and window -//! and correction states emitted. +//! and correction states emitted, and states sent as deltas. //! //! ```yaml //! collector_views: //! type: urn:asap:processor:collector_views -//! config: {planner_views: /etc/asap/collector-views.json} +//! config: +//! planner_views: /etc/asap/collector-views.json +//! # optional; absent: windows are emitted at their close only +//! open_window_emit_interval_ms: 1000 //! ``` use std::path::PathBuf; @@ -67,6 +84,11 @@ pub const COLLECTOR_VIEWS_URN: &str = "urn:asap:processor:collector_views"; pub struct CollectorViewsConfig { /// The control plane's `collector-views.json`. pub planner_views: PathBuf, + /// Also emit every open window's new samples this often (ms), as deltas + /// after its first emission, so ASAPQuery-backend answers open windows + /// with fresh partial states. Absent: a window is emitted at its close. + #[serde(default)] + pub open_window_emit_interval_ms: Option, } /// The idle timer's period: a second, or the narrowest window if narrower. @@ -105,12 +127,20 @@ struct ViewMetrics { /// Correction states (a closed window's late samples) sent downstream. #[metric(name = "states.correction", unit = "{state}")] states_correction: Counter, + /// States sent as deltas (sequence ≥ 1 of their lineage): open-window + /// emissions after the first, closes after one, and corrections. + #[metric(name = "states.delta", unit = "{state}")] + states_delta: Counter, } struct CollectorViews { executor: ViewExecutor, timer_period: Duration, timer_started: bool, + /// `open_window_emit_interval_ms`, and when open windows were last + /// emitted. + open_window_emit_interval: Option, + open_windows_emitted_at: std::time::Instant, /// Per view, in `collector-views.json` order: its node id, its metrics, /// and the executor's counts as last reported. node_ids: Vec, @@ -149,6 +179,9 @@ impl CollectorViews { } else { self.metrics[i].states_correction.inc(); } + if state.lineage.is_some_and(|l| l.sequence > 0) { + self.metrics[i].states_delta.inc(); + } } } } @@ -190,7 +223,15 @@ impl local::Processor for CollectorViews { } Message::Control(NodeControlMsg::TimerTick { .. }) => { let closed = self.executor.close_idle(tumbling_idle_close_now_ms()); - self.emit(closed, effects).await + self.emit(closed, effects).await?; + match self.open_window_emit_interval { + Some(interval) if self.open_windows_emitted_at.elapsed() >= interval => { + self.open_windows_emitted_at = std::time::Instant::now(); + let open = self.executor.emit_open(); + self.emit(open, effects).await + } + _ => Ok(()), + } } Message::Control(NodeControlMsg::Shutdown { .. }) => { let closed = self.executor.drain(); @@ -246,10 +287,20 @@ fn create( ) }) .collect(); + if config.open_window_emit_interval_ms == Some(0) { + return Err("open_window_emit_interval_ms must be positive".into()); + } + let open_window_emit_interval = config + .open_window_emit_interval_ms + .map(Duration::from_millis); Ok(CollectorViews { executor, - timer_period: narrowest.min(MAX_TIMER_PERIOD), + timer_period: open_window_emit_interval + .map_or(narrowest, |interval| narrowest.min(interval)) + .min(MAX_TIMER_PERIOD), timer_started: false, + open_window_emit_interval, + open_windows_emitted_at: std::time::Instant::now(), node_ids: views.views.iter().map(|v| v.identity.node_id).collect(), metrics, reported: vec![ViewCounts::default(); views.views.len()], @@ -429,6 +480,7 @@ pub(crate) mod tests { ("samples.rejected", 1), ("states.emitted", 4), ("states.correction", 1), + ("states.delta", 1), ] .into_iter() .map(|(name, value)| ((view.clone(), name.to_string()), value)) diff --git a/asap-precompute-rs/src/otap/planner_views.rs b/asap-precompute-rs/src/otap/planner_views.rs index dbb842b..c65fadd 100644 --- a/asap-precompute-rs/src/otap/planner_views.rs +++ b/asap-precompute-rs/src/otap/planner_views.rs @@ -66,6 +66,11 @@ pub struct CollectorViewsFile { /// Per metric a `Scan` of the plan reads: whether the backend still /// reads its raw samples. `raw_forward` drops the metrics marked `false`. pub backend_reads_raw: BTreeMap, + /// The collector's declared `window_close_delay_ms`, copied by the + /// control plane for ASAPQuery-backend's idle close; the collector + /// ignores it. + #[serde(default)] + pub window_close_delay_ms: Option, /// The collector views: the nodes whose states leave the collector. pub outputs: Vec, /// The collector sub-DAG; `roots = outputs`. @@ -724,6 +729,14 @@ mod tests { assert_eq!(parse(&text).expect("loads").views.len(), 1); } + /// ASAPQuery-backend's control plane copies the collector's + /// `window_close_delay_ms` into the file: it loads, and is ignored. + #[test] + fn a_file_with_the_window_close_delay_loads() { + let text = q01_with(|f| f["window_close_delay_ms"] = 6000.into()); + assert_eq!(parse(&text).expect("loads").views.len(), 1); + } + #[test] fn unknown_fields_are_refused() { let text = q01_with(|f| f["extra"] = 1.into()); diff --git a/asap-precompute-rs/src/otap/schema.rs b/asap-precompute-rs/src/otap/schema.rs index 39d764d..7596ce1 100644 --- a/asap-precompute-rs/src/otap/schema.rs +++ b/asap-precompute-rs/src/otap/schema.rs @@ -31,6 +31,19 @@ pub const META_NODE_ID: &str = "asap.node_id"; /// Metric metadata of a collector view's state: the planner's /// `ViewStateKey`, as JSON (string). pub const META_VIEW_STATE_KEY: &str = "asap.view_state_key"; +/// Metric metadata of a collector view's state: the producer epoch, the +/// sending collector instance's random start id, as decimal text (string). +pub const META_PRODUCER_EPOCH: &str = "asap.producer_epoch"; +/// A collector view state's place in its lineage, 0 for a full (RECORD, int). +pub const ATTR_SEQUENCE: &str = "asap.sequence"; +/// `"full"` or `"delta"` (RECORD, string). +pub const ATTR_STATE_KIND: &str = "asap.state_kind"; +/// A delta's base: its sequence − 1 (RECORD, int; deltas only). +pub const ATTR_BASE_SEQUENCE: &str = "asap.base_sequence"; +/// [`ATTR_STATE_KIND`] of a full state. +pub const STATE_KIND_FULL: &str = "full"; +/// [`ATTR_STATE_KIND`] of a delta. +pub const STATE_KIND_DELTA: &str = "delta"; /// A collector view's metric is named `.asap_view.`; /// names containing it are reserved. pub const VIEW_NAME_INFIX: &str = ".asap_view."; diff --git a/asap-precompute-rs/src/otap/view_executor.rs b/asap-precompute-rs/src/otap/view_executor.rs index ffedbd3..2c720b9 100644 --- a/asap-precompute-rs/src/otap/view_executor.rs +++ b/asap-precompute-rs/src/otap/view_executor.rs @@ -46,6 +46,18 @@ //! ([`ViewExecutor::counts`]). A run that fails anyway loses that window //! only ([`Closed::failures`]). //! +//! Emissions and lineages: [`ViewExecutor::emit_open`] seals every open +//! window's current run without closing the window (a later sample starts a +//! new run), so a window may be emitted several times: open, at its close, +//! and in corrections. Each emission holds the samples taken since the +//! previous one. Per run group, window and series (keyed by a hash of the +//! series key, which outlives its reusable id) the executor numbers the +//! emissions 0, 1, 2, … within its producer epoch, kept while the window is +//! within retention: 0 is a full, every later one a delta on the one before +//! ([`Lineage`]). For DDSketch a delta is exactly the new samples' bucket +//! counts; for KLL it is a KLL of the new samples, which merges within the +//! sketch's rank error. +//! //! Runs execute on one single-threaded [`LocalPool`], driven to a stall after //! every batch and every close; nothing here blocks. @@ -81,7 +93,7 @@ use futures::StreamExt; use super::config::SKETCH_TYPES; use super::planner_views::{CollectorView, PlannerViews}; -use crate::envelope::{SketchEnvelope, SketchType, ViewIdentity}; +use crate::envelope::{Lineage, SketchEnvelope, SketchType, ViewIdentity}; use crate::matchers::write_series_key; use crate::observation::{KeyValue, Observation, ObservationValueKind, SourceDescriptor}; use crate::window::window_end_ms; @@ -98,6 +110,8 @@ type Row = (u32, u64, f64); /// The collector views of one installed plan, built on the executor. pub struct ViewExecutor { + /// This instance's producer epoch, stamped on every state's lineage. + epoch: u64, compiled: CompiledPhysicalDAG, /// The views, by source metric name. metrics: HashMap, @@ -180,6 +194,13 @@ struct RunGroup { windows: BTreeMap, /// Open correction runs of closed windows, by window end (ms). corrections: BTreeMap, + /// Per window end (ms) still within retention, per series (by the hash + /// of its key, which outlives its reusable id), the sequence of its next + /// state. Every view of the group filters series by labels only, so a + /// series has a state in every view taking it whenever it has one in + /// any: one sequence per (group, series, window) is the sequence of + /// each (view, series, window) lineage. + sequences: BTreeMap>, /// The on-time samples taken since the last flush. rows: Vec, /// The late samples within retention taken since the last flush. @@ -268,6 +289,11 @@ impl ViewExecutor { /// outputs by source metric and tumbling width. Fails on a view whose /// states the collector cannot encode. pub fn new(views: &PlannerViews) -> Result { + Self::with_epoch(views, random_epoch()) + } + + /// [`Self::new`] with producer epoch `epoch` (tests, and golden bytes). + pub fn with_epoch(views: &PlannerViews, epoch: u64) -> Result { let roots: Vec = views.views.iter().map(|v| v.identity.node_id).collect(); let compiled = compile(&views.dag, &[], &roots)?; let mut metrics: HashMap = HashMap::default(); @@ -297,6 +323,7 @@ impl ViewExecutor { metric.groups[group].add(index, view, &views.dag, &compiled)?; } Ok(Self { + epoch, compiled, metrics, pool: LocalPool::new(), @@ -356,10 +383,27 @@ impl ViewExecutor { pub fn flush(&mut self) -> Closed { let mut closed = Closed::default(); self.send(&mut closed); - self.seal(&mut closed, false); + self.seal(&mut closed, false, false); + closed + } + + /// Like [`Self::flush`], then emits every open window's samples taken + /// since its last emission, leaving the window open: a later sample of + /// it starts a new run, emitted at the next emission or the close as a + /// delta on this one. The processor calls it every + /// `open_window_emit_interval_ms`. + pub fn emit_open(&mut self) -> Closed { + let mut closed = Closed::default(); + self.send(&mut closed); + self.seal(&mut closed, false, true); closed } + /// This instance's producer epoch. + pub fn epoch(&self) -> u64 { + self.epoch + } + /// Like [`Self::flush`], then closes every window ending before the /// window holding `now_ms` (the processor's idle timer, `now_ms` already /// less its grace) and every correction run. @@ -370,7 +414,7 @@ impl ViewExecutor { let through = window_end_ms(now_ms, group.width_ms).saturating_sub(group.width_ms); group.closed_through_ms = group.closed_through_ms.max(through); } - self.seal(&mut closed, true); + self.seal(&mut closed, true, false); closed } @@ -384,7 +428,7 @@ impl ViewExecutor { group.closed_through_ms = group.closed_through_ms.max(last); } } - self.seal(&mut closed, true); + self.seal(&mut closed, true, false); closed } @@ -411,10 +455,12 @@ impl ViewExecutor { self.pool.run_until_stalled(); } - /// Ends the run of every window its group has closed, and with - /// `corrections` every correction run, encodes the states, and evicts - /// the series no open window or correction run holds. - fn seal(&mut self, closed: &mut Closed, corrections: bool) { + /// Ends the run of every window its group has closed, with `open` every + /// open window's run too (the window stays open), and with + /// `corrections` every correction run; encodes the states, each with the + /// next sequence of its lineage; and evicts the series no open window or + /// correction run holds. + fn seal(&mut self, closed: &mut Closed, corrections: bool, open: bool) { // (metric, group, window end, run result, is a correction). let mut closing = Vec::new(); for (name, metric) in &mut self.metrics { @@ -432,6 +478,11 @@ impl ViewExecutor { closing.push((name.clone(), index, end, run.result, false)); } } + if open { + for (end, run) in std::mem::take(&mut group.windows) { + closing.push((name.clone(), index, end, run.result, false)); + } + } if corrections { for (end, run) in std::mem::take(&mut group.corrections) { closing.push((name.clone(), index, end, run.result, true)); @@ -444,8 +495,12 @@ impl ViewExecutor { } self.pool.run_until_stalled(); for (name, index, end, result, correction) in &closing { - let metric = &self.metrics[name]; - let group = &metric.groups[*index]; + let metric = self.metrics.get_mut(name).expect("a closing metric"); + let group = &mut metric.groups[*index]; + let sequences = group.sequences.entry(*end).or_default(); + // One sequence per series of this run, shared by its views. + let mut of_run: HashMap = HashMap::new(); + let epoch = self.epoch; let outcome = result .borrow_mut() .take() @@ -456,6 +511,16 @@ impl ViewExecutor { }) .and_then(|outputs| { let mut states = Vec::new(); + let mut lineage = |series: &Series| Lineage { + producer_epoch: epoch, + sequence: *of_run + .entry(key_hash(&series.key)) + .or_insert_with_key(|hash| { + let next = sequences.entry(*hash).or_insert(0); + *next += 1; + *next - 1 + }), + }; for (view, batches) in group.views.iter().zip(&outputs) { for batch in batches { encode( @@ -464,6 +529,7 @@ impl ViewExecutor { *end, group.width_ms, &metric.series, + &mut lineage, &mut states, )?; } @@ -481,6 +547,9 @@ impl ViewExecutor { for (name, ..) in &closing { if let Some(metric) = self.metrics.get_mut(name) { metric.evict_closed_series(); + for group in &mut metric.groups { + group.forget_past_retention(); + } } } } @@ -547,6 +616,7 @@ impl RunGroup { closed_through_ms: 0, windows: BTreeMap::new(), corrections: BTreeMap::new(), + sequences: BTreeMap::new(), rows: Vec::new(), late_rows: Vec::new(), } @@ -644,6 +714,14 @@ impl RunGroup { > self.closed_through_ms + self.width_ms } + /// Forgets the sequences of windows past retention: no correction of + /// them is sent any more. + fn forget_past_retention(&mut self) { + let newest_end = self.closed_through_ms + self.width_ms; + self.sequences + .retain(|&end, _| end + self.retention_ms > newest_end); + } + /// Sends the rows taken since the last flush to the runs of their /// windows, and the late rows to their windows' correction runs, one /// batch per window and `Scan` schema, opening runs as needed. A window @@ -899,6 +977,7 @@ fn encode( end_ms: u64, width_ms: u64, series: &[Option], + lineage: &mut impl FnMut(&Series) -> Lineage, out: &mut Vec, ) -> Result<(), Error> { let fields = &batch.schema().fields; @@ -936,11 +1015,31 @@ fn encode( count, aggregation_temporality: DELTA_TEMPORALITY, value: 0.0, + lineage: Some(lineage(series)), }); } Ok(()) } +/// A stable hash of a series key (SipHash with fixed keys), naming the +/// series across id reuse. +fn key_hash(key: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + key.hash(&mut hasher); + hasher.finish() +} + +/// A random producer epoch: the process's randomly keyed hasher over the +/// wall clock and the process id. +fn random_epoch() -> u64 { + use std::hash::BuildHasher; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + std::collections::hash_map::RandomState::new().hash_one((now, std::process::id())) +} + /// State `index` of `states` as ASAPv1 bytes, and the samples it holds. fn asapv1( sketch: SketchAlgorithm, @@ -1441,6 +1540,200 @@ mod tests { } } + /// `samples()` with window T's offset-10 samples held back as in + /// [`build_with_late`], through an executor of epoch 7 that also emits + /// its open windows after every third flush: every state, open-window + /// emissions, closes and corrections alike, by (view, series, window), + /// in emission order. + fn build_open_with_late(file: &str) -> Map<(u64, String, u64), Vec> { + let (late, on_time): (Vec, Vec) = samples() + .into_iter() + .partition(|obs| obs.timestamp_ms == T - 5_000 + 10); + let views = super::super::planner_views::parse(file).unwrap(); + let mut executor = ViewExecutor::with_epoch(&views, 7).unwrap(); + let mut all = Vec::new(); + for (i, chunk) in on_time.chunks(7).enumerate() { + for obs in chunk { + executor.observe(obs); + } + all.extend(states(executor.flush())); + if i % 3 == 2 { + all.extend(states(executor.emit_open())); + } + } + for obs in &late { + executor.observe(obs); + } + all.extend(states(executor.flush())); + let closed = executor.drain(); + all.extend(closed.corrections.clone()); + all.extend(states(closed)); + let mut by_lineage: Map<(u64, String, u64), Vec> = Map::new(); + for state in all { + let key = ( + state.view.as_ref().unwrap().node_id, + series_key(&state.resource_labels, &state.labels), + state.window_end_ms, + ); + by_lineage.entry(key).or_default().push(state); + } + for (key, states) in &by_lineage { + let sequences: Vec = states + .iter() + .map(|s| { + let lineage = s.lineage.expect("a view state has a lineage"); + assert_eq!(lineage.producer_epoch, 7); + lineage.sequence + }) + .collect(); + assert_eq!( + sequences, + (0..states.len() as u64).collect::>(), + "{key:?}: a full, then deltas in order" + ); + } + assert!( + by_lineage.values().any(|states| states.len() >= 3), + "some windows are emitted open, at close and corrected" + ); + by_lineage + } + + /// DDSketch: a window's full and its deltas (open-window emissions, the + /// close, a correction) merged in order are byte-for-byte the state the + /// same samples give emitted once at close. + #[test] + fn ddsketch_full_and_deltas_equal_the_at_close_state() { + let at_close = by_key(&build(Q01, &samples(), 7)) + .into_iter() + .map(|(key, s)| (key, s.payload.clone())) + .collect::>(); + let merged: Map<_, Vec> = build_open_with_late(Q01) + .into_iter() + .map(|(key, states)| { + let mut sketch = DdSketch::from_asapv1(&states[0].payload).unwrap(); + for delta in &states[1..] { + sketch + .merge(&DdSketch::from_asapv1(&delta.payload).unwrap()) + .unwrap(); + } + (key, sketch.to_asapv1().unwrap()) + }) + .collect(); + assert_eq!(merged, at_close); + } + + /// KLL: a window's full and its deltas merged answer every quantile + /// within KLL k = 200's rank error (1.65 %) of the at-close state. + #[test] + fn kll_full_and_deltas_are_within_the_bound_of_the_at_close_state() { + use asap_sketchlib::Kll; + let file = kll_q01(); + let at_close = build(&file, &samples(), 7); + let at_close = by_key(&at_close); + let merged = build_open_with_late(&file); + assert_eq!(merged.len(), at_close.len()); + for (key, states) in &merged { + let mut sketch: Kll = Kll::from_asapv1(&states[0].payload).unwrap(); + for delta in &states[1..] { + sketch.merge(&Kll::from_asapv1(&delta.payload).unwrap()); + } + let reference: Kll = Kll::from_asapv1(&at_close[key].payload).unwrap(); + assert_eq!(sketch.count(), reference.count(), "{key:?}"); + let n = reference.count() as f64; + for q in [0.1, 0.25, 0.5, 0.75, 0.9, 0.99] { + let error = (reference.rank(sketch.quantile(q)) as f64 + - reference.rank(reference.quantile(q)) as f64) + .abs() + / n; + assert!(error <= 0.0165, "{key:?} q{q}: rank error {error}"); + } + } + } + + /// Two corrections of one series' window with equal bytes (two late + /// samples of equal value, sent at two ticks) are two records: deltas + /// 1 on base 0 and 2 on base 1. + #[test] + fn corrections_with_equal_bytes_have_distinct_sequences() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut executor = ViewExecutor::with_epoch(&views, 3).unwrap(); + executor.observe(&sample(0, T - 3_000, 1.0)); + executor.observe(&sample(0, T + 2_000, 1.0)); + let closed = states(executor.flush()); + assert_eq!(closed.len(), 1, "window T closes"); + assert_eq!( + closed[0].lineage, + Some(Lineage { + producer_epoch: 3, + sequence: 0 + }) + ); + let mut corrections = Vec::new(); + for _ in 0..2 { + executor.observe(&sample(0, T - 1_000, 4.0)); + executor.flush(); + // The clock at T: closes no further window, only corrections. + let closed = executor.close_idle(T); + corrections.extend(closed.corrections); + } + assert_eq!(corrections.len(), 2); + assert_eq!(corrections[0].payload, corrections[1].payload); + let lineages: Vec<(u64, Option)> = corrections + .iter() + .map(|c| { + let l = c.lineage.unwrap(); + (l.sequence, l.base_sequence()) + }) + .collect(); + assert_eq!(lineages, [(1, Some(0)), (2, Some(1))]); + } + + /// A restarted collector (a new executor, so a new epoch) starts its own + /// lineage of a window the previous one already emitted: a full, 0. + #[test] + fn a_restart_starts_each_window_with_a_full_of_a_new_epoch() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut before = ViewExecutor::with_epoch(&views, 1).unwrap(); + before.observe(&sample(0, T - 3_000, 1.0)); + let first = states(before.emit_open()); + assert_eq!(first[0].lineage.unwrap().sequence, 0); + before.observe(&sample(0, T - 2_000, 2.0)); + assert_eq!(states(before.emit_open())[0].lineage.unwrap().sequence, 1); + let mut after = ViewExecutor::new(&views).unwrap(); + assert_ne!(after.epoch(), before.epoch()); + after.observe(&sample(0, T - 1_000, 3.0)); + let restarted = states(after.drain()); + assert_eq!( + restarted[0].lineage, + Some(Lineage { + producer_epoch: after.epoch(), + sequence: 0 + }) + ); + assert_eq!(restarted[0].window_end_ms, T); + } + + /// An open-window emission keeps the window open: its later samples are + /// on time and are emitted at its close as a delta on the open one; an + /// emission with no new sample sends nothing. + #[test] + fn open_window_emission_keeps_the_window_open() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut executor = ViewExecutor::with_epoch(&views, 5).unwrap(); + executor.observe(&sample(0, T - 4_000, 1.0)); + let open = states(executor.emit_open()); + assert_eq!((open.len(), open[0].count), (1, 1)); + assert!(states(executor.emit_open()).is_empty(), "nothing new"); + executor.observe(&sample(0, T - 1_000, 2.0)); + let closed = executor.drain(); + assert!(closed.corrections.is_empty(), "on time, not a correction"); + let closed = states(closed); + assert_eq!(closed.len(), 1); + assert_eq!(closed[0].count, 1); + assert_eq!(closed[0].lineage.unwrap().sequence, 1); + } + /// Out of order within an open window is on time. A sample of a window a /// later sample, the idle close or a drain closed is late: within the /// view's 60 s retention (counted back from the group's newest window) diff --git a/asap-precompute-rs/src/precompute.rs b/asap-precompute-rs/src/precompute.rs index 6493224..04bd3b1 100644 --- a/asap-precompute-rs/src/precompute.rs +++ b/asap-precompute-rs/src/precompute.rs @@ -474,6 +474,7 @@ impl PrecomputeImpl { count: entry.count, aggregation_temporality: cfg.temporality, value: p.value, + lineage: None, } }) .collect(); @@ -499,6 +500,7 @@ impl PrecomputeImpl { count: entry.count, aggregation_temporality: cfg.temporality, value: 0.0, + lineage: None, }]) } } diff --git a/asap-precompute-rs/tests/collector_views_e2e.rs b/asap-precompute-rs/tests/collector_views_e2e.rs index a86c958..21e81e9 100644 --- a/asap-precompute-rs/tests/collector_views_e2e.rs +++ b/asap-precompute-rs/tests/collector_views_e2e.rs @@ -17,6 +17,7 @@ use otel_arrow_dfe_config::node::NodeUserConfig; use otel_arrow_dfe_config::observed_state::{ObservedStateSettings, SendPolicy}; use otel_arrow_dfe_config::pipeline::PipelineConfig; use otel_arrow_dfe_config::policy::{ChannelCapacityPolicy, TelemetryPolicy}; +use otel_arrow_dfe_config::SignalType; use otel_arrow_dfe_config::{DeployedPipelineKey, PipelineGroupId, PipelineId}; use otel_arrow_dfe_engine::capability::registry::Capabilities; use otel_arrow_dfe_engine::config::{ExporterConfig, ReceiverConfig}; @@ -461,14 +462,19 @@ fn stream(batches: u64) -> Vec { } /// The states the executor emits for [`stream`] (12 s, three windows), as -/// the OTLP bytes the exporter sends, are the golden bytes: decoding and -/// series interning may change, the states and their encoding may not. Set -/// `ASAP_UPDATE_GOLDEN=1` to rewrite the file. +/// the OTLP bytes the exporter sends, are the golden bytes apart from their +/// lineage: with open-window emission off, every state is its window's +/// full (sequence 0), and removing `asap.producer_epoch` from each metric's +/// metadata and `asap.sequence` / `asap.state_kind` from each point leaves +/// exactly the message the golden file holds (the file predates lineages and +/// is unchanged). Decoding and series interning may change, the states and +/// their encoding may not. Set `ASAP_UPDATE_GOLDEN=1` to rewrite the file +/// from the stripped messages. #[test] fn emitted_states_match_the_golden_bytes() { let views = planner_views::load(std::path::Path::new(FIXTURE)).unwrap(); - let mut executor = ViewExecutor::new(&views).unwrap(); - let mut emitted = Vec::new(); + let mut executor = ViewExecutor::with_epoch(&views, 42).unwrap(); + let mut emitted: Vec = Vec::new(); let mut take = |closed: asap_precompute_rs::otap::view_executor::Closed| { assert!(closed.failures.is_empty(), "{:?}", closed.failures); assert!( @@ -478,12 +484,9 @@ fn emitted_states_match_the_golden_bytes() { if closed.states.is_empty() { return; } - let (_, payload) = encode_envelopes_to_pdata(&closed.states) - .unwrap() - .into_parts(); - let bytes: OtlpProtoBytes = payload.try_into_with_default().unwrap(); - emitted.extend((bytes.as_bytes().len() as u32).to_le_bytes()); - emitted.extend(bytes.as_bytes()); + let mut data = otlp(encode_envelopes_to_pdata(&closed.states).unwrap()); + strip_full_lineage(&mut data, 42); + emitted.push(data); }; for data in stream(12) { decode_each(pdata(data), |obs| executor.observe(obs)).unwrap(); @@ -495,11 +498,82 @@ fn emitted_states_match_the_golden_bytes() { "/tests/golden/collector-views-states.bin" ); if std::env::var_os("ASAP_UPDATE_GOLDEN").is_some() { - std::fs::write(path, &emitted).unwrap(); + let mut bytes = Vec::new(); + for data in &emitted { + let otlp: OtlpProtoBytes = + OtapPayload::try_from(OtlpProtoMessage::Metrics(data.clone())) + .unwrap() + .try_into_with_default() + .unwrap(); + bytes.extend((otlp.as_bytes().len() as u32).to_le_bytes()); + bytes.extend(otlp.as_bytes()); + } + std::fs::write(path, &bytes).unwrap(); + } + let golden = std::fs::read(path).unwrap(); + assert!(golden.len() > 10_000, "states of three windows"); + let mut rest = golden.as_slice(); + let mut expected = Vec::new(); + while !rest.is_empty() { + let len = u32::from_le_bytes(rest[..4].try_into().unwrap()) as usize; + let bytes = OtlpProtoBytes::new_from_bytes(SignalType::Metrics, rest[4..4 + len].to_vec()); + let OtlpProtoMessage::Metrics(data) = OtlpProtoMessage::try_from(bytes).unwrap() else { + panic!("metrics"); + }; + expected.push(data); + rest = &rest[4 + len..]; } - assert!(emitted.len() > 10_000, "states of three windows"); assert!( - emitted == std::fs::read(path).unwrap(), - "the emitted states differ from {path}" + emitted == expected, + "the emitted states, less their lineage, differ from {path}" ); } + +/// Removes the lineage of `data`'s collector view states, checking that each +/// is a full of epoch `epoch`: the metric's `asap.producer_epoch` metadata +/// and the point's `asap.sequence` (0) and `asap.state_kind` (`"full"`). +fn strip_full_lineage(data: &mut MetricsData, epoch: u64) { + let text = |kv: &KeyValue| match kv.value.as_ref().and_then(|v| v.value.as_ref()) { + Some(AnyValueKind::StringValue(s)) => Some(s.clone()), + _ => None, + }; + let int = |kv: &KeyValue| match kv.value.as_ref().and_then(|v| v.value.as_ref()) { + Some(AnyValueKind::IntValue(v)) => Some(*v), + _ => None, + }; + for metric in data + .resource_metrics + .iter_mut() + .flat_map(|r| &mut r.scope_metrics) + .flat_map(|s| &mut s.metrics) + { + let before = metric.metadata.len(); + metric.metadata.retain(|kv| { + if kv.key != "asap.producer_epoch" { + return true; + } + assert_eq!(text(kv), Some(epoch.to_string())); + false + }); + assert_eq!(before, metric.metadata.len() + 1, "one producer epoch"); + let Some(Data::Summary(summary)) = &mut metric.data else { + panic!("a collector view's state is a Summary point"); + }; + for point in &mut summary.data_points { + let before = point.attributes.len(); + point.attributes.retain(|kv| match kv.key.as_str() { + "asap.sequence" => { + assert_eq!(int(kv), Some(0), "a full"); + false + } + "asap.state_kind" => { + assert_eq!(text(kv).as_deref(), Some("full")); + false + } + "asap.base_sequence" => panic!("a full has no base"), + _ => true, + }); + assert_eq!(before, point.attributes.len() + 2); + } + } +} diff --git a/asap-precompute-rs/tests/fixtures/collector-views/q01/otlp-body.pb b/asap-precompute-rs/tests/fixtures/collector-views/q01/otlp-body.pb index 48cd55b89219f59d389382bba0492d69b2502d5c..de20a2ab41c5817d30314783dd4ee0f9f1679c5f 100644 GIT binary patch delta 174 zcmbQs+RMhw)zLPQSw;O(YXbvULqh|D&9FP=0M5-jQBsD%eGcQG`4J68vR+^Ku zxqwlZ(Ija-NI)2@te_}Ar8GIUC_c3yKRH8aDp#% C&Nw#! delta 60 zcmeBWo6E|~HKTPRvx@qsmIel{hK2?Pp%);QKuTgsqF!QgVnKXaW@@>fVbuO6pzyAZ NeoBm+*D&fb0sv*}6ifgB diff --git a/asap-precompute-rs/tests/otap_pipeline_e2e.rs b/asap-precompute-rs/tests/otap_pipeline_e2e.rs index fe54d94..1c15059 100644 --- a/asap-precompute-rs/tests/otap_pipeline_e2e.rs +++ b/asap-precompute-rs/tests/otap_pipeline_e2e.rs @@ -63,6 +63,7 @@ fn scalar_input(start: i32, end: i32) -> OtapPdata { count: 0, aggregation_temporality: 0, value: f64::from(value), + lineage: None, }) .collect::>(); encode_envelopes_to_pdata(&observations).expect("encode scalar input") diff --git a/docs/data_model.md b/docs/data_model.md index 578009a..ebb6f7f 100644 --- a/docs/data_model.md +++ b/docs/data_model.md @@ -349,9 +349,18 @@ OTAP structure, not the `sketch.*` carrier above: | Tier | Raw sample | Collector view state | |---|---|---| -| Schema (Metric) | name, type, unit, description | name `.asap_view.`, type Summary, the source metric's unit and description, `Metric.metadata`: `asap.plan_id` (string), `asap.node_id` (int), `asap.view_state_key` (the planner's `ViewStateKey`, JSON) | +| Schema (Metric) | name, type, unit, description | name `.asap_view.`, type Summary, the source metric's unit and description, `Metric.metadata`: `asap.plan_id` (string), `asap.node_id` (int), `asap.view_state_key` (the planner's `ViewStateKey`, JSON), `asap.producer_epoch` (the collector instance, a random u64 as decimal text) | | Dictionary | Resource, Scope and point attributes | the same, as received (no `sketch.*` Resource attributes, no `sketch.series_id`) | -| Record | `time_unix_nano` + value | Summary point: window `(start_time_unix_nano, time_unix_nano]`, `count`, point attribute `sketch.envelope` (ASAPv1) | +| Record | `time_unix_nano` + value | Summary point: window `(start_time_unix_nano, time_unix_nano]`, `count`, point attributes `sketch.envelope` (ASAPv1), `asap.sequence` (int), `asap.state_kind` (`"full"` or `"delta"`), `asap.base_sequence` (int, deltas only) | + +A view state's lineage is the records one collector instance (its producer +epoch) sends for one (view, series, window): a full with sequence 0, then +deltas `n ≥ 1` on base `n − 1`, each the state of the samples folded since +the previous record (an open-window emission with the processor's +`open_window_emit_interval_ms`, the close, a correction). ASAPQuery-backend +merges a delta only onto its exact base and drops duplicates by +`(epoch, sequence)`; its `docs/design/collector-sketch-ingest.md` (section 8) +defines the receiver rules. The sketch type of a view state is read from θ in its view state key. OTAP Arrow keeps the metadata in its metric attribute table, and the OTAP to OTLP