From 8852ebbcf8324a8d1bd9933f1f8cfe48259ef2a5 Mon Sep 17 00:00:00 2001 From: Zeying Zhu <50204836+zzylol@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:39:58 +0000 Subject: [PATCH 1/2] collector_views: test the lineage frame in sketch.envelope (failing first) Tests for moving a state's lineage out of the OTLP point attributes and into a binary frame in front of its ASAPv1 bytes in `sketch.envelope`: - envelope: pinned frame bytes for sequences 0, 1 and 300 and their round trip (the same vectors as ASAPQuery-backend's decoder), and refusals with their reason (a bare ASAPv1 state, frame version 2, unknown flags, a truncated or overflowing varint, a kind that disagrees with its sequence and base). - codec: the q01 state's point carries no lineage attributes and its sketch.envelope is `A1 00 00` + the ASAPv1 bytes; a bad frame, a bare ASAPv1 state under a metric with a producer epoch, and a framed state under a metric without one are refused. - collector_views_e2e: the golden comparison strips the epoch metadata and the full's 3-byte frame; the q01 wire fixture otlp-body.pb is the framed body (781 -> 724 bytes). Lineage::frame and Lineage::unframe are stubs here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- asap-precompute-rs/src/envelope.rs | 55 ++++++++++++ asap-precompute-rs/src/otap/codec.rs | 81 ++++++++++++------ .../tests/collector_views_e2e.rs | 46 +++++----- .../fixtures/collector-views/q01/otlp-body.pb | Bin 781 -> 724 bytes 4 files changed, 130 insertions(+), 52 deletions(-) diff --git a/asap-precompute-rs/src/envelope.rs b/asap-precompute-rs/src/envelope.rs index b51a585..b5ee55d 100644 --- a/asap-precompute-rs/src/envelope.rs +++ b/asap-precompute-rs/src/envelope.rs @@ -105,6 +105,16 @@ impl Lineage { pub fn base_sequence(&self) -> Option { self.sequence.checked_sub(1) } + + /// Not implemented yet: `asapv1` as is. + pub fn frame(&self, asapv1: &[u8]) -> Vec { + asapv1.to_vec() + } + + /// Not implemented yet. + pub fn unframe(_bytes: &[u8]) -> Result<(u64, &[u8]), String> { + Err("lineage frames are not implemented yet".into()) + } } /// One emitted sketch (or scalar estimate) plus its runtime metadata. @@ -217,4 +227,49 @@ mod tests { let decoded: SketchEnvelope = serde_json::from_str(&json).expect("deserialize"); assert_eq!(env, decoded); } + + /// The lineage frame's bytes, pinned: ASAPQuery-backend's decoder holds + /// the same vectors. + #[test] + fn lineage_frames_are_these_bytes_and_round_trip() { + let asapv1 = b"ASAPv1\x01rest"; + let lineage = |sequence| Lineage { + producer_epoch: 7, + sequence, + }; + let cases: [(u64, &[u8]); 3] = [ + (0, &[0xA1, 0x00, 0x00]), + (1, &[0xA1, 0x01, 0x01, 0x00]), + (300, &[0xA1, 0x01, 0xAC, 0x02, 0xAB, 0x02]), + ]; + for (sequence, head) in cases { + let framed = lineage(sequence).frame(asapv1); + assert_eq!(&framed[..head.len()], head, "sequence {sequence}"); + assert_eq!(&framed[head.len()..], asapv1); + assert_eq!(Lineage::unframe(&framed), Ok((sequence, &asapv1[..]))); + } + let max = lineage(u64::MAX).frame(asapv1); + assert_eq!(Lineage::unframe(&max), Ok((u64::MAX, &asapv1[..]))); + } + + /// Bytes that are no version 1 lineage frame, or whose kind disagrees + /// with its sequence and base, are refused, saying why. + #[test] + fn bad_lineage_frames_are_refused() { + let refused = |bytes: &[u8]| Lineage::unframe(bytes).unwrap_err(); + assert!(refused(b"ASAPv1\x01rest").contains("without a lineage frame")); + assert!(refused(&[0xA2, 0x00, 0x00]).contains("version 2")); + assert!(refused(&[0x00]).contains("not a lineage frame")); + assert!(refused(&[]).contains("not a lineage frame")); + assert!(refused(&[0xA1]).contains("truncated")); + assert!(refused(&[0xA1, 0x02, 0x00]).contains("flags")); + assert!(refused(&[0xA1, 0x00, 0x80]).contains("truncated")); + assert!(refused(&[0xA1, 0x00, 0x01]).contains("a full has sequence 1")); + assert!(refused(&[0xA1, 0x01, 0x00, 0x00]).contains("base")); + assert!(refused(&[0xA1, 0x01, 0x03, 0x01]).contains("base 1")); + let overflow = [ + 0xA1, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, + ]; + assert!(refused(&overflow).contains("overflows")); + } } diff --git a/asap-precompute-rs/src/otap/codec.rs b/asap-precompute-rs/src/otap/codec.rs index 710cd48..c36bd03 100644 --- a/asap-precompute-rs/src/otap/codec.rs +++ b/asap-precompute-rs/src/otap/codec.rs @@ -2671,12 +2671,21 @@ mod tests { ("label_0", "l0"), ( "sketch.envelope", - &format!("<{} bytes>", state.payload.len()) + &format!("<{} bytes>", state.payload.len() + 3) ), - ("asap.sequence", "0"), - ("asap.state_kind", "full"), ]) ); + // The state's ASAPv1 bytes behind a full's lineage frame. + let envelope = match point.attributes[3] + .value + .as_ref() + .and_then(|v| v.value.as_ref()) + { + Some(Value::BytesValue(bytes)) => bytes, + other => panic!("sketch.envelope bytes, got {other:?}"), + }; + assert_eq!(envelope[..3], [0xA1, 0x00, 0x00]); + assert_eq!(envelope[3..], state.payload[..]); assert_eq!(point.start_time_unix_nano, 1_767_225_595_000_000_000); assert_eq!(point.time_unix_nano, 1_767_225_600_000_000_000); assert_eq!(point.count, 50); @@ -2693,8 +2702,8 @@ mod tests { 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). + /// A delta's frame carries its sequence and base, 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); @@ -2722,33 +2731,49 @@ mod tests { assert_eq!(lineages, [full.lineage, delta.lineage, other_epoch.lineage]); } - /// A lineage whose kind does not match its sequence and base is refused. + /// A state whose lineage frame is bad (a kind that does not match its + /// sequence and base), a bare ASAPv1 state under a metric with a producer + /// epoch (a collector from before the frame), and a framed state under a + /// metric without one are refused. #[test] - fn an_inconsistent_lineage_is_refused_on_decode() { - use otel_arrow_dfe_pdata::proto::opentelemetry::common::v1::{ - any_value, AnyValue, KeyValue, - }; + fn a_bad_or_missing_lineage_frame_is_refused_on_decode() { + use otel_arrow_dfe_pdata::proto::opentelemetry::common::v1::any_value::Value; use otel_arrow_dfe_pdata::proto::opentelemetry::metrics::v1::metric::Data; + use otel_arrow_dfe_pdata::proto::opentelemetry::metrics::v1::Metric; 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"); + let state = q01_state(1_767_225_600_000); + let refused = |edit: &dyn Fn(&mut Metric)| { + let pdata = encode_envelopes_to_pdata(std::slice::from_ref(&state)).expect("encode"); + let (_, mut data) = otlp_request(pdata); + let metric = &mut data.resource_metrics[0].scope_metrics[0].metrics[0]; + edit(metric); + let pdata = OtapPdata::new_todo_context( + OtapPayload::try_from(OtlpProtoMessage::Metrics(data)).expect("from OTLP"), + ); + decode_pdata_to_observations(pdata) + .expect_err("refused") + .to_string() }; - // 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}"); + let set_envelope = |metric: &mut Metric, bytes: Vec| { + let Some(Data::Summary(summary)) = &mut metric.data else { + panic!("a Summary"); + }; + let attribute = summary.data_points[0] + .attributes + .iter_mut() + .find(|kv| kv.key == "sketch.envelope") + .unwrap(); + attribute.value.as_mut().unwrap().value = Some(Value::BytesValue(bytes)); + }; + // A "full" of sequence 0 with a base: the delta flag on sequence 0. + let mut full_with_base = vec![0xA1, 0x01, 0x00, 0x00]; + full_with_base.extend(&state.payload); + let error = refused(&|metric| set_envelope(metric, full_with_base.clone())); + assert!(error.contains("base"), "{error}"); + let error = refused(&|metric| set_envelope(metric, state.payload.clone())); + assert!(error.contains("without a lineage frame"), "{error}"); + let error = refused(&|metric| metric.metadata.retain(|kv| kv.key != "asap.producer_epoch")); + assert!(error.contains("asap.producer_epoch"), "{error}"); } /// Two views over one source metric are two Metric entries, each with its diff --git a/asap-precompute-rs/tests/collector_views_e2e.rs b/asap-precompute-rs/tests/collector_views_e2e.rs index a1a0c62..5b50fa3 100644 --- a/asap-precompute-rs/tests/collector_views_e2e.rs +++ b/asap-precompute-rs/tests/collector_views_e2e.rs @@ -7,6 +7,7 @@ use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; +use asap_precompute_rs::envelope::Lineage; 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; @@ -304,14 +305,17 @@ fn attributes(kvs: &[KeyValue]) -> Vec<(String, String)> { } fn envelope(point_attributes: &[KeyValue]) -> Vec { - point_attributes + let framed = point_attributes .iter() .find(|kv| kv.key == "sketch.envelope") .and_then(|kv| match kv.value.as_ref()?.value.as_ref()? { AnyValueKind::BytesValue(bytes) => Some(bytes.clone()), _ => None, }) - .expect("a sketch.envelope") + .expect("a sketch.envelope"); + let (sequence, asapv1) = Lineage::unframe(&framed).expect("a lineage frame"); + assert_eq!(sequence, 0, "an on-time state is its window's full"); + asapv1.to_vec() } /// The OTLP received is the OTLP sent: one Summary point per series under @@ -498,9 +502,9 @@ fn emitted_states(in_place: bool) -> Vec { /// 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 +/// metadata and the full's lineage frame from each point's `sketch.envelope` +/// 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() { @@ -547,16 +551,13 @@ fn emitted_states_match_the_golden_bytes() { /// 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"`). +/// and the full's lineage frame (`A1 00 00`) in front of the point's +/// `sketch.envelope` bytes. 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() @@ -576,20 +577,17 @@ fn strip_full_lineage(data: &mut MetricsData, epoch: u64) { 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); + let envelope = point + .attributes + .iter_mut() + .find(|kv| kv.key == "sketch.envelope") + .and_then(|kv| kv.value.as_mut()) + .and_then(|v| v.value.as_mut()); + let Some(AnyValueKind::BytesValue(bytes)) = envelope else { + panic!("a state has sketch.envelope bytes"); + }; + assert_eq!(bytes[..3], [0xA1, 0x00, 0x00], "a full's lineage frame"); + bytes.drain(..3); } } } 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 de20a2ab41c5817d30314783dd4ee0f9f1679c5f..c93f5681b4a99abe25449ba1aae997fed5cb6458 100644 GIT binary patch delta 95 zcmeBWyTZ!Mb-r~Xvx@r4)&>TyhK2?Pq4^+|KuTgsqF!QgVnKXaW@@>fVbq}}pzz*_ uejW-p8-XnT;_TFt Date: Mon, 30 Nov 2026 15:43:52 +0000 Subject: [PATCH 2/2] collector_views: carry the lineage in a binary frame in sketch.envelope A collector view state's sequence and kind move from three OTLP point attributes (asap.sequence, asap.state_kind, asap.base_sequence) into a binary lineage frame in front of its ASAPv1 bytes in sketch.envelope: [ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128 | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ] 0xA1 is the frame's marker (0xA) and version (1); an ASAPv1 envelope starts with b'A' (0x41), so the two never collide. A full adds 3 bytes, a delta below sequence 128 adds 4. The decoder refuses a bare ASAPv1 state under a metric with asap.producer_epoch (a collector from before the frame), another frame version, unknown flags, and a kind that disagrees with its sequence and base. asap.producer_epoch stays Metric metadata: it is the same for every point of the metric, so it costs ~40 bytes per metric instead of a 10-byte varint (a random u64) per state; it would only be cheaper in the frame for metrics of fewer than about four states. Bytes per state, same input (the golden test's 12 s stream, three messages of 80 states, OTLP protobuf): no lineage 215.9 B lineage attributes 264.6 B (+48.7, +22.6%) lineage frame 219.7 B (+3.8, +1.8%) The q01 one-state wire fixture goes 781 -> 724 bytes (669 without lineage). The golden states file is unchanged: its test strips the epoch and the full's 3-byte frame, leaving the pre-lineage messages. The schema constants for the three attributes are removed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- asap-precompute-rs/src/envelope.rs | 109 ++++++++++++++- asap-precompute-rs/src/otap/codec.rs | 124 +++++++----------- .../src/otap/collector_views.rs | 5 +- asap-precompute-rs/src/otap/schema.rs | 13 +- docs/data_model.md | 18 ++- 5 files changed, 173 insertions(+), 96 deletions(-) diff --git a/asap-precompute-rs/src/envelope.rs b/asap-precompute-rs/src/envelope.rs index b5ee55d..6357236 100644 --- a/asap-precompute-rs/src/envelope.rs +++ b/asap-precompute-rs/src/envelope.rs @@ -90,8 +90,8 @@ impl SketchType { /// 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. +/// `asap.producer_epoch` metadata and the sequence in the lineage frame +/// around the state's ASAPv1 bytes in `sketch.envelope` ([`Lineage::frame`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Lineage { /// The collector instance: a random number drawn at start. @@ -100,21 +100,116 @@ pub struct Lineage { pub sequence: u64, } +/// The first byte of a version 1 lineage frame. The high nibble `0xA` marks +/// a lineage frame and the low one is its version; an ASAPv1 envelope starts +/// with `b'A'` (`0x41`), so a bare one is never taken for a frame. +pub const LINEAGE_FRAME_V1: u8 = 0xA1; +/// The flags byte's bit of a delta; the other bits are 0. +const LINEAGE_FRAME_DELTA: u8 = 0x01; + impl Lineage { /// A delta's base sequence; `None` for a full. pub fn base_sequence(&self) -> Option { self.sequence.checked_sub(1) } - /// Not implemented yet: `asapv1` as is. + /// `asapv1` behind this record's lineage frame, the bytes of its + /// `sketch.envelope`: + /// + /// ```text + /// [ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128 + /// | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ] + /// ``` + /// + /// A full is 3 bytes longer than its ASAPv1 bytes (`A1 00 00`); a delta + /// below sequence 128 is 4 longer. The epoch is not in the frame: it is + /// the metric's, shared by all of its points. pub fn frame(&self, asapv1: &[u8]) -> Vec { - asapv1.to_vec() + let mut framed = Vec::with_capacity(asapv1.len() + 2 + 2 * 10); + framed.push(LINEAGE_FRAME_V1); + match self.base_sequence() { + None => { + framed.push(0); + push_uleb128(&mut framed, self.sequence); + } + Some(base) => { + framed.push(LINEAGE_FRAME_DELTA); + push_uleb128(&mut framed, self.sequence); + push_uleb128(&mut framed, base); + } + } + framed.extend_from_slice(asapv1); + framed + } + + /// The sequence of a framed state ([`Self::frame`]) and its ASAPv1 + /// bytes. Errs, saying why, for bytes that are no version 1 frame (a + /// bare ASAPv1 envelope from a collector without lineage frames, or + /// another frame version), with unknown flags, or whose kind disagrees + /// with its sequence and base (a full is sequence 0, a delta `n ≥ 1` has + /// base `n − 1`). + pub fn unframe(bytes: &[u8]) -> Result<(u64, &[u8]), String> { + match bytes.first() { + Some(&LINEAGE_FRAME_V1) => {} + Some(_) if bytes.starts_with(b"ASAPv1") => { + return Err("a bare ASAPv1 state without a lineage frame".into()) + } + Some(&first) if first >> 4 == 0xA => { + return Err(format!( + "lineage frame version {}; this reader reads version 1", + first & 0x0F + )) + } + _ => return Err("not a lineage frame".into()), + } + let flags = *bytes.get(1).ok_or("a truncated lineage frame")?; + if flags & !LINEAGE_FRAME_DELTA != 0 { + return Err(format!("unknown lineage frame flags {flags:#04x}")); + } + let mut rest = &bytes[2..]; + let sequence = read_uleb128(&mut rest)?; + if flags & LINEAGE_FRAME_DELTA == 0 { + if sequence != 0 { + return Err(format!("a full has sequence {sequence}, not 0")); + } + } else { + let base = read_uleb128(&mut rest)?; + if sequence == 0 || base != sequence - 1 { + return Err(format!( + "a delta of sequence {sequence} has base {base}, not its sequence − 1" + )); + } + } + Ok((sequence, rest)) + } +} + +fn push_uleb128(out: &mut Vec, mut value: u64) { + loop { + let byte = (value & 0x7F) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + return; + } + out.push(byte | 0x80); } +} - /// Not implemented yet. - pub fn unframe(_bytes: &[u8]) -> Result<(u64, &[u8]), String> { - Err("lineage frames are not implemented yet".into()) +fn read_uleb128(bytes: &mut &[u8]) -> Result { + let mut value = 0u64; + for (i, &byte) in bytes.iter().enumerate().take(10) { + let bits = u64::from(byte & 0x7F); + if i == 9 && bits > 1 { + return Err("a lineage frame varint overflows u64".into()); + } + value |= bits << (7 * i); + if byte & 0x80 == 0 { + *bytes = &bytes[i + 1..]; + return Ok(value); + } } + Err("a truncated lineage frame varint".into()) } /// One emitted sketch (or scalar estimate) plus its runtime metadata. diff --git a/asap-precompute-rs/src/otap/codec.rs b/asap-precompute-rs/src/otap/codec.rs index c36bd03..9bf918d 100644 --- a/asap-precompute-rs/src/otap/codec.rs +++ b/asap-precompute-rs/src/otap/codec.rs @@ -74,10 +74,7 @@ use crate::config::{sketch_size_string, SketchParams}; 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::META_PRODUCER_EPOCH; 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, @@ -267,6 +264,10 @@ struct AsapMetricsView<'a> { resources: Vec, /// Each producer epoch's `asap.producer_epoch` text. epochs: HashMap, + /// Per row, a collector view state's `sketch.envelope` bytes: its + /// ASAPv1 bytes behind its lineage frame ([`Lineage::frame`]); empty for + /// a row with no lineage. + framed: Vec>, } struct AsapResourceGroup { @@ -335,50 +336,40 @@ impl<'a> AsapMetricsView<'a> { .filter_map(|env| env.lineage) .map(|lineage| (lineage.producer_epoch, lineage.producer_epoch.to_string())) .collect(); + let framed = envelopes + .iter() + .map(|env| match env.lineage { + Some(lineage) if !env.payload.is_empty() => lineage.frame(&env.payload), + _ => Vec::new(), + }) + .collect(); Self { envelopes, resources, epochs, + framed, } } /// One row's worth of attributes, built directly from the /// envelope's own fields. `sketch.envelope` only appears when this /// row actually carries a sketch payload. - fn attributes_for_row(&self, row: usize) -> Vec> { + 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 and its place - // in its lineage. + // The received point attributes, then the state, behind its + // lineage frame when it has a lineage. let mut attrs = string_attributes(&env.labels); if !env.payload.is_empty() { + let bytes = match env.lineage { + Some(_) => &self.framed[row], + None => &env.payload, + }; attrs.push(AsapAttribute { key: ATTR_ENVELOPE, - value: AsapAnyValue::Bytes(&env.payload), + value: AsapAnyValue::Bytes(bytes), }); } - 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); @@ -1935,45 +1926,33 @@ fn producer_epoch(metric: &M, name: &str) -> Result, 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`). +/// A state's lineage and ASAPv1 bytes from its metric's epoch and its +/// `sketch.envelope` bytes: with an epoch, the bytes are a lineage frame +/// ([`Lineage::unframe`]); without one, bare ASAPv1 bytes with no lineage. +/// An error when the frame is bad, or when there is an epoch and no frame +/// or a frame and no epoch. 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:?}" - ))) + envelope: Vec, +) -> Result<(Option, Vec), CodecError> { + let framed = envelope.first().is_some_and(|&b| b >> 4 == 0xA); + match epoch { + None if framed => Err(CodecError::Decode(format!( + "a state in a lineage frame under a metric without {META_PRODUCER_EPOCH}" + ))), + None => Ok((None, envelope)), + Some(producer_epoch) => { + let (sequence, asapv1) = Lineage::unframe(&envelope) + .map_err(|e| CodecError::Decode(format!("sketch.envelope: {e}")))?; + Ok(( + Some(Lineage { + producer_epoch, + sequence, + }), + asapv1.to_vec(), + )) } - }; - Ok(Some(lineage)) + } } impl DecodeAccumulator { @@ -1988,7 +1967,6 @@ 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() { @@ -1996,13 +1974,6 @@ 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) } @@ -2020,11 +1991,12 @@ impl DecodeAccumulator { } } - let payload = envelope_bytes + let envelope_bytes = envelope_bytes .filter(|bytes| !bytes.is_empty()) .ok_or_else(|| { CodecError::Decode("summary sketch is missing sketch.envelope".into()) })?; + let (lineage, payload) = decode_lineage(metric.producer_epoch, envelope_bytes)?; let sketch_type = metric.sketch_type(inherited_schema)?; validate_self_describing_payload(sketch_type, &payload).map_err(CodecError::Decode)?; let timestamp_ms = dp.time_unix_nano() / 1_000_000; @@ -2043,7 +2015,7 @@ impl DecodeAccumulator { count: dp.count(), aggregation_temporality: 0, value: dp.sum(), - lineage: decode_lineage(metric.producer_epoch, sequence, kind.as_deref(), base)?, + lineage, }; let mut observation = Observation::new( timestamp_ms, diff --git a/asap-precompute-rs/src/otap/collector_views.rs b/asap-precompute-rs/src/otap/collector_views.rs index 6f5691b..2edc0ef 100644 --- a/asap-precompute-rs/src/otap/collector_views.rs +++ b/asap-precompute-rs/src/otap/collector_views.rs @@ -24,8 +24,9 @@ //! 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 +//! metadata, and the record's sequence and kind in the lineage frame in +//! front of its `sketch.envelope` bytes ([`crate::envelope::Lineage::frame`]). +//! 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 diff --git a/asap-precompute-rs/src/otap/schema.rs b/asap-precompute-rs/src/otap/schema.rs index 7596ce1..4bb2dd7 100644 --- a/asap-precompute-rs/src/otap/schema.rs +++ b/asap-precompute-rs/src/otap/schema.rs @@ -33,17 +33,10 @@ pub const META_NODE_ID: &str = "asap.node_id"; 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). +/// The rest of a state's lineage (its sequence, and whether it is a full or +/// a delta) is in the lineage frame around its `sketch.envelope` bytes +/// ([`crate::envelope::Lineage::frame`]). 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/docs/data_model.md b/docs/data_model.md index ebb6f7f..566b775 100644 --- a/docs/data_model.md +++ b/docs/data_model.md @@ -351,7 +351,7 @@ OTAP structure, not the `sketch.*` carrier above: |---|---|---| | 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 attributes `sketch.envelope` (ASAPv1), `asap.sequence` (int), `asap.state_kind` (`"full"` or `"delta"`), `asap.base_sequence` (int, deltas only) | +| Record | `time_unix_nano` + value | Summary point: window `(start_time_unix_nano, time_unix_nano]`, `count`, point attribute `sketch.envelope`: the state's ASAPv1 bytes behind its lineage frame (below) | 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 @@ -362,6 +362,22 @@ 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 sequence and kind travel in a binary lineage frame in front of the +state's ASAPv1 bytes in `sketch.envelope` (`envelope::Lineage::frame`): + +```text +[ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128 + | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ] +``` + +`0xA1` is the frame's marker (`0xA`) and version (1). A full adds 3 bytes +(`A1 00 00`), a delta below sequence 128 adds 4. A reader refuses a bare +ASAPv1 state under a metric with `asap.producer_epoch` (a collector from +before the frame), another frame version, unknown flags, and a kind that +disagrees with its sequence and base. The epoch stays metric metadata: it is +the same for every point of the metric, so it is sent once per metric +instead of once per state. + 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 conversion writes it back as `Metric.metadata`. `tests/fixtures/collector-views/q01`