diff --git a/asap-precompute-rs/src/matchers.rs b/asap-precompute-rs/src/matchers.rs index f23fe17..a038a42 100644 --- a/asap-precompute-rs/src/matchers.rs +++ b/asap-precompute-rs/src/matchers.rs @@ -1,8 +1,8 @@ //! [`LabelMatcher`] and series-key helpers. //! -//! The type surface is final. The exact byte layout of -//! [`series_key`] / [`attributes_key`] is locked by the byte-parity -//! tests. +//! The exact byte layout of [`series_key`] / [`attributes_key`] is +//! Prometheus' label-set text, locked by the golden vectors in +//! `tests/golden/series-keys.json`. use crate::config::AggId; use crate::observation::{KeyValue, Observation}; @@ -122,20 +122,17 @@ pub(crate) fn lookup_label<'a>(labels: &'a [KeyValue], key: &str) -> Option<&'a /// Produces a stable string identifying the `(agg_id, label_key)` /// series for storage and snapshot lookup. /// -/// Output format MUST stay byte-identical to today's per-processor -/// `seriesKey` / `attributesKey` output for the same input — that's -/// how the snapshot cache survives the refactor. -/// -/// Today's format: +/// Format: `||`, each label set written as +/// Prometheus writes one ([`attributes_key`]), e.g. /// /// ```text -/// with aggregateBy: "k1=v1;k2=v2;" for the listed keys, missing keys skipped -/// without aggregateBy: "k1=v1;k2=v2;" for ALL labels, sorted by key +/// 42|{"service.name"="web"}|{"http.method"="GET", region="us-east"} /// ``` /// -/// The `agg_id` is prepended as a stable per-Precompute prefix so -/// the same global series-key namespace can hold series from -/// multiple Precompute instances. +/// Each label set is quoted and braced, so the key tells every two label +/// sets apart, whatever their values hold. The `agg_id` is prepended as a +/// stable per-Precompute prefix so the same global series-key namespace can +/// hold series from multiple Precompute instances. pub fn series_key( agg_id: AggId, resource_labels: &[KeyValue], @@ -177,13 +174,26 @@ pub(crate) fn write_series_key( write_attributes_key(buf, labels, aggregate_by); } -/// Returns just the per-label-set portion of [`series_key`]. +/// Returns just the per-label-set portion of [`series_key`]: the labels as +/// Prometheus' `Labels.String()` writes them (`model/labels`), e.g. +/// `{"http.method"="GET", region="us-east"}`. /// -/// When `aggregate_by` is -/// empty, all labels are included sorted by key; otherwise only the -/// listed keys are included in their `aggregate_by` order. Missing -/// keys are skipped (no `k=;` placeholder), matching today's -/// behavior. +/// - Names are sorted, joined by `, `; a name that is not a legacy +/// Prometheus label name (`[a-zA-Z_][a-zA-Z0-9_]*`, e.g. `http.method` +/// or the empty name) is quoted, as Prometheus 3 quotes UTF-8 names. +/// No name is refused. +/// - Values are quoted as Go's `strconv.Quote` quotes them, except that +/// non-ASCII runes other than the C1 controls are written as they are +/// (Go escapes other non-printable runes too, e.g. U+00A0). Only `"` and +/// `\` delimit, so the key stays unambiguous. +/// - Values are UTF-8: the OTAP decoder has already read attribute bytes +/// as UTF-8, replacing invalid bytes with U+FFFD, as the labels the +/// series is emitted with read. +/// +/// When `aggregate_by` is non-empty, only the listed keys are included in +/// their `aggregate_by` order (config validation sorts it); missing keys +/// are skipped. With duplicate names (not valid OTLP), each label is +/// written, sorted by name then value. pub fn attributes_key(labels: &[KeyValue], aggregate_by: &[String]) -> String { let mut buf = String::new(); write_attributes_key(&mut buf, labels, aggregate_by); @@ -191,42 +201,94 @@ pub fn attributes_key(labels: &[KeyValue], aggregate_by: &[String]) -> String { } fn write_attributes_key(buf: &mut String, labels: &[KeyValue], aggregate_by: &[String]) { - if aggregate_by.is_empty() { - // Already sorted with unique keys (e.g. one label): same output as - // the sorted walk below, without collecting the keys. - if labels.windows(2).all(|w| w[0].key < w[1].key) { - for kv in labels { - buf.push_str(&kv.key); - buf.push('='); - buf.push_str(&kv.value); - buf.push(';'); - } - return; - } - // Sort by key for stable output. - let mut keys: Vec<&str> = labels.iter().map(|kv| kv.key.as_str()).collect(); - keys.sort(); - for k in keys { + buf.push('{'); + let mut first = true; + if !aggregate_by.is_empty() { + for k in aggregate_by { if let Some(v) = lookup_label(labels, k) { - buf.push_str(k); - buf.push('='); - buf.push_str(v); - buf.push(';'); + write_label(buf, &mut first, k, v); } } - return; + } else if labels.windows(2).all(|w| w[0].key < w[1].key) { + // Already sorted with unique keys (e.g. one label): no sort. + for kv in labels { + write_label(buf, &mut first, &kv.key, &kv.value); + } + } else { + let mut sorted: Vec<&KeyValue> = labels.iter().collect(); + sorted.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value))); + for kv in sorted { + write_label(buf, &mut first, &kv.key, &kv.value); + } } - // aggregate_by is already sorted by config validation; we - // preserve the caller's order rather than re-sort, so legacy - // callers that sort upstream get bit-identical keys. - for k in aggregate_by { - if let Some(v) = lookup_label(labels, k) { - buf.push_str(k); - buf.push('='); - buf.push_str(v); - buf.push(';'); + buf.push('}'); +} + +/// Writes `name="value"` (see [`attributes_key`]), after `, ` unless it is +/// the first label. +fn write_label(buf: &mut String, first: &mut bool, name: &str, value: &str) { + if !std::mem::take(first) { + buf.push_str(", "); + } + if is_legacy_label_name(name) { + buf.push_str(name); + } else { + write_quoted(buf, name); + } + buf.push('='); + write_quoted(buf, value); +} + +/// Whether Prometheus' legacy validation accepts `name` +/// (`model.LegacyValidation.IsValidLabelName`): `[a-zA-Z_][a-zA-Z0-9_]*`. +fn is_legacy_label_name(name: &str) -> bool { + let bytes = name.as_bytes(); + bytes + .first() + .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_') + && bytes + .iter() + .all(|b| b.is_ascii_alphanumeric() || *b == b'_') +} + +/// Writes `text` in double quotes, escaped as Go's `strconv.Quote` escapes +/// it (see [`attributes_key`] for the one difference). +fn write_quoted(buf: &mut String, text: &str) { + buf.push('"'); + // Bytes that start an escape: C0 controls, `"`, `\`, DEL, and 0xC2, the + // lead byte of the C1 controls (U+0080..U+009F). + let plain = |b: &u8| *b >= 0x20 && !matches!(*b, b'"' | b'\\' | 0x7f | 0xc2); + if text.as_bytes().iter().all(plain) { + buf.push_str(text); + } else { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let hex = |n: u32| HEX[n as usize & 0xf] as char; + for c in text.chars() { + match c { + '"' => buf.push_str("\\\""), + '\\' => buf.push_str("\\\\"), + '\x07' => buf.push_str("\\a"), + '\x08' => buf.push_str("\\b"), + '\x0c' => buf.push_str("\\f"), + '\n' => buf.push_str("\\n"), + '\r' => buf.push_str("\\r"), + '\t' => buf.push_str("\\t"), + '\x0b' => buf.push_str("\\v"), + c if c < ' ' || c == '\x7f' => { + buf.push_str("\\x"); + buf.push(hex(c as u32 >> 4)); + buf.push(hex(c as u32)); + } + c if c.is_control() => { + buf.push_str("\\u00"); + buf.push(hex(c as u32 >> 4)); + buf.push(hex(c as u32)); + } + c => buf.push(c), + } } } + buf.push('"'); } /// Filters `labels` to only those in `aggregate_by`, preserving @@ -336,13 +398,75 @@ mod tests { fn sorted_fast_path_writes_the_same_key_as_the_sorted_walk() { let sorted = vec![KeyValue::new("a", "1"), KeyValue::new("b", "2")]; let unsorted = vec![KeyValue::new("b", "2"), KeyValue::new("a", "1")]; - assert_eq!(attributes_key(&sorted, &[]), "a=1;b=2;"); - assert_eq!(attributes_key(&unsorted, &[]), "a=1;b=2;"); + assert_eq!(attributes_key(&sorted, &[]), r#"{a="1", b="2"}"#); + assert_eq!(attributes_key(&unsorted, &[]), r#"{a="1", b="2"}"#); let mut buf = "stale".to_string(); write_series_key(&mut buf, 7, &sorted, &unsorted, &[]); assert_eq!(buf, series_key(7, &sorted, &unsorted, &[])); } + /// The label-set key is Prometheus' `Labels.String()`: the vectors were + /// printed by Go's `strconv.Quote` and the legacy label-name rule, as + /// `model/labels` writes them. + #[test] + fn attributes_key_is_prometheus_labels_string() { + let vectors: Vec = + serde_json::from_str(include_str!("../tests/golden/series-keys.json")).unwrap(); + for vector in vectors { + let labels: Vec = vector["labels"] + .as_array() + .unwrap() + .iter() + .map(|pair| KeyValue::new(pair[0].as_str().unwrap(), pair[1].as_str().unwrap())) + .collect(); + let want = vector["key"].as_str().unwrap(); + assert_eq!(attributes_key(&labels, &[]), want, "{labels:?}"); + let names: Vec = labels.iter().map(|kv| kv.key.clone()).collect(); + let mut by = names.clone(); + by.sort(); + assert_eq!(attributes_key(&labels, &by), want, "aggregate_by {by:?}"); + } + } + + /// Label sets that differ only in where a value ends are different keys: + /// `a=b, c=d` is not `a="b;c=d"`, and neither forges the other's quotes. + #[test] + fn values_holding_separators_are_different_keys() { + let sets: [&[(&str, &str)]; 7] = [ + &[("a", "b"), ("c", "d")], + &[("a", "b;c=d")], + &[("a", "b;c=d;")], + &[("a", "b"), ("c", "d;")], + &[("a", r#"b", c="d"#)], + &[("a", r#"b\"#), ("c", "d")], + &[("a=b", ""), ("c", "d")], + ]; + let keys: std::collections::BTreeSet = sets + .iter() + .map(|set| { + let labels: Vec = + set.iter().map(|(k, v)| KeyValue::new(*k, *v)).collect(); + series_key(0, &[], &labels, &[]) + }) + .collect(); + assert_eq!(keys.len(), sets.len(), "{keys:#?}"); + // Nor does a value move a label across the resource boundary. + let a = [KeyValue::new("a", "b")]; + assert_ne!(series_key(0, &a, &[], &[]), series_key(0, &[], &a, &[])); + } + + /// Prometheus quotes non-printable runes too (`strconv.Quote`); the key + /// escapes only the C0 and C1 controls, DEL, `"` and `\`, and writes + /// other runes as they are, which keeps it unambiguous. + #[test] + fn non_ascii_runes_other_than_controls_are_written_as_is() { + let labels = [KeyValue::new("v", "a\u{a0}b\u{200b}c\u{85}")]; + assert_eq!( + attributes_key(&labels, &[]), + "{v=\"a\u{a0}b\u{200b}c\\u0085\"}" + ); + } + #[test] fn per_attribute_reuses_the_scratch_for_each_selected_key() { let obs = Observation::new( diff --git a/asap-precompute-rs/src/otap/view_executor.rs b/asap-precompute-rs/src/otap/view_executor.rs index 6877fd1..47de70b 100644 --- a/asap-precompute-rs/src/otap/view_executor.rs +++ b/asap-precompute-rs/src/otap/view_executor.rs @@ -158,8 +158,9 @@ pub struct Closed { /// One source metric: its series and the run groups reading it. struct SourceMetric { - /// Series key (`write_series_key` of resource, then point attributes) - /// to series id. + /// Series key (`write_series_key` of resource, then point attributes: + /// Prometheus' label-set text, so values holding `;`, `=` or quotes + /// never merge two series) to series id. ids: HashMap, /// [`ScalarPoint::identity`] to series id: each attribute order a /// series' points arrived in. @@ -2036,20 +2037,25 @@ mod tests { /// 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"`.) + /// hashes alike here; values holding the key's own separators and + /// quotes too. #[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] = [ + let sets: [(Attributes<'_>, Attributes<'_>); 11] = [ (none, &[("ab", "c")]), (none, &[("a", "bc")]), (none, &[("a", "b"), ("c", "d")]), (&[("a", "b")], none), (&[("a", "b")], &[("a", "b")]), (none, &[("a", "b")]), + (none, &[("a", "b;c=d")]), + (none, &[("a", "b;c=d;")]), + (none, &[("a", "b"), ("c", "d;")]), + (none, &[("a", r#"b", c="d"#)]), + (none, &[("a", "b\\"), ("c", "d")]), ]; let points: Vec<_> = sets .iter() diff --git a/asap-precompute-rs/src/sketches/cms.rs b/asap-precompute-rs/src/sketches/cms.rs index 8e360a4..1ab4531 100644 --- a/asap-precompute-rs/src/sketches/cms.rs +++ b/asap-precompute-rs/src/sketches/cms.rs @@ -174,7 +174,7 @@ mod tests { CMSObserver.observe(&mut sketch, &obs).expect("observe"); } let attr_key = attributes_key(&labels, &[]); - assert_eq!(attr_key, "host=h1;"); + assert_eq!(attr_key, r#"{host="h1"}"#); assert!(sketch.estimate_count(attr_key.as_bytes()) >= 25.0); assert!(sketch.estimate_count(b"flow_count") < 25.0); } diff --git a/asap-precompute-rs/src/sketches/countsketch.rs b/asap-precompute-rs/src/sketches/countsketch.rs index c4d127c..a6e5c6c 100644 --- a/asap-precompute-rs/src/sketches/countsketch.rs +++ b/asap-precompute-rs/src/sketches/countsketch.rs @@ -111,13 +111,12 @@ impl SketchObserver for CountSketchObserver { w.update(&obs.value.bytes, obs.value.float.round() as i64); return Ok(()); } - let attr_key = crate::matchers::attributes_key(&obs.labels, &[]); - let key = if attr_key.is_empty() { - &self.default_key + if obs.labels.is_empty() { + w.update(self.default_key.as_bytes(), 1); } else { - &attr_key - }; - w.update(key.as_bytes(), 1); + let key = crate::matchers::attributes_key(&obs.labels, &[]); + w.update(key.as_bytes(), 1); + } Ok(()) } } @@ -180,7 +179,7 @@ mod tests { observer.observe(&mut sketch, &obs).expect("observe"); } let attr_key = attributes_key(&labels, &[]); - assert_eq!(attr_key, "path=/api;"); + assert_eq!(attr_key, r#"{path="/api"}"#); let counted = sketch.estimate_count(attr_key.as_bytes()); assert!(counted >= (n as f64) * 0.5, "counted={counted}"); assert!(sketch.estimate_count(b"events_per_path").abs() < counted); diff --git a/asap-precompute-rs/tests/golden/series-keys.json b/asap-precompute-rs/tests/golden/series-keys.json new file mode 100644 index 0000000..0f483db --- /dev/null +++ b/asap-precompute-rs/tests/golden/series-keys.json @@ -0,0 +1,20 @@ +[ + {"labels": [], "key": "{}"}, + {"labels": [["a", "b"], ["c", "d"]], "key": "{a=\"b\", c=\"d\"}"}, + {"labels": [["a", "b;c=d"]], "key": "{a=\"b;c=d\"}"}, + {"labels": [["a", "b"], ["c", "d;"]], "key": "{a=\"b\", c=\"d;\"}"}, + {"labels": [["a", "b;c=d;"]], "key": "{a=\"b;c=d;\"}"}, + {"labels": [["quote", "say \"hi\""]], "key": "{quote=\"say \\\"hi\\\"\"}"}, + {"labels": [["backslash", "C:\\dir\\"]], "key": "{backslash=\"C:\\\\dir\\\\\"}"}, + {"labels": [["newline", "line1\nline2"]], "key": "{newline=\"line1\\nline2\"}"}, + {"labels": [["controls", "\u0007\b\f\r\t\u000b\u0000\u0001\u001f\u007f"]], "key": "{controls=\"\\a\\b\\f\\r\\t\\v\\x00\\x01\\x1f\\x7f\"}"}, + {"labels": [["empty", ""]], "key": "{empty=\"\"}"}, + {"labels": [["unicode", "héllo 世界 🎉"]], "key": "{unicode=\"héllo 世界 🎉\"}"}, + {"labels": [["c1", "a\u0085b"]], "key": "{c1=\"a\\u0085b\"}"}, + {"labels": [["http.method", "GET"], ["service.name", "web"]], "key": "{\"http.method\"=\"GET\", \"service.name\"=\"web\"}"}, + {"labels": [["", "v"]], "key": "{\"\"=\"v\"}"}, + {"labels": [["9lives", "x"], ["_ok", "y"], ["Ok_9", "z"]], "key": "{\"9lives\"=\"x\", Ok_9=\"z\", _ok=\"y\"}"}, + {"labels": [["k=v", "x"], ["k", "v=x"]], "key": "{k=\"v=x\", \"k=v\"=\"x\"}"}, + {"labels": [["z", "1"], ["a", "2"], ["m", "3"]], "key": "{a=\"2\", m=\"3\", z=\"1\"}"}, + {"labels": [["a", "\"}, b=\""]], "key": "{a=\"\\\"}, b=\\\"\"}"} +] diff --git a/asap-precompute-rs/tests/runtime.rs b/asap-precompute-rs/tests/runtime.rs index ca5bc9a..734e328 100644 --- a/asap-precompute-rs/tests/runtime.rs +++ b/asap-precompute-rs/tests/runtime.rs @@ -72,7 +72,8 @@ fn make_factory() -> Box Box + Send + Sync> { // // Hardcoded golden values pin the series-key output. // -// Format: "||". +// Format: "||", each label set as +// Prometheus' `Labels.String()` writes it. #[test] fn series_key_no_aggregate_by_full_set() { @@ -90,7 +91,7 @@ fn series_key_no_aggregate_by_full_set() { let got = series_key(42, &res, &dp, &[]); assert_eq!( got, - "42|host.name=node-1;service.name=web;|http.method=GET;http.status=200;" + r#"42|{"host.name"="node-1", "service.name"="web"}|{"http.method"="GET", "http.status"="200"}"# ); } @@ -115,7 +116,7 @@ fn series_key_with_aggregate_by_filters_keys() { ); assert_eq!( got, - "7|region=us-east;service.name=api;|http.method=POST;http.status=500;" + r#"7|{region="us-east", "service.name"="api"}|{"http.method"="POST", "http.status"="500"}"# ); } @@ -130,7 +131,7 @@ fn series_key_aggregate_by_with_missing_keys_skipped() { &dp, &["a".to_string(), "b".to_string(), "c".to_string()], ); - assert_eq!(got, "1|service.name=ingest;|a=1;c=3;"); + assert_eq!(got, r#"1|{"service.name"="ingest"}|{a="1", c="3"}"#); } #[test] @@ -138,7 +139,7 @@ fn series_key_empty_dp_attrs() { // Fixture 4. let res = vec![KeyValue::new("deployment.environment", "prod")]; let got = series_key(99, &res, &[], &[]); - assert_eq!(got, "99|deployment.environment=prod;|"); + assert_eq!(got, r#"99|{"deployment.environment"="prod"}|{}"#); } #[test] @@ -146,7 +147,7 @@ fn series_key_empty_resource_attrs() { // Fixture 5. let dp = vec![KeyValue::new("x", "1"), KeyValue::new("y", "2")]; let got = series_key(3, &[], &dp, &[]); - assert_eq!(got, "3||x=1;y=2;"); + assert_eq!(got, r#"3|{}|{x="1", y="2"}"#); } #[test] @@ -159,7 +160,7 @@ fn attributes_key_sorts_by_key() { KeyValue::new("m", "3"), ]; let got = attributes_key(&labels, &[]); - assert_eq!(got, "a=2;m=3;z=1;"); + assert_eq!(got, r#"{a="2", m="3", z="1"}"#); } // ----------------------------------------------------------------