diff --git a/asap-precompute-rs/src/otap/codec.rs b/asap-precompute-rs/src/otap/codec.rs index 7621986..710cd48 100644 --- a/asap-precompute-rs/src/otap/codec.rs +++ b/asap-precompute-rs/src/otap/codec.rs @@ -1478,28 +1478,181 @@ pub fn decode_pdata_to_observations(pdata: OtapPdata) -> Result Result { + decode_into( + pdata, + ObservationSink { + scratch: Observation::default(), + f, + }, + ) +} + +/// Walks `pdata` like [`decode_each`], passing only its float points to `f`, +/// each as a [`ScalarPoint`] whose labels are still the encoded +/// [`ScalarPoint::identity`]: no label is copied or checked as UTF-8 unless +/// the caller asks for it ([`ScalarPoint::labels`]). A point carrying a +/// sketch envelope is checked as [`decode_each`] checks it, then skipped. +pub fn decode_each_scalar( + pdata: OtapPdata, + f: impl FnMut(&ScalarPoint<'_>), +) -> Result { + decode_into(pdata, ScalarSink(f)) +} + +/// [`decode_each`] and [`decode_each_scalar`] over either representation. +fn decode_into(pdata: OtapPdata, sink: impl PointSink) -> Result { let (_context, payload) = pdata.into_parts(); match payload.into_data() { PayloadData::OtlpBytes(OtlpProtoBytes::ExportMetricsRequest(bytes)) => { let view = RawMetricsData::try_new(&bytes).map_err(|e| CodecError::Decode(format!("{e}")))?; - decode_view(&view, f) + decode_view(&view, sink) } PayloadData::OtlpBytes(_) => Ok(0), PayloadData::OtapArrowRecords(records @ OtapArrowRecords::Metrics(_)) => { let view = OtapMetricsView::try_from(&records) .map_err(|e| CodecError::Decode(format!("{e}")))?; - decode_view(&view, f) + decode_view(&view, sink) } PayloadData::OtapArrowRecords(_) => Ok(0), } } +/// One float data point, read in place: its labels stay encoded in +/// [`Self::identity`] until [`Self::labels`] decodes them. +pub struct ScalarPoint<'a> { + /// Metric name. + pub metric: &'a str, + /// Point timestamp (ms). + pub timestamp_ms: u64, + /// The value (an integer point's, as `f64`). + pub value: f64, + /// The Resource's string attributes, as [`Observation::resource_labels`]. + pub resource_labels: &'a [KeyValue], + /// As [`Observation::source`]. + pub source: &'a Arc, + /// The point's series identity: its resource labels, its series scope + /// labels and its string attributes, in received order, each section a + /// `u32` count of `(u32 length, key, u32 length, value)` pairs (the + /// attributes' section runs to the end without a count). Two points of + /// equal identity are of one series; the converse holds only for + /// attributes received in the same order. + pub identity: &'a [u8], + /// The series scope's labels ([`Observation::labels`] starts with them). + series_labels: &'a [KeyValue], + /// Where the point's attributes start in `identity`. + attributes_at: usize, +} + +impl ScalarPoint<'_> { + /// [`Observation::labels`] of this point: the series scope's labels, + /// then each string attribute (read as UTF-8 lossily). + pub fn labels(&self) -> Vec { + let mut labels = Vec::new(); + self.write_labels(&mut labels); + labels + } + + /// Writes [`Self::labels`] into `labels`, reusing its buffers. + fn write_labels(&self, labels: &mut Vec) { + for (index, label) in self.series_labels.iter().enumerate() { + set_label(labels, index, label.key.as_bytes(), label.value.as_bytes()); + } + let mut count = self.series_labels.len(); + for (key, value) in identity_pairs(&self.identity[self.attributes_at..]) { + set_label(labels, count, key, value); + count += 1; + } + labels.truncate(count); + } +} + +/// Appends one `(key, value)` pair to an identity (see +/// [`ScalarPoint::identity`]). +fn push_identity_pair(identity: &mut Vec, key: &[u8], value: &[u8]) { + for part in [key, value] { + identity.extend_from_slice(&(part.len() as u32).to_le_bytes()); + identity.extend_from_slice(part); + } +} + +/// Appends one counted section of labels to an identity. +fn push_identity_labels(identity: &mut Vec, labels: &[KeyValue]) { + identity.extend_from_slice(&(labels.len() as u32).to_le_bytes()); + for label in labels { + push_identity_pair(identity, label.key.as_bytes(), label.value.as_bytes()); + } +} + +/// The `(key, value)` pairs of an identity's uncounted attribute section. +fn identity_pairs(mut bytes: &[u8]) -> impl Iterator { + let mut part = move || { + let (len, rest) = bytes.split_first_chunk::<4>()?; + let (part, rest) = rest.split_at(u32::from_le_bytes(*len) as usize); + bytes = rest; + Some(part) + }; + std::iter::from_fn(move || Some((part()?, part()?))) +} + +/// Where the walk passes each data point. +trait PointSink { + /// A float point. + fn scalar(&mut self, point: &ScalarPoint<'_>); + /// A point carrying a sketch envelope (any metric type). + fn envelope(&mut self, observation: &Observation); +} + +/// [`decode_each`]'s sink: every point as an [`Observation`], rewritten in +/// one buffer. +struct ObservationSink { + scratch: Observation, + f: F, +} + +impl PointSink for ObservationSink { + fn scalar(&mut self, point: &ScalarPoint<'_>) { + let obs = &mut self.scratch; + point.write_labels(&mut obs.labels); + obs.value = ObservationValue::float(point.value); + obs.timestamp_ms = point.timestamp_ms; + if obs.metric != point.metric { + obs.metric.clear(); + obs.metric.push_str(point.metric); + } + if !Arc::ptr_eq(&obs.source, point.source) { + obs.source = Arc::clone(point.source); + } + if obs.resource_labels.as_slice() != point.resource_labels { + obs.resource_labels.clear(); + obs.resource_labels.extend_from_slice(point.resource_labels); + } + (self.f)(obs); + } + + fn envelope(&mut self, observation: &Observation) { + (self.f)(observation); + } +} + +/// [`decode_each_scalar`]'s sink. +struct ScalarSink(F); + +impl)> PointSink for ScalarSink { + fn scalar(&mut self, point: &ScalarPoint<'_>) { + (self.0)(point); + } + + fn envelope(&mut self, _: &Observation) {} +} + /// [`decode_each`] over either representation's view. -fn decode_view(view: &V, f: impl FnMut(&Observation)) -> Result { +fn decode_view(view: &V, sink: S) -> Result { let mut acc = DecodeAccumulator { + identity: Vec::new(), + identity_prefix: 0, scratch: Observation::default(), - sink: f, + sink, }; let mut skipped_non_scalar = 0usize; @@ -1558,6 +1711,10 @@ fn decode_view(view: &V, f: impl FnMut(&Observation)) -> Result< } } } + acc.identity.clear(); + push_identity_labels(&mut acc.identity, &resource_labels); + push_identity_labels(&mut acc.identity, &series_labels); + acc.identity_prefix = acc.identity.len(); for metric in scope.metrics() { let name = String::from_utf8_lossy(metric.name()).into_owned(); let Some(data) = metric.data() else { @@ -1654,10 +1811,14 @@ fn set_text(text: &mut String, bytes: &[u8]) { /// point body twice, or trying to unify their different concrete /// iterator types into one `Vec` first (which doesn't compile — /// `gauge`/`sum` would need to outlive the branch that produced them). -struct DecodeAccumulator { - /// Rewritten for each data point. +struct DecodeAccumulator { + /// The data point's [`ScalarPoint::identity`], rewritten for each one + /// after the scope's `identity_prefix` bytes. + identity: Vec, + identity_prefix: usize, + /// Rewritten for each data point carrying a sketch envelope. scratch: Observation, - sink: F, + sink: S, } /// Parses an optional `sketch.type` value; absent means `Unspecified`. @@ -1815,7 +1976,7 @@ fn decode_lineage( Ok(Some(lineage)) } -impl DecodeAccumulator { +impl DecodeAccumulator { fn push_summary_data_point( &mut self, dp: D, @@ -1892,7 +2053,7 @@ impl DecodeAccumulator { ObservationValue::envelope(envelope), ); observation.source = Arc::clone(&metric.source); - (self.sink)(&observation); + self.sink.envelope(&observation); Ok(()) } @@ -1918,95 +2079,89 @@ impl DecodeAccumulator { let timestamp_ms = dp.time_unix_nano() / 1_000_000; let mut envelope_bytes: Option> = None; - let mut sketch_type_raw = inherited_schema.sketch_type.clone(); + // `Some` once the point names its own sketch type. + let mut sketch_type_raw: Option> = None; let mut schema_version = inherited_schema.schema_version; let mut window_start_ms: Option = None; let mut window_end_ms: Option = None; - let obs = &mut self.scratch; - for (index, label) in series_labels.iter().enumerate() { - set_label( - &mut obs.labels, - index, - label.key.as_bytes(), - label.value.as_bytes(), - ); - } - let mut label_count = series_labels.len(); + self.identity.truncate(self.identity_prefix); for attr in dp.attributes() { let Some(val) = attr.value() else { continue }; let key = attr.key(); - match std::str::from_utf8(key).unwrap_or_default() { - ATTR_ENVELOPE => envelope_bytes = val.as_bytes().map(<[u8]>::to_vec), - ATTR_SKETCH_TYPE => { - sketch_type_raw = val - .as_string() - .map(|s| String::from_utf8_lossy(s).into_owned()); - } - ATTR_SCHEMA_VERSION => { - schema_version = val.as_int64().filter(|v| *v >= 0).map(|v| v as u32); - } - ATTR_WINDOW_START_MS => { - window_start_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64); - } - ATTR_WINDOW_END_MS => { - window_end_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64); - } - _ => { - // Non-reserved: treated as a per-row label. Only - // string-typed values are representable as a label; - // a non-string, non-reserved attribute is dropped. - if let Some(s) = val.as_string() { - set_label(&mut obs.labels, label_count, key, s); - label_count += 1; - } - } + // Compared as bytes: a key that is not UTF-8 is no reserved one. + if key == ATTR_ENVELOPE.as_bytes() { + envelope_bytes = val.as_bytes().map(<[u8]>::to_vec); + } else if key == ATTR_SKETCH_TYPE.as_bytes() { + sketch_type_raw = Some( + val.as_string() + .map(|s| String::from_utf8_lossy(s).into_owned()), + ); + } else if key == ATTR_SCHEMA_VERSION.as_bytes() { + schema_version = val.as_int64().filter(|v| *v >= 0).map(|v| v as u32); + } else if key == ATTR_WINDOW_START_MS.as_bytes() { + window_start_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64); + } else if key == ATTR_WINDOW_END_MS.as_bytes() { + window_end_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64); + } else if let Some(s) = val.as_string() { + // Non-reserved: treated as a per-row label. Only + // string-typed values are representable as a label; + // a non-string, non-reserved attribute is dropped. + push_identity_pair(&mut self.identity, key, s); } } - obs.labels.truncate(label_count); + let point = ScalarPoint { + metric: &metric.name, + timestamp_ms, + value, + resource_labels, + source: &metric.source, + identity: &self.identity, + series_labels, + attributes_at: self.identity_prefix, + }; // An empty `sketch.envelope` from some other producer routes to // the scalar path rather than an empty-payload envelope. - obs.value = match envelope_bytes.filter(|b| !b.is_empty()) { - Some(payload) => { - let sketch_type = match &metric.view { - Some(_) => metric.sketch_type(inherited_schema)?, - None => parse_sketch_type(sketch_type_raw.as_deref())?, - }; - validate_self_describing_payload(sketch_type, &payload) - .map_err(CodecError::Decode)?; - ObservationValue::envelope(SketchEnvelope { - schema_version: schema_version.unwrap_or(0), - sketch_type, - view: metric.view.clone(), - resource_labels: Vec::new(), - labels: obs.labels.clone(), - source: Arc::clone(&metric.source), - window_start_ms: window_start_ms.unwrap_or(0), - window_end_ms: window_end_ms.unwrap_or(0), - payload, - metric_name: metric.name.clone(), - count: 0, - aggregation_temporality: 0, - value, - lineage: None, - }) - } - None => ObservationValue::float(value), + let Some(payload) = envelope_bytes.filter(|b| !b.is_empty()) else { + self.sink.scalar(&point); + return Ok(()); + }; + let sketch_type = match &metric.view { + Some(_) => metric.sketch_type(inherited_schema)?, + None => match &sketch_type_raw { + Some(raw) => parse_sketch_type(raw.as_deref())?, + None => parse_sketch_type(inherited_schema.sketch_type.as_deref())?, + }, }; + validate_self_describing_payload(sketch_type, &payload).map_err(CodecError::Decode)?; + let obs = &mut self.scratch; + point.write_labels(&mut obs.labels); + obs.value = ObservationValue::envelope(SketchEnvelope { + schema_version: schema_version.unwrap_or(0), + sketch_type, + view: metric.view.clone(), + resource_labels: Vec::new(), + labels: obs.labels.clone(), + source: Arc::clone(&metric.source), + window_start_ms: window_start_ms.unwrap_or(0), + window_end_ms: window_end_ms.unwrap_or(0), + payload, + metric_name: metric.name.clone(), + count: 0, + aggregation_temporality: 0, + value, + lineage: None, + }); obs.timestamp_ms = timestamp_ms; if obs.metric != metric.name { obs.metric.clear(); obs.metric.push_str(&metric.name); } - if !Arc::ptr_eq(&obs.source, &metric.source) { - obs.source = Arc::clone(&metric.source); - } - if obs.resource_labels.as_slice() != resource_labels { - obs.resource_labels.clear(); - obs.resource_labels.extend_from_slice(resource_labels); - } - (self.sink)(obs); + obs.source = Arc::clone(&metric.source); + obs.resource_labels.clear(); + obs.resource_labels.extend_from_slice(resource_labels); + self.sink.envelope(obs); Ok(()) } } diff --git a/asap-precompute-rs/src/otap/collector_views.rs b/asap-precompute-rs/src/otap/collector_views.rs index b461446..6f5691b 100644 --- a/asap-precompute-rs/src/otap/collector_views.rs +++ b/asap-precompute-rs/src/otap/collector_views.rs @@ -70,7 +70,7 @@ use otel_arrow_dfe_telemetry::metrics::MetricSet; use otel_arrow_dfe_telemetry_macros::{attribute_set, metric_set}; use serde::Deserialize; -use super::codec::{decode_each, encode_envelopes_to_pdata}; +use super::codec::{decode_each_scalar, encode_envelopes_to_pdata}; use super::planner_views::load; use super::processor::tumbling_idle_close_now_ms; use super::view_executor::{Closed, ViewCounts, ViewExecutor}; @@ -213,7 +213,8 @@ impl local::Processor for CollectorViews { Message::PData(pdata) => { effects.notify_ack(AckMsg::new(pdata.clone())).await?; let executor = &mut self.executor; - if let Err(error) = decode_each(pdata, |obs| executor.observe(obs)) { + if let Err(error) = decode_each_scalar(pdata, |point| executor.observe_point(point)) + { effects .info(&format!("collector_views: dropping input: {error}")) .await; diff --git a/asap-precompute-rs/src/otap/view_executor.rs b/asap-precompute-rs/src/otap/view_executor.rs index 2c720b9..6877fd1 100644 --- a/asap-precompute-rs/src/otap/view_executor.rs +++ b/asap-precompute-rs/src/otap/view_executor.rs @@ -91,6 +91,7 @@ use futures::executor::LocalPool; use futures::task::LocalSpawnExt; use futures::StreamExt; +use super::codec::ScalarPoint; use super::config::SKETCH_TYPES; use super::planner_views::{CollectorView, PlannerViews}; use crate::envelope::{Lineage, SketchEnvelope, SketchType, ViewIdentity}; @@ -105,6 +106,14 @@ const RUN_MEMORY_LIMIT_BYTES: usize = 1 << 30; /// An OTLP delta point's temporality, as `asap_sketches` stamps its states. const DELTA_TEMPORALITY: i32 = 1; +/// The hasher of [`SourceMetric::by_identity`]. Unit tests hash every +/// identity alike, so each lookup there is decided by comparing the bytes, as +/// a hash collision is. +#[cfg(not(test))] +type IdentityHasher = ahash::RandomState; +#[cfg(test)] +type IdentityHasher = std::hash::BuildHasherDefault; + /// One sample routed to a run group: (series id, timestamp ms, value). type Row = (u32, u64, f64); @@ -152,6 +161,9 @@ struct SourceMetric { /// Series key (`write_series_key` of resource, then point attributes) /// to series id. ids: HashMap, + /// [`ScalarPoint::identity`] to series id: each attribute order a + /// series' points arrived in. + by_identity: HashMap, u32, IdentityHasher>, /// By series id; `None` once evicted, until the id is reused. series: Vec>, /// Evicted ids, reused first. @@ -302,6 +314,7 @@ impl ViewExecutor { .entry(view.source_metric.clone()) .or_insert_with(|| SourceMetric { ids: HashMap::default(), + by_identity: HashMap::default(), series: Vec::new(), free_ids: Vec::new(), groups: Vec::new(), @@ -340,10 +353,32 @@ impl ViewExecutor { if obs.value.kind != ObservationValueKind::Float { return; } - let Some(metric) = self.metrics.get_mut(obs.metric.as_str()) else { + self.take(&obs.metric, obs.timestamp_ms, obs.value.float, |metric| { + metric.intern(obs) + }); + } + + /// [`Self::observe`] of a point read in place + /// ([`super::codec::decode_each_scalar`]): a point whose identity was + /// seen before finds its series without decoding its labels. + pub fn observe_point(&mut self, point: &ScalarPoint<'_>) { + self.take(point.metric, point.timestamp_ms, point.value, |metric| { + metric.intern_point(point) + }); + } + + /// [`Self::observe`] of a float sample, its series id from `intern` + /// (called at most once: when the first group takes the sample). + fn take( + &mut self, + metric: &str, + timestamp_ms: u64, + value: f64, + mut intern: impl FnMut(&mut SourceMetric) -> u32, + ) { + let Some(metric) = self.metrics.get_mut(metric) else { return; }; - let value = obs.value.float; let mut id = None; for group in 0..metric.groups.len() { let run_group = &mut metric.groups[group]; @@ -353,8 +388,8 @@ impl ViewExecutor { } continue; } - let on_time = run_group.admit(obs.timestamp_ms); - if !on_time && !run_group.retains(obs.timestamp_ms) { + let on_time = run_group.admit(timestamp_ms); + if !on_time && !run_group.retains(timestamp_ms) { for view in &run_group.views { self.counts[view.index].beyond_retention += 1; } @@ -363,8 +398,8 @@ impl ViewExecutor { for view in &run_group.views { self.counts[view.index].folded += 1; } - let end = window_end_ms(obs.timestamp_ms, run_group.width_ms); - let id = *id.get_or_insert_with(|| metric.intern(obs)); + let end = window_end_ms(timestamp_ms, run_group.width_ms); + let id = *id.get_or_insert_with(|| intern(metric)); let series = metric.series[id as usize].as_mut().expect("interned"); series.last_window_end_ms = series.last_window_end_ms.max(end); let run_group = &mut metric.groups[group]; @@ -373,7 +408,7 @@ impl ViewExecutor { } else { &mut run_group.late_rows }; - rows.push((id, obs.timestamp_ms, value)); + rows.push((id, timestamp_ms, value)); } } @@ -558,7 +593,29 @@ impl ViewExecutor { impl SourceMetric { /// `obs`'s series id, interning the series on its first point. fn intern(&mut self, obs: &Observation) -> u32 { - write_series_key(&mut self.key, 0, &obs.resource_labels, &obs.labels, &[]); + self.intern_labels(&obs.resource_labels, &obs.labels, &obs.source) + } + + /// `point`'s series id: by its identity bytes if seen before (the map + /// compares the bytes, so a hash collision is no match), else as + /// [`Self::intern`] of its decoded labels, remembering the identity. + fn intern_point(&mut self, point: &ScalarPoint<'_>) -> u32 { + if let Some(&id) = self.by_identity.get(point.identity) { + return id; + } + let id = self.intern_labels(point.resource_labels, &point.labels(), point.source); + self.by_identity.insert(point.identity.into(), id); + id + } + + /// The series id of these labels, interning the series on first sight. + fn intern_labels( + &mut self, + resource_labels: &[KeyValue], + labels: &[KeyValue], + source: &Arc, + ) -> u32 { + write_series_key(&mut self.key, 0, resource_labels, labels, &[]); if let Some(&id) = self.ids.get(self.key.as_str()) { return id; } @@ -566,9 +623,9 @@ impl SourceMetric { let series = Series { key: self.key.clone(), identity: id.to_string().into(), - resource_labels: obs.resource_labels.clone(), - labels: obs.labels.clone(), - source: Arc::clone(&obs.source), + resource_labels: resource_labels.to_vec(), + labels: labels.to_vec(), + source: Arc::clone(source), last_window_end_ms: 0, }; match self.series.get_mut(id as usize) { @@ -591,6 +648,7 @@ impl SourceMetric { .map(|g| g.closed_through_ms) .min() .unwrap_or(0); + let evicted = self.free_ids.len(); for (id, slot) in self.series.iter_mut().enumerate() { if slot .as_ref() @@ -601,6 +659,12 @@ impl SourceMetric { self.free_ids.push(id as u32); } } + if self.free_ids.len() > evicted { + // Before an evicted id is reused. + let series = &self.series; + self.by_identity + .retain(|_, id| series[*id as usize].is_some()); + } } } @@ -1084,6 +1148,7 @@ mod tests { use asap_executor::sources::InMemoryDataStore; use asap_executor::values::Value; use asap_sketchlib::DdSketch; + use otel_arrow_dfe_otap::pdata::OtapPdata; use std::collections::BTreeMap as Map; const Q01: &str = include_str!("../../tests/fixtures/collector-views/q01/collector-views.json"); @@ -1855,6 +1920,183 @@ mod tests { assert_eq!(labels, ["l1", "l2"]); } + /// Hashes everything to 0 (see [`IdentityHasher`]). + #[derive(Default)] + pub(super) struct CollidingHasher; + + impl std::hash::Hasher for CollidingHasher { + fn finish(&self) -> u64 { + 0 + } + + fn write(&mut self, _: &[u8]) {} + } + + /// `(key, value)` string attributes, in order. + type Attributes<'a> = &'a [(&'a str, &'a str)]; + + /// One OTLP request of `data`: per point, its Resource attributes, its + /// attributes, timestamp (ms) and value. + fn request(points: &[(Attributes<'_>, Attributes<'_>, u64, f64)]) -> OtapPdata { + use otel_arrow_dfe_pdata::proto::opentelemetry::common::v1::{ + AnyValue, KeyValue as Attribute, + }; + use otel_arrow_dfe_pdata::proto::opentelemetry::metrics::v1::{ + Gauge, Metric, MetricsData, NumberDataPoint, ResourceMetrics, ScopeMetrics, + }; + use otel_arrow_dfe_pdata::proto::opentelemetry::resource::v1::Resource; + use otel_arrow_dfe_pdata::proto::OtlpProtoMessage; + use otel_arrow_dfe_pdata::OtapPayload; + let attributes = |pairs: &[(&str, &str)]| -> Vec { + pairs + .iter() + .map(|(k, v)| Attribute::new(*k, AnyValue::new_string(*v))) + .collect() + }; + let resource_metrics: Vec = points + .iter() + .map(|(resource, point, ts, value)| { + let point = NumberDataPoint::build() + .time_unix_nano(ts * 1_000_000) + .value_double(*value) + .attributes(attributes(point)) + .finish(); + ResourceMetrics { + resource: Some(Resource { + attributes: attributes(resource), + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric::build() + .name("data") + .data_gauge(Gauge::new(vec![point])) + .finish()], + ..Default::default() + }], + ..Default::default() + } + }) + .collect(); + OtapPdata::new_todo_context( + OtapPayload::try_from(OtlpProtoMessage::Metrics(MetricsData::new( + resource_metrics, + ))) + .expect("from OTLP"), + ) + } + + /// `pdata` through [`super::super::codec::decode_each_scalar`] and + /// [`ViewExecutor::observe_point`]. + fn decode(executor: &mut ViewExecutor, pdata: OtapPdata) { + super::super::codec::decode_each_scalar(pdata, |point| executor.observe_point(point)) + .expect("decodes"); + } + + /// Points of equal attributes are one series, whichever request and + /// whichever attribute order they arrive in; an id is looked up by the + /// point's bytes (every identity hashes alike here). + #[test] + fn equal_attributes_in_different_requests_are_one_series() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut executor = ViewExecutor::new(&views).unwrap(); + let resource: Attributes<'_> = &[("service.name", "j0")]; + let ab: Attributes<'_> = &[("region", "r0"), ("label_0", "l0")]; + let ba: Attributes<'_> = &[("label_0", "l0"), ("region", "r0")]; + decode(&mut executor, request(&[(resource, ab, T - 3_000, 1.0)])); + decode( + &mut executor, + request(&[ + (resource, ab, T - 2_000, 2.0), + (resource, ba, T - 1_000, 3.0), + ]), + ); + decode(&mut executor, request(&[(resource, ba, T - 500, 4.0)])); + // Both orders are remembered, for the one series. + let metric = &executor.metrics["data"]; + assert_eq!(metric.series.iter().flatten().count(), 1); + assert_eq!(metric.by_identity.len(), 2); + assert!(metric.by_identity.values().all(|&id| id == 0)); + let drained = states(executor.drain()); + assert_eq!(drained.len(), 1, "{drained:?}"); + assert_eq!(drained[0].count, 4); + // The labels of the series' first point, in its order. + assert_eq!( + drained[0].labels, + [ + KeyValue::new("region", "r0"), + KeyValue::new("label_0", "l0") + ] + ); + assert_eq!( + drained[0].resource_labels, + [KeyValue::new("service.name", "j0")] + ); + assert!(executor.metrics["data"].by_identity.is_empty(), "evicted"); + } + + /// Attribute sets that differ only in how their bytes split into keys, + /// values and sections are distinct series, though every identity + /// hashes alike here. (Values holding `;` or `=` are left out: the + /// series key itself does not tell `a=b;c=d` from `a="b;c=d"`.) + #[test] + fn different_attributes_never_share_a_series() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut executor = ViewExecutor::new(&views).unwrap(); + let none: Attributes<'_> = &[]; + let sets: [(Attributes<'_>, Attributes<'_>); 6] = [ + (none, &[("ab", "c")]), + (none, &[("a", "bc")]), + (none, &[("a", "b"), ("c", "d")]), + (&[("a", "b")], none), + (&[("a", "b")], &[("a", "b")]), + (none, &[("a", "b")]), + ]; + let points: Vec<_> = sets + .iter() + .enumerate() + .map(|(i, (resource, point))| (*resource, *point, T - 1_000, 1.0 + i as f64)) + .collect(); + // Twice, in two requests: the second finds each by its identity. + let mut seen = std::collections::BTreeSet::new(); + for pdata in [request(&points), request(&points)] { + decode(&mut executor, pdata); + let metric = &executor.metrics["data"]; + assert_eq!(metric.series.iter().flatten().count(), sets.len()); + assert_eq!(metric.by_identity.len(), sets.len()); + seen.extend(metric.by_identity.values().copied()); + } + assert_eq!(seen.len(), sets.len()); + let drained = states(executor.drain()); + assert_eq!(drained.len(), sets.len()); + assert!(drained.iter().all(|s| s.count == 2), "{drained:?}"); + } + + /// An evicted series' identity is forgotten with it, so a freed id taken + /// by another series is not found under the old identity. + #[test] + fn evicted_identities_are_forgotten() { + let views = super::super::planner_views::parse(Q01).unwrap(); + let mut executor = ViewExecutor::new(&views).unwrap(); + let none: Attributes<'_> = &[]; + let l0: Attributes<'_> = &[("label_0", "l0")]; + let l1: Attributes<'_> = &[("label_0", "l1")]; + decode(&mut executor, request(&[(none, l0, T - 1_000, 1.0)])); + states(executor.flush()); + // Series l1 in the next window takes l0's id once l0 is evicted. + decode(&mut executor, request(&[(none, l1, T + 1_000, 2.0)])); + states(executor.flush()); + decode(&mut executor, request(&[(none, l0, T + 2_000, 3.0)])); + let metric = &executor.metrics["data"]; + assert_eq!(metric.series.iter().flatten().count(), 2); + assert_eq!(metric.by_identity.len(), 2); + let mut drained: Vec<(String, u64)> = states(executor.drain()) + .into_iter() + .map(|s| (s.labels[0].value.clone(), s.count)) + .collect(); + drained.sort(); + assert_eq!(drained, [("l0".to_string(), 1), ("l1".to_string(), 1)]); + } + /// Other metrics, and points that are not float samples, are ignored. #[test] fn points_no_view_reads_are_ignored() { diff --git a/asap-precompute-rs/tests/collector_views_e2e.rs b/asap-precompute-rs/tests/collector_views_e2e.rs index 21e81e9..a1a0c62 100644 --- a/asap-precompute-rs/tests/collector_views_e2e.rs +++ b/asap-precompute-rs/tests/collector_views_e2e.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; -use asap_precompute_rs::otap::codec::{decode_each, encode_envelopes_to_pdata}; +use asap_precompute_rs::otap::codec::{decode_each, decode_each_scalar, encode_envelopes_to_pdata}; use asap_precompute_rs::otap::planner_views; use asap_precompute_rs::otap::view_executor::ViewExecutor; use asap_sketchlib::DdSketch; @@ -462,16 +462,10 @@ 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 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() { +/// the OTLP messages the exporter sends, less their lineage (see +/// [`strip_full_lineage`]): decoding and series interning may change, the +/// states and their encoding may not. +fn emitted_states(in_place: bool) -> Vec { let views = planner_views::load(std::path::Path::new(FIXTURE)).unwrap(); let mut executor = ViewExecutor::with_epoch(&views, 42).unwrap(); let mut emitted: Vec = Vec::new(); @@ -489,10 +483,28 @@ fn emitted_states_match_the_golden_bytes() { emitted.push(data); }; for data in stream(12) { - decode_each(pdata(data), |obs| executor.observe(obs)).unwrap(); + if in_place { + decode_each_scalar(pdata(data), |point| executor.observe_point(point)).unwrap(); + } else { + decode_each(pdata(data), |obs| executor.observe(obs)).unwrap(); + } take(executor.flush()); } take(executor.drain()); + emitted +} + +/// [`emitted_states`] are the golden bytes apart from their lineage, whether +/// the points are read in place (as the processor reads them) or as +/// observations: 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). Set `ASAP_UPDATE_GOLDEN=1` to rewrite the file from the +/// stripped messages. +#[test] +fn emitted_states_match_the_golden_bytes() { + let emitted = emitted_states(true); let path = concat!( env!("CARGO_MANIFEST_DIR"), "/tests/golden/collector-views-states.bin" @@ -510,6 +522,10 @@ fn emitted_states_match_the_golden_bytes() { } std::fs::write(path, &bytes).unwrap(); } + assert!( + emitted == emitted_states(false), + "reading points in place changes the states" + ); let golden = std::fs::read(path).unwrap(); assert!(golden.len() > 10_000, "states of three windows"); let mut rest = golden.as_slice();