:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): assign series_fingerprint at ingest (#67195)
Daniel Viscae2a5dc0a3939
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 1ab0611b225b..860cf3807382 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1883,6 +1883,7 @@ dependencies = ["serde","serde_derive","serde_json",+ "siphasher 1.0.2","thiserror 2.0.18","tokio","tonic 0.12.3",diff --git a/rust/capture-logs/Cargo.toml b/rust/capture-logs/Cargo.tomlindex 7523fd8bb9bf..a9a2f8ce6662 100644--- a/rust/capture-logs/Cargo.toml+++ b/rust/capture-logs/Cargo.toml@@ -30,6 +30,7 @@ base64 = { workspace = true }rdkafka = { workspace = true }uuid = { workspace = true }chrono = { workspace = true }+siphasher = { workspace = true }apache-avro = { version = "0.21.0", features = ["zstandard"] }prost = { workspace = true }bytes = { workspace = true }diff --git a/rust/capture-logs/src/metric_record.rs b/rust/capture-logs/src/metric_record.rsindex 64f044dd958b..9a06d402c54d 100644--- a/rust/capture-logs/src/metric_record.rs+++ b/rust/capture-logs/src/metric_record.rs@@ -1,4 +1,5 @@use std::collections::HashMap;+use std::hash::Hasher;use anyhow::Result;use base64::{prelude::BASE64_STANDARD, Engine};@@ -18,6 +19,7 @@ use opentelemetry_proto::tonic::{};use serde::{Deserialize, Serialize};use serde_json::{json, Value as JsonValue};+use siphasher::sip::SipHasher13;use tracing::debug;use uuid::Uuid;@@ -46,6 +48,10 @@ pub struct KafkaMetricRow {pub resource_attributes: HashMap<String, String>,pub instrumentation_scope: String,pub attributes: HashMap<String, String>,+ /// Stable per-series identity, assigned here at ingest and stored verbatim by+ /// ClickHouse (which never recomputes it). Links a sample to its series at read+ /// time. i64 carries the u64 hash bits to fit Avro's `long`.+ pub series_fingerprint: i64,}/// Flatten an OTEL Metric into one or more KafkaMetricRow records.@@ -295,6 +301,16 @@ fn build_number_row(}).collect();+ // Identity is assigned once, here. Computed before the synthetic $originalTimestamp+ // is added so an overridden timestamp never splits a series.+ let series_fingerprint = compute_series_fingerprint(+ metric_name,+ metric_type,+ service_name,+ resource_attributes,+ &attributes,+ );+if let Some(original) = original_timestamp {attributes.insert("$originalTimestamp".to_string(), original.to_rfc3339());}@@ -321,11 +337,57 @@ fn build_number_row(resource_attributes: resource_attributes.clone(),instrumentation_scope: instrumentation_scope.to_string(),attributes,+ series_fingerprint,};Ok((row, was_overridden))}+/// Stable, order-independent 64-bit identity for a metric series, assigned at ingest.+///+/// Computed once here and carried to ClickHouse as `series_fingerprint`, so storage+/// never recomputes it — the TSDB / Snuffle-default approach. The hash is internal+/// (samples link to their series within this system only), so it need not match any+/// ClickHouse hash; any deterministic algorithm works. SipHash-1-3 with a fixed key is+/// stable across builds. Returned as i64 (the u64 bit pattern) to fit Avro's `long`;+/// ClickHouse reinterprets it back to UInt64.+///+/// `metric_type` is part of the identity: a gauge and a sum sharing a name and labels+/// are different series, and `metric_series` stores `metric_type` per fingerprint — so+/// omitting it would let one type's row silently overwrite the other's on dedup.+fn compute_series_fingerprint(+ metric_name: &str,+ metric_type: &str,+ service_name: &str,+ resource_attributes: &HashMap<String, String>,+ attributes: &HashMap<String, String>,+) -> i64 {+ let mut hasher = SipHasher13::new();+ hash_str(&mut hasher, metric_name);+ hash_str(&mut hasher, metric_type);+ hash_str(&mut hasher, service_name);+ hash_sorted_map(&mut hasher, resource_attributes);+ hash_sorted_map(&mut hasher, attributes);+ hasher.finish() as i64+}++/// Length-prefixed so e.g. {"ab":"c"} and {"a":"bc"} can never collide.+fn hash_str(hasher: &mut SipHasher13, s: &str) {+ hasher.write_u64(s.len() as u64);+ hasher.write(s.as_bytes());+}++/// Sort by key so HashMap iteration order can never change the fingerprint.+fn hash_sorted_map(hasher: &mut SipHasher13, map: &HashMap<String, String>) {+ let mut pairs: Vec<(&str, &str)> = map.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();+ pairs.sort_unstable();+ hasher.write_u64(pairs.len() as u64);+ for (key, value) in pairs {+ hash_str(hasher, key);+ hash_str(hasher, value);+ }+}+/// Flatten exponential histogram buckets into explicit bounds and counts.fn flatten_exponential_buckets(scale: i32,@@ -680,4 +742,140 @@ mod tests {assert_eq!(rows[0].trace_id, "");assert_eq!(rows[0].span_id, "");}++ // --- Series fingerprint ---++ fn attrs(pairs: &[(&str, &str)]) -> HashMap<String, String> {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()+ }++ #[test]+ fn test_series_fingerprint_is_order_independent() {+ // The same logical label set must hash identically regardless of HashMap+ // iteration order — this is the invariant the whole join depends on.+ let resource = attrs(&[("k8s.pod", "\"p\""), ("k8s.node", "\"n\"")]);+ let a1 = attrs(&[("topic", "\"t\""), ("partition", "\"9\"")]);+ let a2 = attrs(&[("partition", "\"9\""), ("topic", "\"t\"")]);+ assert_eq!(+ compute_series_fingerprint("m", "gauge", "svc", &resource, &a1),+ compute_series_fingerprint("m", "gauge", "svc", &resource, &a2),+ );+ }++ #[test]+ fn test_series_fingerprint_distinguishes_label_changes() {+ let r = attrs(&[("k8s.pod", "\"p\"")]);+ let base =+ compute_series_fingerprint("m", "gauge", "svc", &r, &attrs(&[("partition", "\"9\"")]));+ // a different value, a different key, a different metric, and a different service+ // each yield a different series+ assert_ne!(+ base,+ compute_series_fingerprint("m", "gauge", "svc", &r, &attrs(&[("partition", "\"10\"")]))+ );+ assert_ne!(+ base,+ compute_series_fingerprint("m", "gauge", "svc", &r, &attrs(&[("part", "\"9\"")]))+ );+ assert_ne!(+ base,+ compute_series_fingerprint("m2", "gauge", "svc", &r, &attrs(&[("partition", "\"9\"")]))+ );+ assert_ne!(+ base,+ compute_series_fingerprint("m", "gauge", "svc2", &r, &attrs(&[("partition", "\"9\"")]))+ );+ }++ #[test]+ fn test_series_fingerprint_no_delimiter_collision() {+ // Length-prefixing must stop {"ab":"c"} from colliding with {"a":"bc"}.+ let r = HashMap::new();+ assert_ne!(+ compute_series_fingerprint("m", "gauge", "", &r, &attrs(&[("ab", "c")])),+ compute_series_fingerprint("m", "gauge", "", &r, &attrs(&[("a", "bc")])),+ );+ }++ #[test]+ fn test_series_fingerprint_distinguishes_metric_type() {+ // A gauge and a sum with the same name and labels are semantically distinct+ // series; metric_series stores metric_type per fingerprint, so they must not+ // collapse onto one deduped row. Regression guard for the type dimension.+ let r = attrs(&[("k8s.pod", "\"p\"")]);+ let a = attrs(&[("partition", "\"9\"")]);+ assert_ne!(+ compute_series_fingerprint("m", "gauge", "svc", &r, &a),+ compute_series_fingerprint("m", "sum", "svc", &r, &a),+ );+ }++ #[test]+ fn test_series_fingerprint_is_pinned() {+ // Golden value: locks the algorithm so an accidental hash-library or+ // canonicalization change is caught (it would silently re-key every series).+ let r = attrs(&[("k8s.pod", "\"p\"")]);+ let a = attrs(&[("topic", "\"t\""), ("partition", "\"9\"")]);+ assert_eq!(+ compute_series_fingerprint("m", "gauge", "svc", &r, &a),+ GOLDEN_FINGERPRINT+ );+ }++ const GOLDEN_FINGERPRINT: i64 = 4834068360040973060;++ #[test]+ fn test_build_row_sets_fingerprint() {+ let row = build_test_row(&[]);+ assert_ne!(+ row.series_fingerprint, 0,+ "every row must carry a series identity"+ );+ }++ fn build_row_at(time_unix_nano: u64) -> (KafkaMetricRow, bool) {+ build_number_row(+ "test.metric",+ "gauge",+ "",+ &HashMap::new(),+ "test-service",+ "[email protected]",+ time_unix_nano,+ 0,+ &[],+ 1.0,+ None,+ None,+ &[],+ 0,+ )+ .expect("build_number_row should succeed")+ }++ #[test]+ fn test_series_fingerprint_ignores_timestamp_override() {+ // $originalTimestamp is a synthetic attribute added only when a point's timestamp+ // falls outside the ±24h window, and it is inserted AFTER the fingerprint is+ // computed. A stale point and a fresh one for the same series must therefore share+ // a fingerprint. Guards the compute-before-insert ordering in build_number_row.+ let fresh_nanos = Utc::now().timestamp_nanos_opt().unwrap() as u64;+ let stale_nanos = (Utc::now() - TimeDelta::hours(48))+ .timestamp_nanos_opt()+ .unwrap() as u64;++ let (fresh, fresh_overridden) = build_row_at(fresh_nanos);+ let (stale, stale_overridden) = build_row_at(stale_nanos);++ // The override must actually fire for the stale point, else the test is vacuous.+ assert!(!fresh_overridden);+ assert!(stale_overridden);+ assert!(!fresh.attributes.contains_key("$originalTimestamp"));+ assert!(stale.attributes.contains_key("$originalTimestamp"));+ // Despite that attribute difference, both map to one series.+ assert_eq!(fresh.series_fingerprint, stale.series_fingerprint);+ }}diff --git a/rust/capture-logs/src/metrics_avro_schema.rs b/rust/capture-logs/src/metrics_avro_schema.rsindex 7b19f07d4b5b..91c7d559a68c 100644--- a/rust/capture-logs/src/metrics_avro_schema.rs+++ b/rust/capture-logs/src/metrics_avro_schema.rs@@ -116,6 +116,12 @@ pub const METRICS_AVRO_SCHEMA: &str = r#""values": "string"}],"doc": "A map of custom string-valued attributes associated with the data point."+ },+ {+ "name": "series_fingerprint",+ "type": ["null", "long"],+ "default": null,+ "doc": "Stable per-series identity assigned at ingest (hash of metric_name + sorted resource/data-point attributes). Stored verbatim by ClickHouse, never recomputed. u64 bits carried as a signed long."}]}"#;