diff --git a/Cargo.lock b/Cargo.lock index 7ea6085686a..17f0097e262 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -34,7 +34,6 @@ dependencies = [ "datadog-agent-config", "datadog-agent-config-docs", "datadog-agent-runtime", - "datadog-agent-tag-normalization", "datadog-protos", "derive-where", "futures", @@ -61,9 +60,9 @@ dependencies = [ "saluki-metadata", "saluki-metrics", "saluki-tls", + "saluki-transform-kernels", "serde", "serde_json", - "simdutf8", "stringtheory", "tempfile", "tikv-jemallocator", @@ -5950,6 +5949,7 @@ dependencies = [ "saluki-metadata", "saluki-metrics", "saluki-tls", + "saluki-transform-kernels", "serde", "serde_json", "sha2 0.11.1", @@ -6184,6 +6184,26 @@ dependencies = [ "tracing", ] +[[package]] +name = "saluki-transform-kernels" +version = "0.1.0" +dependencies = [ + "datadog-agent-tag-normalization", + "ddsketch", + "foldhash 0.2.0", + "hashbrown 0.17.2", + "regex", + "saluki-antithesis", + "saluki-common", + "saluki-core", + "saluki-error", + "serde", + "simdutf8", + "smallvec", + "stringtheory", + "tracing", +] + [[package]] name = "same-file" version = "1.0.6" diff --git a/Cargo.toml b/Cargo.toml index c48ea1b72fb..bf7978b9094 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ members = [ "lib/saluki-metrics", "lib/saluki-metrics-macros", "lib/saluki-tls", + "lib/saluki-transform-kernels", "lib/stringtheory", "test/antithesis/harness", "test/antithesis/intake", @@ -88,6 +89,7 @@ saluki-env = { path = "lib/saluki-env" } saluki-error = { path = "lib/saluki-error" } saluki-io = { path = "lib/saluki-io" } saluki-metadata = { path = "lib/saluki-metadata" } +saluki-transform-kernels = { path = "lib/saluki-transform-kernels" } saluki-metrics = { path = "lib/saluki-metrics" } saluki-metrics-macros = { path = "lib/saluki-metrics-macros" } saluki-tls = { path = "lib/saluki-tls" } diff --git a/bin/agent-data-plane/Cargo.toml b/bin/agent-data-plane/Cargo.toml index 559020dc0bc..a7cf9d8596d 100644 --- a/bin/agent-data-plane/Cargo.toml +++ b/bin/agent-data-plane/Cargo.toml @@ -26,7 +26,6 @@ datadog-agent-apm = { workspace = true } datadog-agent-commons = { workspace = true } datadog-agent-config = { workspace = true } datadog-agent-runtime = { workspace = true, features = ["taskdump"] } -datadog-agent-tag-normalization = { workspace = true } datadog-protos = { workspace = true } futures = { workspace = true } http = { workspace = true } @@ -49,9 +48,9 @@ saluki-error = { workspace = true } saluki-io = { workspace = true } saluki-metadata = { workspace = true } saluki-metrics = { workspace = true } +saluki-transform-kernels = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } -simdutf8 = { workspace = true } stringtheory = { workspace = true } tempfile = { workspace = true } tokio = { workspace = true, features = [ diff --git a/bin/agent-data-plane/src/components/dogstatsd_filterlist/mod.rs b/bin/agent-data-plane/src/components/dogstatsd_filterlist/mod.rs index 56cc2822f73..a866493f2f8 100644 --- a/bin/agent-data-plane/src/components/dogstatsd_filterlist/mod.rs +++ b/bin/agent-data-plane/src/components/dogstatsd_filterlist/mod.rs @@ -1,699 +1,3 @@ -//! Shared DogStatsD metric filterlist matcher. +//! Shared DogStatsD metric filterlist matcher delegated to [`saluki_transform_kernels::filterlist`]. -use super::metric_name::{is_normalized, normalize_into, normalize_prefix_into, NameBuf}; - -/// Metric names or prefixes that the DogStatsD filters drop. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct MetricNameFilter { - /// Metric names or prefixes that are dropped. - pub values: Vec, - - /// Whether entries match by prefix rather than exact name. - pub match_prefix: bool, - - /// Additional prefix rules with exceptions shared across all rules. - pub prefix_rules: Vec, -} - -/// A metric-name prefix to drop, with exceptions shared across all prefix rules. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct MetricPrefixRule { - /// Prefix to drop. An empty prefix matches every stored metric name. - pub prefix: String, - - /// Prefixes to keep, unless blocked by the unconditional filter entries. - pub except_prefix: Vec, - - /// Exact names to keep, unless blocked by the unconditional filter entries. - pub except_exact: Vec, -} - -/// Compiled blocklist for metric names that should be filtered. -/// -/// `metric_filterlist` entries are exact names by default. They are treated as prefixes only when -/// the global `metric_filterlist_match_prefix` setting is enabled. -/// -/// Per-entry prefix rules (and their exceptions) come from `metric_filterlist_prefix`. They do not -/// come from `metric_filterlist`. -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub(super) struct Blocklist { - // Sorted, deduplicated, and not covered by `prefixes`. - exact: Vec, - // Sorted, deduplicated, and compacted prefixes from `metric_filterlist` when - // `metric_filterlist_match_prefix` is enabled. - prefixes: Vec, - // Sorted, deduplicated, and compacted prefixes from `metric_filterlist_prefix`. - rule_prefixes: Vec, - // Global exceptions from `metric_filterlist_prefix`. - except_exact: Vec, - except_prefix: Vec, -} - -#[derive(Clone, Debug, Default, Eq, PartialEq)] -struct PrefixRule { - prefix: String, - except_exact: Vec, - except_prefix: Vec, -} - -/// Diagnostics from compiling a runtime metric filter. -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub(super) struct CompilationReport { - /// `metric_filterlist` entries dropped because no stored metric name can match them. - pub dropped_entries: Vec, - /// `metric_filterlist_prefix` rules dropped because their prefixes cannot match any stored - /// metric name. - pub dropped_rules: Vec, - /// `metric_filterlist_prefix` exceptions dropped because they cannot match any stored metric - /// name. - pub dropped_exceptions: Vec, - /// `metric_filterlist_prefix` rules shadowed by an unconditional global prefix from - /// `metric_filterlist` when `metric_filterlist_match_prefix` is enabled. - pub shadowed_rules: Vec, -} - -/// Compiles a runtime [`MetricNameFilter`] into a matcher. -pub(super) fn compile_metric_filter(metric_filter: &MetricNameFilter) -> (Blocklist, CompilationReport) { - let (normalized_entries, dropped_entries) = normalize_entries(&metric_filter.values, metric_filter.match_prefix); - let (normalized_rules, dropped_rules, dropped_exceptions) = normalize_prefix_rules(&metric_filter.prefix_rules); - - let (matcher, shadowed_rules) = Blocklist::new_with_prefix_rules( - normalized_entries.iter().map(String::as_str), - metric_filter.match_prefix, - &normalized_rules, - ); - - ( - matcher, - CompilationReport { - dropped_entries, - dropped_rules, - dropped_exceptions, - shadowed_rules, - }, - ) -} - -impl Blocklist { - /// Creates a matcher for `metric_filterlist` only. - /// - /// Entries are taken verbatim and are expected to already be normalized in the same namespace - /// the intake stores metric names in. - #[cfg(test)] - pub(super) fn new(values: I, match_prefix: bool) -> Self - where - T: AsRef, - I: IntoIterator, - { - let (matcher, _) = Self::new_with_prefix_rules(values, match_prefix, &[]); - matcher - } - - /// Creates a matcher from normalized `metric_filterlist` and `metric_filterlist_prefix` - /// entries. - /// - /// Returns any `metric_filterlist_prefix` rules shadowed by an unconditional - /// `metric_filterlist` prefix introduced by global `metric_filterlist_match_prefix` mode. - fn new_with_prefix_rules(values: I, match_prefix: bool, rules: &[PrefixRule]) -> (Self, Vec) - where - T: AsRef, - I: IntoIterator, - { - let mut exact = Vec::new(); - let mut prefixes = Vec::new(); - for value in values { - if match_prefix { - prefixes.push(value.as_ref().to_string()); - } else { - exact.push(value.as_ref().to_string()); - } - } - - let mut rule_prefixes = Vec::with_capacity(rules.len()); - let mut except_exact = Vec::new(); - let mut except_prefix = Vec::new(); - for rule in rules { - rule_prefixes.push(rule.prefix.clone()); - except_exact.extend(rule.except_exact.iter().cloned()); - except_prefix.extend(rule.except_prefix.iter().cloned()); - } - - prefixes = compact_prefixes(prefixes); - exact = compact_exact(exact, &prefixes); - except_prefix = compact_prefixes(except_prefix); - except_exact = compact_exact(except_exact, &except_prefix); - - let mut shadowed_rules = Vec::new(); - if !prefixes.is_empty() { - rule_prefixes.retain(|prefix| { - let shadowed = test_prefixes(&prefixes, prefix.as_bytes()); - if shadowed { - shadowed_rules.push(prefix.clone()); - } - !shadowed - }); - } - rule_prefixes = compact_prefixes(rule_prefixes); - - ( - Self { - exact, - prefixes, - rule_prefixes, - except_exact, - except_prefix, - }, - shadowed_rules, - ) - } - - /// Returns whether `name` matches a configured metric name. - /// - /// The name is normalized before being compared. Metric names arrive exactly as they were - /// submitted, but the intake rewrites them on ingest: a raw name such as `my metric-name` is - /// stored as `my_metric_name`, which is what users copy into a filterlist. - pub(super) fn contains(&self, name: &str) -> bool { - if self.len() == 0 { - return false; - } - - // Fast path: already normalized, so compare the name as given. - if is_normalized(name) { - return self.search(name.as_bytes()); - } - - let mut buf = NameBuf::new(); - match normalize_into(&mut buf, name) { - Some(normalized) => self.search(normalized), - None => false, - } - } - - /// Returns whether `name` is blocked by a prefix rule but has an exception below its namespace. - /// - /// This is used to preserve histogram inputs that are needed to generate allowed post-aggregate - /// series (for example, preserving `foo` when `foo.avg` is explicitly excepted). - pub(super) fn has_descendant_exception(&self, name: &str) -> bool { - if self.rule_prefixes.is_empty() || (self.except_exact.is_empty() && self.except_prefix.is_empty()) { - return false; - } - - // Fast path: already normalized, so compare the name as given. - if is_normalized(name) { - return self.has_descendant_exception_normalized(name.as_bytes()); - } - - let mut buf = NameBuf::new(); - match normalize_into(&mut buf, name) { - Some(normalized) => self.has_descendant_exception_normalized(normalized), - None => false, - } - } - - fn has_descendant_exception_normalized(&self, name: &[u8]) -> bool { - // metric_filterlist exact/prefix entries always win over metric_filterlist_prefix rules. - if binary_search_exact(&self.exact, name) || test_prefixes(&self.prefixes, name) { - return false; - } - - // Not blocked by a prefix rule, or already excepted as-is. - if !test_prefixes(&self.rule_prefixes, name) - || test_prefixes(&self.except_prefix, name) - || binary_search_exact(&self.except_exact, name) - { - return false; - } - - let has_descendant = |exceptions: &[String]| { - let index = exceptions - .partition_point(|candidate| candidate.bytes().cmp(name.iter().copied().chain([b'.'])).is_lt()); - - exceptions.get(index).is_some_and(|candidate| { - candidate - .as_bytes() - .strip_prefix(name) - .is_some_and(|suffix| suffix.starts_with(b".")) - }) - }; - - has_descendant(&self.except_exact) || has_descendant(&self.except_prefix) - } - - /// Restricts exact entries and keeps all prefix behavior unchanged. - pub(super) fn restrict_exact(&self, keep: impl Fn(&str) -> bool) -> Self { - let exact = self - .exact - .iter() - .filter(|entry| keep(entry.as_str())) - .cloned() - .collect::>(); - - Self { - exact, - prefixes: self.prefixes.clone(), - rule_prefixes: self.rule_prefixes.clone(), - except_exact: self.except_exact.clone(), - except_prefix: self.except_prefix.clone(), - } - } - - /// Returns the number of compiled entries. - pub(super) fn len(&self) -> usize { - self.exact.len() + self.prefixes.len() + self.rule_prefixes.len() - } - - /// Returns whether the matcher blocks every stored metric name. - pub(super) fn matches_all(&self) -> bool { - if self.prefixes.len() == 1 && self.prefixes[0].is_empty() { - return true; - } - - self.rule_prefixes.len() == 1 - && self.rule_prefixes[0].is_empty() - && self.except_exact.is_empty() - && self.except_prefix.is_empty() - } - - /// Looks `name` up in the compiled entries. - /// - /// `name` must already be normalized. - fn search(&self, name: &[u8]) -> bool { - if binary_search_exact(&self.exact, name) { - return true; - } - - if test_prefixes(&self.prefixes, name) { - return true; - } - - if !test_prefixes(&self.rule_prefixes, name) { - return false; - } - - if test_prefixes(&self.except_prefix, name) { - return false; - } - - !binary_search_exact(&self.except_exact, name) - } -} - -/// Normalizes raw `metric_filterlist` entries. -/// -/// `match_prefix` corresponds to the global `metric_filterlist_match_prefix` setting: per-entry -/// prefixes are configured with `metric_filterlist_prefix` instead. -/// -/// Dropped entries cannot match any metric name stored by the intake. -fn normalize_entries(entries: &[String], match_prefix: bool) -> (Vec, Vec) { - let mut normalized = Vec::with_capacity(entries.len()); - let mut dropped = Vec::new(); - let mut buf = NameBuf::new(); - - for entry in entries { - let key = if match_prefix { - normalize_prefix_into(&mut buf, entry) - } else { - normalize_into(&mut buf, entry) - }; - - match key { - Some(key) => normalized.push( - simdutf8::basic::from_utf8(key) - .expect("normalized metric names are ASCII") - .to_owned(), - ), - None => dropped.push(entry.clone()), - } - } - - (normalized, dropped) -} - -/// Normalizes raw `metric_filterlist_prefix` rules. -/// -/// Prefix and `except_prefix` entries normalize as prefixes; `except_exact` entries normalize as -/// full names. -fn normalize_prefix_rules(rules: &[MetricPrefixRule]) -> (Vec, Vec, Vec) { - let mut normalized = Vec::with_capacity(rules.len()); - let mut dropped_rules = Vec::new(); - let mut dropped_exceptions = Vec::new(); - let mut buf = NameBuf::new(); - - for rule in rules { - let Some(prefix) = normalize_prefix_into(&mut buf, &rule.prefix) else { - dropped_rules.push(rule.prefix.clone()); - continue; - }; - - let mut normalized_rule = PrefixRule { - prefix: simdutf8::basic::from_utf8(prefix) - .expect("normalized metric names are ASCII") - .to_owned(), - except_exact: Vec::new(), - except_prefix: Vec::new(), - }; - - for exact in &rule.except_exact { - match normalize_into(&mut buf, exact) { - Some(key) => normalized_rule.except_exact.push( - simdutf8::basic::from_utf8(key) - .expect("normalized metric names are ASCII") - .to_owned(), - ), - None => dropped_exceptions.push(exact.clone()), - } - } - - for prefix in &rule.except_prefix { - match normalize_prefix_into(&mut buf, prefix) { - Some(key) => normalized_rule.except_prefix.push( - simdutf8::basic::from_utf8(key) - .expect("normalized metric names are ASCII") - .to_owned(), - ), - None => dropped_exceptions.push(prefix.clone()), - } - } - - normalized.push(normalized_rule); - } - - (normalized, dropped_rules, dropped_exceptions) -} - -/// Compact a list of prefixes by removing any prefixes that already have a shorter prefix -/// defined for it. -fn compact_prefixes(mut prefixes: Vec) -> Vec { - if prefixes.is_empty() { - return Vec::new(); - } - - prefixes.sort_unstable(); - - let mut compacted = Vec::with_capacity(prefixes.len()); - for prefix in prefixes { - if compacted.last().map(|kept| prefix.starts_with(kept)).unwrap_or(false) { - continue; - } - compacted.push(prefix); - } - - compacted -} - -/// Remove any exact matches that are duplicates or are already defined by a given -/// prefix rule. -fn compact_exact(mut exact: Vec, prefixes: &[String]) -> Vec { - if exact.is_empty() { - return Vec::new(); - } - - exact.sort_unstable(); - exact.dedup(); - - if prefixes.is_empty() { - return exact; - } - - exact.retain(|name| !test_prefixes(prefixes, name.as_bytes())); - exact -} - -fn binary_search_exact(entries: &[String], name: &[u8]) -> bool { - entries - .binary_search_by(|candidate| candidate.as_bytes().cmp(name)) - .is_ok() -} - -/// Returns true if `name` starts with one of `prefixes`. -/// -/// `prefixes` must be sorted and compacted by [`compact_prefixes`]. -fn test_prefixes(prefixes: &[String], name: &[u8]) -> bool { - if prefixes.is_empty() { - return false; - } - - let index = prefixes - .binary_search_by(|candidate| candidate.as_bytes().cmp(name)) - .unwrap_or_else(|idx| idx); - - if index > 0 && name.starts_with(prefixes[index - 1].as_bytes()) { - return true; - } - - index < prefixes.len() && prefixes[index].as_bytes() == name -} - -#[cfg(test)] -mod tests { - use super::*; - - fn rule(prefix: &str, except_exact: &[&str], except_prefix: &[&str]) -> MetricPrefixRule { - MetricPrefixRule { - prefix: prefix.to_string(), - except_exact: except_exact.iter().map(ToString::to_string).collect(), - except_prefix: except_prefix.iter().map(ToString::to_string).collect(), - } - } - - #[test] - fn compiles_entries_verbatim() { - let compiled = |values: &[&str]| Blocklist::new(values.iter().copied(), true).prefixes; - - assert_eq!(compiled(&[]), Vec::::new()); - assert_eq!(compiled(&["a"]), vec!["a"]); - assert_eq!(compiled(&["a", "aa"]), vec!["a"]); - assert_eq!(compiled(&["a", "aa", "b", "bb"]), vec!["a", "b"]); - assert_eq!(compiled(&["a", "b", "bb"]), vec!["a", "b"]); - - // Entries are taken verbatim. Normalization happens before compilation. - assert_eq!(compiled(&["a-b", "a_b"]), vec!["a-b", "a_b"]); - } - - #[test] - fn prefix_entries_are_not_rewritten() { - let blocklist = Blocklist::new(["redis.checkpoint_"], true); - - assert!(blocklist.contains("redis.checkpoint_bytes")); - assert!( - blocklist.contains("redis.checkpoint-bytes"), - "raw name normalizes into the family" - ); - - assert!(!blocklist.contains("redis.checkpointing.count")); - assert!(!blocklist.contains("redis.checkpointed")); - } - - #[test] - fn matching_normalizes_the_metric_name() { - // (expected, name, entries, match_prefix) - let cases: &[(bool, &str, &[&str], bool)] = &[ - (true, "my metric-name", &["my_metric_name"], false), - (true, "custom.metric one", &["custom.metric_one"], false), - (true, "host.cpu%util", &["host.cpu_util"], false), - (true, "1app.requests", &["app.requests"], false), - (true, "café.requests", &["caf.requests"], false), - (true, "multiple-norm-1", &["multiple_norm_1"], false), - (true, "multiple_norm-1", &["multiple_norm_1"], false), - (false, "my_metric_name", &["my metric-name"], false), - (false, "my metric-name", &["my-metric-name"], false), - (false, "my.metric", &["my_metric"], false), - (false, "other metric", &["my_metric"], false), - (true, "custom.metric name.count", &["custom.metric_name"], true), - (false, "custom.metric name.count", &["custom.other"], true), - (false, "", &["foo"], false), - (false, "123", &["foo"], false), - ]; - - for (expected, name, entries, match_prefix) in cases { - let blocklist = Blocklist::new(entries.iter().copied(), *match_prefix); - assert_eq!( - blocklist.contains(name), - *expected, - "name: {:?}, entries: {:?}, match_prefix: {}", - name, - entries, - match_prefix - ); - } - } - - #[test] - fn overlong_names_never_match() { - let name = "foo".repeat(200); - - assert!(!Blocklist::new(["foo"], true).contains(&name)); - assert!(!Blocklist::new([name.as_str()], false).contains(&name)); - } - - #[test] - fn matches_exact_and_prefix_entries() { - // (expected, name, entries, match_prefix) - let cases: &[(bool, &str, &[&str], bool)] = &[ - (false, "some", &[], false), - (false, "some", &[], true), - (false, "foo", &["bar", "baz"], false), - (false, "foo", &["bar", "baz"], true), - (false, "bar", &["foo", "baz"], false), - (false, "bar", &["foo", "baz"], true), - (true, "baz", &["foo", "baz"], false), - (true, "baz", &["foo", "baz"], true), - (false, "foobar", &["foo", "baz"], false), - (true, "foobar", &["foo", "baz"], true), - ]; - - for (expected, name, entries, match_prefix) in cases { - let blocklist = Blocklist::new(entries.iter().copied(), *match_prefix); - assert_eq!( - blocklist.contains(name), - *expected, - "name: {:?}, entries: {:?}, match_prefix: {}", - name, - entries, - match_prefix - ); - } - } - - #[test] - fn prefix_rule_exceptions_apply_across_rules() { - let rules = vec![ - PrefixRule { - prefix: "foo.".to_string(), - except_exact: vec!["foo.bar".to_string()], - except_prefix: Vec::new(), - }, - PrefixRule { - prefix: "foo.b".to_string(), - except_exact: Vec::new(), - except_prefix: Vec::new(), - }, - ]; - - let (matcher, shadowed_rules) = Blocklist::new_with_prefix_rules(Vec::::new(), false, &rules); - assert!(shadowed_rules.is_empty()); - - assert!(!matcher.contains("foo.bar")); - assert!(matcher.contains("foo.baz")); - assert!(matcher.contains("foo.other")); - } - - #[test] - fn shadowed_rules_are_dropped_when_global_prefixes_cover_them() { - let rules = vec![PrefixRule { - prefix: "postgresql.locks.".to_string(), - except_exact: vec!["postgresql.locks.waiting".to_string()], - except_prefix: Vec::new(), - }]; - - let (matcher, shadowed_rules) = Blocklist::new_with_prefix_rules(["postgresql."], true, &rules); - - assert_eq!(shadowed_rules, vec!["postgresql.locks.".to_string()]); - assert!(matcher.rule_prefixes.is_empty()); - assert!(matcher.contains("postgresql.locks.waiting")); - } - - #[test] - fn matches_all_detects_unconditional_prefixes() { - assert!(Blocklist::new([""], true).matches_all()); - - let rules = vec![PrefixRule { - prefix: "".to_string(), - except_exact: Vec::new(), - except_prefix: Vec::new(), - }]; - let (matcher, _) = Blocklist::new_with_prefix_rules(Vec::::new(), false, &rules); - assert!(matcher.matches_all()); - - let rules_with_exception = vec![PrefixRule { - prefix: "".to_string(), - except_exact: vec!["keep.me".to_string()], - except_prefix: Vec::new(), - }]; - let (matcher, _) = Blocklist::new_with_prefix_rules(Vec::::new(), false, &rules_with_exception); - assert!(!matcher.matches_all()); - } - - #[test] - fn restrict_exact_keeps_prefix_state() { - let rules = vec![PrefixRule { - prefix: "bar.".to_string(), - except_exact: vec!["bar.keep".to_string()], - except_prefix: Vec::new(), - }]; - let (matcher, _) = Blocklist::new_with_prefix_rules(["foo.count", "foo.max"], false, &rules); - - let restricted = matcher.restrict_exact(|name| name.ends_with(".count")); - - assert_eq!(restricted.exact, vec!["foo.count".to_string()]); - assert_eq!(restricted.prefixes, matcher.prefixes); - assert_eq!(restricted.rule_prefixes, matcher.rule_prefixes); - assert_eq!(restricted.except_exact, matcher.except_exact); - assert_eq!(restricted.except_prefix, matcher.except_prefix); - } - - #[test] - fn compile_metric_filter_normalizes_entries_and_rules() { - let metric_filter = MetricNameFilter { - values: vec!["my metric-name".to_string(), "123".to_string(), "service_".to_string()], - match_prefix: false, - prefix_rules: vec![rule("prefix.", &["prefix exact"], &["prefix-keep-"])], - }; - - let (matcher, report) = compile_metric_filter(&metric_filter); - - assert_eq!(report.dropped_entries, vec!["123".to_string()]); - assert!(report.dropped_rules.is_empty()); - assert!(report.dropped_exceptions.is_empty()); - assert!(report.shadowed_rules.is_empty()); - - // Exact entries normalize as full names. - assert!(matcher.contains("my metric-name")); - assert!(matcher.contains("my_metric_name")); - assert!(matcher.contains("service")); - assert!(matcher.contains("service_")); - assert!(!matcher.contains("service.other")); - - // Prefix rules normalize their prefix and exceptions as prefixes. - assert!(matcher.contains("prefix.stuff")); - assert!(!matcher.contains("prefix_exact")); - assert!(!matcher.contains("prefix_keep_metric")); - } - - #[test] - fn compile_metric_filter_prefix_mode_preserves_boundaries() { - let metric_filter = MetricNameFilter { - values: vec!["service_".to_string()], - match_prefix: true, - prefix_rules: Vec::new(), - }; - - let (matcher, report) = compile_metric_filter(&metric_filter); - assert!(report.dropped_entries.is_empty()); - - assert!(matcher.contains("service_requests")); - assert!(matcher.contains("service requests")); - assert!(!matcher.contains("service.requests")); - assert!(!matcher.contains("service")); - } - - #[test] - fn compile_metric_filter_drops_unusable_prefix_rule_but_keeps_others() { - let metric_filter = MetricNameFilter { - values: Vec::new(), - match_prefix: false, - prefix_rules: vec![ - rule("123", &[], &[]), - rule("foo.", &["123", "foo.keep"], &["123", "foo.skip."]), - ], - }; - - let (matcher, report) = compile_metric_filter(&metric_filter); - assert_eq!(report.dropped_rules, vec!["123".to_string()]); - assert_eq!(report.dropped_exceptions, vec!["123".to_string(), "123".to_string()]); - - assert!(matcher.contains("foo.anything")); - assert!(!matcher.contains("foo.keep")); - assert!(!matcher.contains("foo.skip.waiting")); - } -} +pub use saluki_transform_kernels::filterlist::{compile_metric_filter, Blocklist, MetricNameFilter, MetricPrefixRule}; diff --git a/bin/agent-data-plane/src/components/dogstatsd_no_agg_split/mod.rs b/bin/agent-data-plane/src/components/dogstatsd_no_agg_split/mod.rs index 63a1a9fad5e..5307a32e632 100644 --- a/bin/agent-data-plane/src/components/dogstatsd_no_agg_split/mod.rs +++ b/bin/agent-data-plane/src/components/dogstatsd_no_agg_split/mod.rs @@ -19,15 +19,15 @@ use saluki_core::{ transforms::{Transform, TransformBuilder, TransformContext}, BuildContext, }, - data_model::event::{ - metric::{Metric, MetricValues}, - Event, EventType, - }, + data_model::event::{metric::Metric, Event, EventType}, observability::ComponentMetricsExt as _, topology::{EventsBuffer, EventsDispatcher, OutputDefinition}, }; use saluki_error::GenericError; use saluki_metrics::MetricsBuilder; +use saluki_transform_kernels::timestamp_split::{ + counter_values_to_rate, is_supported_passthrough_type, try_split_timestamped_values, +}; use tokio::{pin, select, time::interval}; use tracing::{debug, error, trace, warn}; @@ -37,12 +37,6 @@ use self::telemetry::Telemetry; const PASSTHROUGH_OUTPUT: &str = "passthrough"; const PASSTHROUGH_IDLE_FLUSH_CHECK_INTERVAL: Duration = Duration::from_secs(2); -// Timestamped counters carry no duration. Core Agent encodes them as rates using this fixed compatibility interval, -// independently of its time sampler's interval. Changing an Agent-owned aggregation window must not reinterpret -// a client-provided point. This is a protocol convention, not a configurable aggregation default. -// https://github.com/DataDog/datadog-agent/blob/78c2c984e848055b4aa63c5f6a9e94a534a07a44/pkg/aggregator/no_aggregation_stream_worker.go#L223-L235 -const PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL: Duration = Duration::from_secs(10); - /// DogStatsD no-aggregation-pipeline split transform configuration. /// /// Timestamped counters become rates with a fixed 10-second normalization interval, independently of the configured @@ -109,41 +103,6 @@ fn has_timestamped_metrics(events: &EventsBuffer) -> bool { .any(|metric| metric.values().any_timestamped()) } -fn try_split_timestamped_values(mut metric: Metric) -> (Option, Option) { - if metric.values().all_timestamped() { - (Some(metric), None) - } else if metric.values().any_timestamped() { - // Only _some_ of the values are timestamped, so we'll split the timestamped values into a new metric. - let new_metric_values = metric.values_mut().split_timestamped(); - let new_metric = Metric::from_parts(metric.context().clone(), new_metric_values, metric.metadata().clone()); - - (Some(new_metric), Some(metric)) - } else { - // No timestamped values, so this metric isn't part of the no-aggregation pipeline. - (None, Some(metric)) - } -} - -/// Returns `true` if the given metric values can be forwarded by the no-aggregation pipeline. -/// -/// Like the Datadog Agent, only gauges, counters and rates are supported: there's no way to forward a single -/// timestamped histogram, distribution or set point without aggregating it. -/// -/// -fn is_supported_passthrough_type(values: &MetricValues) -> bool { - matches!( - values, - MetricValues::Counter(_) | MetricValues::Rate(..) | MetricValues::Gauge(_) - ) -} - -fn counter_values_to_rate(values: MetricValues) -> MetricValues { - match values { - MetricValues::Counter(points) => MetricValues::rate(points, PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL), - values => values, - } -} - struct PassthroughBatcher { active_buffer: EventsBuffer, active_buffer_start: Instant, @@ -375,6 +334,7 @@ mod tests { DatadogMetricsConfiguration, UseV3ApiConfig, UseV3ApiSeriesConfig, V3ApiConfig, V3ApiSettings, V3SeriesMode, }; use saluki_components::forwarders::OpwMetricsConfiguration; + use saluki_core::data_model::event::metric::MetricValues; use saluki_core::{ components::test_util::TestComponentDriver, data_model::event::metric::{context::Context, ScalarPoints}, diff --git a/bin/agent-data-plane/src/components/dogstatsd_post_aggregate_filter/mod.rs b/bin/agent-data-plane/src/components/dogstatsd_post_aggregate_filter/mod.rs index 02dc9cdb2f1..ec6f8a71076 100644 --- a/bin/agent-data-plane/src/components/dogstatsd_post_aggregate_filter/mod.rs +++ b/bin/agent-data-plane/src/components/dogstatsd_post_aggregate_filter/mod.rs @@ -3,27 +3,23 @@ //! Drops post-aggregation scalar metrics whose generated histogram aggregate names match the metric filterlist. use async_trait::async_trait; use saluki_common::sync::live::Live; -use saluki_components::transforms::HistogramConfiguration; use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder}; use saluki_core::{ components::{ transforms::{Transform, TransformBuilder, TransformContext}, BuildContext, }, - data_model::event::{ - metric::{Metric, MetricValues}, - EventType, - }, + data_model::event::{metric::Metric, EventType}, observability::ComponentMetricsExt, topology::{EventsBuffer, OutputDefinition}, }; use saluki_error::GenericError; use saluki_metrics::MetricsBuilder; -use stringtheory::MetaString; +use saluki_transform_kernels::filterlist::PostAggregateFilterKernel; use tokio::select; use tracing::{debug, error}; -use crate::components::dogstatsd_filterlist::{compile_metric_filter, Blocklist, MetricNameFilter}; +use crate::components::dogstatsd_filterlist::MetricNameFilter; mod telemetry; @@ -35,7 +31,8 @@ use self::telemetry::Telemetry; /// aggregate transform has expanded histograms into scalar metrics. pub struct DogStatsDPostAggregateFilterConfiguration { metric_filter: Live, - histogram_suffixes: HistogramSuffixes, + histogram_aggregates: Vec, + histogram_percentiles: Vec, } impl DogStatsDPostAggregateFilterConfiguration { @@ -47,7 +44,8 @@ impl DogStatsDPostAggregateFilterConfiguration { ) -> Self { Self { metric_filter, - histogram_suffixes: HistogramSuffixes::new(histogram_aggregates, histogram_percentiles), + histogram_aggregates: histogram_aggregates.to_vec(), + histogram_percentiles: histogram_percentiles.to_vec(), } } } @@ -65,13 +63,16 @@ impl TransformBuilder for DogStatsDPostAggregateFilterConfiguration { async fn build(&self, context: BuildContext) -> Result, GenericError> { let metrics_builder = MetricsBuilder::from_component_context(context.component_context()); - let mut filter = DogStatsDPostAggregateFilter { - matcher: Blocklist::default(), + let kernel = PostAggregateFilterKernel::new( + &self.metric_filter, + &self.histogram_aggregates, + &self.histogram_percentiles, + ); + let filter = DogStatsDPostAggregateFilter { + kernel, metric_filter: self.metric_filter.clone(), - histogram_suffixes: self.histogram_suffixes.clone(), telemetry: Telemetry::new(&metrics_builder), }; - filter.sync_matcher(); Ok(Box::new(filter)) } @@ -85,68 +86,19 @@ impl MemoryBounds for DogStatsDPostAggregateFilterConfiguration { } } -#[derive(Clone, Debug, Eq, PartialEq)] -struct HistogramSuffixes { - values: Vec, -} - -impl HistogramSuffixes { - /// Builds the suffixes of histogram aggregate outputs, matching the Agent's histogram filterlist: - /// - /// - /// Like the Agent, every configured aggregate is a suffix, and a percentile that isn't a number between 0 and 1 is - /// skipped rather than failing the configuration: - /// - /// - /// Percentiles are parsed by the aggregate transform's histogram configuration, so these suffixes always match the - /// percentile series it emits. Skipped percentiles aren't logged here: that configuration logs each one. - fn new(aggregates: &[String], percentiles: &[String]) -> Self { - let mut values = aggregates - .iter() - .map(|aggregate| MetaString::from(aggregate.as_str())) - .collect::>(); - values.extend(HistogramConfiguration::percentile_suffixes(percentiles)); - - Self { values } - } - - /// Returns whether the filterlist entry targets a generated histogram aggregate output. - /// - /// Post-aggregate filtering only owns entries shaped like `.`. Other filterlist entries remain - /// the listener filter's responsibility in `dogstatsd_prefix_filter`. - fn contains_filter_entry(&self, value: &str) -> bool { - self.values.iter().any(|suffix| { - let suffix: &str = suffix.as_ref(); - value - .strip_suffix(suffix) - .map(|prefix| prefix.ends_with('.')) - .unwrap_or(false) - }) - } -} - -fn is_scalar_series_metric(metric: &Metric) -> bool { - matches!( - metric.values(), - MetricValues::Counter(_) | MetricValues::Rate(_, _) | MetricValues::Gauge(_) | MetricValues::Set(_) - ) -} - struct DogStatsDPostAggregateFilter { - matcher: Blocklist, + kernel: PostAggregateFilterKernel, metric_filter: Live, - histogram_suffixes: HistogramSuffixes, telemetry: Telemetry, } impl DogStatsDPostAggregateFilter { fn sync_matcher(&mut self) { - let (matcher, _) = compile_metric_filter(&self.metric_filter); - self.matcher = matcher.restrict_exact(|value| self.histogram_suffixes.contains_filter_entry(value)); + self.kernel.update_filter(&self.metric_filter); } fn should_filter_metric(&self, metric: &Metric) -> bool { - is_scalar_series_metric(metric) && self.matcher.contains(metric.context().name()) + self.kernel.should_filter(metric) } fn transform_buffer(&self, buffer: &mut EventsBuffer) { @@ -225,21 +177,18 @@ mod tests { .into_iter() .map(ToString::to_string) .collect::>(); - let histogram_suffixes = HistogramSuffixes::new(&histogram_aggregates, &histogram_percentiles); let metric_filter = MetricNameFilter { values: values.into_iter().map(ToString::to_string).collect(), match_prefix, prefix_rules: Vec::new(), }; - let mut filter = DogStatsDPostAggregateFilter { - matcher: Blocklist::default(), + let kernel = PostAggregateFilterKernel::new(&metric_filter, &histogram_aggregates, &histogram_percentiles); + DogStatsDPostAggregateFilter { + kernel, metric_filter: Live::new_fixed(metric_filter), - histogram_suffixes, telemetry, - }; - filter.sync_matcher(); - filter + } } fn noop_filter(values: Vec<&str>, match_prefix: bool) -> DogStatsDPostAggregateFilter { @@ -308,7 +257,6 @@ mod tests { // https://github.com/DataDog/datadog-agent/blob/12213fe95538f47d98d73bd945a87b3e24189285/comp/filterlist/impl/filterlist_test.go#L19 #[test] fn prefix_rules_apply_to_histogram_outputs_with_global_exceptions() { - let histogram_suffixes = HistogramSuffixes::new(&["avg".to_string()], &[]); let metric_filter = MetricNameFilter { values: Vec::new(), match_prefix: false, @@ -319,13 +267,12 @@ mod tests { }], }; - let mut filter = DogStatsDPostAggregateFilter { - matcher: Blocklist::default(), + let kernel = PostAggregateFilterKernel::new(&metric_filter, &["avg".to_string()], &[]); + let filter = DogStatsDPostAggregateFilter { + kernel, metric_filter: Live::new_fixed(metric_filter), - histogram_suffixes, telemetry: Telemetry::noop(), }; - filter.sync_matcher(); let names = filter_metric_names( &filter, @@ -416,12 +363,12 @@ mod tests { // Like the Agent's `ParsePercentiles`, a value that isn't a number, or a number outside [0.0, 1.0], is skipped // and the valid percentiles around it still apply. Aggregates are kept as configured. let to_strings = |values: &[&str]| values.iter().map(|v| v.to_string()).collect::>(); - let suffixes = HistogramSuffixes::new( + let suffixes = saluki_transform_kernels::filterlist::HistogramSuffixes::new( &to_strings(&["max", "p99"]), &to_strings(&["abc", "0.95", "1.1", "-0.1"]), ); - let values = suffixes.values.iter().map(|v| v.as_ref()).collect::>(); + let values = suffixes.values().iter().map(|v| v.as_ref()).collect::>(); assert_eq!(values, ["max", "p99", "95percentile"]); } diff --git a/bin/agent-data-plane/src/components/dogstatsd_prefix_filter/mod.rs b/bin/agent-data-plane/src/components/dogstatsd_prefix_filter/mod.rs index b5734f6e772..5f4bfb2d996 100644 --- a/bin/agent-data-plane/src/components/dogstatsd_prefix_filter/mod.rs +++ b/bin/agent-data-plane/src/components/dogstatsd_prefix_filter/mod.rs @@ -4,10 +4,7 @@ use async_trait::async_trait; use metrics::{Counter, Gauge}; use saluki_common::sync::live::Live; use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder}; -use saluki_core::data_model::event::{ - metric::{Metric, MetricValues}, - EventType, -}; +use saluki_core::data_model::event::{metric::Metric, EventType}; use saluki_core::{ components::{ transforms::{Transform, TransformBuilder, TransformContext}, @@ -18,7 +15,7 @@ use saluki_core::{ }; use saluki_error::GenericError; use saluki_metrics::MetricsBuilder; -use stringtheory::MetaString; +use saluki_transform_kernels::filterlist::PrefixFilterKernel; use tokio::select; use tracing::{debug, error, warn}; @@ -63,18 +60,14 @@ impl TransformBuilder for DogStatsDPrefixFilterConfiguration { } async fn build(&self, context: BuildContext) -> Result, GenericError> { - // Ensure our metric prefix has a trailing period so that we don't have to check for, and possibly add it, when we're - // actually processing metrics. - let mut metric_prefix = self.metric_prefix.clone(); - if !metric_prefix.is_empty() && !metric_prefix.ends_with(".") { - metric_prefix.push('.'); - } let metrics_builder = MetricsBuilder::from_component_context(context.component_context()); let telemetry = FilterlistTelemetry::new(&metrics_builder); let mut filter = DogStatsDPrefixFilter { - metric_prefix, - metric_prefix_blocklist: self.metric_prefix_blocklist.clone(), - matcher: Blocklist::default(), + kernel: PrefixFilterKernel::new( + self.metric_prefix.clone(), + self.metric_prefix_blocklist.clone(), + Blocklist::default(), + ), metric_filter: self.metric_filter.clone(), telemetry, }; @@ -132,17 +125,11 @@ impl FilterlistTelemetry { } struct DogStatsDPrefixFilter { - metric_prefix: String, - metric_prefix_blocklist: Vec, - matcher: Blocklist, + kernel: PrefixFilterKernel, metric_filter: Live, telemetry: FilterlistTelemetry, } -fn is_histogram_metric(metric: &Metric) -> bool { - matches!(metric.values(), MetricValues::Histogram(_)) -} - impl DogStatsDPrefixFilter { fn sync_matcher(&mut self, count_update: bool) { let (matcher, report) = compile_metric_filter(&self.metric_filter); @@ -177,65 +164,19 @@ impl DogStatsDPrefixFilter { } self.telemetry.set_filterlist_size(matcher.len()); - self.matcher = matcher; + self.kernel.set_matcher(matcher); if count_update { self.telemetry.increment_filterlist_updates(); } } fn process_metric(&self, metric: &mut Metric) -> bool { - // Metrics that keep their submitted name are passed through without touching their context. - // - // This is the common case, covering deployments with no namespace prefix configured as well as metrics that - // are already prefixed. Rebuilding the context here would clone the host, tags, and origin tags, and - // recalculate the context key, for every metric, so the name is only rewritten when prefixing changes it. - let name = metric.context().name(); - if self.metric_prefix.is_empty() || self.has_excluded_prefix(name) { - return !self.is_filtered(metric, name); + let kept = self.kernel.apply(metric); + if !kept { + self.telemetry.increment_listener_filtered_points(); + debug!("Metric {} excluded due to blocklist.", metric.context().name()); } - - let mut prefixed_metric_name = self.metric_prefix.clone(); - prefixed_metric_name.push_str(name); - let new_metric_name = MetaString::from(prefixed_metric_name); - - if self.is_filtered(metric, &new_metric_name) { - return false; - } - - // Update metric with the new prefixed name. - let new_context = metric.context().with_name(new_metric_name); - let existing_context = metric.context_mut(); - *existing_context = new_context; - - true - } - - /// Returns whether `metric` is filtered out by the metric filterlist. - /// - /// `name` is the name the metric carries once prefixing has been applied, since that is the name the filterlist - /// is written against. Histogram inputs are kept when an aggregate output below their namespace is excepted, - /// because the aggregate transform still needs the input to generate that excepted output. - fn is_filtered(&self, metric: &Metric, name: &str) -> bool { - if !self.matcher.contains(name) { - return false; - } - - if is_histogram_metric(metric) && self.matcher.has_descendant_exception(name) { - return false; - } - - self.telemetry.increment_listener_filtered_points(); - debug!("Metric {} excluded due to blocklist.", name); - - true - } - - fn has_excluded_prefix(&self, metric_name: &str) -> bool { - !self.metric_prefix.is_empty() - && self - .metric_prefix_blocklist - .iter() - .any(|prefix| metric_name.starts_with(prefix)) + kept } } @@ -336,16 +277,8 @@ mod tests { } fn build(self) -> DogStatsDPrefixFilter { - // `DogStatsDPrefixFilterConfiguration::build` adds the same trailing period. - let mut metric_prefix = self.metric_prefix; - if !metric_prefix.is_empty() && !metric_prefix.ends_with('.') { - metric_prefix.push('.'); - } - DogStatsDPrefixFilter { - metric_prefix, - metric_prefix_blocklist: self.metric_prefix_blocklist, - matcher: self.matcher, + kernel: PrefixFilterKernel::new(self.metric_prefix, self.metric_prefix_blocklist, self.matcher), metric_filter: self.metric_filter, telemetry: self.telemetry, } @@ -376,7 +309,7 @@ mod tests { #[test] fn metric_on_blocklist_is_dropped_and_others_pass() { let filter = FilterBuilder::new() - .matcher(Blocklist::new(["foobar", "test"], false)) + .matcher(Blocklist::from_normalized(["foobar", "test"], false)) .build(); let mut metric = Metric::gauge("foobar", 1.0); @@ -390,7 +323,9 @@ mod tests { /// Metrics that keep their submitted name must pass through without their context being rebuilt. #[test] fn passthrough_metric_does_not_rebuild_its_context() { - let filter = FilterBuilder::new().matcher(Blocklist::new(["blocked"], false)).build(); + let filter = FilterBuilder::new() + .matcher(Blocklist::from_normalized(["blocked"], false)) + .build(); let mut metric = Metric::gauge("passes.through", 1.0); let original_context = metric.context().clone(); @@ -423,7 +358,9 @@ mod tests { } let token = ResourceGroupRegistry::global().register_resource_group(GROUP); - let filter = FilterBuilder::new().matcher(Blocklist::new(["blocked"], false)).build(); + let filter = FilterBuilder::new() + .matcher(Blocklist::from_normalized(["blocked"], false)) + .build(); let mut metric = Metric::gauge("passes.through", 1.0); // Run once outside the measured window so that any one-time lazy initialization is not counted. @@ -449,7 +386,7 @@ mod tests { fn blocklist_matches_against_the_prefixed_name() { let filter = FilterBuilder::new() .prefix("foo.") - .matcher(Blocklist::new(["foo.bar", "test"], false)) + .matcher(Blocklist::from_normalized(["foo.bar", "test"], false)) .build(); // `bar` is prefixed to `foo.bar`, which the blocklist matches. @@ -467,7 +404,7 @@ mod tests { #[test] fn prefix_matching_blocklist_drops_metrics_by_prefix() { let filter = FilterBuilder::new() - .matcher(Blocklist::new(["b", "test"], true)) + .matcher(Blocklist::from_normalized(["b", "test"], true)) .build(); // Match-prefix mode is enabled, so `bar` matches prefix `b`. @@ -483,7 +420,7 @@ mod tests { fn prefix_matching_blocklist_applies_after_prefixing() { let filter = FilterBuilder::new() .prefix("foo") - .matcher(Blocklist::new(["foo.", "test"], true)) + .matcher(Blocklist::from_normalized(["foo.", "test"], true)) .build(); // The computed name is `foo.bar`; with match-prefix mode enabled, it matches prefix `foo.`. @@ -710,7 +647,7 @@ mod tests { let telemetry = FilterlistTelemetry::new(&MetricsBuilder::default()); let filter = FilterBuilder::new() - .matcher(Blocklist::new(["foo", "bar"], true)) + .matcher(Blocklist::from_normalized(["foo", "bar"], true)) .telemetry(telemetry) .build(); diff --git a/bin/agent-data-plane/src/components/host_tags/mod.rs b/bin/agent-data-plane/src/components/host_tags/mod.rs index b3a2b2f0eac..98faa9b82d1 100644 --- a/bin/agent-data-plane/src/components/host_tags/mod.rs +++ b/bin/agent-data-plane/src/components/host_tags/mod.rs @@ -1,21 +1,15 @@ -use std::{ - sync::Arc, - time::{Duration, Instant}, -}; +use std::time::{Duration, Instant}; use async_trait::async_trait; use datadog_agent_commons::ipc::{client::RemoteAgentClient, config::RemoteAgentClientConfiguration}; use saluki_core::{ accounting::{MemoryBounds, MemoryBoundsBuilder}, components::{transforms::*, BuildContext}, - data_model::{ - event::metric::Metric, - tags::{SharedTagSet, Tag}, - }, + data_model::event::metric::Metric, topology::EventsBuffer, }; use saluki_error::GenericError; -use stringtheory::MetaString; +use saluki_transform_kernels::host_tags::{filter_metric_host_tags, HostTagsKernel}; /// Host Tags synchronous transform. /// @@ -56,7 +50,7 @@ impl SynchronousTransformBuilder for HostTagsConfiguration { // We only pay attention to the "system" tags, as the "google_cloud_platform" tags are not relevant here. let client = RemoteAgentClient::connect(&self.client_config).await?; let host_tags_reply = client.get_host_tags().await?.into_inner(); - Some(metric_host_tags(host_tags_reply.system)) + Some(filter_metric_host_tags(host_tags_reply.system)) } else { None }; @@ -64,7 +58,7 @@ impl SynchronousTransformBuilder for HostTagsConfiguration { Ok(Box::new(HostTagsEnrichment { start: Instant::now(), expected_tags_duration: self.expected_tags_duration, - host_tags, + kernel: HostTagsKernel::new(host_tags), })) } } @@ -77,37 +71,15 @@ impl MemoryBounds for HostTagsConfiguration { } } -/// Prefix of the Agent's infrastructure-mode mark (`InfraModeTagKey` in `pkg/config/utils/inframode.go`). -const INFRA_MODE_TAG_PREFIX: &str = "infra_mode:"; - -/// Converts the Core Agent's system host tags into the tags attached to metrics. -/// -/// `GetHostTags` includes the Agent's `infra_mode:*` mark, which the Agent strips before copying host tags onto -/// metrics: the intake moves series carrying it out of the customer's metric namespace. -fn metric_host_tags(system: Vec) -> SharedTagSet { - system - .into_iter() - .filter(|tag| !tag.starts_with(INFRA_MODE_TAG_PREFIX)) - .map(|s| Arc::from(s.as_str())) - .map(MetaString::from) - .map(Tag::from) - .collect() -} - pub struct HostTagsEnrichment { start: Instant, expected_tags_duration: Duration, - host_tags: Option, + kernel: HostTagsKernel, } impl HostTagsEnrichment { fn enrich_metric(&mut self, metric: &mut Metric) { - let host_tags = match self.host_tags.as_ref() { - Some(host_tags) => host_tags, - None => return, - }; - - metric.context_mut().mutate_tags(|tags| tags.merge_shared(host_tags)); + self.kernel.apply(metric); } } @@ -115,7 +87,7 @@ impl SynchronousTransform for HostTagsEnrichment { fn transform_buffer(&mut self, event_buffer: &mut EventsBuffer) { // Skip adding host tags if duration has elapsed. if self.start.elapsed() >= self.expected_tags_duration { - self.host_tags = None; + self.kernel.clear(); return; } @@ -129,7 +101,10 @@ impl SynchronousTransform for HostTagsEnrichment { mod tests { use std::time::{Duration, Instant}; - use saluki_core::data_model::event::metric::{context::Context, Metric}; + use saluki_core::data_model::{ + event::metric::{context::Context, Metric}, + tags::{SharedTagSet, Tag}, + }; use super::*; @@ -139,7 +114,7 @@ mod tests { let mut host_tags_enrichment = HostTagsEnrichment { start: Instant::now(), expected_tags_duration: Duration::from_secs(30), - host_tags: Some(host_tags.clone()), + kernel: HostTagsKernel::new(Some(host_tags.clone())), }; // Enrich a metric, and ensure the host tags are added. @@ -151,7 +126,7 @@ mod tests { } // Simulate exceeding our configured enrichment duration by clearing host tags. - host_tags_enrichment.host_tags = None; + host_tags_enrichment.kernel.clear(); // We should no longer enrich the metric with host tags. let mut metric2 = Metric::gauge(Context::from_static_parts("test", &[]), 1.0); @@ -163,7 +138,7 @@ mod tests { fn infra_mode_host_tags_are_not_attached_to_metrics() { // Mirrors the Agent's `WithoutInfraModeTags` (DataDog/datadog-agent#57905), which drops only // `infra_mode:*`. - let host_tags = metric_host_tags(vec![ + let host_tags = filter_metric_host_tags(vec![ "env:prod".to_string(), "infra_mode:cloud_cost_only".to_string(), "infra_mode:".to_string(), diff --git a/bin/agent-data-plane/src/components/metric_filter/mod.rs b/bin/agent-data-plane/src/components/metric_filter/mod.rs index 97996cebd97..1a2b998500d 100644 --- a/bin/agent-data-plane/src/components/metric_filter/mod.rs +++ b/bin/agent-data-plane/src/components/metric_filter/mod.rs @@ -1,11 +1,8 @@ //! Metric filtering shared by MRF and endpoint allow lists. -use std::collections::HashSet; - use async_trait::async_trait; use metrics::{Counter, Gauge}; use saluki_common::sync::live::Live; -use saluki_components::config::metrics_endpoint_routing::compact_metric_prefixes; use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder}; use saluki_core::{ components::{ @@ -18,27 +15,14 @@ use saluki_core::{ }; use saluki_error::GenericError; use saluki_metrics::MetricsBuilder; +use saluki_transform_kernels::routing_filter::MetricAllowlistKernel; +pub use saluki_transform_kernels::routing_filter::MetricMirroring; use tokio::select; use tracing::{debug, error}; -use super::metric_name::{is_normalized, normalize_into, NameBuf}; - const ALLOWLIST_METRICS_FILTERED_METRIC: &str = "metrics_endpoint_allowlist_metrics_filtered_total"; const ALLOWLIST_SIZE_METRIC: &str = "metrics_endpoint_allowlist_size"; -/// Multi-Region Failover metric mirroring settings, delivered as a [`Live`] value. -/// -/// Activation and the allowlist arrive together, so each update rebuilds the filter from one configuration version. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct MetricMirroring { - /// Whether metrics are mirrored to the failover region. - pub enabled: bool, - - /// Metric names permitted to be mirrored, matched exactly. While mirroring is enabled, an empty list mirrors every - /// metric. - pub allowlist: Vec, -} - /// Configuration for a metric filter between enrichment and encoding. /// /// MRF follows live settings for activation and its allowlist. Endpoint routing uses a fixed metric allowlist. @@ -111,65 +95,20 @@ impl FilterSource { } } -/// The matching rule used by both sources. An empty set naturally matches nothing. -enum Filter { - DropAll, - All, - MrfAllowlist(HashSet), - Allowlist { - names: HashSet>, - prefixes: Vec, - }, -} +/// Wraps [`MetricAllowlistKernel`] with component batch dispatch and telemetry. +struct Filter(MetricAllowlistKernel); impl Filter { fn for_allowlist(names: &[String], prefixes: &[String]) -> Self { - let mut prefixes = prefixes.to_vec(); - // Remove covered prefixes so a binary search only needs to check its predecessor. - compact_metric_prefixes(&mut prefixes); - Self::Allowlist { - names: names.iter().map(|name| name.as_bytes().to_vec()).collect(), - prefixes, - } + Self(MetricAllowlistKernel::for_allowlist(names, prefixes)) } fn for_mrf(enabled: bool, routing: &MetricMirroring) -> Self { - if !enabled || !routing.enabled { - Self::DropAll - } else if routing.allowlist.is_empty() { - Self::All - } else { - Self::MrfAllowlist(routing.allowlist.iter().cloned().collect()) - } + Self(MetricAllowlistKernel::for_mirroring(enabled, routing)) } fn should_forward(&self, metric: &Metric) -> bool { - match self { - Self::DropAll => false, - Self::All => true, - Self::MrfAllowlist(names) => names.contains(metric.context().name()), - Self::Allowlist { names, prefixes } => { - let name = metric.context().name(); - if is_normalized(name) { - return Self::matches_allowlist(name.as_bytes(), names, prefixes); - } - let mut buf = NameBuf::new(); - match normalize_into(&mut buf, name) { - Some(normalized) => Self::matches_allowlist(normalized, names, prefixes), - None => false, - } - } - } - } - - fn matches_allowlist(name: &[u8], names: &HashSet>, prefixes: &[String]) -> bool { - if names.contains(name) { - return true; - } - match prefixes.binary_search_by(|prefix| prefix.as_bytes().cmp(name)) { - Ok(_) => true, - Err(index) => index > 0 && name.starts_with(prefixes[index - 1].as_bytes()), - } + self.0.should_forward(metric) } fn filter_events(&self, events: &mut EventsBuffer, telemetry: &Telemetry) -> usize { @@ -218,13 +157,10 @@ impl Telemetry { } fn set_allowlist_sizes(&self, filter: &Filter) { - match filter { - Filter::Allowlist { names, prefixes } => { - // Report stored matcher entries, after exact-name deduplication and prefix compaction. - self.exact_size.set(names.len() as f64); - self.prefix_size.set(prefixes.len() as f64); - } - Filter::DropAll | Filter::All | Filter::MrfAllowlist(_) => {} + if let MetricAllowlistKernel::NormalizedAllowlist { names, prefixes } = &filter.0 { + // Report stored matcher entries, after exact-name deduplication and prefix compaction. + self.exact_size.set(names.len() as f64); + self.prefix_size.set(prefixes.len() as f64); } } diff --git a/bin/agent-data-plane/src/components/mod.rs b/bin/agent-data-plane/src/components/mod.rs index 2443d81e2a9..db321a0274f 100644 --- a/bin/agent-data-plane/src/components/mod.rs +++ b/bin/agent-data-plane/src/components/mod.rs @@ -6,7 +6,6 @@ pub mod dogstatsd_prefix_filter; pub mod host_tags; pub mod liveness; pub mod metric_filter; -mod metric_name; pub mod ottl; pub mod ottl_filter_processor; pub mod ottl_transform_processor; diff --git a/bin/agent-data-plane/src/components/tag_filterlist/mod.rs b/bin/agent-data-plane/src/components/tag_filterlist/mod.rs index 5dddd4d2fe1..74bc28e668f 100644 --- a/bin/agent-data-plane/src/components/tag_filterlist/mod.rs +++ b/bin/agent-data-plane/src/components/tag_filterlist/mod.rs @@ -22,11 +22,9 @@ mod telemetry; -use std::{collections::hash_map::Entry, num::NonZeroUsize, time::Duration}; +use std::{num::NonZeroUsize, time::Duration}; use async_trait::async_trait; -use datadog_agent_tag_normalization::{can_have_value, rule_key, tag_key, TagBuf}; -use saluki_common::collections::{FastHashMap, FastHashSet}; use saluki_common::sync::live::Live; use saluki_core::{ accounting::{MemoryBounds, MemoryBoundsBuilder}, @@ -35,364 +33,33 @@ use saluki_core::{ transforms::{Transform, TransformBuilder, TransformContext}, BuildContext, }, - data_model::{ - event::{ - metric::{ - context::{Context, TagSetMutViewState}, - Metric, MetricValues, - }, - EventType, + data_model::event::{ + metric::{ + context::{Context, TagSetMutViewState}, + Metric, }, - tags::{BorrowedTag, Tag}, + EventType, }, observability::ComponentMetricsExt, topology::OutputDefinition, }; use saluki_error::GenericError; use saluki_metrics::MetricsBuilder; +use saluki_transform_kernels::tag_filter::{ + compile_filters_with_values, filter_metric_tags, is_tag_filter_eligible, CompiledFilters, + CompiledValuePrefixFilters, +}; +pub use saluki_transform_kernels::tag_filter::{ + FilterAction, FilterMetricTagsOutcome, MetricTagFilterEntry, MetricTagValueAllowlistEntry, TagValueMismatchAction, +}; use tokio::select; -use tracing::{debug, error, warn}; - -use super::metric_name::{self, NameBuf}; - -/// One whole-tag filter entry. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct MetricTagFilterEntry { - /// Metric name the entry applies to, compared after metric-name normalization. An entry with an empty name is - /// ignored. - pub metric_name: String, - - /// Whether the listed tags are kept or removed. - pub action: FilterAction, - - /// Tag keys the action applies to, compared after tag-key normalization. - pub tags: Vec, -} - -/// Whether a whole-tag filter entry keeps or removes its tags. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum FilterAction { - /// Keep only the listed tags. - Include, - - /// Remove the listed tags. - Exclude, -} - -/// One tag value allow-list entry. -/// -/// The tag name is compared after tag-key normalization. Value matching is exact and case-sensitive, including any -/// whitespace. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct MetricTagValueAllowlistEntry { - /// Metric-name prefix the entry applies to. - pub metric_prefix: String, - - /// Tag key whose values are constrained, compared after tag-key normalization. Bare tags have no value and are not - /// changed. - pub tag_name: String, - - /// Tag values retained unchanged. An empty list treats every key/value tag as a mismatch. - pub values: Vec, - - /// Action applied when a tag value is absent from `values`. - pub on_miss: TagValueMismatchAction, - - /// Replacement value used when `on_miss` is [`Replace`][TagValueMismatchAction::Replace], emitted as configured - /// after the normalized tag name. - pub replacement: String, -} - -/// Action applied when a tag value is absent from its allow-list. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum TagValueMismatchAction { - /// Removes the tag. - Remove, - - /// Replaces the tag value with the entry's replacement. - Replace, -} +use tracing::{debug, error}; const CONTEXT_CACHE_TTI: Duration = Duration::from_secs(30); const CONTEXT_CACHE_EXPIRATION_INTERVAL: Duration = Duration::from_secs(1); use self::telemetry::Telemetry; -#[derive(Clone, Eq, PartialEq)] -enum CompiledMismatchAction { - Remove, - Replace(Tag), -} - -#[derive(Clone)] -struct CompiledTagValueAllowlist { - allowed_values: FastHashSet, - on_miss: CompiledMismatchAction, -} - -struct CompiledKeyFilter { - is_exclude: bool, - tag_names: FastHashSet, -} - -#[derive(Clone)] -struct CompiledValuePrefixFilter { - metric_prefix: String, - value_allowlists: FastHashMap, -} - -#[derive(Clone, Default)] -struct CompiledValuePrefixFilters(Vec); - -impl CompiledValuePrefixFilters { - fn sort(&mut self) { - self.0 - .sort_unstable_by(|left, right| left.metric_prefix.cmp(&right.metric_prefix)); - } - - fn get(&self, metric_name: &str) -> Option<&CompiledValuePrefixFilter> { - find_matching_prefix(&self.0, metric_name, |filter| filter.metric_prefix.as_str()) - } - - fn rule_count(&self) -> usize { - self.0.iter().map(|filter| filter.value_allowlists.len()).sum() - } -} - -fn find_matching_prefix<'a, T>(entries: &'a [T], value: &str, prefix: impl Fn(&T) -> &str) -> Option<&'a T> { - match entries.binary_search_by(|candidate| prefix(candidate).cmp(value)) { - Ok(index) => Some(&entries[index]), - Err(index) if index > 0 && value.starts_with(prefix(&entries[index - 1])) => Some(&entries[index - 1]), - _ => None, - } -} - -/// Compiled exact-name whole-tag filters and metric-prefix value filters. -#[derive(Default)] -pub struct CompiledFilters { - key_filters: FastHashMap, - value_prefix_filters: CompiledValuePrefixFilters, -} - -impl CompiledFilters { - fn rule_count(&self) -> usize { - self.key_filters.len() + self.value_prefix_filters.rule_count() - } - - /// Returns the whole-tag rule for `metric_name`, compared in the form Datadog stores metric names in. - fn key_filter(&self, metric_name: &str) -> Option<&CompiledKeyFilter> { - if self.key_filters.is_empty() { - return None; - } - if metric_name::is_normalized(metric_name) { - return self.key_filters.get(metric_name); - } - - let mut buf = NameBuf::new(); - self.key_filters.get(normalize_metric_name(&mut buf, metric_name)?) - } -} - -/// Normalizes `name` into `buf`, returning `None` if the intake never stores it. See [`metric_name::normalize_into`]. -fn normalize_metric_name<'buf>(buf: &'buf mut NameBuf, name: &str) -> Option<&'buf str> { - let normalized = metric_name::normalize_into(buf, name)?; - Some(simdutf8::basic::from_utf8(normalized).expect("normalized metric names are ASCII")) -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -/// Outcome of attempting to apply tag filter rules to a metric. -pub enum FilterMetricTagsOutcome { - /// No rule existed for the metric name. - RuleMiss, - /// A rule existed, but applying it didn't change any tags. - NoChange, - /// A rule existed and removed one or more tags. - Modified { - /// Total number of instrumented and origin tags removed. - removed_tags: usize, - }, -} - -/// Compile a slice of filter entries into an O(1)-lookup table. -/// -/// Metric names and tag keys are normalized first. An entry whose metric name the intake never stores, and a tag key -/// no stored tag can have, can't match anything, so each is dropped with a warning. -/// -/// Merge rules, applied to entries whose normalized metric names are equal: -/// - Same metric name + same action → union of tag key sets. -/// - Same metric name + conflicting actions → `exclude` wins, with a warning. -pub fn compile_filters(entries: &[MetricTagFilterEntry]) -> CompiledFilters { - let mut filters = CompiledFilters::default(); - let mut name_buf = NameBuf::new(); - // For each normalized metric name, the first configured name and whether any entry listed tags. Only used for - // warnings. - let mut sources: FastHashMap = FastHashMap::default(); - - for entry in entries { - if entry.metric_name.is_empty() { - continue; - } - - let Some(metric_name) = normalize_metric_name(&mut name_buf, &entry.metric_name) else { - warn!( - setting = "metric_tag_filterlist", - metric_name = %entry.metric_name, - "Dropping entry because Datadog never stores its metric name." - ); - continue; - }; - let metric_name = metric_name.to_string(); - - let is_exclude = entry.action == FilterAction::Exclude; - let mut tag_set = FastHashSet::default(); - tag_set.reserve(entry.tags.len()); - for tag in &entry.tags { - match rule_key(tag) { - Some(key) => { - tag_set.insert(key); - } - None => warn!( - setting = "metric_tag_filterlist", - metric_name = %entry.metric_name, - tag = %tag, - "Ignoring tag key containing ':'. List the tag key only, without a value." - ), - } - } - - let source = sources - .entry(metric_name.clone()) - .or_insert_with(|| (entry.metric_name.clone(), false)); - source.1 |= !entry.tags.is_empty(); - - match filters.key_filters.entry(metric_name) { - Entry::Vacant(vacant) => { - vacant.insert(CompiledKeyFilter { - is_exclude, - tag_names: tag_set, - }); - } - Entry::Occupied(mut occupied) => { - if occupied.get().is_exclude == is_exclude { - occupied.get_mut().tag_names.extend(tag_set); - continue; - } - warn!( - setting = "metric_tag_filterlist", - metric_name = %occupied.key(), - first_entry = %source.0, - conflicting_entry = %entry.metric_name, - "Entries for the same metric configure both include and exclude. Keeping only the exclude entries." - ); - if is_exclude { - *occupied.get_mut() = CompiledKeyFilter { - is_exclude, - tag_names: tag_set, - }; - } - } - } - } - - for (metric_name, filter) in &filters.key_filters { - if !filter.is_exclude && filter.tag_names.is_empty() && sources[metric_name].1 { - warn!( - setting = "metric_tag_filterlist", - metric_name = %sources[metric_name].0, - "Include rule has no usable tag keys left, so it removes every tag." - ); - } - } - - filters -} - -/// Adds value allow-list entries to a compiled filter table. -/// -/// Rules are keyed by the normalized form of their tag names. The configuration boundary validates the configured -/// strings, so each metric matches at most one prefix. A rule whose tag name no stored tag with a value can have, or -/// whose tag name normalizes to the same key as an earlier rule for the same prefix, is dropped with a warning, as -/// `metric_tag_filterlist` does with entries that can't match. -/// -/// Unlike whole-tag rule names, metric prefixes are not normalized: they are compared exactly with the metric name as -/// ADP sees it. This keeps prefix matching and its overlap validation simple for this experimental setting. -pub fn add_value_allowlists(filters: &mut CompiledFilters, entries: &[MetricTagValueAllowlistEntry]) { - for entry in entries { - let tag_key = rule_key(&entry.tag_name) - .expect("the configuration boundary rejects value allow-list tag names containing ':'"); - if !can_have_value(&tag_key) { - warn!( - setting = "metric_tag_value_allowlist", - metric_prefix = %entry.metric_prefix, - tag_name = %entry.tag_name, - "Ignoring rule because its tag name is too long for Datadog to store a tag with that name and a value." - ); - continue; - } - - let on_miss = match entry.on_miss { - TagValueMismatchAction::Remove => CompiledMismatchAction::Remove, - TagValueMismatchAction::Replace => { - CompiledMismatchAction::Replace(Tag::from(format!("{}:{}", tag_key, entry.replacement))) - } - }; - - let mut allowed_values = FastHashSet::default(); - allowed_values.reserve(entry.values.len()); - allowed_values.extend(entry.values.iter().cloned()); - let allowlist = CompiledTagValueAllowlist { - allowed_values, - on_miss, - }; - - if let Some(filter) = filters - .value_prefix_filters - .0 - .iter_mut() - .find(|filter| filter.metric_prefix == entry.metric_prefix) - { - match filter.value_allowlists.entry(tag_key) { - Entry::Vacant(vacant) => { - vacant.insert(allowlist); - } - Entry::Occupied(occupied) => warn!( - setting = "metric_tag_value_allowlist", - metric_prefix = %entry.metric_prefix, - tag_name = %entry.tag_name, - normalized_tag_name = %occupied.key(), - "Ignoring rule because its tag name normalizes to the same tag key as an earlier rule for this \ - prefix." - ), - } - } else { - let mut value_allowlists = FastHashMap::default(); - value_allowlists.insert(tag_key, allowlist); - filters.value_prefix_filters.0.push(CompiledValuePrefixFilter { - metric_prefix: entry.metric_prefix.clone(), - value_allowlists, - }); - } - } - - filters.value_prefix_filters.sort(); -} - -fn compile_all_filters( - entries: &[MetricTagFilterEntry], value_allowlists: &[MetricTagValueAllowlistEntry], -) -> CompiledFilters { - let mut filters = compile_filters(entries); - add_value_allowlists(&mut filters, value_allowlists); - filters -} - -fn compile_filters_with_values( - entries: &[MetricTagFilterEntry], value_prefix_filters: CompiledValuePrefixFilters, -) -> CompiledFilters { - let mut filters = compile_filters(entries); - filters.value_prefix_filters = value_prefix_filters; - filters -} - /// Metric Tag Filterlist transform. /// /// Removes, retains, or replaces tags on counter and sketch-backed metrics based on per-metric configuration. Gauges @@ -426,7 +93,7 @@ impl TagFilterlistConfiguration { entries: Live>, value_allowlists: &[MetricTagValueAllowlistEntry], context_cache_capacity: usize, ) -> Self { - let value_prefix_filters = compile_all_filters(&[], value_allowlists).value_prefix_filters; + let value_prefix_filters = CompiledValuePrefixFilters::compile(value_allowlists); Self { entries, value_prefix_filters, @@ -508,9 +175,7 @@ impl Transform for TagFilterlist { maybe_events = context.events().next() => match maybe_events { Some(mut events) => { for metric in events.events_mut::() { - if metric.values().is_sketch() - || matches!(metric.values(), MetricValues::Counter(_)) - { + if is_tag_filter_eligible(metric) { let original_context = metric.context().clone(); if let Some(cached) = self.context_cache.get(&original_context) { @@ -563,105 +228,9 @@ impl Transform for TagFilterlist { } } -#[inline] -fn filter_tag( - tag: &str, key_filter: Option<&CompiledKeyFilter>, value_filter: Option<&CompiledValuePrefixFilter>, - key_buf: &mut TagBuf, replacements: &mut Vec, -) -> bool { - let key = tag_key(tag, key_buf); - - if let Some(key_filter) = key_filter { - if key_filter.is_exclude == key_filter.tag_names.contains(key.key) { - return false; - } - } - - // A raw tag whose `:` falls past the intake's length limit is stored as a bare tag, so it has no value here either. - if !key.has_value { - return true; - } - let Some(allowlist) = value_filter.and_then(|filter| filter.value_allowlists.get(key.key)) else { - return true; - }; - - let Some(value) = BorrowedTag::from(tag).value() else { - return true; - }; - if allowlist.allowed_values.contains(value) { - return true; - } - - match &allowlist.on_miss { - CompiledMismatchAction::Remove => false, - CompiledMismatchAction::Replace(replacement) if replacement.as_str() == tag => true, - CompiledMismatchAction::Replace(replacement) => { - replacements.push(replacement.clone()); - false - } - } -} - -/// Filters the tags of a metric according to the compiled filter table. -/// -/// Both instrumented tags and origin tags are filtered using the same key and value rules, matching normalized metric -/// names and tag keys. Whole-tag filtering runs first, so an `include` rule must include a value-filtered tag key for -/// its allow-list to apply. A metric and tag match at most one value rule: configuration validation rejects overlapping -/// prefixes and duplicate rules, and compilation drops rules whose tag names normalize to the same key. Value rules -/// leave bare tags unchanged; empty-string values are processed and can be retained by including `""` in the configured -/// values. -/// -/// The caller applies this function only to counters and sketch-backed metrics. If the metric name doesn't have an -/// exact whole-tag rule or a matching value-rule prefix, the metric is unchanged. If filtering would not change any -/// tags, the metric context is left untouched (zero allocations). -#[inline] -pub fn filter_metric_tags( - metric: &mut Metric, state: &mut TagSetMutViewState, filters: &CompiledFilters, -) -> FilterMetricTagsOutcome { - let metric_name = metric.context().name(); - let key_filter = filters.key_filter(metric_name); - let value_filter = filters.value_prefix_filters.get(metric_name); - if key_filter.is_none() && value_filter.is_none() { - return FilterMetricTagsOutcome::RuleMiss; - } - - let mut key_buf = TagBuf::new(); - let mut tag_replacements = Vec::new(); - let mut origin_tag_replacements = Vec::new(); - let mut tag_set_view = metric.context_mut().tags_mut_view(state); - tag_set_view.retain_tags(|tag| filter_tag(tag, key_filter, value_filter, &mut key_buf, &mut tag_replacements)); - tag_set_view.retain_origin_tags(|tag| { - filter_tag( - tag, - key_filter, - value_filter, - &mut key_buf, - &mut origin_tag_replacements, - ) - }); - let total_removed = tag_set_view.finish(); - - if !tag_replacements.is_empty() || !origin_tag_replacements.is_empty() { - metric.context_mut().with_tag_sets_mut(|tags, origin_tags| { - for replacement in tag_replacements { - tags.insert_tag(replacement); - } - for replacement in origin_tag_replacements { - origin_tags.insert_tag(replacement); - } - }); - } - - if total_removed == 0 { - FilterMetricTagsOutcome::NoChange - } else { - FilterMetricTagsOutcome::Modified { - removed_tags: total_removed, - } - } -} - #[cfg(test)] mod tests { + use saluki_common::collections::FastHashSet; use saluki_core::{ components::test_util::{ComponentControl, Output, TestComponentDriver}, data_model::{ @@ -677,6 +246,7 @@ mod tests { topology::EventsBuffer, }; use saluki_metrics::{test::TestRecorder, MetricsBuilder}; + use saluki_transform_kernels::tag_filter::{compile_all_filters, compile_filters}; use super::*; @@ -1154,8 +724,8 @@ mod tests { ]; let filters = compile_filters(&entries); - assert!(!filters.key_filters.contains_key("")); - assert!(filters.key_filters.contains_key("my.dist")); + assert!(!filters.has_key_filter("")); + assert!(filters.has_key_filter("my.dist")); } fn key_entry(metric_name: &str, action: FilterAction, tags: &[&str]) -> MetricTagFilterEntry { @@ -1225,9 +795,9 @@ mod tests { )]); // `123`, `` and `_` all normalize to the empty key, which the intake stores for `:x` and `123:x`. - let key_filter = filters.key_filters.get("my.dist").expect("rule should compile"); + let (_, tag_names_set) = filters.key_filter_entry("my.dist").expect("rule should compile"); assert_eq!( - key_filter.tag_names, + *tag_names_set, FastHashSet::from_iter(["env".to_string(), String::new()]) ); @@ -1243,7 +813,7 @@ mod tests { key_entry("123", FilterAction::Exclude, &["env"]), ]); assert_eq!( - filters.key_filters.len(), + filters.key_filter_count(), 1, "a name the intake never stores is dropped" ); @@ -1278,18 +848,18 @@ mod tests { key_entry("other.metric", FilterAction::Include, &["host"]), key_entry("_other.metric", FilterAction::Exclude, &["Env"]), ]); - assert_eq!(filters.key_filters.len(), 2); + assert_eq!(filters.key_filter_count(), 2); - let union = filters.key_filters.get("my.metric").expect("merged rule"); - assert!(union.is_exclude); + let (union_is_exclude, union_tags) = filters.key_filter_entry("my.metric").expect("merged rule"); + assert!(union_is_exclude); assert_eq!( - union.tag_names, + *union_tags, FastHashSet::from_iter(["env".to_string(), "host".to_string()]) ); - let exclude_wins = filters.key_filters.get("other.metric").expect("merged rule"); - assert!(exclude_wins.is_exclude); - assert_eq!(exclude_wins.tag_names, FastHashSet::from_iter(["env".to_string()])); + let (exclude_is_exclude, exclude_tags) = filters.key_filter_entry("other.metric").expect("merged rule"); + assert!(exclude_is_exclude); + assert_eq!(*exclude_tags, FastHashSet::from_iter(["env".to_string()])); } #[test] diff --git a/lib/saluki-components/Cargo.toml b/lib/saluki-components/Cargo.toml index 53405a80765..753cb416229 100644 --- a/lib/saluki-components/Cargo.toml +++ b/lib/saluki-components/Cargo.toml @@ -73,6 +73,7 @@ saluki-io = { workspace = true } saluki-metadata = { workspace = true } saluki-metrics = { workspace = true } saluki-tls = { workspace = true } +saluki-transform-kernels = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } diff --git a/lib/saluki-components/src/config/metrics_endpoint_routing.rs b/lib/saluki-components/src/config/metrics_endpoint_routing.rs index 8991c572409..330b73b9b05 100644 --- a/lib/saluki-components/src/config/metrics_endpoint_routing.rs +++ b/lib/saluki-components/src/config/metrics_endpoint_routing.rs @@ -3,24 +3,11 @@ use std::collections::{BTreeMap, HashMap}; use saluki_error::{generic_error, GenericError}; +/// Sorts literal prefixes and removes duplicates and prefixes covered by another prefix. +pub use saluki_transform_kernels::routing_filter::compact_metric_prefixes; use crate::common::datadog::routing::{RoutingTargetCatalog, RoutingTargetSet}; -/// Sorts literal prefixes and removes duplicates and prefixes covered by another prefix. -pub fn compact_metric_prefixes(prefixes: &mut Vec) { - prefixes.sort_unstable(); - if !prefixes.is_empty() { - let mut retained = 0; - for next in 1..prefixes.len() { - if !prefixes[next].starts_with(&prefixes[retained]) { - retained += 1; - prefixes.swap(retained, next); - } - } - prefixes.truncate(retained + 1); - } -} - /// A group of configured endpoints that share exact-name and prefix metric allowlists. #[derive(Clone, Debug, Eq, PartialEq)] pub struct EndpointAllowlistGroup { diff --git a/lib/saluki-components/src/transforms/aggregate/config.rs b/lib/saluki-components/src/transforms/aggregate/config.rs index e3a3f7744ea..15f6c4fe765 100644 --- a/lib/saluki-components/src/transforms/aggregate/config.rs +++ b/lib/saluki-components/src/transforms/aggregate/config.rs @@ -1,308 +1 @@ -use saluki_core::data_model::event::metric::HistogramSummary; -use stringtheory::MetaString; -use tracing::error; - -/// A histogram statistic to calculate. -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq, serde::Serialize))] -pub enum HistogramStatistic { - /// Total count of values in the histogram. - Count, - - /// Sum of all values in the histogram. - Sum, - - /// Minimum value in the histogram. - Minimum, - - /// Maximum value in the histogram. - Maximum, - - /// Average value in the histogram. - Average, - - /// Median value in the histogram. - Median, - - /// Calculate the given percentile from the histogram. - Percentile { - /// Quantile value to calculate. - q: f64, - - /// Suffix to append to the metric name, representing the percentile. - /// - /// For example, a percentile of 95% (quantile value of 0.95) would have a suffix of `95percentile`. - suffix: MetaString, - }, -} - -impl HistogramStatistic { - /// Returns the suffix to be used for metrics representing this statistic. - pub fn suffix(&self) -> &str { - match self { - HistogramStatistic::Count => "count", - HistogramStatistic::Sum => "sum", - HistogramStatistic::Minimum => "min", - HistogramStatistic::Maximum => "max", - HistogramStatistic::Average => "avg", - HistogramStatistic::Median => "median", - HistogramStatistic::Percentile { suffix, .. } => suffix, - } - } - - /// Returns `true` if this statistics should be represented as a rate. - pub fn is_rate_statistic(&self) -> bool { - matches!(self, HistogramStatistic::Count) - } - - /// Returns the value of this statistic from the given histogram summary. - pub fn value_from_histogram(&self, summary: &HistogramSummary<'_>) -> f64 { - match self { - HistogramStatistic::Count => summary.count() as f64, - HistogramStatistic::Sum => summary.sum(), - HistogramStatistic::Minimum => summary.min().unwrap_or(0.0), - HistogramStatistic::Maximum => summary.max().unwrap_or(0.0), - HistogramStatistic::Average => summary.avg(), - HistogramStatistic::Median => summary.median().unwrap_or(0.0), - HistogramStatistic::Percentile { q, .. } => { - saluki_antithesis::always_ge!(*q, 0.0, "histogram percentile quantile at or above zero"); - saluki_antithesis::always_le!(*q, 1.0, "histogram percentile quantile at or below one"); - summary.quantile(*q).unwrap_or(0.0) - } - } - } -} - -/// Why a configured histogram percentile was skipped. -enum InvalidPercentile { - /// The entry isn't a number. - Unparseable(std::num::ParseFloatError), - - /// The entry is a number, but not between `0.0` and `1.0`. - OutOfRange, -} - -/// Parses a configured percentile in quantile form, such as `0.95`, into a whole percentile, such as `95`. -fn parse_percentile(faux_percentile: &str) -> Result { - let quantile = faux_percentile.parse::().map_err(InvalidPercentile::Unparseable)?; - if !(0.0..=1.0).contains(&quantile) { - return Err(InvalidPercentile::OutOfRange); - } - Ok((quantile * 100.0 + 0.5) as u32) -} - -/// Returns the metric name suffix for a whole percentile, such as `95percentile`. -fn percentile_suffix(percentile: u32) -> MetaString { - format!("{}percentile", percentile).into() -} - -/// Statistics to calculate over histograms, and how to copy them to distributions. -#[derive(Clone)] -#[cfg_attr(test, derive(Debug, PartialEq))] -pub struct HistogramConfiguration { - statistics: Vec, - copy_to_distribution: bool, - copy_to_distribution_prefix: String, -} - -impl HistogramConfiguration { - /// Creates a new `HistogramConfiguration` from the aggregates and percentiles to calculate. - /// - /// Aggregates name a statistic to compute over each histogram: `count`, `sum`, `min`, `max`, `avg`, or `median`. - /// Percentiles are expressed in quantile form, between `0.0` and `1.0` inclusive: 95% becomes `0.95`. Quantiles - /// that extend beyond two decimal places are rounded to the nearest whole percentile. - /// - /// Like the Datadog Agent, an invalid entry is logged and skipped rather than failing the configuration, and the - /// remaining entries still apply: - /// - /// - an aggregate that names an unsupported statistic - /// () - /// - a percentile that isn't a number between `0.0` and `1.0` - /// () - /// - /// The Datadog Agent logs an unsupported aggregate on every flush; this logs each invalid entry once, when the - /// configuration is built. - pub fn new( - aggregates: &[String], percentiles: &[String], copy_to_distribution: bool, copy_to_distribution_prefix: String, - ) -> Self { - let mut statistics = Vec::new(); - - for aggregate in aggregates { - match aggregate.as_str() { - "count" => statistics.push(HistogramStatistic::Count), - "sum" => statistics.push(HistogramStatistic::Sum), - "min" => statistics.push(HistogramStatistic::Minimum), - "max" => statistics.push(HistogramStatistic::Maximum), - "avg" => statistics.push(HistogramStatistic::Average), - "median" => statistics.push(HistogramStatistic::Median), - _ => error!( - "Configured aggregate '{}' in 'histogram_aggregates' is not implemented, skipping.", - aggregate - ), - } - } - - for faux_percentile in percentiles { - match parse_percentile(faux_percentile) { - Ok(percentile) => statistics.push(HistogramStatistic::Percentile { - q: f64::from(percentile) / 100.0, - suffix: percentile_suffix(percentile), - }), - Err(InvalidPercentile::Unparseable(e)) => error!( - "Could not parse '{}' from 'histogram_percentiles' (skipping): {}", - faux_percentile, e - ), - Err(InvalidPercentile::OutOfRange) => error!( - "'histogram_percentiles' must be between 0 and 1: skipping '{}'.", - faux_percentile - ), - } - } - - Self { - statistics, - copy_to_distribution, - copy_to_distribution_prefix, - } - } - - /// Returns the metric name suffixes, such as `95percentile`, that the valid entries in `percentiles` produce. - /// - /// Entries are parsed exactly as [`HistogramConfiguration::new`] parses them, so the suffixes always match the - /// percentile series it emits. Invalid entries are skipped without logging: `new` already logs each one. - pub fn percentile_suffixes(percentiles: &[String]) -> Vec { - percentiles - .iter() - .filter_map(|faux_percentile| parse_percentile(faux_percentile).ok()) - .map(percentile_suffix) - .collect() - } - - /// Creates a configuration from already-parsed statistics, for tests that exercise histogram aggregation rather - /// than configuration. - #[cfg(test)] - pub fn from_statistics( - statistics: &[HistogramStatistic], copy_to_distribution: bool, copy_to_distribution_prefix: String, - ) -> Self { - Self { - statistics: statistics.to_vec(), - copy_to_distribution, - copy_to_distribution_prefix, - } - } - - /// Returns the configured aggregate statistics to calculate. - pub fn statistics(&self) -> &[HistogramStatistic] { - &self.statistics - } - - /// Returns `true` if histograms should be copied to distributions. - pub fn copy_to_distribution(&self) -> bool { - self.copy_to_distribution - } - - /// Returns the prefix to append to the distributions copied from histograms. - pub fn copy_to_distribution_prefix(&self) -> &str { - &self.copy_to_distribution_prefix - } -} - -/// Fixture values for tests that exercise histogram aggregation rather than configuration. -#[cfg(test)] -impl Default for HistogramConfiguration { - fn default() -> Self { - Self { - statistics: vec![ - HistogramStatistic::Maximum, - HistogramStatistic::Median, - HistogramStatistic::Average, - HistogramStatistic::Count, - HistogramStatistic::Percentile { - q: 0.95, - suffix: "95percentile".into(), - }, - ], - copy_to_distribution: false, - copy_to_distribution_prefix: "".into(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Like the Datadog Agent, invalid entries are skipped, and the valid entries around them still apply: an aggregate - /// that names no supported statistic, and a percentile that isn't a quantile between `0.0` and `1.0`. - #[test] - fn unsupported_aggregates_and_percentiles_are_skipped() { - let to_strings = |values: &[&str]| values.iter().map(|v| v.to_string()).collect::>(); - let config = HistogramConfiguration::new( - &to_strings(&["max", "p99", "count"]), - &to_strings(&["abc", "0.95", "1.1", "-0.1"]), - false, - String::new(), - ); - - assert_eq!( - config.statistics(), - &[ - HistogramStatistic::Maximum, - HistogramStatistic::Count, - HistogramStatistic::Percentile { - q: 0.95, - suffix: "95percentile".into(), - }, - ] - ); - } - - #[test] - fn all_invalid_entries_leave_no_statistics() { - let config = HistogramConfiguration::new(&["p99".to_string()], &["abc".to_string()], false, String::new()); - assert!(config.statistics().is_empty()); - } - - #[test] - fn percentile_suffixes_match_agent_rounding() { - let config = HistogramConfiguration::new(&[], &["0.299".to_string(), "0.73".to_string()], false, String::new()); - - assert_eq!( - config.statistics(), - &[ - HistogramStatistic::Percentile { - q: 0.30, - suffix: "30percentile".into(), - }, - HistogramStatistic::Percentile { - q: 0.73, - suffix: "73percentile".into(), - }, - ] - ); - } - - #[test] - fn percentile_suffixes_match_the_emitted_percentile_statistics() { - // The post-aggregate filter relies on these suffixes matching the percentile series the aggregate transform - // emits, including for skipped and rounded entries. - let percentiles = ["0.5", "0.299", "abc", "1.5", "-0.1", "0.0", "1.0"].map(String::from); - let config = HistogramConfiguration::new(&[], &percentiles, false, String::new()); - - let emitted = config - .statistics() - .iter() - .map(|statistic| statistic.suffix().to_string()) - .collect::>(); - let suffixes = HistogramConfiguration::percentile_suffixes(&percentiles) - .iter() - .map(|suffix| suffix.to_string()) - .collect::>(); - - assert_eq!( - suffixes, - ["50percentile", "30percentile", "0percentile", "100percentile"] - ); - assert_eq!(suffixes, emitted); - } -} +pub use saluki_transform_kernels::histogram::HistogramConfiguration; diff --git a/lib/saluki-components/src/transforms/aggregate/mod.rs b/lib/saluki-components/src/transforms/aggregate/mod.rs index 32c22d1b3fd..4c5ef623ea0 100644 --- a/lib/saluki-components/src/transforms/aggregate/mod.rs +++ b/lib/saluki-components/src/transforms/aggregate/mod.rs @@ -6,8 +6,6 @@ use std::{ }; use async_trait::async_trait; -use ddsketch::DDSketch; -use hashbrown::{hash_map::Entry, HashMap}; use saluki_common::time::get_unix_timestamp; use saluki_core::{ accounting::{MemoryBounds, MemoryBoundsBuilder, UsageExpr}, @@ -21,8 +19,12 @@ use saluki_core::{ }; use saluki_error::{generic_error, GenericError}; use saluki_metrics::MetricsBuilder; -use smallvec::SmallVec; -use stringtheory::MetaString; +#[cfg(test)] +use saluki_transform_kernels::aggregate::{align_to_bucket_start, is_bucket_closed}; +use saluki_transform_kernels::aggregate::{ + expand_flushed_metric, extract_closed_values, AggregateCore, AggregatedMetric, +}; +pub use saluki_transform_kernels::aggregate::{AggregateContextSnapshotEntry, AggregateMetricType}; use tokio::{ select, sync::{mpsc, oneshot}, @@ -35,72 +37,9 @@ use self::telemetry::{origin_telemetry_bytes, FlushCounts, OriginContextId, Tele mod config; pub use self::config::HistogramConfiguration; -use self::config::HistogramStatistic; const CONTEXT_SNAPSHOT_REQUEST_CHANNEL_CAPACITY: usize = 1; -/// The shape of metric values retained by the aggregate transform. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum AggregateMetricType { - /// Counter values. - Counter, - - /// Rate values. - Rate, - - /// Gauge values. - Gauge, - - /// Set values. - Set, - - /// Histogram values. - Histogram, - - /// Distribution values. - Distribution, -} - -impl From<&MetricValues> for AggregateMetricType { - fn from(values: &MetricValues) -> Self { - match values { - MetricValues::Counter(_) => Self::Counter, - MetricValues::Rate(_, _) => Self::Rate, - MetricValues::Gauge(_) => Self::Gauge, - MetricValues::Set(_) => Self::Set, - MetricValues::Histogram(_) => Self::Histogram, - MetricValues::Distribution(_) => Self::Distribution, - } - } -} - -/// A retained metric context and its small aggregation metadata. -/// -/// Cloning an entry shares the underlying context name and tags rather than copying their contents. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct AggregateContextSnapshotEntry { - context: Context, - metric_type: AggregateMetricType, -} - -impl AggregateContextSnapshotEntry { - /// Returns the retained metric context. - pub fn context(&self) -> &Context { - &self.context - } - - /// Returns the shape of the retained metric values. - pub fn metric_type(&self) -> AggregateMetricType { - self.metric_type - } - - /// Creates a snapshot entry for downstream test and benchmark fixtures. - #[cfg(any(test, feature = "test-util"))] - pub fn for_test(context: Context, metric_type: AggregateMetricType) -> Self { - Self { context, metric_type } - } -} - type AggregateContextSnapshot = Vec; type AggregateContextSnapshotRequest = oneshot::Sender; type AggregateContextSnapshotRequestReceiver = mpsc::Receiver; @@ -426,7 +365,7 @@ impl MemoryBounds for AggregateConfiguration { UsageExpr::sum( "context map entry", UsageExpr::struct_size::("context"), - UsageExpr::struct_size::("aggregated metric"), + UsageExpr::struct_size::>("aggregated metric"), ), UsageExpr::config("aggregate_context_limit", self.context_limit), )) @@ -547,7 +486,7 @@ impl Transform for Aggregate { trace!("Dropping metric due to context limit."); if !was_breached { // First drop since the last recovery — emit a single warning. - warn!(context_limit = self.state.context_limit, "Context limit reached, \ + warn!(context_limit = self.state.context_limit(), "Context limit reached, \ dropping metrics. Consider increasing `aggregate_context_limit`."); } self.telemetry.increment_events_dropped(); @@ -581,40 +520,9 @@ async fn receive_context_snapshot_request( } } -#[derive(Clone)] -struct AggregatedMetric { - values: MetricValues, - metadata: MetricMetadata, - last_seen: u64, - origin_id: OriginContextId, -} - -impl AggregatedMetric { - fn merge(&mut self, timestamp: u64, values: MetricValues, metadata: MetricMetadata) { - // Other metadata changes within a flush interval are ignored to keep things simple. - self.last_seen = timestamp; - self.values.merge(values); - - // The first non-empty unit wins and persists until the entry is removed; non-counters are removed once all - // values are flushed, so a stale unit outlives its samples by at most one flush. - if self.metadata.unit.is_empty() { - self.metadata.unit = metadata.unit; - } - } -} - struct AggregationState { - contexts: HashMap, - contexts_remove_buf: Vec, - context_limit: usize, - bucket_width_secs: NonZeroU64, - counter_expire_secs: Option, - last_flush: u64, - hist_config: HistogramConfiguration, + core: AggregateCore, telemetry: Telemetry, - /// Tracks whether the context limit has been breached. Starts out as `false`. Set to `true` on the first dropped - /// metric. Reset to `false` when the context count drops below the limit during flush. - context_limit_breached: bool, } impl AggregationState { @@ -622,372 +530,80 @@ impl AggregationState { bucket_width_secs: NonZeroU64, context_limit: usize, counter_expiration: Option, hist_config: HistogramConfiguration, telemetry: Telemetry, ) -> Self { - let counter_expire_secs = counter_expiration.map(|d| d.as_secs()).and_then(NonZeroU64::new); - Self { - contexts: HashMap::default(), - contexts_remove_buf: Vec::new(), - context_limit, - bucket_width_secs, - counter_expire_secs, - last_flush: 0, - hist_config, + core: AggregateCore::new(bucket_width_secs, context_limit, counter_expiration, hist_config), telemetry, - context_limit_breached: false, } } fn is_empty(&self) -> bool { - self.contexts.is_empty() + self.core.is_empty() + } + + fn context_limit(&self) -> usize { + self.core.context_limit() } fn snapshot_contexts(&self) -> Vec { - let mut snapshot = Vec::with_capacity(self.contexts.len()); - for (context, aggregated) in &self.contexts { - snapshot.push(AggregateContextSnapshotEntry { - context: context.clone(), - metric_type: AggregateMetricType::from(&aggregated.values), - }); - } - snapshot + self.core.snapshot_contexts() } fn insert(&mut self, timestamp: u64, metric: Metric) -> bool { - // If we haven't seen this context yet, and it would put us over the limit to insert it, then return early. - if !self.contexts.contains_key(metric.context()) && self.contexts.len() >= self.context_limit { - self.context_limit_breached = true; - return false; - } - - // An empty state has no counters to keep alive. The owner skips flushing an empty state, so its last flush can - // be arbitrarily old; carrying that timestamp into a newly inserted counter would synthesize zero buckets from - // before the counter existed. - if self.contexts.is_empty() { - self.last_flush = 0; - } - - let (context, mut values, metadata) = metric.into_parts(); - - // Collapse all non-timestamped values into a single timestamped value. - // - // We do this pre-aggregation step because unless we're merging into an existing context, we'll end up with - // however many values were in the original metric instead of full aggregated values. - let bucket_ts = align_to_bucket_start(timestamp, self.bucket_width_secs); - values.collapse_non_timestamped(bucket_ts); - - trace!( - bucket_ts, - kind = values.as_str(), - "Inserting metric into aggregation state." - ); - - // If we're already tracking this context, update the last seen time and merge the new values into the existing - // values. Otherwise, create a new entry. - match self.contexts.entry(context) { - Entry::Occupied(mut entry) => entry.get_mut().merge(timestamp, values, metadata), - Entry::Vacant(entry) => { - let origin_id = self.telemetry.increment_contexts(entry.key(), &values); - - entry.insert(AggregatedMetric { - values, - metadata, - last_seen: timestamp, - origin_id, - }); - - saluki_antithesis::always_le!( - self.contexts.len(), - self.context_limit, - "aggregate context map within context_limit", - { "len": self.contexts.len(), "limit": self.context_limit } - ); - } - } - - true + let telemetry = &self.telemetry; + self.core.insert_with(timestamp, metric, |context, values| { + telemetry.increment_contexts(context, values) + }) } async fn flush( &mut self, current_time: u64, flush_open_buckets: bool, dispatcher: &mut BufferedDispatcher<'_, EventsBuffer>, ) -> Result<(), GenericError> { - // A previous flush may have failed after marking some contexts for removal. Re-evaluate them: - // ingestion may have added values since then, and their telemetry admission is still live. - self.contexts_remove_buf.clear(); - let bucket_width_secs = self.bucket_width_secs; - let counter_expire_secs = self.counter_expire_secs.map(|d| d.get()).unwrap_or(0); - - // Values with a timestamp less than or equal to `split_timestamp` are flushed. Normally that's just before the - // start of the current bucket, so only closed buckets are flushed. When flushing open buckets, it's every value. - let split_timestamp = if flush_open_buckets { - u64::MAX - } else { - align_to_bucket_start(current_time, bucket_width_secs).saturating_sub(1) - }; - - // Calculate the buckets we need to potentially generate zero-value counters for. - // - // We only need to do this if we've flushed before, since we won't have any knowledge of which counters are idle - // or not until that happens. - let mut zero_value_buckets = SmallVec::<[(u64, MetricValues); 4]>::new(); - if self.last_flush != 0 { - let start = align_to_bucket_start(self.last_flush, bucket_width_secs); - - // Clock-skew guards. Bucketing reads the wall clock while the flush cadence is monotonic, so a wall-clock - // jump is not bounded by the flush interval. A backward jump empties the zero-value range (a silent counter - // gap); a forward jump makes the loop below run once per bucket across the whole jumped span — O(jump) work - // and allocation. Assert before the loop so a flood fails fast rather than after the damage is done. - saluki_antithesis::always_ge!( - current_time, - self.last_flush, - "aggregate flush wall-clock did not move backward", - { "current_time": current_time, "last_flush": self.last_flush } - ); - // The 10_000 bound is generous. A default 15s flush over a 10s bucket yields one or two buckets. The bound - // trips only on a multi-hour wall-clock jump, never on a slow-but-sane flush. - saluki_antithesis::always_le!( - current_time.saturating_sub(self.last_flush) / bucket_width_secs.get(), - 10_000, - "aggregate zero-value bucket span bounded across a flush", - { - "current_time": current_time, - "last_flush": self.last_flush, - "bucket_width_secs": bucket_width_secs.get() - } - ); - - for bucket_start in (start..current_time).step_by(bucket_width_secs.get() as usize) { - if is_bucket_closed(current_time, bucket_start, bucket_width_secs, flush_open_buckets) { - zero_value_buckets.push((bucket_start, MetricValues::counter((bucket_start, 0.0)))); - } - } - - // Anti-vacuity anchor: prove the idle-counter zero-value path actually runs in some timeline. - saluki_antithesis::sometimes!( - !zero_value_buckets.is_empty(), - "aggregate flush generated zero-value counter buckets", - { "count": zero_value_buckets.len() } - ); - } - - // Iterate over each context we're tracking, and flush any values that are in buckets which are now closed. - debug!(timestamp = current_time, "Flushing buckets."); - + let window = self.core.prepare_flush(current_time, flush_open_buckets); + let bucket_width_secs = self.core.bucket_width_secs(); + let hist_config = self.core.hist_config().clone(); let mut flush_counts = FlushCounts::default(); + let mut expanded = Vec::new(); - for (context, am) in self.contexts.iter_mut() { - // Figure out if we should remove this metric or not if it has no values in open buckets. - // - // We have a special carve-out for counters here, which we have the ability to keep alive after they are - // flushed, based on a configured expiration period. This allows us to continue emitting a zero value for - // counters when they're idle, which can make them appear "live" in downstream systems, even when they're - // not. - // - // This is useful for sparsely-updated counters. - let should_expire_if_empty = match &am.values { - MetricValues::Counter(..) => { - saluki_antithesis::always_le!( - am.last_seen, - u64::MAX - counter_expire_secs, - "aggregate counter expiry add does not overflow", - { "last_seen": am.last_seen, "counter_expire_secs": counter_expire_secs } - ); - counter_expire_secs == 0 || am.last_seen.saturating_add(counter_expire_secs) < current_time - } - _ => true, - }; - - // If we're dealing with a counter, we'll merge in our calculated set of zero values. We only merge in the - // values that represent now-closed buckets. - // - // This is also safe to do even when there are real values in those buckets since adding zero to anything is - // a no-op from the perspective of what we end up flushing, and it doesn't mess with the "last seen" time. - if let MetricValues::Counter(..) = &mut am.values { - let expires_at = am.last_seen.saturating_add(counter_expire_secs); - for (zv_bucket_start, zero_value) in &zero_value_buckets { - if expires_at > *zv_bucket_start { - am.values.merge(zero_value.clone()); - } else { - // Since zero-value buckets are in order, we can break early if this bucket is past the - // expiration cutoff of the counter. No other bucket will be within the expiration range. - break; - } - } - } - - // Finally, figure out if the current metric can be removed. - // - // For any metric with values that are in open buckets, we split off the values that are in closed buckets - // and keep the metric alive. When all the values are in closed buckets, or there are no values, we'll - // remove the metric if `should_remove_if_empty` is `true`. - // - // This means we'll always remove all-closed/empty non-counter metrics, and we _may_ remove all-closed/empty - // counters. - if let Some(closed_bucket_values) = am.values.split_at_timestamp(split_timestamp) { + let (contexts, remove_buf) = self.core.contexts_and_remove_buf_mut(); + for (context, am) in contexts { + let (closed_values, should_remove) = extract_closed_values(am, &window); + if let Some(closed_bucket_values) = closed_values { self.telemetry .increment_flushed(&closed_bucket_values, &mut flush_counts); - // We got some closed bucket values, so flush those out. - transform_and_push_metric( + expanded.clear(); + expand_flushed_metric( context.clone(), closed_bucket_values, am.metadata.clone(), bucket_width_secs, - &self.hist_config, - dispatcher, - ) - .await?; - } - - if am.values.is_empty() && should_expire_if_empty { - self.contexts_remove_buf.push(context.clone()); + &hist_config, + |metric| expanded.push(metric), + ); + for metric in expanded.drain(..) { + dispatcher.push(Event::Metric(metric)).await?; + } } - } - // Remove any contexts that were marked as needing to be removed. - let contexts_len_before = self.contexts.len(); - for context in self.contexts_remove_buf.drain(..) { - if let Some(am) = self.contexts.remove(&context) { - self.telemetry.decrement_contexts(&context, &am.values, am.origin_id); + if should_remove { + remove_buf.push(context.clone()); } } - let contexts_len_after = self.contexts.len(); - let contexts_delta = contexts_len_before.saturating_sub(contexts_len_after); - let target_contexts_capacity = contexts_len_after.saturating_add(contexts_delta / 2); - self.contexts.shrink_to(target_contexts_capacity); - - if self.context_limit_breached && self.contexts.len() < self.context_limit { - self.context_limit_breached = false; - } - - self.last_flush = current_time; + let telemetry = &self.telemetry; + self.core.finish_flush(current_time, |context, values, origin_id| { + telemetry.decrement_contexts(context, values, origin_id); + }); self.telemetry.record_last_flush_counts(&flush_counts); Ok(()) } fn context_limit_breached(&self) -> bool { - self.context_limit_breached + self.core.context_limit_breached() } } -async fn transform_and_push_metric( - context: Context, mut values: MetricValues, metadata: MetricMetadata, bucket_width_secs: NonZeroU64, - hist_config: &HistogramConfiguration, dispatcher: &mut BufferedDispatcher<'_, EventsBuffer>, -) -> Result<(), GenericError> { - let bucket_width = Duration::from_secs(bucket_width_secs.get()); - - match values { - // If we're dealing with a histogram, we calculate a configured set of aggregates/percentiles from it, and emit - // them as individual metrics. - MetricValues::Histogram(ref mut points) => { - // Convert histogram to distribution - if hist_config.copy_to_distribution() { - let sketch_points = points - .into_iter() - .map(|(ts, hist)| { - let mut sketch = DDSketch::default(); - for sample in hist.samples() { - sketch.insert_n(sample.value.into_inner(), sample.weight.0 as u64); - } - (ts, sketch) - }) - .collect::(); - let distribution_values = MetricValues::distribution(sketch_points); - let metric_context = if !hist_config.copy_to_distribution_prefix().is_empty() { - context.with_name(format!( - "{}{}", - hist_config.copy_to_distribution_prefix(), - context.name() - )) - } else { - context.clone() - }; - let new_metric = Metric::from_parts(metric_context, distribution_values, metadata.clone()); - dispatcher.push(Event::Metric(new_metric)).await?; - } - // We collect our histogram points in their "summary" view, which sorts the underlying samples allowing - // proper quantile queries to be answered, hence our "sorted" points. We do it this way because rather than - // sort every time we insert, or cloning the points, we only sort when a summary view is constructed, which - // requires mutable access to sort the samples in-place. - let mut sorted_points = Vec::new(); - for (ts, h) in points { - sorted_points.push((ts, h.summary_view())); - } - - for statistic in hist_config.statistics() { - let new_points = sorted_points - .iter() - .map(|(ts, hs)| (*ts, statistic.value_from_histogram(hs))) - .collect::(); - - let new_values = if statistic.is_rate_statistic() { - MetricValues::rate(new_points, bucket_width) - } else { - MetricValues::gauge(new_points) - }; - - // Counts are dimensionless, so clear any unit inherited from the input histogram. - let new_metadata = if matches!(statistic, HistogramStatistic::Count) { - metadata.clone().with_unit(MetaString::empty()) - } else { - metadata.clone() - }; - - let new_context = context.with_name(format!("{}.{}", context.name(), statistic.suffix())); - let new_metric = Metric::from_parts(new_context, new_values, new_metadata); - dispatcher.push(Event::Metric(new_metric)).await?; - } - - Ok(()) - } - - // If we're not dealing with a histogram, then all we need to worry about is converting counters to rates before - // forwarding our single, aggregated metric. - values => { - let adjusted_values = counter_values_to_rate(values, bucket_width_secs); - - let metric = Metric::from_parts(context, adjusted_values, metadata); - dispatcher.push(Event::Metric(metric)).await - } - } -} - -fn counter_values_to_rate(values: MetricValues, interval_secs: NonZeroU64) -> MetricValues { - match values { - MetricValues::Counter(points) => MetricValues::rate(points, Duration::from_secs(interval_secs.get())), - values => values, - } -} - -const fn align_to_bucket_start(timestamp: u64, bucket_width_secs: NonZeroU64) -> u64 { - timestamp - (timestamp % bucket_width_secs.get()) -} - -const fn is_bucket_closed( - current_time: u64, bucket_start: u64, bucket_width_secs: NonZeroU64, flush_open_buckets: bool, -) -> bool { - // A bucket is considered "closed" if the current time is greater than the end of the bucket, or if - // `flush_open_buckets` is `true`. - // - // Buckets represent a half-open interval, where the start is inclusive and the end is exclusive. This means that - // for a bucket start of 10, and a width of 10, the bucket is 10 seconds "wide", and its start and end are 10 and - // 20, with the 20 excluded, or [10, 20) in interval notation. Simply put, if we have a timestamp of 10, or anything - // smaller than 20, we would consider it to fall within the bucket... but 20 or more would be outside of the bucket. - // - // We can also represent this visually: - // - // <--------- bucket 1 ----------> <--------- bucket 2 ----------> <--------- bucket 3 ----------> - // [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] - // - // We can see that each bucket is 10 seconds wide (10 elements, one for each second), and that their ends are - // effectively `start + width - 1`. This means that for any of these buckets to be considered "closed", the current - // time has to be _greater_ than `start + width - 1`. For example, if the current time is 19, then no buckets are - // closed, and if the current time is 29, then bucket 1 is closed but buckets 2 and 3 are still open, and if the - // current time is 30, then both buckets 1 and 2 are closed, but bucket 3 is still open. - (bucket_start + bucket_width_secs.get() - 1) < current_time || flush_open_buckets -} - // TODO: One thing we ought to consider is a property test, specifically a state machine property test, where we // generate a randomized offset to start time from, a bucket width, flush interval, and operations, and so on... and // then we run it to make sure that we are always generating sequential timestamps for data points, etc. @@ -1004,10 +620,10 @@ mod tests { topology::{interconnect::Dispatcher, EventsDispatcher, OutputName}, }; use saluki_metrics::test::TestRecorder; + use saluki_transform_kernels::histogram::HistogramStatistic; use stringtheory::MetaString; use tokio::sync::{mpsc, oneshot}; - use super::config::HistogramStatistic; use super::*; const BUCKET_WIDTH_SECS: NonZeroU64 = NonZeroU64::new(10).expect("not zero"); @@ -1264,7 +880,7 @@ mod tests { let mut snapshot = state.snapshot_contexts(); assert_eq!(snapshot.len(), 2); - assert!(snapshot.capacity() >= state.contexts.len()); + assert!(snapshot.capacity() >= state.core.len()); snapshot.sort_by(|a, b| a.context().host().cmp(&b.context().host())); assert_eq!(snapshot[0].context(), &histogram_context); @@ -1361,10 +977,7 @@ mod tests { ); let context = Context::from_static_name("open.snapshot"); assert!(state.insert(insert_ts(1), Metric::gauge(context.clone(), 1.0))); - let expected = vec![AggregateContextSnapshotEntry { - context, - metric_type: AggregateMetricType::Gauge, - }]; + let expected = vec![AggregateContextSnapshotEntry::new(context, AggregateMetricType::Gauge)]; let (response, mut receiver) = oneshot::channel(); let snapshot_calls = Cell::new(0); @@ -1392,7 +1005,8 @@ mod tests { let bounds = registry.as_bounds(); let expected_minimum = size_of::(); - let aggregation_state_bytes = context_limit * (size_of::() + size_of::()); + let aggregation_state_bytes = + context_limit * (size_of::() + size_of::>()); let context_snapshot_bytes = context_limit * size_of::(); assert_eq!(bounds.total_minimum_required_bytes(), expected_minimum); @@ -2205,23 +1819,23 @@ mod tests { let mut buffered = dispatcher.buffered().unwrap(); assert!(state.flush(flush_ts(1), false, &mut buffered).await.is_err()); assert!( - !state.contexts_remove_buf.is_empty(), + !state.core.pending_removals().is_empty(), "failure must follow a pending expiry" ); - assert_eq!(state.contexts.len(), count); + assert_eq!(state.core.len(), count); let metric = ("aggregate_active_contexts_by_origin", &[("container", "one")]); assert_eq!(recorder.gauge(metric), Some(count as f64)); // A context marked for removal before the failure can receive new, still-open values. - let revived = state.contexts_remove_buf[0].clone(); + let revived = state.core.pending_removals()[0].clone(); let future_ts = flush_ts(1) + 100; assert!(state.insert(future_ts, Metric::gauge(revived.clone(), (future_ts, 1.0)))); let _ = get_flushed_metrics_with_open_windows(flush_ts(1), false, &mut state).await; - assert_eq!(state.contexts.len(), 1); - assert!(state.contexts.contains_key(&revived)); + assert_eq!(state.core.len(), 1); + assert!(state.core.contains_context(&revived)); assert_eq!(recorder.gauge(metric), Some(1.0)); let _ = get_flushed_metrics_with_open_windows(future_ts + 100, false, &mut state).await; - assert!(state.contexts.is_empty()); + assert!(state.core.is_empty()); assert_eq!(recorder.gauge(metric), Some(0.0)); } diff --git a/lib/saluki-components/src/transforms/autoscaling_failover_gateway/mod.rs b/lib/saluki-components/src/transforms/autoscaling_failover_gateway/mod.rs index 46efe531db2..d3c3681f109 100644 --- a/lib/saluki-components/src/transforms/autoscaling_failover_gateway/mod.rs +++ b/lib/saluki-components/src/transforms/autoscaling_failover_gateway/mod.rs @@ -9,13 +9,11 @@ use saluki_core::{ transforms::{Transform, TransformBuilder, TransformContext}, BuildContext, }, - data_model::event::{ - metric::{Metric, MetricValues}, - EventType, - }, + data_model::event::{metric::Metric, EventType}, topology::{EventsBuffer, OutputDefinition}, }; use saluki_error::GenericError; +use saluki_transform_kernels::routing_filter::MetricAllowlistKernel; use tokio::select; use tracing::{debug, error}; @@ -36,49 +34,22 @@ impl AutoscalingFailoverGatewayConfiguration { } } -/// Routing and filtering state for the autoscaling failover metrics gateway. -#[derive(Debug)] -enum GatewayMode { - /// Autoscaling failover is disabled or has no allowed metrics; drop all events. - Inactive, - /// Autoscaling failover is active; forward only matching series metrics. - FilteredForward { allowlist: HashSet }, -} - /// Autoscaling failover metrics gateway transform. pub struct AutoscalingFailoverGateway { - mode: GatewayMode, + kernel: MetricAllowlistKernel, } impl AutoscalingFailoverGateway { fn new(failover_config: AutoscalingFailoverConfiguration) -> Self { - let mode = Self::mode_for_config(&failover_config); - - Self { mode } - } - - fn mode_for_config(failover_config: &AutoscalingFailoverConfiguration) -> GatewayMode { - if !failover_config.is_branch_requested() { - GatewayMode::Inactive - } else { - GatewayMode::FilteredForward { - allowlist: failover_config.metrics().iter().cloned().collect(), - } - } + let kernel = MetricAllowlistKernel::for_series_allowlist( + failover_config.is_branch_requested(), + failover_config.metrics(), + ); + Self { kernel } } fn should_forward(&self, metric: &Metric) -> bool { - let GatewayMode::FilteredForward { allowlist } = &self.mode else { - return false; - }; - if !matches!( - metric.values(), - MetricValues::Counter(..) | MetricValues::Rate(..) | MetricValues::Gauge(..) | MetricValues::Set(..) - ) { - return false; - } - - allowlist.contains(metric.context().name()) + self.kernel.should_forward(metric) } async fn process_event_batch( @@ -141,7 +112,7 @@ impl Transform for AutoscalingFailoverGateway { let mut health = context.take_health_handle(); health.mark_ready(); - debug!(mode = ?self.mode, "Autoscaling failover metrics gateway transform started."); + debug!(kernel = ?self.kernel, "Autoscaling failover metrics gateway transform started."); loop { select! { diff --git a/lib/saluki-components/src/transforms/dogstatsd_mapper/mod.rs b/lib/saluki-components/src/transforms/dogstatsd_mapper/mod.rs index da089dabfa2..5da501bc2e1 100644 --- a/lib/saluki-components/src/transforms/dogstatsd_mapper/mod.rs +++ b/lib/saluki-components/src/transforms/dogstatsd_mapper/mod.rs @@ -1,10 +1,7 @@ -use std::collections::HashMap; use std::num::NonZeroUsize; -use std::sync::LazyLock; use std::time::Duration; use async_trait::async_trait; -use regex::Regex; use saluki_core::cache::{Cache, CacheBuilder}; use saluki_core::{ accounting::{MemoryBounds, MemoryBoundsBuilder}, @@ -17,20 +14,16 @@ use saluki_core::{ context::{Context, ContextResolver, ContextResolverBuilder}, Metric, }, - tags::{SharedTagSet, TagSet}, + tags::SharedTagSet, }, topology::EventsBuffer, }; -use saluki_error::{generic_error, ErrorContext, GenericError}; +use saluki_error::GenericError; +use saluki_transform_kernels::mapper::MapperKernel; +pub use saluki_transform_kernels::mapper::{DogStatsDMapperProfile, DogStatsDMetricMapping}; use stringtheory::MetaString; use tracing::warn; -const MATCH_TYPE_WILDCARD: &str = "wildcard"; -const MATCH_TYPE_REGEX: &str = "regex"; - -static ALLOWED_WILDCARD_MATCH_PATTERN: LazyLock = - LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9\-_*.]+$").expect("Invalid regex in ALLOWED_WILDCARD_MATCH_PATTERN")); - /// DogStatsD mapper transform. pub struct DogStatsDMapperConfiguration { /// Total size of the string interner used for contexts, in bytes. @@ -45,33 +38,6 @@ pub struct DogStatsDMapperConfiguration { profiles: Vec, } -/// A DogStatsD metric mapping profile. -pub struct DogStatsDMapperProfile { - /// Profile name used in configuration errors. - pub name: String, - - /// Metric-name prefix this profile applies to. - pub prefix: String, - - /// Metric mappings evaluated for this profile. - pub mappings: Vec, -} - -/// A metric-name mapping in a [`DogStatsDMapperProfile`]. -pub struct DogStatsDMetricMapping { - /// Pattern matched against the incoming metric name. - pub metric_match: String, - - /// Pattern type: `wildcard`, `regex`, or empty for the default wildcard behavior. - pub match_type: String, - - /// Metric name emitted after a match. - pub name: String, - - /// Tags emitted after expanding capture groups. - pub tags: HashMap, -} - impl DogStatsDMapperConfiguration { /// Creates a DogStatsD mapper configuration. pub fn new( @@ -84,80 +50,15 @@ impl DogStatsDMapperConfiguration { } } - /// Validates the configured profiles and compiles their match patterns. - /// - /// This mirrors the Datadog Agent's `NewMetricMapper`, including its error messages: - /// - /// - /// # Errors - /// - /// Returns an error describing the first invalid profile or mapping. - fn compile_profiles(&self) -> Result, GenericError> { - let mut profiles = Vec::with_capacity(self.profiles.len()); - for (profile_index, config_profile) in self.profiles.iter().enumerate() { - if config_profile.name.is_empty() { - return Err(generic_error!("missing profile name {}", profile_index)); - } - if config_profile.prefix.is_empty() { - return Err(generic_error!("missing prefix for profile: {}", config_profile.name)); - } - - let mut profile = MappingProfile { - prefix: config_profile.prefix.clone(), - mappings: Vec::with_capacity(config_profile.mappings.len()), - }; - - for (mapping_index, mapping) in config_profile.mappings.iter().enumerate() { - let match_type = match mapping.match_type.as_str() { - // Default to wildcard when not set. - "" => MATCH_TYPE_WILDCARD, - MATCH_TYPE_WILDCARD => MATCH_TYPE_WILDCARD, - MATCH_TYPE_REGEX => MATCH_TYPE_REGEX, - unknown => { - return Err(generic_error!( - "profile: {}, mapping num {}: invalid match type `{}`, expected `wildcard` or `regex`", - config_profile.name, - mapping_index, - unknown, - )) - } - }; - if mapping.name.is_empty() { - return Err(generic_error!( - "profile: {}, mapping num {}: name is required", - config_profile.name, - mapping_index - )); - } - if mapping.metric_match.is_empty() { - return Err(generic_error!( - "profile: {}, mapping num {}: match is required", - config_profile.name, - mapping_index - )); - } - let regex = build_regex(&mapping.metric_match, match_type)?; - profile.mappings.push(MetricMapping { - name: mapping.name.clone(), - tags: mapping.tags.clone(), - regex, - }); - } - profiles.push(profile); - } - - Ok(profiles) - } - fn build_mapper(&self, context: BuildContext) -> Result { // Like the Datadog Agent, an invalid profile or mapping disables metric mapping entirely, rather than failing // DogStatsD: metrics pass through unmapped, and the error is logged. // https://github.com/DataDog/datadog-agent/blob/e02f16838240688a60db91d6b99cd8fbecbd9750/comp/dogstatsd/server/impl/server.go#L497-L507 - let profiles = match self.compile_profiles() { - Ok(profiles) => profiles, + let kernel = match MapperKernel::compile(&self.profiles) { + Ok(kernel) => kernel, Err(e) => { warn!("Could not create metric mapper: {}", e); - Vec::new() + MapperKernel::default() } }; @@ -179,58 +80,12 @@ impl DogStatsDMapperConfiguration { Ok(MetricMapper { context_resolver, - profiles, + kernel, cache, }) } } -/// Builds the regex for a mapping's match pattern. -/// -/// This mirrors the Datadog Agent's `buildRegex`: -/// -fn build_regex(match_re: &str, match_type: &str) -> Result { - let mut pattern = match_re.to_owned(); - if match_type == MATCH_TYPE_WILDCARD { - // Check it against the allowed wildcard pattern - if !ALLOWED_WILDCARD_MATCH_PATTERN.is_match(&pattern) { - return Err(generic_error!( - "invalid wildcard match pattern `{}`, it does not match allowed match regex `{}`", - pattern, - ALLOWED_WILDCARD_MATCH_PATTERN.as_str() - )); - } - if pattern.contains("**") { - return Err(generic_error!( - "invalid wildcard match pattern `{}`, it should not contain consecutive `*`", - pattern - )); - } - pattern = pattern.replace(".", "\\."); - pattern = pattern.replace("*", "([^.]*)"); - } - - let final_pattern = format!("^{}$", pattern); - - Regex::new(&final_pattern).with_error_context(|| { - format!( - "Failed to compile regular expression `{}` for `{}` match type", - final_pattern, match_type - ) - }) -} - -struct MappingProfile { - prefix: String, - mappings: Vec, -} - -struct MetricMapping { - name: String, - tags: HashMap, - regex: Regex, -} - #[derive(Clone)] struct CachedMapResult { name: MetaString, @@ -238,7 +93,7 @@ struct CachedMapResult { } struct MetricMapper { - profiles: Vec, + kernel: MapperKernel, context_resolver: ContextResolver, cache: Option>>, } @@ -248,19 +103,13 @@ impl MetricMapper { // With no profiles, nothing can match. Skip the cache lookup, and the negative cache entry a miss would add, for // every metric. This covers both the common case of no configured profiles and a mapper disabled by an invalid // profile. - if self.profiles.is_empty() { + if self.kernel.is_empty() { return None; } - // TODO: We should really be able to immutably borrow both the incoming tag set and the cached extra tags and - // chain them together for our call into `resolve_with_origin_tags`, avoiding any allocations... but we need - // some supporting work on the `TagSet` side to make it possible. - let metric_name = context.name(); let tags = context.tags(); let origin_tags = context.origin_tags(); - // TODO: If host-bearing remaps show measurable allocation overhead, preserve the context's underlying host - // representation through the resolver instead of rematerializing it from `&str`. let host = context.host(); // See if we have a cached result for this metric name. @@ -283,58 +132,31 @@ impl MetricMapper { } } - // Slow path: iterate profiles and run regexes. - let mut new_name = String::new(); - let mut expanded_tag_value = String::new(); - - for profile in &self.profiles { - if !metric_name.starts_with(&profile.prefix) && profile.prefix != "*" { - continue; - } - - for mapping in &profile.mappings { - if let Some(captures) = mapping.regex.captures(metric_name) { - new_name.clear(); - captures.expand(&mapping.name, &mut new_name); - - let mut extra_tags = TagSet::with_capacity(mapping.tags.len()); - for (tag_key, tag_value_expr) in &mapping.tags { - expanded_tag_value.clear(); - expanded_tag_value.push_str(tag_key); - expanded_tag_value.push(':'); - captures.expand(tag_value_expr, &mut expanded_tag_value); - - extra_tags.insert_tag(expanded_tag_value.as_str()); - } - - // Freeze the tags here so they can be shared / cached. - let extra_tags = extra_tags.into_shared(); - - let mut merged_tags = tags.to_mutable(); - merged_tags.merge_shared(&extra_tags); - - let resolved = self.context_resolver.resolve_with_optional_host_and_origin_tags( - new_name.as_str(), - host, - merged_tags, - origin_tags.clone(), - )?; - - if let Some(cache) = &self.cache { - cache.insert( - metric_name.into(), - Some(CachedMapResult { - name: resolved.name().into(), - extra_tags, - }), - ); - } - return Some(resolved); - } + // Slow path: run the compiled mapper kernel. + if let Some(mapped) = self.kernel.match_name(metric_name) { + let mut merged_tags = tags.to_mutable(); + merged_tags.merge_shared(&mapped.extra_tags); + + let resolved = self.context_resolver.resolve_with_optional_host_and_origin_tags( + mapped.name.as_ref(), + host, + merged_tags, + origin_tags.clone(), + )?; + + if let Some(cache) = &self.cache { + cache.insert( + metric_name.into(), + Some(CachedMapResult { + name: resolved.name().into(), + extra_tags: mapped.extra_tags, + }), + ); } + return Some(resolved); } - // We also cache "negative" results -- no match for this metric in the configured profiles -- to save ourselves some work. + // Cache negative results so repeated non-matching metric names avoid re-evaluating regexes. if let Some(cache) = &self.cache { cache.insert(metric_name.into(), None); } @@ -899,8 +721,7 @@ mod tests { for (description, config, expected_substring) in cases { let config = DogStatsDMapperConfiguration::new(NonZeroUsize::new(64 * 1024).expect("not zero"), 1000, config); - let err = config - .compile_profiles() + let err = super::MapperKernel::compile(&config.profiles) .err() .unwrap_or_else(|| panic!("[{description}] configuration should be rejected")); let message = err.to_string(); diff --git a/lib/saluki-transform-kernels/Cargo.toml b/lib/saluki-transform-kernels/Cargo.toml new file mode 100644 index 00000000000..aa47e9d4dea --- /dev/null +++ b/lib/saluki-transform-kernels/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "saluki-transform-kernels" +version = "0.1.0" +edition = { workspace = true } +license = { workspace = true } +repository = { workspace = true } + +[lints] +workspace = true + +[dependencies] +datadog-agent-tag-normalization = { workspace = true } +ddsketch = { workspace = true } +foldhash = { workspace = true } +hashbrown = { workspace = true } +regex = { workspace = true, features = ["std", "unicode-perl"] } +saluki-antithesis = { workspace = true } +saluki-common = { workspace = true } +saluki-core = { workspace = true } +saluki-error = { workspace = true } +serde = { workspace = true } +simdutf8 = { workspace = true } +smallvec = { workspace = true } +stringtheory = { workspace = true } +tracing = { workspace = true } diff --git a/lib/saluki-transform-kernels/src/aggregate.rs b/lib/saluki-transform-kernels/src/aggregate.rs new file mode 100644 index 00000000000..252ed908404 --- /dev/null +++ b/lib/saluki-transform-kernels/src/aggregate.rs @@ -0,0 +1,564 @@ +//! Pure synchronous metric aggregation kernel (`AggregateCore`). +//! +//! Accumulates incoming metrics into fixed-width time buckets, merges samples per context, synthesizes zero-value +//! buckets for idle counters until expiration, expands histograms into configured scalar statistics and optional +//! distributions, and converts counters to rates on flush. + +use std::{num::NonZeroU64, time::Duration}; + +use ddsketch::DDSketch; +use hashbrown::{hash_map::Entry, HashMap}; +use saluki_core::data_model::event::metric::{ + context::Context, Metric, MetricMetadata, MetricValues, ScalarPoints, SketchPoints, +}; +use smallvec::SmallVec; +use stringtheory::MetaString; +use tracing::{debug, trace}; + +use crate::histogram::{HistogramConfiguration, HistogramStatistic}; + +/// The shape of metric values retained by [`AggregateCore`]. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AggregateMetricType { + /// Counter values. + Counter, + + /// Rate values. + Rate, + + /// Gauge values. + Gauge, + + /// Set values. + Set, + + /// Histogram values. + Histogram, + + /// Distribution values. + Distribution, +} + +impl From<&MetricValues> for AggregateMetricType { + fn from(values: &MetricValues) -> Self { + match values { + MetricValues::Counter(_) => Self::Counter, + MetricValues::Rate(_, _) => Self::Rate, + MetricValues::Gauge(_) => Self::Gauge, + MetricValues::Set(_) => Self::Set, + MetricValues::Histogram(_) => Self::Histogram, + MetricValues::Distribution(_) => Self::Distribution, + } + } +} + +/// A retained metric context and its small aggregation metadata. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AggregateContextSnapshotEntry { + context: Context, + metric_type: AggregateMetricType, +} + +impl AggregateContextSnapshotEntry { + /// Creates a new snapshot entry. + pub fn new(context: Context, metric_type: AggregateMetricType) -> Self { + Self { context, metric_type } + } + + /// Returns the retained metric context. + pub fn context(&self) -> &Context { + &self.context + } + + /// Returns the shape of the retained metric values. + pub fn metric_type(&self) -> AggregateMetricType { + self.metric_type + } + + /// Creates a snapshot entry for tests and benchmarks. + pub fn for_test(context: Context, metric_type: AggregateMetricType) -> Self { + Self::new(context, metric_type) + } +} + +/// One retained context entry inside [`AggregateCore`]. +#[derive(Clone)] +pub struct AggregatedMetric { + /// Accumulated metric values across open and closed buckets. + pub values: MetricValues, + + /// Metric metadata (such as unit and origin). + pub metadata: MetricMetadata, + + /// Wall-clock timestamp of the most recent sample merged into this entry. + pub last_seen: u64, + + /// Caller-defined per-context attachment (for example, an origin telemetry handle). + pub attachment: M, +} + +impl AggregatedMetric { + fn merge(&mut self, timestamp: u64, values: MetricValues, metadata: MetricMetadata) { + self.last_seen = timestamp; + self.values.merge(values); + + // The first non-empty unit wins and persists until the entry is removed. + if self.metadata.unit.is_empty() { + self.metadata.unit = metadata.unit; + } + } +} + +/// Precomputed flush window parameters returned by [`AggregateCore::prepare_flush`]. +pub struct FlushWindow { + /// Flush values with timestamp `<= split_timestamp`. + pub split_timestamp: u64, + /// Current flush timestamp. + pub current_time: u64, + /// Counter expiration duration in seconds (`0` disables keep-alive). + pub counter_expire_secs: u64, + /// Zero-value counter buckets synthesized for idle counters since the last flush. + pub zero_value_buckets: SmallVec<[(u64, MetricValues); 4]>, +} + +/// Pure synchronous metric aggregation state machine. +pub struct AggregateCore { + contexts: HashMap, foldhash::quality::RandomState>, + contexts_remove_buf: Vec, + context_limit: usize, + bucket_width_secs: NonZeroU64, + counter_expire_secs: Option, + last_flush: u64, + hist_config: HistogramConfiguration, + context_limit_breached: bool, +} + +impl AggregateCore<()> { + /// Inserts `metric` into the aggregation state at `timestamp`. + /// + /// Returns `false` if inserting a new context would exceed `context_limit`. + pub fn insert(&mut self, timestamp: u64, metric: Metric) -> bool { + self.insert_with(timestamp, metric, |_, _| ()) + } + + /// Flushes all closed buckets (or all buckets when `flush_open_buckets` is `true`) into `on_metric`. + pub fn flush_into(&mut self, current_time: u64, flush_open_buckets: bool, mut on_metric: impl FnMut(Metric)) { + let window = self.prepare_flush(current_time, flush_open_buckets); + let bucket_width_secs = self.bucket_width_secs; + let hist_config = self.hist_config.clone(); + + for (context, am) in self.contexts.iter_mut() { + let (closed_values, should_remove) = extract_closed_values(am, &window); + if let Some(closed_values) = closed_values { + expand_flushed_metric( + context.clone(), + closed_values, + am.metadata.clone(), + bucket_width_secs, + &hist_config, + &mut on_metric, + ); + } + if should_remove { + self.contexts_remove_buf.push(context.clone()); + } + } + + self.finish_flush(current_time, |_, _, _| {}); + } +} + +impl AggregateCore { + /// Creates a new `AggregateCore`. + pub fn new( + bucket_width_secs: NonZeroU64, context_limit: usize, counter_expiration: Option, + hist_config: HistogramConfiguration, + ) -> Self { + let counter_expire_secs = counter_expiration.map(|d| d.as_secs()).and_then(NonZeroU64::new); + + Self { + contexts: HashMap::default(), + contexts_remove_buf: Vec::new(), + context_limit, + bucket_width_secs, + counter_expire_secs, + last_flush: 0, + hist_config, + context_limit_breached: false, + } + } + + /// Returns `true` when no contexts are retained. + pub fn is_empty(&self) -> bool { + self.contexts.is_empty() + } + + /// Returns the number of currently retained contexts. + pub fn len(&self) -> usize { + self.contexts.len() + } + + /// Returns the configured maximum number of retained contexts. + pub fn context_limit(&self) -> usize { + self.context_limit + } + + /// Returns the configured bucket width in seconds. + pub fn bucket_width_secs(&self) -> NonZeroU64 { + self.bucket_width_secs + } + + /// Returns the configured histogram aggregation settings. + pub fn hist_config(&self) -> &HistogramConfiguration { + &self.hist_config + } + + /// Returns `true` if a metric was dropped due to `context_limit` since the last recovery. + pub fn context_limit_breached(&self) -> bool { + self.context_limit_breached + } + + /// Returns `true` if `context` is currently retained. + pub fn contains_context(&self, context: &Context) -> bool { + self.contexts.contains_key(context) + } + + /// Returns a snapshot of all currently retained contexts and their metric types. + pub fn snapshot_contexts(&self) -> Vec { + let mut snapshot = Vec::with_capacity(self.contexts.len()); + for (context, aggregated) in &self.contexts { + snapshot.push(AggregateContextSnapshotEntry::new( + context.clone(), + AggregateMetricType::from(&aggregated.values), + )); + } + snapshot + } + + /// Inserts `metric` at `timestamp`, invoking `on_new_context` only when creating a new context entry. + /// + /// Returns `false` if inserting a new context would exceed `context_limit`. + pub fn insert_with( + &mut self, timestamp: u64, metric: Metric, on_new_context: impl FnOnce(&Context, &MetricValues) -> M, + ) -> bool { + if !self.contexts.contains_key(metric.context()) && self.contexts.len() >= self.context_limit { + self.context_limit_breached = true; + return false; + } + + // An empty state has no counters to keep alive; reset `last_flush` so a newly inserted counter never + // synthesizes zero buckets from before it existed. + if self.contexts.is_empty() { + self.last_flush = 0; + } + + let (context, mut values, metadata) = metric.into_parts(); + let bucket_ts = align_to_bucket_start(timestamp, self.bucket_width_secs); + values.collapse_non_timestamped(bucket_ts); + + trace!( + bucket_ts, + kind = values.as_str(), + "Inserting metric into aggregation state." + ); + + match self.contexts.entry(context) { + Entry::Occupied(mut entry) => entry.get_mut().merge(timestamp, values, metadata), + Entry::Vacant(entry) => { + let attachment = on_new_context(entry.key(), &values); + + entry.insert(AggregatedMetric { + values, + metadata, + last_seen: timestamp, + attachment, + }); + + saluki_antithesis::always_le!( + self.contexts.len(), + self.context_limit, + "aggregate context map within context_limit", + { "len": self.contexts.len(), "limit": self.context_limit } + ); + } + } + + true + } + + /// Prepares a flush pass over retained contexts, computing the split timestamp and idle-counter zero buckets. + pub fn prepare_flush(&mut self, current_time: u64, flush_open_buckets: bool) -> FlushWindow { + self.contexts_remove_buf.clear(); + let bucket_width_secs = self.bucket_width_secs; + let counter_expire_secs = self.counter_expire_secs.map(|d| d.get()).unwrap_or(0); + + let split_timestamp = if flush_open_buckets { + u64::MAX + } else { + align_to_bucket_start(current_time, bucket_width_secs).saturating_sub(1) + }; + + let mut zero_value_buckets = SmallVec::<[(u64, MetricValues); 4]>::new(); + if self.last_flush != 0 { + let start = align_to_bucket_start(self.last_flush, bucket_width_secs); + + saluki_antithesis::always_ge!( + current_time, + self.last_flush, + "aggregate flush wall-clock did not move backward", + { "current_time": current_time, "last_flush": self.last_flush } + ); + saluki_antithesis::always_le!( + current_time.saturating_sub(self.last_flush) / bucket_width_secs.get(), + 10_000, + "aggregate zero-value bucket span bounded across a flush", + { + "current_time": current_time, + "last_flush": self.last_flush, + "bucket_width_secs": bucket_width_secs.get() + } + ); + + for bucket_start in (start..current_time).step_by(bucket_width_secs.get() as usize) { + if is_bucket_closed(current_time, bucket_start, bucket_width_secs, flush_open_buckets) { + zero_value_buckets.push((bucket_start, MetricValues::counter((bucket_start, 0.0)))); + } + } + + saluki_antithesis::sometimes!( + !zero_value_buckets.is_empty(), + "aggregate flush generated zero-value counter buckets", + { "count": zero_value_buckets.len() } + ); + } + + debug!(timestamp = current_time, "Flushing buckets."); + + FlushWindow { + split_timestamp, + current_time, + counter_expire_secs, + zero_value_buckets, + } + } + + /// Returns a mutable iterator over retained contexts and access to the pending-removal buffer for custom flush + /// drivers (such as async dispatchers). + pub fn contexts_and_remove_buf_mut( + &mut self, + ) -> ( + hashbrown::hash_map::IterMut<'_, Context, AggregatedMetric>, + &mut Vec, + ) { + (self.contexts.iter_mut(), &mut self.contexts_remove_buf) + } + + /// Returns the pending-removal buffer from the most recent flush pass. + pub fn pending_removals(&self) -> &[Context] { + &self.contexts_remove_buf + } + + /// Completes a flush pass by removing expired contexts, shrinking the table, and recording `last_flush`. + pub fn finish_flush(&mut self, current_time: u64, mut on_removed: impl FnMut(&Context, &MetricValues, M)) { + let contexts_len_before = self.contexts.len(); + for context in self.contexts_remove_buf.drain(..) { + if let Some(am) = self.contexts.remove(&context) { + on_removed(&context, &am.values, am.attachment); + } + } + let contexts_len_after = self.contexts.len(); + + let contexts_delta = contexts_len_before.saturating_sub(contexts_len_after); + let target_contexts_capacity = contexts_len_after.saturating_add(contexts_delta / 2); + self.contexts.shrink_to(target_contexts_capacity); + + if self.context_limit_breached && self.contexts.len() < self.context_limit { + self.context_limit_breached = false; + } + + self.last_flush = current_time; + } +} + +/// Applies idle-counter zero synthesis and splits closed bucket values from `am`. +/// +/// Returns `(closed_values, should_remove_context)`. +pub fn extract_closed_values(am: &mut AggregatedMetric, window: &FlushWindow) -> (Option, bool) { + let should_expire_if_empty = match &am.values { + MetricValues::Counter(..) => { + saluki_antithesis::always_le!( + am.last_seen, + u64::MAX - window.counter_expire_secs, + "aggregate counter expiry add does not overflow", + { "last_seen": am.last_seen, "counter_expire_secs": window.counter_expire_secs } + ); + window.counter_expire_secs == 0 + || am.last_seen.saturating_add(window.counter_expire_secs) < window.current_time + } + _ => true, + }; + + if let MetricValues::Counter(..) = &mut am.values { + let expires_at = am.last_seen.saturating_add(window.counter_expire_secs); + for (zv_bucket_start, zero_value) in &window.zero_value_buckets { + if expires_at > *zv_bucket_start { + am.values.merge(zero_value.clone()); + } else { + break; + } + } + } + + let closed_values = am.values.split_at_timestamp(window.split_timestamp); + let should_remove = am.values.is_empty() && should_expire_if_empty; + + (closed_values, should_remove) +} + +/// Transforms closed bucket values for emission (expanding histograms and converting counters to rates). +pub fn expand_flushed_metric( + context: Context, mut values: MetricValues, metadata: MetricMetadata, bucket_width_secs: NonZeroU64, + hist_config: &HistogramConfiguration, mut emit: impl FnMut(Metric), +) { + let bucket_width = Duration::from_secs(bucket_width_secs.get()); + + match values { + MetricValues::Histogram(ref mut points) => { + if hist_config.copy_to_distribution() { + let sketch_points = points + .into_iter() + .map(|(ts, hist)| { + let mut sketch = DDSketch::default(); + for sample in hist.samples() { + sketch.insert_n(sample.value.into_inner(), sample.weight.0 as u64); + } + (ts, sketch) + }) + .collect::(); + let distribution_values = MetricValues::distribution(sketch_points); + let metric_context = if !hist_config.copy_to_distribution_prefix().is_empty() { + context.with_name(format!( + "{}{}", + hist_config.copy_to_distribution_prefix(), + context.name() + )) + } else { + context.clone() + }; + emit(Metric::from_parts( + metric_context, + distribution_values, + metadata.clone(), + )); + } + + let mut sorted_points = Vec::new(); + for (ts, h) in points { + sorted_points.push((ts, h.summary_view())); + } + + for statistic in hist_config.statistics() { + let new_points = sorted_points + .iter() + .map(|(ts, hs)| (*ts, statistic.value_from_histogram(hs))) + .collect::(); + + let new_values = if statistic.is_rate_statistic() { + MetricValues::rate(new_points, bucket_width) + } else { + MetricValues::gauge(new_points) + }; + + // Counts are dimensionless, so clear any unit inherited from the input histogram. + let new_metadata = if matches!(statistic, HistogramStatistic::Count) { + metadata.clone().with_unit(MetaString::empty()) + } else { + metadata.clone() + }; + + let new_context = context.with_name(format!("{}.{}", context.name(), statistic.suffix())); + emit(Metric::from_parts(new_context, new_values, new_metadata)); + } + } + values => { + let adjusted_values = counter_values_to_rate(values, bucket_width_secs); + emit(Metric::from_parts(context, adjusted_values, metadata)); + } + } +} + +/// Converts counter values into rates normalized over `interval_secs`. +pub fn counter_values_to_rate(values: MetricValues, interval_secs: NonZeroU64) -> MetricValues { + match values { + MetricValues::Counter(points) => MetricValues::rate(points, Duration::from_secs(interval_secs.get())), + values => values, + } +} + +/// Aligns `timestamp` down to the start of its `bucket_width_secs` bucket. +pub const fn align_to_bucket_start(timestamp: u64, bucket_width_secs: NonZeroU64) -> u64 { + timestamp - (timestamp % bucket_width_secs.get()) +} + +/// Returns whether the half-open bucket `[bucket_start, bucket_start + bucket_width_secs)` is closed at `current_time`. +pub const fn is_bucket_closed( + current_time: u64, bucket_start: u64, bucket_width_secs: NonZeroU64, flush_open_buckets: bool, +) -> bool { + (bucket_start + bucket_width_secs.get() - 1) < current_time || flush_open_buckets +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aggregates_counters_into_rates_and_emits_zero_buckets_until_expiry() { + let width = NonZeroU64::new(10).expect("non-zero"); + let mut core = AggregateCore::<()>::new( + width, + 100, + Some(Duration::from_secs(20)), + HistogramConfiguration::default(), + ); + + assert!(core.insert(12, Metric::counter("hits", 3.0))); + assert!(core.insert(15, Metric::counter("hits", 7.0))); + + // Flush at t=20 closes bucket [10, 20). + let mut flushed = Vec::new(); + core.flush_into(20, false, |m| flushed.push(m)); + assert_eq!(flushed.len(), 1); + assert_eq!(flushed[0].context().name(), "hits"); + assert!(matches!( + flushed[0].values(), + MetricValues::Rate(_, interval) if *interval == Duration::from_secs(10) + )); + + // Idle flush at t=30 emits a zero-value bucket for [20, 30) because last_seen (15) + 20 > 20. + flushed.clear(); + core.flush_into(30, false, |m| flushed.push(m)); + assert_eq!(flushed.len(), 1); + assert!(!core.is_empty()); + + // Flush at t=50 expires the counter. + flushed.clear(); + core.flush_into(50, false, |m| flushed.push(m)); + assert!(core.is_empty()); + } + + #[test] + fn enforces_context_limit_and_recovers_after_flush() { + let width = NonZeroU64::new(10).expect("non-zero"); + let mut core = AggregateCore::<()>::new(width, 1, None, HistogramConfiguration::default()); + + assert!(core.insert(10, Metric::gauge("a", 1.0))); + assert!(!core.insert(10, Metric::gauge("b", 2.0))); + assert!(core.context_limit_breached()); + + let mut flushed = Vec::new(); + core.flush_into(20, false, |m| flushed.push(m)); + assert_eq!(flushed.len(), 1); + assert!(!core.context_limit_breached()); + assert!(core.insert(20, Metric::gauge("b", 2.0))); + } +} diff --git a/lib/saluki-transform-kernels/src/filterlist.rs b/lib/saluki-transform-kernels/src/filterlist.rs new file mode 100644 index 00000000000..2567c5b68c4 --- /dev/null +++ b/lib/saluki-transform-kernels/src/filterlist.rs @@ -0,0 +1,725 @@ +//! Metric name filterlist compilation, namespace prefixing, and post-aggregate histogram filtering. + +use saluki_core::data_model::event::metric::{Metric, MetricValues}; +use serde::{Deserialize, Serialize}; +use stringtheory::MetaString; + +use crate::histogram::HistogramConfiguration; +use crate::metric_name::{is_normalized, normalize_into, normalize_prefix_into, NameBuf}; + +/// Metric names or prefixes that a metric filterlist drops. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct MetricNameFilter { + /// Metric names or prefixes that are dropped. + pub values: Vec, + + /// Whether entries in `values` match by prefix instead of exact name. + pub match_prefix: bool, + + /// Additional prefix rules with exceptions shared across all prefix rules. + pub prefix_rules: Vec, +} + +impl MetricNameFilter { + /// Returns `true` when no filter entries or prefix rules are configured. + pub fn is_empty(&self) -> bool { + self.values.is_empty() && self.prefix_rules.is_empty() + } +} + +/// A metric-name prefix to drop, with exceptions shared across all prefix rules. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct MetricPrefixRule { + /// Prefix to drop. An empty prefix matches every stored metric name. + pub prefix: String, + + /// Prefixes to keep, unless blocked by unconditional filter entries. + pub except_prefix: Vec, + + /// Exact names to keep, unless blocked by unconditional filter entries. + pub except_exact: Vec, +} + +/// Compiled filter matcher for metric names that should be dropped. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct Blocklist { + exact: Vec, + prefixes: Vec, + rule_prefixes: Vec, + except_exact: Vec, + except_prefix: Vec, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +struct PrefixRule { + prefix: String, + except_exact: Vec, + except_prefix: Vec, +} + +/// Diagnostics produced when compiling a [`MetricNameFilter`]. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct CompilationReport { + /// Entries dropped because no stored metric name can match them. + pub dropped_entries: Vec, + /// Prefix rules dropped because their prefixes cannot match any stored metric name. + pub dropped_rules: Vec, + /// Prefix-rule exceptions dropped because they cannot match any stored metric name. + pub dropped_exceptions: Vec, + /// Prefix rules shadowed by an unconditional prefix entry. + pub shadowed_rules: Vec, +} + +/// Compiles a [`MetricNameFilter`] into a [`Blocklist`] and a [`CompilationReport`]. +pub fn compile_metric_filter(metric_filter: &MetricNameFilter) -> (Blocklist, CompilationReport) { + let (normalized_entries, dropped_entries) = normalize_entries(&metric_filter.values, metric_filter.match_prefix); + let (normalized_rules, dropped_rules, dropped_exceptions) = normalize_prefix_rules(&metric_filter.prefix_rules); + + let (matcher, shadowed_rules) = Blocklist::new_with_prefix_rules( + normalized_entries.iter().map(String::as_str), + metric_filter.match_prefix, + &normalized_rules, + ); + + ( + matcher, + CompilationReport { + dropped_entries, + dropped_rules, + dropped_exceptions, + shadowed_rules, + }, + ) +} + +impl Blocklist { + /// Creates a matcher from already-normalized entries without prefix rules. + pub fn from_normalized(values: I, match_prefix: bool) -> Self + where + T: AsRef, + I: IntoIterator, + { + let (matcher, _) = Self::new_with_prefix_rules(values, match_prefix, &[]); + matcher + } + + fn new_with_prefix_rules(values: I, match_prefix: bool, rules: &[PrefixRule]) -> (Self, Vec) + where + T: AsRef, + I: IntoIterator, + { + let mut exact = Vec::new(); + let mut prefixes = Vec::new(); + for value in values { + if match_prefix { + prefixes.push(value.as_ref().to_string()); + } else { + exact.push(value.as_ref().to_string()); + } + } + + let mut rule_prefixes = Vec::with_capacity(rules.len()); + let mut except_exact = Vec::new(); + let mut except_prefix = Vec::new(); + for rule in rules { + rule_prefixes.push(rule.prefix.clone()); + except_exact.extend(rule.except_exact.iter().cloned()); + except_prefix.extend(rule.except_prefix.iter().cloned()); + } + + prefixes = compact_prefixes(prefixes); + exact = compact_exact(exact, &prefixes); + except_prefix = compact_prefixes(except_prefix); + except_exact = compact_exact(except_exact, &except_prefix); + + let mut shadowed_rules = Vec::new(); + if !prefixes.is_empty() { + rule_prefixes.retain(|prefix| { + let shadowed = test_prefixes(&prefixes, prefix.as_bytes()); + if shadowed { + shadowed_rules.push(prefix.clone()); + } + !shadowed + }); + } + rule_prefixes = compact_prefixes(rule_prefixes); + + ( + Self { + exact, + prefixes, + rule_prefixes, + except_exact, + except_prefix, + }, + shadowed_rules, + ) + } + + /// Returns whether `name` matches this filter list after normalization. + pub fn contains(&self, name: &str) -> bool { + if self.is_empty() { + return false; + } + + if is_normalized(name) { + return self.search(name.as_bytes()); + } + + let mut buf = NameBuf::new(); + match normalize_into(&mut buf, name) { + Some(normalized) => self.search(normalized), + None => false, + } + } + + /// Returns whether `name` is blocked by a prefix rule while having an exception below its namespace. + /// + /// This preserves histogram inputs that are needed to produce excepted post-aggregate series (for example, + /// preserving `foo` when `foo.avg` is excepted). + pub fn has_descendant_exception(&self, name: &str) -> bool { + if self.rule_prefixes.is_empty() || (self.except_exact.is_empty() && self.except_prefix.is_empty()) { + return false; + } + + if is_normalized(name) { + return self.has_descendant_exception_normalized(name.as_bytes()); + } + + let mut buf = NameBuf::new(); + match normalize_into(&mut buf, name) { + Some(normalized) => self.has_descendant_exception_normalized(normalized), + None => false, + } + } + + fn has_descendant_exception_normalized(&self, name: &[u8]) -> bool { + if binary_search_exact(&self.exact, name) || test_prefixes(&self.prefixes, name) { + return false; + } + + if !test_prefixes(&self.rule_prefixes, name) + || test_prefixes(&self.except_prefix, name) + || binary_search_exact(&self.except_exact, name) + { + return false; + } + + let has_descendant = |exceptions: &[String]| { + let index = exceptions + .partition_point(|candidate| candidate.bytes().cmp(name.iter().copied().chain([b'.'])).is_lt()); + + exceptions.get(index).is_some_and(|candidate| { + candidate + .as_bytes() + .strip_prefix(name) + .is_some_and(|suffix| suffix.starts_with(b".")) + }) + }; + + has_descendant(&self.except_exact) || has_descendant(&self.except_prefix) + } + + /// Restricts exact entries while leaving all prefix behavior unchanged. + pub fn restrict_exact(&self, keep: impl Fn(&str) -> bool) -> Self { + let exact = self + .exact + .iter() + .filter(|entry| keep(entry.as_str())) + .cloned() + .collect::>(); + + Self { + exact, + prefixes: self.prefixes.clone(), + rule_prefixes: self.rule_prefixes.clone(), + except_exact: self.except_exact.clone(), + except_prefix: self.except_prefix.clone(), + } + } + + /// Returns the number of compiled entries. + pub fn len(&self) -> usize { + self.exact.len() + self.prefixes.len() + self.rule_prefixes.len() + } + + /// Returns `true` when this filter list has no compiled entries. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns whether this filter list matches every stored metric name. + pub fn matches_all(&self) -> bool { + if self.prefixes.len() == 1 && self.prefixes[0].is_empty() { + return true; + } + + self.rule_prefixes.len() == 1 + && self.rule_prefixes[0].is_empty() + && self.except_exact.is_empty() + && self.except_prefix.is_empty() + } + + fn search(&self, name: &[u8]) -> bool { + if binary_search_exact(&self.exact, name) { + return true; + } + + if test_prefixes(&self.prefixes, name) { + return true; + } + + if !test_prefixes(&self.rule_prefixes, name) { + return false; + } + + if test_prefixes(&self.except_prefix, name) { + return false; + } + + !binary_search_exact(&self.except_exact, name) + } +} + +/// Pure kernel that applies a metric namespace prefix and a listener-side metric filter list. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PrefixFilterKernel { + metric_prefix: String, + metric_prefix_blocklist: Vec, + matcher: Blocklist, +} + +impl PrefixFilterKernel { + /// Creates a new `PrefixFilterKernel`. + /// + /// A non-empty `metric_prefix` without a trailing period receives one so metric processing does not re-check it. + pub fn new(metric_prefix: String, metric_prefix_blocklist: Vec, matcher: Blocklist) -> Self { + let mut normalized_prefix = metric_prefix; + if !normalized_prefix.is_empty() && !normalized_prefix.ends_with('.') { + normalized_prefix.push('.'); + } + + Self { + metric_prefix: normalized_prefix, + metric_prefix_blocklist, + matcher, + } + } + + /// Creates a new `PrefixFilterKernel` by compiling `metric_filter`. + pub fn from_filter( + metric_prefix: String, metric_prefix_blocklist: Vec, metric_filter: &MetricNameFilter, + ) -> (Self, CompilationReport) { + let (matcher, report) = compile_metric_filter(metric_filter); + (Self::new(metric_prefix, metric_prefix_blocklist, matcher), report) + } + + /// Replaces the compiled [`Blocklist`]. + pub fn set_matcher(&mut self, matcher: Blocklist) { + self.matcher = matcher; + } + + /// Returns a reference to the compiled [`Blocklist`]. + pub fn matcher(&self) -> &Blocklist { + &self.matcher + } + + /// Returns `true` when this kernel neither adds a prefix nor drops any metric. + pub fn is_noop(&self) -> bool { + self.metric_prefix.is_empty() && self.matcher.is_empty() + } + + /// Applies namespace prefixing and filterlist matching to `metric`. + /// + /// Returns `true` if `metric` is kept, or `false` if it is dropped by the filter list. Metrics whose name does not + /// change keep their original [`saluki_core::data_model::event::metric::context::Context`] untouched. + pub fn apply(&self, metric: &mut Metric) -> bool { + let original_name = metric.context().name(); + if self.metric_prefix.is_empty() || self.has_excluded_prefix(original_name) { + return !self.is_filtered(metric, original_name); + } + + let mut prefixed_metric_name = self.metric_prefix.clone(); + prefixed_metric_name.push_str(original_name); + let new_metric_name = MetaString::from(prefixed_metric_name); + + if self.is_filtered(metric, &new_metric_name) { + return false; + } + + let new_context = metric.context().with_name(new_metric_name); + *metric.context_mut() = new_context; + + true + } + + fn is_filtered(&self, metric: &Metric, name: &str) -> bool { + if !self.matcher.contains(name) { + return false; + } + + if matches!(metric.values(), MetricValues::Histogram(_)) && self.matcher.has_descendant_exception(name) { + return false; + } + + true + } + + fn has_excluded_prefix(&self, metric_name: &str) -> bool { + !self.metric_prefix.is_empty() + && self + .metric_prefix_blocklist + .iter() + .any(|prefix| metric_name.starts_with(prefix)) + } +} + +/// Suffixes produced when histograms are expanded into scalar aggregate series. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct HistogramSuffixes { + values: Vec, +} + +impl HistogramSuffixes { + /// Builds the suffixes produced by the given histogram aggregates and percentiles. + pub fn new(aggregates: &[String], percentiles: &[String]) -> Self { + let mut values = aggregates + .iter() + .map(|aggregate| MetaString::from(aggregate.as_str())) + .collect::>(); + values.extend(HistogramConfiguration::percentile_suffixes(percentiles)); + + Self { values } + } + + /// Returns the compiled suffix list. + pub fn values(&self) -> &[MetaString] { + &self.values + } + + /// Returns whether `value` targets a generated histogram aggregate output (`.`). + pub fn contains_filter_entry(&self, value: &str) -> bool { + self.values.iter().any(|suffix| { + let suffix: &str = suffix.as_ref(); + value + .strip_suffix(suffix) + .map(|prefix| prefix.ends_with('.')) + .unwrap_or(false) + }) + } +} + +/// Pure kernel that drops post-aggregation scalar metrics matching histogram-aggregate filter entries. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct PostAggregateFilterKernel { + matcher: Blocklist, + histogram_suffixes: HistogramSuffixes, +} + +impl PostAggregateFilterKernel { + /// Creates a new `PostAggregateFilterKernel` from a metric filter and histogram output suffixes. + pub fn new( + metric_filter: &MetricNameFilter, histogram_aggregates: &[String], histogram_percentiles: &[String], + ) -> Self { + let histogram_suffixes = HistogramSuffixes::new(histogram_aggregates, histogram_percentiles); + let mut kernel = Self { + matcher: Blocklist::default(), + histogram_suffixes, + }; + kernel.update_filter(metric_filter); + kernel + } + + /// Rebuilds the matcher from `metric_filter`, keeping only exact entries that match a histogram suffix. + pub fn update_filter(&mut self, metric_filter: &MetricNameFilter) { + let (matcher, _) = compile_metric_filter(metric_filter); + self.matcher = matcher.restrict_exact(|value| self.histogram_suffixes.contains_filter_entry(value)); + } + + /// Returns `true` when this kernel drops no metrics. + pub fn is_noop(&self) -> bool { + self.matcher.is_empty() + } + + /// Returns `true` if `metric` should be dropped. + pub fn should_filter(&self, metric: &Metric) -> bool { + is_scalar_series_metric(metric) && self.matcher.contains(metric.context().name()) + } + + /// Returns `true` if `metric` should be kept. + pub fn should_keep(&self, metric: &Metric) -> bool { + !self.should_filter(metric) + } +} + +fn is_scalar_series_metric(metric: &Metric) -> bool { + matches!( + metric.values(), + MetricValues::Counter(_) | MetricValues::Rate(_, _) | MetricValues::Gauge(_) | MetricValues::Set(_) + ) +} + +fn normalize_entries(entries: &[String], match_prefix: bool) -> (Vec, Vec) { + let mut normalized = Vec::with_capacity(entries.len()); + let mut dropped = Vec::new(); + let mut buf = NameBuf::new(); + + for entry in entries { + let key = if match_prefix { + normalize_prefix_into(&mut buf, entry) + } else { + normalize_into(&mut buf, entry) + }; + + match key { + Some(key) => normalized.push( + simdutf8::basic::from_utf8(key) + .expect("normalized metric names are ASCII") + .to_owned(), + ), + None => dropped.push(entry.clone()), + } + } + + (normalized, dropped) +} + +fn normalize_prefix_rules(rules: &[MetricPrefixRule]) -> (Vec, Vec, Vec) { + let mut normalized = Vec::with_capacity(rules.len()); + let mut dropped_rules = Vec::new(); + let mut dropped_exceptions = Vec::new(); + let mut buf = NameBuf::new(); + + for rule in rules { + let Some(prefix) = normalize_prefix_into(&mut buf, &rule.prefix) else { + dropped_rules.push(rule.prefix.clone()); + continue; + }; + + let mut normalized_rule = PrefixRule { + prefix: simdutf8::basic::from_utf8(prefix) + .expect("normalized metric names are ASCII") + .to_owned(), + except_exact: Vec::new(), + except_prefix: Vec::new(), + }; + + for exact in &rule.except_exact { + match normalize_into(&mut buf, exact) { + Some(key) => normalized_rule.except_exact.push( + simdutf8::basic::from_utf8(key) + .expect("normalized metric names are ASCII") + .to_owned(), + ), + None => dropped_exceptions.push(exact.clone()), + } + } + + for prefix in &rule.except_prefix { + match normalize_prefix_into(&mut buf, prefix) { + Some(key) => normalized_rule.except_prefix.push( + simdutf8::basic::from_utf8(key) + .expect("normalized metric names are ASCII") + .to_owned(), + ), + None => dropped_exceptions.push(prefix.clone()), + } + } + + normalized.push(normalized_rule); + } + + (normalized, dropped_rules, dropped_exceptions) +} + +fn compact_prefixes(mut prefixes: Vec) -> Vec { + if prefixes.is_empty() { + return Vec::new(); + } + + prefixes.sort_unstable(); + + let mut compacted = Vec::with_capacity(prefixes.len()); + for prefix in prefixes { + if compacted.last().map(|kept| prefix.starts_with(kept)).unwrap_or(false) { + continue; + } + compacted.push(prefix); + } + + compacted +} + +fn compact_exact(mut exact: Vec, prefixes: &[String]) -> Vec { + if exact.is_empty() { + return Vec::new(); + } + + exact.sort_unstable(); + exact.dedup(); + + if prefixes.is_empty() { + return exact; + } + + exact.retain(|name| !test_prefixes(prefixes, name.as_bytes())); + exact +} + +fn binary_search_exact(entries: &[String], name: &[u8]) -> bool { + entries + .binary_search_by(|candidate| candidate.as_bytes().cmp(name)) + .is_ok() +} + +fn test_prefixes(prefixes: &[String], name: &[u8]) -> bool { + if prefixes.is_empty() { + return false; + } + + let index = prefixes + .binary_search_by(|candidate| candidate.as_bytes().cmp(name)) + .unwrap_or_else(|idx| idx); + + if index > 0 && name.starts_with(prefixes[index - 1].as_bytes()) { + return true; + } + + index < prefixes.len() && prefixes[index].as_bytes() == name +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prefix_filter_kernel_prepends_and_filters() { + let filter = MetricNameFilter { + values: vec!["app.blocked".to_string()], + match_prefix: false, + prefix_rules: vec![], + }; + let (kernel, _) = PrefixFilterKernel::from_filter("app".to_string(), vec!["datadog.".to_string()], &filter); + + let mut allowed = Metric::gauge("requests", 1.0); + assert!(kernel.apply(&mut allowed)); + assert_eq!(allowed.context().name(), "app.requests"); + + let mut excluded_prefix = Metric::gauge("datadog.agent.running", 1.0); + let original = excluded_prefix.context().clone(); + assert!(kernel.apply(&mut excluded_prefix)); + assert!(original.ptr_eq(excluded_prefix.context())); + assert_eq!(excluded_prefix.context().name(), "datadog.agent.running"); + + let mut blocked = Metric::gauge("blocked", 1.0); + assert!(!kernel.apply(&mut blocked)); + } + + #[test] + fn prefix_filter_keeps_histogram_with_descendant_exception() { + let filter = MetricNameFilter { + values: vec![], + match_prefix: false, + prefix_rules: vec![MetricPrefixRule { + prefix: "service.".to_string(), + except_exact: vec!["service.latency.avg".to_string()], + except_prefix: vec![], + }], + }; + let (kernel, _) = PrefixFilterKernel::from_filter(String::new(), vec![], &filter); + + let mut hist = Metric::histogram("service.latency", 42.0); + assert!(kernel.apply(&mut hist)); + + let mut gauge = Metric::gauge("service.latency", 42.0); + assert!(!kernel.apply(&mut gauge)); + } + + #[test] + fn post_aggregate_filter_kernel_filters_only_histogram_suffix_exact_entries() { + let filter = MetricNameFilter { + values: vec!["req.latency.avg".to_string(), "req.other".to_string()], + match_prefix: false, + prefix_rules: vec![], + }; + let kernel = PostAggregateFilterKernel::new(&filter, &["avg".to_string()], &["0.95".to_string()]); + + assert!(kernel.should_filter(&Metric::gauge("req.latency.avg", 1.0))); + assert!(!kernel.should_filter(&Metric::gauge("req.other", 1.0))); + assert!(!kernel.should_filter(&Metric::distribution("req.latency.avg", 1.0))); + } + + fn rule(prefix: &str, except_exact: &[&str], except_prefix: &[&str]) -> MetricPrefixRule { + MetricPrefixRule { + prefix: prefix.to_string(), + except_exact: except_exact.iter().map(ToString::to_string).collect(), + except_prefix: except_prefix.iter().map(ToString::to_string).collect(), + } + } + + #[test] + fn compiles_entries_verbatim() { + let compiled = |values: &[&str]| Blocklist::from_normalized(values.iter().copied(), true).prefixes; + + assert_eq!(compiled(&[]), Vec::::new()); + assert_eq!(compiled(&["a"]), vec!["a"]); + assert_eq!(compiled(&["a", "aa"]), vec!["a"]); + assert_eq!(compiled(&["a", "aa", "b", "bb"]), vec!["a", "b"]); + assert_eq!(compiled(&["a", "b", "bb"]), vec!["a", "b"]); + assert_eq!(compiled(&["a-b", "a_b"]), vec!["a-b", "a_b"]); + } + + #[test] + fn matching_normalizes_the_metric_name() { + let cases: &[(bool, &str, &[&str], bool)] = &[ + (true, "my metric-name", &["my_metric_name"], false), + (true, "custom.metric one", &["custom.metric_one"], false), + (true, "host.cpu%util", &["host.cpu_util"], false), + (true, "1app.requests", &["app.requests"], false), + (true, "café.requests", &["caf.requests"], false), + (false, "my_metric_name", &["my metric-name"], false), + (true, "custom.metric name.count", &["custom.metric_name"], true), + (false, "", &["foo"], false), + (false, "123", &["foo"], false), + ]; + + for (expected, name, entries, match_prefix) in cases { + let blocklist = Blocklist::from_normalized(entries.iter().copied(), *match_prefix); + assert_eq!(blocklist.contains(name), *expected, "name: {:?}", name); + } + } + + #[test] + fn prefix_rule_exceptions_and_shadowing() { + let metric_filter = MetricNameFilter { + values: vec!["postgresql.".to_string()], + match_prefix: true, + prefix_rules: vec![rule("postgresql.locks.", &["postgresql.locks.waiting"], &[])], + }; + let (matcher, report) = compile_metric_filter(&metric_filter); + assert_eq!(report.shadowed_rules, vec!["postgresql.locks.".to_string()]); + assert!(matcher.contains("postgresql.locks.waiting")); + } + + #[test] + fn compile_metric_filter_drops_unusable_entries_and_preserves_prefix_boundaries() { + let metric_filter = MetricNameFilter { + values: vec!["service_".to_string(), "123".to_string()], + match_prefix: true, + prefix_rules: vec![ + rule("123", &[], &[]), + rule("foo.", &["123", "foo.keep"], &["123", "foo.skip."]), + ], + }; + let (matcher, report) = compile_metric_filter(&metric_filter); + + assert_eq!(report.dropped_entries, vec!["123".to_string()]); + assert_eq!(report.dropped_rules, vec!["123".to_string()]); + assert_eq!(report.dropped_exceptions, vec!["123".to_string(), "123".to_string()]); + assert!(matcher.contains("service_requests")); + assert!(!matcher.contains("service.requests")); + assert!(matcher.contains("foo.anything")); + assert!(!matcher.contains("foo.keep")); + assert!(!matcher.contains("foo.skip.waiting")); + } +} diff --git a/lib/saluki-transform-kernels/src/histogram.rs b/lib/saluki-transform-kernels/src/histogram.rs new file mode 100644 index 00000000000..cac3e4ee086 --- /dev/null +++ b/lib/saluki-transform-kernels/src/histogram.rs @@ -0,0 +1,279 @@ +//! Histogram aggregate statistics and percentile suffix calculation. + +use saluki_core::data_model::event::metric::HistogramSummary; +use serde::{Deserialize, Serialize}; +use stringtheory::MetaString; +use tracing::error; + +/// A histogram statistic to calculate. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum HistogramStatistic { + /// Total count of values in the histogram. + Count, + + /// Sum of all values in the histogram. + Sum, + + /// Minimum value in the histogram. + Minimum, + + /// Maximum value in the histogram. + Maximum, + + /// Average value in the histogram. + Average, + + /// Median value in the histogram. + Median, + + /// Calculate the given percentile from the histogram. + Percentile { + /// Quantile value to calculate, in `[0.0, 1.0]`. + q: f64, + + /// Suffix to append to the metric name, such as `95percentile`. + suffix: MetaString, + }, +} + +impl HistogramStatistic { + /// Returns the suffix used for metrics representing this statistic. + pub fn suffix(&self) -> &str { + match self { + HistogramStatistic::Count => "count", + HistogramStatistic::Sum => "sum", + HistogramStatistic::Minimum => "min", + HistogramStatistic::Maximum => "max", + HistogramStatistic::Average => "avg", + HistogramStatistic::Median => "median", + HistogramStatistic::Percentile { suffix, .. } => suffix, + } + } + + /// Returns `true` if this statistic should be represented as a rate. + pub fn is_rate_statistic(&self) -> bool { + matches!(self, HistogramStatistic::Count) + } + + /// Returns the value of this statistic from the given histogram summary. + pub fn value_from_histogram(&self, summary: &HistogramSummary<'_>) -> f64 { + match self { + HistogramStatistic::Count => summary.count() as f64, + HistogramStatistic::Sum => summary.sum(), + HistogramStatistic::Minimum => summary.min().unwrap_or(0.0), + HistogramStatistic::Maximum => summary.max().unwrap_or(0.0), + HistogramStatistic::Average => summary.avg(), + HistogramStatistic::Median => summary.median().unwrap_or(0.0), + HistogramStatistic::Percentile { q, .. } => { + saluki_antithesis::always_ge!(*q, 0.0, "histogram percentile quantile at or above zero"); + saluki_antithesis::always_le!(*q, 1.0, "histogram percentile quantile at or below one"); + summary.quantile(*q).unwrap_or(0.0) + } + } + } +} + +enum InvalidPercentile { + Unparseable(std::num::ParseFloatError), + OutOfRange, +} + +fn parse_percentile(faux_percentile: &str) -> Result { + let quantile = faux_percentile.parse::().map_err(InvalidPercentile::Unparseable)?; + if !(0.0..=1.0).contains(&quantile) { + return Err(InvalidPercentile::OutOfRange); + } + Ok((quantile * 100.0 + 0.5) as u32) +} + +fn percentile_suffix(percentile: u32) -> MetaString { + format!("{}percentile", percentile).into() +} + +/// Statistics to calculate over histograms, and how to copy them to distributions. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct HistogramConfiguration { + statistics: Vec, + copy_to_distribution: bool, + copy_to_distribution_prefix: String, +} + +impl HistogramConfiguration { + /// Creates a new `HistogramConfiguration` from the aggregates and percentiles to calculate. + /// + /// Aggregates name a statistic to compute over each histogram: `count`, `sum`, `min`, `max`, `avg`, or `median`. + /// Percentiles are expressed in quantile form between `0.0` and `1.0` inclusive. Invalid entries are logged and + /// skipped. + pub fn new( + aggregates: &[String], percentiles: &[String], copy_to_distribution: bool, copy_to_distribution_prefix: String, + ) -> Self { + let mut statistics = Vec::new(); + + for aggregate in aggregates { + match aggregate.as_str() { + "count" => statistics.push(HistogramStatistic::Count), + "sum" => statistics.push(HistogramStatistic::Sum), + "min" => statistics.push(HistogramStatistic::Minimum), + "max" => statistics.push(HistogramStatistic::Maximum), + "avg" => statistics.push(HistogramStatistic::Average), + "median" => statistics.push(HistogramStatistic::Median), + _ => error!( + "Configured aggregate '{}' in 'histogram_aggregates' is not implemented, skipping.", + aggregate + ), + } + } + + for faux_percentile in percentiles { + match parse_percentile(faux_percentile) { + Ok(percentile) => statistics.push(HistogramStatistic::Percentile { + q: f64::from(percentile) / 100.0, + suffix: percentile_suffix(percentile), + }), + Err(InvalidPercentile::Unparseable(e)) => error!( + "Could not parse '{}' from 'histogram_percentiles' (skipping): {}", + faux_percentile, e + ), + Err(InvalidPercentile::OutOfRange) => error!( + "'histogram_percentiles' must be between 0 and 1: skipping '{}'.", + faux_percentile + ), + } + } + + Self { + statistics, + copy_to_distribution, + copy_to_distribution_prefix, + } + } + + /// Returns the metric name suffixes, such as `95percentile`, that valid entries in `percentiles` produce. + pub fn percentile_suffixes(percentiles: &[String]) -> Vec { + percentiles + .iter() + .filter_map(|faux_percentile| parse_percentile(faux_percentile).ok()) + .map(percentile_suffix) + .collect() + } + + /// Creates a configuration from already-parsed statistics. + pub fn from_statistics( + statistics: &[HistogramStatistic], copy_to_distribution: bool, copy_to_distribution_prefix: String, + ) -> Self { + Self { + statistics: statistics.to_vec(), + copy_to_distribution, + copy_to_distribution_prefix, + } + } + + /// Returns the configured aggregate statistics to calculate. + pub fn statistics(&self) -> &[HistogramStatistic] { + &self.statistics + } + + /// Returns `true` if histograms should be copied to distributions. + pub fn copy_to_distribution(&self) -> bool { + self.copy_to_distribution + } + + /// Returns the prefix to prepend to the metric name when copying histograms to distributions. + pub fn copy_to_distribution_prefix(&self) -> &str { + &self.copy_to_distribution_prefix + } +} + +impl Default for HistogramConfiguration { + fn default() -> Self { + Self { + statistics: vec![ + HistogramStatistic::Maximum, + HistogramStatistic::Median, + HistogramStatistic::Average, + HistogramStatistic::Count, + HistogramStatistic::Percentile { + q: 0.95, + suffix: MetaString::from_static("95percentile"), + }, + ], + copy_to_distribution: false, + copy_to_distribution_prefix: String::new(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unsupported_aggregates_and_percentiles_are_skipped() { + let to_strings = |values: &[&str]| values.iter().map(|v| v.to_string()).collect::>(); + let config = HistogramConfiguration::new( + &to_strings(&["max", "p99", "count"]), + &to_strings(&["abc", "0.95", "1.1", "-0.1"]), + false, + String::new(), + ); + + assert_eq!( + config.statistics(), + &[ + HistogramStatistic::Maximum, + HistogramStatistic::Count, + HistogramStatistic::Percentile { + q: 0.95, + suffix: "95percentile".into(), + }, + ] + ); + } + + #[test] + fn all_invalid_entries_leave_no_statistics() { + let config = HistogramConfiguration::new(&["p99".to_string()], &["abc".to_string()], false, String::new()); + assert!(config.statistics().is_empty()); + } + + #[test] + fn percentile_suffixes_match_rounding() { + let config = HistogramConfiguration::new(&[], &["0.299".to_string(), "0.73".to_string()], false, String::new()); + + assert_eq!( + config.statistics(), + &[ + HistogramStatistic::Percentile { + q: 0.30, + suffix: "30percentile".into(), + }, + HistogramStatistic::Percentile { + q: 0.73, + suffix: "73percentile".into(), + }, + ] + ); + } + + #[test] + fn percentile_suffixes_match_the_emitted_percentile_statistics() { + let percentiles = ["0.5", "0.299", "abc", "1.5", "-0.1", "0.0", "1.0"].map(String::from); + let config = HistogramConfiguration::new(&[], &percentiles, false, String::new()); + + let emitted = config + .statistics() + .iter() + .map(|statistic| statistic.suffix().to_string()) + .collect::>(); + let suffixes = HistogramConfiguration::percentile_suffixes(&percentiles) + .iter() + .map(|suffix| suffix.to_string()) + .collect::>(); + + assert_eq!( + suffixes, + ["50percentile", "30percentile", "0percentile", "100percentile"] + ); + assert_eq!(suffixes, emitted); + } +} diff --git a/lib/saluki-transform-kernels/src/host_tags.rs b/lib/saluki-transform-kernels/src/host_tags.rs new file mode 100644 index 00000000000..90c89b42be2 --- /dev/null +++ b/lib/saluki-transform-kernels/src/host_tags.rs @@ -0,0 +1,119 @@ +//! Pure host-tag enrichment kernel for metrics. + +use std::sync::Arc; + +use saluki_core::data_model::{ + event::metric::Metric, + tags::{SharedTagSet, Tag}, +}; +use stringtheory::MetaString; + +/// Prefix of the infrastructure-mode tag mark that must not be attached to customer metrics. +const INFRA_MODE_TAG_PREFIX: &str = "infra_mode:"; + +/// Converts raw system host tags into the [`SharedTagSet`] attached to metrics. +/// +/// Drops `infra_mode:*` tags so they do not move metrics out of the customer namespace. +pub fn filter_metric_host_tags(system_tags: I) -> SharedTagSet +where + I: IntoIterator, + S: AsRef, +{ + system_tags + .into_iter() + .filter(|tag| !tag.as_ref().starts_with(INFRA_MODE_TAG_PREFIX)) + .map(|s| Arc::from(s.as_ref())) + .map(MetaString::from) + .map(Tag::from) + .collect() +} + +/// Pure kernel that merges a set of host tags into metrics while active. +#[derive(Clone, Debug, Default)] +pub struct HostTagsKernel { + host_tags: Option, +} + +impl HostTagsKernel { + /// Creates a new `HostTagsKernel` with optional initial host tags. + pub fn new(host_tags: Option) -> Self { + Self { host_tags } + } + + /// Creates a new `HostTagsKernel` from raw system host tag strings, stripping `infra_mode:*` tags. + pub fn from_system_tags(system_tags: I) -> Self + where + I: IntoIterator, + S: AsRef, + { + let tags = filter_metric_host_tags(system_tags); + Self { + host_tags: (!tags.is_empty()).then_some(tags), + } + } + + /// Returns `true` when host tags are currently active. + pub fn is_active(&self) -> bool { + self.host_tags.is_some() + } + + /// Clears the host tags so subsequent calls become no-ops. + pub fn clear(&mut self) { + self.host_tags = None; + } + + /// Replaces the active host tags. + pub fn set_host_tags(&mut self, host_tags: Option) { + self.host_tags = host_tags; + } + + /// Merges the active host tags into `metric`. + pub fn apply(&self, metric: &mut Metric) { + let Some(host_tags) = self.host_tags.as_ref() else { + return; + }; + + metric.context_mut().mutate_tags(|tags| tags.merge_shared(host_tags)); + } +} + +#[cfg(test)] +mod tests { + use saluki_core::data_model::event::metric::context::Context; + + use super::*; + + #[test] + fn attaches_host_tags_until_cleared() { + let mut kernel = HostTagsKernel::from_system_tags(["env:prod", "role:web"]); + assert!(kernel.is_active()); + + let mut m1 = Metric::gauge(Context::from_static_parts("test", &[]), 1.0); + kernel.apply(&mut m1); + assert!(m1.context().tags().has_tag(Tag::from("env:prod"))); + assert!(m1.context().tags().has_tag(Tag::from("role:web"))); + + kernel.clear(); + assert!(!kernel.is_active()); + + let mut m2 = Metric::gauge(Context::from_static_parts("test", &[]), 1.0); + kernel.apply(&mut m2); + assert_eq!(m2.context().tags().len(), 0); + } + + #[test] + fn strips_infra_mode_tags_only() { + let tags = filter_metric_host_tags([ + "env:prod", + "infra_mode:cloud_cost_only", + "infra_mode:", + "infra_mode", + "infra_mode_extra:x", + ]); + + assert_eq!(tags.len(), 3); + assert!(tags.has_tag(Tag::from("env:prod"))); + assert!(tags.has_tag(Tag::from("infra_mode"))); + assert!(tags.has_tag(Tag::from("infra_mode_extra:x"))); + } +} diff --git a/lib/saluki-transform-kernels/src/lib.rs b/lib/saluki-transform-kernels/src/lib.rs new file mode 100644 index 00000000000..0ccb983966f --- /dev/null +++ b/lib/saluki-transform-kernels/src/lib.rs @@ -0,0 +1,18 @@ +//! Pure transformation kernels decoupled from Saluki's component and task runtime. +//! +//! Each module in this crate encapsulates deterministic, synchronous domain logic for a data processing stage. +//! Async topology components and compiled pipeline engines delegate to these kernels so both paths share identical +//! semantics. + +#![deny(warnings)] +#![deny(missing_docs)] + +pub mod aggregate; +pub mod filterlist; +pub mod histogram; +pub mod host_tags; +pub mod mapper; +pub mod metric_name; +pub mod routing_filter; +pub mod tag_filter; +pub mod timestamp_split; diff --git a/lib/saluki-transform-kernels/src/mapper.rs b/lib/saluki-transform-kernels/src/mapper.rs new file mode 100644 index 00000000000..872bd232baf --- /dev/null +++ b/lib/saluki-transform-kernels/src/mapper.rs @@ -0,0 +1,281 @@ +//! Pure DogStatsD metric-name mapper kernel. +//! +//! Compiles wildcard and regular-expression mapping profiles and expands capture groups into rewritten metric names +//! and extracted tags. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use regex::Regex; +use saluki_core::data_model::{ + event::metric::Metric, + tags::{SharedTagSet, TagSet}, +}; +use saluki_error::{generic_error, ErrorContext as _, GenericError}; +use serde::{Deserialize, Serialize}; +use stringtheory::MetaString; + +const MATCH_TYPE_WILDCARD: &str = "wildcard"; +const MATCH_TYPE_REGEX: &str = "regex"; + +static ALLOWED_WILDCARD_MATCH_PATTERN: LazyLock = + LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9\-_*.]+$").expect("allowed wildcard pattern regex should be valid")); + +/// Configuration for a DogStatsD metric mapping profile. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct DogStatsDMapperProfile { + /// Profile name used in configuration errors. + pub name: String, + + /// Metric-name prefix this profile applies to (`"*"` matches every metric). + pub prefix: String, + + /// Metric mappings evaluated in order for this profile. + pub mappings: Vec, +} + +/// Configuration for a single metric mapping in a [`DogStatsDMapperProfile`]. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct DogStatsDMetricMapping { + /// Pattern matched against the incoming metric name. + pub metric_match: String, + + /// Pattern type: `"wildcard"`, `"regex"`, or empty for the default wildcard behavior. + pub match_type: String, + + /// Metric name template emitted after a match. + pub name: String, + + /// Tag key-to-template pairs emitted after expanding capture groups. + pub tags: HashMap, +} + +/// Outcome of matching a metric name against a compiled [`MapperKernel`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MappedMetricName { + /// Expanded target metric name. + pub name: MetaString, + + /// Extracted tags expanded from capture groups. + pub extra_tags: SharedTagSet, +} + +#[derive(Clone)] +struct CompiledProfile { + prefix: String, + mappings: Vec, +} + +#[derive(Clone)] +struct CompiledMapping { + name: String, + tags: HashMap, + regex: Regex, +} + +/// Pure compiled DogStatsD metric mapper kernel. +#[derive(Clone, Default)] +pub struct MapperKernel { + profiles: Vec, +} + +impl MapperKernel { + /// Validates and compiles `profiles` into a [`MapperKernel`]. + /// + /// # Errors + /// + /// Returns an error describing the first invalid profile or mapping. + pub fn compile(profiles: &[DogStatsDMapperProfile]) -> Result { + let mut compiled = Vec::with_capacity(profiles.len()); + for (profile_index, config_profile) in profiles.iter().enumerate() { + if config_profile.name.is_empty() { + return Err(generic_error!("missing profile name {}", profile_index)); + } + if config_profile.prefix.is_empty() { + return Err(generic_error!("missing prefix for profile: {}", config_profile.name)); + } + + let mut mappings = Vec::with_capacity(config_profile.mappings.len()); + for (mapping_index, mapping) in config_profile.mappings.iter().enumerate() { + let match_type = match mapping.match_type.as_str() { + "" | MATCH_TYPE_WILDCARD => MATCH_TYPE_WILDCARD, + MATCH_TYPE_REGEX => MATCH_TYPE_REGEX, + unknown => { + return Err(generic_error!( + "profile: {}, mapping num {}: invalid match type `{}`, expected `wildcard` or `regex`", + config_profile.name, + mapping_index, + unknown, + )) + } + }; + if mapping.name.is_empty() { + return Err(generic_error!( + "profile: {}, mapping num {}: name is required", + config_profile.name, + mapping_index + )); + } + if mapping.metric_match.is_empty() { + return Err(generic_error!( + "profile: {}, mapping num {}: match is required", + config_profile.name, + mapping_index + )); + } + let regex = build_regex(&mapping.metric_match, match_type)?; + mappings.push(CompiledMapping { + name: mapping.name.clone(), + tags: mapping.tags.clone(), + regex, + }); + } + + compiled.push(CompiledProfile { + prefix: config_profile.prefix.clone(), + mappings, + }); + } + + Ok(Self { profiles: compiled }) + } + + /// Returns `true` when no mapping profiles are active. + pub fn is_empty(&self) -> bool { + self.profiles.is_empty() + } + + /// Attempts to match `metric_name` against the compiled profiles and expand the first match. + pub fn match_name(&self, metric_name: &str) -> Option { + if self.profiles.is_empty() { + return None; + } + + let mut new_name = String::new(); + let mut expanded_tag_value = String::new(); + + for profile in &self.profiles { + if !metric_name.starts_with(&profile.prefix) && profile.prefix != "*" { + continue; + } + + for mapping in &profile.mappings { + if let Some(captures) = mapping.regex.captures(metric_name) { + new_name.clear(); + captures.expand(&mapping.name, &mut new_name); + + let mut extra_tags = TagSet::with_capacity(mapping.tags.len()); + for (tag_key, tag_value_expr) in &mapping.tags { + expanded_tag_value.clear(); + expanded_tag_value.push_str(tag_key); + expanded_tag_value.push(':'); + captures.expand(tag_value_expr, &mut expanded_tag_value); + + extra_tags.insert_tag(expanded_tag_value.as_str()); + } + + return Some(MappedMetricName { + name: MetaString::from(new_name), + extra_tags: extra_tags.into_shared(), + }); + } + } + } + + None + } + + /// Rewrites `metric` in place if its name matches a compiled profile. + /// + /// Returns `true` if `metric` was remapped. + pub fn apply(&self, metric: &mut Metric) -> bool { + let Some(mapped) = self.match_name(metric.context().name()) else { + return false; + }; + + let mut new_context = metric.context().with_name(mapped.name); + if !mapped.extra_tags.is_empty() { + new_context.mutate_tags(|tags| tags.merge_shared(&mapped.extra_tags)); + } + *metric.context_mut() = new_context; + true + } +} + +fn build_regex(match_re: &str, match_type: &str) -> Result { + let mut pattern = match_re.to_owned(); + if match_type == MATCH_TYPE_WILDCARD { + if !ALLOWED_WILDCARD_MATCH_PATTERN.is_match(&pattern) { + return Err(generic_error!( + "invalid wildcard match pattern `{}`, it does not match allowed match regex `{}`", + pattern, + ALLOWED_WILDCARD_MATCH_PATTERN.as_str() + )); + } + if pattern.contains("**") { + return Err(generic_error!( + "invalid wildcard match pattern `{}`, it should not contain consecutive `*`", + pattern + )); + } + pattern = pattern.replace('.', "\\."); + pattern = pattern.replace('*', "([^.]*)"); + } + + let final_pattern = format!("^{}$", pattern); + + Regex::new(&final_pattern).with_error_context(|| { + format!( + "Failed to compile regular expression `{}` for `{}` match type", + final_pattern, match_type + ) + }) +} + +#[cfg(test)] +mod tests { + use saluki_core::data_model::{event::metric::context::Context, tags::Tag}; + + use super::*; + + #[test] + fn wildcard_mapping_rewrites_name_and_extracts_tags() { + let profiles = vec![DogStatsDMapperProfile { + name: "test".to_string(), + prefix: "test.".to_string(), + mappings: vec![DogStatsDMetricMapping { + metric_match: "test.job.*.duration".to_string(), + match_type: "wildcard".to_string(), + name: "test.job.duration".to_string(), + tags: HashMap::from([("job".to_string(), "$1".to_string())]), + }], + }]; + + let kernel = MapperKernel::compile(&profiles).expect("valid profile"); + let mut metric = Metric::gauge( + Context::from_static_parts("test.job.ingest.duration", &["env:prod"]), + 1.0, + ); + + assert!(kernel.apply(&mut metric)); + assert_eq!(metric.context().name(), "test.job.duration"); + assert!(metric.context().tags().has_tag(Tag::from("job:ingest"))); + assert!(metric.context().tags().has_tag(Tag::from("env:prod"))); + } + + #[test] + fn rejects_invalid_wildcard_pattern() { + let profiles = vec![DogStatsDMapperProfile { + name: "bad".to_string(), + prefix: "test.".to_string(), + mappings: vec![DogStatsDMetricMapping { + metric_match: "test.**".to_string(), + match_type: "wildcard".to_string(), + name: "test.out".to_string(), + tags: HashMap::new(), + }], + }]; + + assert!(MapperKernel::compile(&profiles).is_err()); + } +} diff --git a/bin/agent-data-plane/src/components/metric_name.rs b/lib/saluki-transform-kernels/src/metric_name.rs similarity index 51% rename from bin/agent-data-plane/src/components/metric_name.rs rename to lib/saluki-transform-kernels/src/metric_name.rs index 1f029739c1c..a4fa846f726 100644 --- a/bin/agent-data-plane/src/components/metric_name.rs +++ b/lib/saluki-transform-kernels/src/metric_name.rs @@ -1,54 +1,48 @@ -//! Metric-name normalization, in the name space the Datadog metrics intake stores names in. +//! Metric-name normalization in the intake storage namespace. //! -//! Metric names are submitted verbatim, but the intake rewrites them on ingest. Any decision made here that has to -//! agree with what the intake stores -- matching a metric filterlist, for example -- must therefore compare normalized -//! names rather than the raw names seen on the wire. +//! Metric names arrive verbatim, while the metrics intake rewrites them on ingest. Decisions that must agree with +//! stored names, such as metric filterlist matching, compare normalized names instead of raw wire names. //! -//! Normalization never allocates. [`is_normalized`] is a single pass that lets callers skip the rewrite entirely for -//! the overwhelmingly common case of an already-normalized name, and [`normalize_into`] rewrites into a caller-provided -//! [`NameBuf`], which is small enough to live on the stack. +//! Normalization never allocates. [`is_normalized`] is a single pass that skips rewriting when a name is already +//! normalized, and [`normalize_into`] rewrites into a caller-provided stack [`NameBuf`]. -/// Maximum allowed length of a metric name, in bytes. Names longer than this are rejected outright by the intake: they -/// are not truncated. -pub(super) const MAX_LENGTH: usize = 350; +/// Maximum allowed length of a metric name, in bytes. +/// +/// The intake rejects longer names instead of truncating them. +pub const MAX_LENGTH: usize = 350; /// Fixed-capacity scratch buffer for a normalized metric name. /// -/// A normalized name is never longer than the name it came from, and a name longer than [`MAX_LENGTH`] is rejected -/// outright, so this capacity is always enough. That is what lets [`normalize_into`] rewrite a name without allocating. -pub(super) struct NameBuf { +/// A normalized name is never longer than its input, and inputs longer than [`MAX_LENGTH`] are rejected before +/// writing, so this buffer always has enough capacity. +pub struct NameBuf { buf: [u8; MAX_LENGTH], len: usize, } +impl Default for NameBuf { + fn default() -> Self { + Self::new() + } +} + impl NameBuf { /// Creates an empty buffer. - pub(super) fn new() -> Self { + pub fn new() -> Self { Self { buf: [0; MAX_LENGTH], len: 0, } } - /// Returns the buffer contents. - /// - /// This is a byte slice rather than a `&str` so that no UTF-8 validation pass is needed. The contents are always - /// valid UTF-8, since only ASCII bytes are ever written, but callers only ever compare them. fn as_bytes(&self) -> &[u8] { &self.buf[..self.len] } - /// Returns the last byte in the buffer, or `None` when the buffer is empty. fn last(&self) -> Option { (self.len > 0).then(|| self.buf[self.len - 1]) } - /// Appends `b` to the buffer. - /// - /// # Panics - /// - /// Panics if the buffer is full. Callers in this module cannot trigger that: `normalize_into` pushes at most one - /// byte per input byte, and it rejects inputs longer than [`MAX_LENGTH`] before pushing anything. fn push(&mut self, b: u8) { debug_assert!(b.is_ascii(), "normalized metric names only contain ASCII bytes"); @@ -56,50 +50,31 @@ impl NameBuf { self.len += 1; } - /// Replaces the last byte in the buffer with `b`. - /// - /// # Panics - /// - /// Panics if the buffer is empty. fn overwrite_last(&mut self, b: u8) { debug_assert!(b.is_ascii(), "normalized metric names only contain ASCII bytes"); self.buf[self.len - 1] = b; } - /// Removes the last byte from the buffer. - /// - /// # Panics - /// - /// Panics if the buffer is empty. fn truncate_last(&mut self) { assert!(self.len > 0, "cannot truncate an empty buffer"); self.len -= 1; } - /// Empties the buffer. fn clear(&mut self) { self.len = 0; } } -/// Returns whether `b` is an ASCII letter. -/// -/// The intake works on bytes, not characters, so non-ASCII letters are deliberately not accepted here. fn is_alpha(b: u8) -> bool { b.is_ascii_alphabetic() } -/// Returns whether `b` is an ASCII letter or digit. fn is_alphanumeric(b: u8) -> bool { b.is_ascii_alphanumeric() } -/// Returns the index of the first ASCII letter in `name`. -/// -/// Returns `None` when `name` is empty, longer than [`MAX_LENGTH`] bytes, or contains no ASCII letter. The intake drops -/// such names outright. fn first_alpha(name: &str) -> Option { if name.is_empty() || name.len() > MAX_LENGTH { return None; @@ -108,33 +83,26 @@ fn first_alpha(name: &str) -> Option { name.as_bytes().iter().position(|&b| is_alpha(b)) } -/// Returns whether `name` is a name the intake would store unchanged, meaning normalizing it would be the identity. +/// Returns whether `name` is already in normalized form. /// -/// This is a single pass and never allocates, which is what lets filterlist matching skip the rewrite entirely for the -/// overwhelmingly common case of an already-normalized name. -/// -/// The predicate is exact: `is_normalized(s)` is true if and only if normalizing `s` yields `s` unchanged. The tests in -/// this module pin that equivalence. -pub(super) fn is_normalized(name: &str) -> bool { +/// This is a single non-allocating pass. It returns `true` if and only if [`normalize_into`] produces `name` +/// unchanged. +pub fn is_normalized(name: &str) -> bool { if name.is_empty() || name.len() > MAX_LENGTH { return false; } let bytes = name.as_bytes(); - // A normalized name always starts with an ASCII letter, because everything before the first one is stripped. + // A normalized name always starts with an ASCII letter because leading non-letters are stripped. if !is_alpha(bytes[0]) { return false; } for i in 1..bytes.len() { match bytes[i] { - // Kept verbatim. Note that runs of periods, and a trailing period, are both legal in a normalized name. b if is_alphanumeric(b) => {} b'.' => {} - - // An underscore is only ever emitted between two alphanumerics: it is not emitted after a period or another - // underscore, a following period overwrites it, and a trailing one is stripped. b'_' => { if !is_alphanumeric(bytes[i - 1]) { return false; @@ -144,7 +112,6 @@ pub(super) fn is_normalized(name: &str) -> bool { return false; } } - _ => return false, } } @@ -152,54 +119,37 @@ pub(super) fn is_normalized(name: &str) -> bool { true } -/// Writes `name` into `buf` as the Datadog intake stores it, and returns the normalized name as ASCII bytes. -/// -/// Returns `None` when the intake would reject the name outright rather than rewrite it, which happens when the name is -/// empty, longer than [`MAX_LENGTH`] bytes, or contains no ASCII letter. Callers should treat such a name as one the -/// intake never stores. -/// -/// The rules, applied byte-wise: +/// Writes `name` into `buf` in normalized form and returns the resulting ASCII bytes. /// -/// 1. Everything before the first ASCII letter is discarded. -/// 2. ASCII alphanumerics are kept verbatim; case is preserved. -/// 3. A period is kept, but a period following an underscore replaces it. -/// 4. Every other byte becomes an underscore, and an underscore is not emitted directly after a period or another -/// underscore. Note that this applies to literal underscores in the input too, so `a._b` becomes `a.b`. -/// 5. A trailing underscore is stripped. +/// Returns `None` when `name` is empty, longer than [`MAX_LENGTH`] bytes, or contains no ASCII letter. /// -/// Because step 4 works on bytes, each byte of a multi-byte UTF-8 sequence is treated separately and the sequence -/// collapses to a single underscore. +/// The rules apply byte-wise: /// -/// Normalizing is idempotent: the output always satisfies [`is_normalized`]. -/// -/// # Design -/// -/// This writes into a caller-provided buffer rather than returning an owned string so that no caller is forced to pay -/// for the rewrite allocation. `buf` is reset first, so a single buffer can be reused across calls. -pub(super) fn normalize_into<'buf>(buf: &'buf mut NameBuf, name: &str) -> Option<&'buf [u8]> { +/// 1. Discard everything before the first ASCII letter. +/// 2. Keep ASCII alphanumerics verbatim, preserving case. +/// 3. Keep periods; a period following an underscore replaces that underscore. +/// 4. Convert every other byte into an underscore, skipping underscores directly after a period or another underscore. +/// 5. Strip a trailing underscore. +pub fn normalize_into<'buf>(buf: &'buf mut NameBuf, name: &str) -> Option<&'buf [u8]> { let start = first_alpha(name)?; buf.clear(); - // The first byte written is `name[start]`, an ASCII letter, so the buffer is never empty in later iterations. for &b in &name.as_bytes()[start..] { if is_alphanumeric(b) { buf.push(b); } else if b == b'.' { match buf.last() { - // Overwrite an underscore that comes directly before a period. Some(b'_') => buf.overwrite_last(b'.'), _ => buf.push(b'.'), } } else { match buf.last() { - // No double underscores, and no underscore directly after a period. Some(b'.') | Some(b'_') => {} _ => buf.push(b'_'), } } } - // Strip a trailing underscore. The buffer holds at least the leading letter, so it cannot become empty. if buf.last() == Some(b'_') { buf.truncate_last(); } @@ -207,16 +157,12 @@ pub(super) fn normalize_into<'buf>(buf: &'buf mut NameBuf, name: &str) -> Option Some(buf.as_bytes()) } -/// Writes `prefix` as the intake stores the start of matching names. -/// -/// A metric-name prefix is not a complete metric name: the last byte is a boundary that can be -/// consumed by full-name normalization. Preserving that boundary keeps a prefix from widening into -/// a larger family. For example, `service_` must keep matching only `service_...` names rather than -/// widening to `service...`. +/// Writes `prefix` into `buf` in normalized prefix form, preserving a trailing delimiter boundary. /// -/// Returns `None` when no stored metric name can start with `prefix`, except that the empty prefix -/// is valid and matches every stored metric name. -pub(super) fn normalize_prefix_into<'buf>(buf: &'buf mut NameBuf, prefix: &str) -> Option<&'buf [u8]> { +/// For example, `service_` stays `service_` instead of stripping its trailing underscore and widening to `service`. +/// Returns `None` when no stored metric name can start with `prefix`, except that the empty prefix is valid and +/// matches every stored metric name. +pub fn normalize_prefix_into<'buf>(buf: &'buf mut NameBuf, prefix: &str) -> Option<&'buf [u8]> { if prefix.is_empty() { buf.clear(); return Some(buf.as_bytes()); @@ -224,9 +170,6 @@ pub(super) fn normalize_prefix_into<'buf>(buf: &'buf mut NameBuf, prefix: &str) normalize_into(buf, prefix)?; - // Restore the boundary a full-name normalization would drop. A non-alphanumeric, non-period - // boundary survives as an underscore when an alphanumeric follows it, unless a period already - // absorbed it. let last = prefix.as_bytes()[prefix.len() - 1]; if !is_alphanumeric(last) && last != b'.' && buf.last() != Some(b'.') { buf.push(b'_'); @@ -239,10 +182,6 @@ pub(super) fn normalize_prefix_into<'buf>(buf: &'buf mut NameBuf, prefix: &str) mod tests { use super::*; - /// Normalizes `name`, returning an owned string. - /// - /// Production code normalizes into a [`NameBuf`] instead, so this exists only to keep the assertions below - /// readable. fn normalize(name: &str) -> Option { let mut buf = NameBuf::new(); normalize_into(&mut buf, name) @@ -256,7 +195,6 @@ mod tests { } const NORMALIZED_NAMES: &[(&str, &str)] = &[ - // Bad metric names, which need remapping. ( "test*&(*._-_Metrictastic*(*)( wut_who_doesthis??", "test.Metrictastic_wut_who_doesthis", @@ -267,42 +205,31 @@ mod tests { "dd.crawler.amazon web services.run_time", "dd.crawler.amazon_web_services.run_time", ), - // Multiple metric names that normalize to the same thing. ("multiple-norm-1", "multiple_norm_1"), ("multiple_norm-1", "multiple_norm_1"), - // Invalid characters are dropped rather than doubled up. ("a$.b", "a.b"), ("a_.b", "a.b"), ("__init__.metric", "init.metric"), ("a___..b", "a..b"), ("a_.", "a."), - // An underscore is only ever kept between two alphanumerics, so literal underscores next to a period or to each - // other are dropped. ("a._b", "a.b"), ("a__b", "a_b"), ("a_b", "a_b"), ("a_", "a"), - // Already normalized, so returned untouched. ("foo", "foo"), ("n_o_i_n_d_e_x.pct_aggr.1234", "n_o_i_n_d_e_x.pct_aggr.1234"), - // Case is preserved, unlike tags. ("MyMetric.Count", "MyMetric.Count"), - // Leading non-letters are stripped, not rejected. ("1app.requests", "app.requests"), ("...foo", "foo"), - // Runs of periods, and a trailing period, survive. ("foo...bar", "foo...bar"), ("foo.bar.", "foo.bar."), - // Spaces and punctuation collapse to a single underscore. ("my metric name", "my_metric_name"), ("app-request-count", "app_request_count"), ("host.cpu%util", "host.cpu_util"), - // Non-ASCII is handled byte-wise and collapses away. ("café.requests", "caf.requests"), ("🍣.metric", "metric"), ]; - /// Names the intake rejects outright rather than rewriting. const UNSTORABLE_NAMES: &[&str] = &["", "_", "...", "123", "🍣"]; #[test] @@ -366,35 +293,18 @@ mod tests { #[test] fn names_over_the_length_limit_are_rejected() { - // A name of exactly `MAX_LENGTH` bytes is accepted. let at_limit = "a".repeat(MAX_LENGTH); assert_eq!(normalize(&at_limit).as_deref(), Some(at_limit.as_str())); - // One byte over is rejected, and is not truncated to fit. let over_limit = "a".repeat(MAX_LENGTH + 1); assert_eq!(normalize(&over_limit), None); - // A name that would fit only after normalization is still rejected, because the intake checks the length of the - // raw name. let shrinks = "a-".repeat(MAX_LENGTH); assert_eq!(normalize(&shrinks), None); } - #[test] - fn is_normalized_matches_the_name_tables() { - for (input, expected) in NORMALIZED_NAMES { - assert_eq!(is_normalized(input), input == expected, "input: {:?}", input); - } - - for input in UNSTORABLE_NAMES { - assert!(!is_normalized(input), "input: {:?}", input); - } - } - #[test] fn is_normalized_agrees_with_normalize() { - // These cover the boundary cases the fast path in `Blocklist::contains` relies on: for a name - // `s`, `is_normalized(s)` is true exactly when normalizing `s` returns `s` unchanged. let inputs = [ "", "_", diff --git a/lib/saluki-transform-kernels/src/routing_filter.rs b/lib/saluki-transform-kernels/src/routing_filter.rs new file mode 100644 index 00000000000..b8740201a5f --- /dev/null +++ b/lib/saluki-transform-kernels/src/routing_filter.rs @@ -0,0 +1,228 @@ +//! Metric routing filter predicates for endpoint allowlists, mirroring, and failover branches. + +use std::collections::HashSet; + +use saluki_core::data_model::event::metric::{Metric, MetricValues}; +use serde::{Deserialize, Serialize}; + +use crate::metric_name::{is_normalized, normalize_into, NameBuf}; + +/// Sorts `prefixes` and removes any prefix already covered by a shorter prefix. +pub fn compact_metric_prefixes(prefixes: &mut Vec) { + prefixes.sort_unstable(); + if !prefixes.is_empty() { + let mut retained = 0; + for next in 1..prefixes.len() { + if !prefixes[next].starts_with(&prefixes[retained]) { + retained += 1; + prefixes.swap(retained, next); + } + } + prefixes.truncate(retained + 1); + } +} + +/// Mirroring policy settings for a failover metric branch. +#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] +pub struct MetricMirroring { + /// Whether metrics are mirrored to the failover destination. + pub enabled: bool, + + /// Metric names permitted to be mirrored, matched verbatim. While mirroring is enabled, an empty list mirrors + /// every metric. + pub allowlist: Vec, +} + +/// Compiled metric routing filter predicate. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum MetricAllowlistKernel { + /// Drops every metric. + DropAll, + + /// Forwards every metric unchanged. + AllowAll, + + /// Forwards metrics whose raw name is in `names`. + ExactAllowlist { + /// Raw metric names permitted through. + names: HashSet, + }, + + /// Forwards metrics whose normalized name matches an exact entry or compacted prefix. + NormalizedAllowlist { + /// Exact normalized names permitted through. + names: HashSet>, + /// Sorted, compacted prefixes permitted through. + prefixes: Vec, + }, + + /// Forwards only scalar series metrics (counter, rate, gauge, set) whose raw name is in `names`. + SeriesAllowlist { + /// Raw metric names permitted through. + names: HashSet, + }, +} + +impl MetricAllowlistKernel { + /// Builds a normalized endpoint-routing allowlist kernel from exact names and prefixes. + /// + /// Empty `names` and `prefixes` drop every metric. + pub fn for_allowlist(names: &[String], prefixes: &[String]) -> Self { + let mut compacted_prefixes = prefixes.to_vec(); + compact_metric_prefixes(&mut compacted_prefixes); + Self::NormalizedAllowlist { + names: names.iter().map(|name| name.as_bytes().to_vec()).collect(), + prefixes: compacted_prefixes, + } + } + + /// Builds a mirroring filter kernel. + /// + /// When `enabled` or `mirroring.enabled` is `false`, every metric is dropped. When both are `true` and + /// `mirroring.allowlist` is empty, every metric is forwarded. + pub fn for_mirroring(enabled: bool, mirroring: &MetricMirroring) -> Self { + if !enabled || !mirroring.enabled { + Self::DropAll + } else if mirroring.allowlist.is_empty() { + Self::AllowAll + } else { + Self::ExactAllowlist { + names: mirroring.allowlist.iter().cloned().collect(), + } + } + } + + /// Builds a scalar-series allowlist kernel for autoscaling failover. + /// + /// When `enabled` is `false` or `metrics` is empty, every metric is dropped. + pub fn for_series_allowlist(enabled: bool, metrics: &[String]) -> Self { + if !enabled || metrics.is_empty() { + Self::DropAll + } else { + Self::SeriesAllowlist { + names: metrics.iter().cloned().collect(), + } + } + } + + /// Returns `true` if `metric` should be forwarded. + pub fn should_forward(&self, metric: &Metric) -> bool { + match self { + Self::DropAll => false, + Self::AllowAll => true, + Self::ExactAllowlist { names } => names.contains(metric.context().name()), + Self::NormalizedAllowlist { names, prefixes } => { + let name = metric.context().name(); + if is_normalized(name) { + return matches_normalized_allowlist(name.as_bytes(), names, prefixes); + } + let mut buf = NameBuf::new(); + match normalize_into(&mut buf, name) { + Some(normalized) => matches_normalized_allowlist(normalized, names, prefixes), + None => false, + } + } + Self::SeriesAllowlist { names } => { + if !matches!( + metric.values(), + MetricValues::Counter(..) + | MetricValues::Rate(..) + | MetricValues::Gauge(..) + | MetricValues::Set(..) + ) { + return false; + } + names.contains(metric.context().name()) + } + } + } + + /// Returns `true` when this kernel unconditionally drops every metric. + pub fn drops_all(&self) -> bool { + matches!(self, Self::DropAll) + || matches!( + self, + Self::NormalizedAllowlist { names, prefixes } if names.is_empty() && prefixes.is_empty() + ) + } + + /// Returns `true` when this kernel unconditionally forwards every metric. + pub fn allows_all(&self) -> bool { + matches!(self, Self::AllowAll) + } +} + +fn matches_normalized_allowlist(name: &[u8], names: &HashSet>, prefixes: &[String]) -> bool { + if names.contains(name) { + return true; + } + match prefixes.binary_search_by(|prefix| prefix.as_bytes().cmp(name)) { + Ok(_) => true, + Err(index) => index > 0 && name.starts_with(prefixes[index - 1].as_bytes()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compact_metric_prefixes_removes_covered_entries() { + let mut prefixes = vec![ + "app.db.".to_string(), + "app.".to_string(), + "sys.".to_string(), + "app.".to_string(), + ]; + compact_metric_prefixes(&mut prefixes); + assert_eq!(prefixes, vec!["app.", "sys."]); + } + + #[test] + fn normalized_allowlist_matches_exact_and_prefix() { + let kernel = MetricAllowlistKernel::for_allowlist(&["my_metric".to_string()], &["app.".to_string()]); + assert!(kernel.should_forward(&Metric::gauge("my-metric", 1.0))); + assert!(kernel.should_forward(&Metric::gauge("app.latency", 1.0))); + assert!(!kernel.should_forward(&Metric::gauge("other.metric", 1.0))); + } + + #[test] + fn mirroring_handles_disabled_empty_and_allowlist() { + let disabled = MetricAllowlistKernel::for_mirroring( + true, + &MetricMirroring { + enabled: false, + allowlist: vec![], + }, + ); + assert!(!disabled.should_forward(&Metric::gauge("anything", 1.0))); + + let all = MetricAllowlistKernel::for_mirroring( + true, + &MetricMirroring { + enabled: true, + allowlist: vec![], + }, + ); + assert!(all.should_forward(&Metric::gauge("anything", 1.0))); + + let filtered = MetricAllowlistKernel::for_mirroring( + true, + &MetricMirroring { + enabled: true, + allowlist: vec!["only.this".to_string()], + }, + ); + assert!(filtered.should_forward(&Metric::gauge("only.this", 1.0))); + assert!(!filtered.should_forward(&Metric::gauge("other", 1.0))); + } + + #[test] + fn series_allowlist_drops_sketches_and_histograms() { + let kernel = MetricAllowlistKernel::for_series_allowlist(true, &["cpu.usage".to_string()]); + assert!(kernel.should_forward(&Metric::gauge("cpu.usage", 1.0))); + assert!(kernel.should_forward(&Metric::counter("cpu.usage", 1.0))); + assert!(!kernel.should_forward(&Metric::distribution("cpu.usage", 1.0))); + assert!(!kernel.should_forward(&Metric::histogram("cpu.usage", 1.0))); + } +} diff --git a/lib/saluki-transform-kernels/src/tag_filter.rs b/lib/saluki-transform-kernels/src/tag_filter.rs new file mode 100644 index 00000000000..8a2e62d2e29 --- /dev/null +++ b/lib/saluki-transform-kernels/src/tag_filter.rs @@ -0,0 +1,568 @@ +//! Pure metric tag filterlist and tag value allowlist kernel. +//! +//! Removes, retains, or replaces tags on counter and sketch-backed metrics based on per-metric whole-tag rules and +//! per-prefix tag value allowlists. +//! +//! # Normalization +//! +//! The intake normalizes metric names and tags on ingest, and users write rules against the normalized form they see +//! in Datadog. Rules therefore match normalized names: a whole-tag rule's metric name is compared after metric-name +//! normalization, and the tag keys of both kinds of rule are compared after tag-key normalization (see `SPEC.md` in +//! the `datadog-agent-tag-normalization` crate). Configured strings are normalized once, when the rules are compiled, +//! and incoming names are normalized only for comparison. Tags that are kept are still sent verbatim, and tag values +//! are still matched exactly. + +use std::collections::hash_map::Entry; + +use datadog_agent_tag_normalization::{can_have_value, rule_key, tag_key, TagBuf}; +use saluki_common::collections::{FastHashMap, FastHashSet}; +use saluki_core::data_model::{ + event::metric::{context::TagSetMutViewState, Metric, MetricValues}, + tags::{BorrowedTag, Tag}, +}; +use serde::{Deserialize, Serialize}; +use tracing::warn; + +use crate::metric_name::{self, NameBuf}; + +/// One whole-tag filter entry. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct MetricTagFilterEntry { + /// Metric name the entry applies to, compared after metric-name normalization. An entry with an empty name is + /// ignored. + pub metric_name: String, + + /// Whether the listed tags are kept or removed. + pub action: FilterAction, + + /// Tag keys the action applies to, compared after tag-key normalization. + pub tags: Vec, +} + +/// Whether a whole-tag filter entry keeps or removes its tags. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum FilterAction { + /// Keep only the listed tags. + Include, + + /// Remove the listed tags. + Exclude, +} + +/// One tag value allowlist entry. +/// +/// The tag name is compared after tag-key normalization. Value matching is exact and case-sensitive, including any +/// whitespace. +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub struct MetricTagValueAllowlistEntry { + /// Metric-name prefix the entry applies to. + pub metric_prefix: String, + + /// Tag key whose values are constrained, compared after tag-key normalization. Bare tags have no value and are + /// unchanged. + pub tag_name: String, + + /// Tag values retained unchanged. An empty list treats every key/value tag as a mismatch. + pub values: Vec, + + /// Action applied when a tag value is absent from `values`. + pub on_miss: TagValueMismatchAction, + + /// Replacement value used when `on_miss` is [`TagValueMismatchAction::Replace`], emitted as configured after the + /// normalized tag name. + pub replacement: String, +} + +/// Action applied when a tag value is absent from its allowlist. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum TagValueMismatchAction { + /// Removes the tag. + Remove, + + /// Replaces the tag value with the entry's replacement. + Replace, +} + +#[derive(Clone, Eq, PartialEq)] +enum CompiledMismatchAction { + Remove, + Replace(Tag), +} + +#[derive(Clone)] +struct CompiledTagValueAllowlist { + allowed_values: FastHashSet, + on_miss: CompiledMismatchAction, +} + +#[derive(Clone)] +struct CompiledKeyFilter { + is_exclude: bool, + tag_names: FastHashSet, +} + +#[derive(Clone)] +struct CompiledValuePrefixFilter { + metric_prefix: String, + value_allowlists: FastHashMap, +} + +/// Compiled per-prefix tag value allowlist table, reusable across whole-tag filter reloads. +#[derive(Clone, Default)] +pub struct CompiledValuePrefixFilters(Vec); + +impl CompiledValuePrefixFilters { + /// Compiles static value allowlist entries once for reuse across whole-tag updates. + pub fn compile(entries: &[MetricTagValueAllowlistEntry]) -> Self { + let mut filters = CompiledFilters::default(); + add_value_allowlists(&mut filters, entries); + filters.value_prefix_filters + } + + fn sort(&mut self) { + self.0.sort_by(|a, b| a.metric_prefix.cmp(&b.metric_prefix)); + } + + fn get(&self, metric_name: &str) -> Option<&CompiledValuePrefixFilter> { + let idx = self + .0 + .partition_point(|filter| filter.metric_prefix.as_str() <= metric_name); + let candidate = idx.checked_sub(1).and_then(|i| self.0.get(i))?; + metric_name + .starts_with(candidate.metric_prefix.as_str()) + .then_some(candidate) + } + + /// Returns the total number of compiled tag value allowlist rules. + pub fn rule_count(&self) -> usize { + self.0.iter().map(|filter| filter.value_allowlists.len()).sum() + } +} + +/// Compiled metric tag filter table holding both whole-tag rules and per-prefix value allowlists. +#[derive(Clone, Default)] +pub struct CompiledFilters { + key_filters: FastHashMap, + value_prefix_filters: CompiledValuePrefixFilters, +} + +impl CompiledFilters { + /// Returns the total number of configured rules (whole-tag metric rules plus value allowlist rules). + pub fn rule_count(&self) -> usize { + self.key_filters.len() + self.value_prefix_filters.rule_count() + } + + /// Returns `true` when no rules are configured. + pub fn is_empty(&self) -> bool { + self.rule_count() == 0 + } + + /// Returns the number of compiled whole-tag metric rules. + pub fn key_filter_count(&self) -> usize { + self.key_filters.len() + } + + /// Returns `true` when a whole-tag filter rule is registered for `metric_name`. + pub fn has_key_filter(&self, metric_name: &str) -> bool { + self.key_filters.contains_key(metric_name) + } + + /// Returns `(is_exclude, tag_names)` for a compiled whole-tag filter rule by its normalized metric name. + pub fn key_filter_entry(&self, metric_name: &str) -> Option<(bool, &FastHashSet)> { + self.key_filters + .get(metric_name) + .map(|filter| (filter.is_exclude, &filter.tag_names)) + } + + /// Returns the compiled value-prefix filters for reuse across whole-tag updates. + pub fn value_prefix_filters(&self) -> &CompiledValuePrefixFilters { + &self.value_prefix_filters + } + + /// Returns the whole-tag rule for `metric_name`, compared in the form Datadog stores metric names in. + fn key_filter(&self, metric_name: &str) -> Option<&CompiledKeyFilter> { + if self.key_filters.is_empty() { + return None; + } + if metric_name::is_normalized(metric_name) { + return self.key_filters.get(metric_name); + } + + let mut buf = NameBuf::new(); + self.key_filters.get(normalize_metric_name(&mut buf, metric_name)?) + } +} + +/// Normalizes `name` into `buf`, returning `None` if the intake never stores it. See [`metric_name::normalize_into`]. +fn normalize_metric_name<'buf>(buf: &'buf mut NameBuf, name: &str) -> Option<&'buf str> { + let normalized = metric_name::normalize_into(buf, name)?; + Some(simdutf8::basic::from_utf8(normalized).expect("normalized metric names are ASCII")) +} + +/// Outcome of attempting to apply tag filter rules to a metric. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum FilterMetricTagsOutcome { + /// No rule existed for the metric name. + RuleMiss, + /// A rule existed, but applying it did not change any tags. + NoChange, + /// A rule existed and modified one or more tags. + Modified { + /// Total number of instrumented and origin tags removed or replaced. + removed_tags: usize, + }, +} + +/// Returns whether `metric` is eligible for tag filtering (counters and sketch-backed metrics). +#[inline] +pub fn is_tag_filter_eligible(metric: &Metric) -> bool { + metric.values().is_sketch() || matches!(metric.values(), MetricValues::Counter(_)) +} + +/// Compiles whole-tag filter entries into an O(1) lookup table. +/// +/// Metric names and tag keys are normalized first. An entry whose metric name the intake never stores, and a tag key +/// no stored tag can have, can't match anything, so each is dropped with a warning. +/// +/// Merge rules, applied to entries whose normalized metric names are equal: +/// - Same metric name + same action -> union of tag key sets. +/// - Same metric name + conflicting actions -> `Exclude` wins, with a warning. +pub fn compile_filters(entries: &[MetricTagFilterEntry]) -> CompiledFilters { + let mut filters = CompiledFilters::default(); + let mut name_buf = NameBuf::new(); + // For each normalized metric name, the first configured name and whether any entry listed tags. Only used for + // warnings. + let mut sources: FastHashMap = FastHashMap::default(); + + for entry in entries { + if entry.metric_name.is_empty() { + continue; + } + + let Some(metric_name) = normalize_metric_name(&mut name_buf, &entry.metric_name) else { + warn!( + setting = "metric_tag_filterlist", + metric_name = %entry.metric_name, + "Dropping entry because Datadog never stores its metric name." + ); + continue; + }; + let metric_name = metric_name.to_string(); + + let is_exclude = entry.action == FilterAction::Exclude; + let mut tag_set = FastHashSet::default(); + tag_set.reserve(entry.tags.len()); + for tag in &entry.tags { + match rule_key(tag) { + Some(key) => { + tag_set.insert(key); + } + None => warn!( + setting = "metric_tag_filterlist", + metric_name = %entry.metric_name, + tag = %tag, + "Ignoring tag key containing ':'. List the tag key only, without a value." + ), + } + } + + let source = sources + .entry(metric_name.clone()) + .or_insert_with(|| (entry.metric_name.clone(), false)); + source.1 |= !entry.tags.is_empty(); + + match filters.key_filters.entry(metric_name) { + Entry::Vacant(vacant) => { + vacant.insert(CompiledKeyFilter { + is_exclude, + tag_names: tag_set, + }); + } + Entry::Occupied(mut occupied) => { + if occupied.get().is_exclude == is_exclude { + occupied.get_mut().tag_names.extend(tag_set); + continue; + } + warn!( + setting = "metric_tag_filterlist", + metric_name = %occupied.key(), + first_entry = %source.0, + conflicting_entry = %entry.metric_name, + "Entries for the same metric configure both include and exclude. Keeping only the exclude entries." + ); + if is_exclude { + *occupied.get_mut() = CompiledKeyFilter { + is_exclude, + tag_names: tag_set, + }; + } + } + } + } + + for (metric_name, filter) in &filters.key_filters { + if !filter.is_exclude && filter.tag_names.is_empty() && sources[metric_name].1 { + warn!( + setting = "metric_tag_filterlist", + metric_name = %sources[metric_name].0, + "Include rule has no usable tag keys left, so it removes every tag." + ); + } + } + + filters +} + +/// Adds value allowlist entries to a compiled filter table. +/// +/// Rules are keyed by the normalized form of their tag names. The configuration boundary validates the configured +/// strings, so each metric matches at most one prefix. A rule whose tag name no stored tag with a value can have, or +/// whose tag name normalizes to the same key as an earlier rule for the same prefix, is dropped with a warning, as +/// `metric_tag_filterlist` does with entries that can't match. +/// +/// Unlike whole-tag rule names, metric prefixes are not normalized: they are compared exactly with the metric name as +/// ADP sees it. This keeps prefix matching and its overlap validation simple for this experimental setting. +pub fn add_value_allowlists(filters: &mut CompiledFilters, entries: &[MetricTagValueAllowlistEntry]) { + for entry in entries { + let tag_key = rule_key(&entry.tag_name) + .expect("the configuration boundary rejects value allow-list tag names containing ':'"); + if !can_have_value(&tag_key) { + warn!( + setting = "metric_tag_value_allowlist", + metric_prefix = %entry.metric_prefix, + tag_name = %entry.tag_name, + "Ignoring rule because its tag name is too long for Datadog to store a tag with that name and a value." + ); + continue; + } + + let on_miss = match entry.on_miss { + TagValueMismatchAction::Remove => CompiledMismatchAction::Remove, + TagValueMismatchAction::Replace => { + CompiledMismatchAction::Replace(Tag::from(format!("{}:{}", tag_key, entry.replacement))) + } + }; + + let mut allowed_values = FastHashSet::default(); + allowed_values.reserve(entry.values.len()); + allowed_values.extend(entry.values.iter().cloned()); + + let allowlist = CompiledTagValueAllowlist { + allowed_values, + on_miss, + }; + + if let Some(filter) = filters + .value_prefix_filters + .0 + .iter_mut() + .find(|filter| filter.metric_prefix == entry.metric_prefix) + { + match filter.value_allowlists.entry(tag_key) { + Entry::Vacant(vacant) => { + vacant.insert(allowlist); + } + Entry::Occupied(occupied) => warn!( + setting = "metric_tag_value_allowlist", + metric_prefix = %entry.metric_prefix, + tag_name = %entry.tag_name, + normalized_tag_name = %occupied.key(), + "Ignoring rule because its tag name normalizes to the same tag key as an earlier rule for this \ + prefix." + ), + } + } else { + let mut value_allowlists = FastHashMap::default(); + value_allowlists.insert(tag_key, allowlist); + filters.value_prefix_filters.0.push(CompiledValuePrefixFilter { + metric_prefix: entry.metric_prefix.clone(), + value_allowlists, + }); + } + } + + filters.value_prefix_filters.sort(); +} + +/// Compiles whole-tag entries and attaches compiled value allowlist filters. +pub fn compile_filters_with_values( + entries: &[MetricTagFilterEntry], value_prefix_filters: CompiledValuePrefixFilters, +) -> CompiledFilters { + let mut filters = compile_filters(entries); + filters.value_prefix_filters = value_prefix_filters; + filters +} + +/// Compiles both whole-tag entries and value allowlist entries in one call. +pub fn compile_all_filters( + entries: &[MetricTagFilterEntry], value_allowlists: &[MetricTagValueAllowlistEntry], +) -> CompiledFilters { + let mut filters = compile_filters(entries); + add_value_allowlists(&mut filters, value_allowlists); + filters +} + +#[inline] +fn filter_tag( + tag: &str, key_filter: Option<&CompiledKeyFilter>, value_filter: Option<&CompiledValuePrefixFilter>, + key_buf: &mut TagBuf, replacements: &mut Vec, +) -> bool { + let key = tag_key(tag, key_buf); + + if let Some(key_filter) = key_filter { + if key_filter.is_exclude == key_filter.tag_names.contains(key.key) { + return false; + } + } + + // A raw tag whose `:` falls past the intake's length limit is stored as a bare tag, so it has no value here either. + if !key.has_value { + return true; + } + let Some(allowlist) = value_filter.and_then(|filter| filter.value_allowlists.get(key.key)) else { + return true; + }; + + let Some(value) = BorrowedTag::from(tag).value() else { + return true; + }; + if allowlist.allowed_values.contains(value) { + return true; + } + + match &allowlist.on_miss { + CompiledMismatchAction::Remove => false, + CompiledMismatchAction::Replace(replacement) if replacement.as_str() == tag => true, + CompiledMismatchAction::Replace(replacement) => { + replacements.push(replacement.clone()); + false + } + } +} + +/// Filters the tags of `metric` according to `filters`. +/// +/// Callers apply this function only to counters and sketch-backed metrics (see [`is_tag_filter_eligible`]). +/// If no rule applies or no tags change, the metric context is left untouched without allocating. +#[inline] +pub fn filter_metric_tags( + metric: &mut Metric, state: &mut TagSetMutViewState, filters: &CompiledFilters, +) -> FilterMetricTagsOutcome { + let metric_name = metric.context().name(); + let key_filter = filters.key_filter(metric_name); + let value_filter = filters.value_prefix_filters.get(metric_name); + if key_filter.is_none() && value_filter.is_none() { + return FilterMetricTagsOutcome::RuleMiss; + } + + let mut key_buf = TagBuf::new(); + let mut tag_replacements = Vec::new(); + let mut origin_tag_replacements = Vec::new(); + let mut tag_set_view = metric.context_mut().tags_mut_view(state); + tag_set_view.retain_tags(|tag| filter_tag(tag, key_filter, value_filter, &mut key_buf, &mut tag_replacements)); + tag_set_view.retain_origin_tags(|tag| { + filter_tag( + tag, + key_filter, + value_filter, + &mut key_buf, + &mut origin_tag_replacements, + ) + }); + let total_removed = tag_set_view.finish(); + + if !tag_replacements.is_empty() || !origin_tag_replacements.is_empty() { + metric.context_mut().with_tag_sets_mut(|tags, origin_tags| { + for replacement in tag_replacements { + tags.insert_tag(replacement); + } + for replacement in origin_tag_replacements { + origin_tags.insert_tag(replacement); + } + }); + } + + if total_removed == 0 { + FilterMetricTagsOutcome::NoChange + } else { + FilterMetricTagsOutcome::Modified { + removed_tags: total_removed, + } + } +} + +/// Pure synchronous kernel holding compiled tag filter rules and scratch view state. +#[derive(Default)] +pub struct TagFilterKernel { + filters: CompiledFilters, + view_state: TagSetMutViewState, +} + +impl TagFilterKernel { + /// Creates a new `TagFilterKernel` from whole-tag entries and value allowlist entries. + pub fn new(entries: &[MetricTagFilterEntry], value_allowlists: &[MetricTagValueAllowlistEntry]) -> Self { + Self { + filters: compile_all_filters(entries, value_allowlists), + view_state: TagSetMutViewState::default(), + } + } + + /// Returns `true` when no rules are configured. + pub fn is_noop(&self) -> bool { + self.filters.is_empty() + } + + /// Applies the compiled tag filter rules to `metric` if its type is eligible. + pub fn apply(&mut self, metric: &mut Metric) -> FilterMetricTagsOutcome { + if !is_tag_filter_eligible(metric) { + return FilterMetricTagsOutcome::RuleMiss; + } + + filter_metric_tags(metric, &mut self.view_state, &self.filters) + } +} + +#[cfg(test)] +mod tests { + use saluki_core::data_model::event::metric::context::Context; + + use super::*; + + #[test] + fn excludes_and_replaces_tags_on_counters_and_sketches_only() { + let entries = vec![MetricTagFilterEntry { + metric_name: "req.count".to_string(), + action: FilterAction::Exclude, + tags: vec!["drop_me".to_string()], + }]; + let value_allowlists = vec![MetricTagValueAllowlistEntry { + metric_prefix: "req.".to_string(), + tag_name: "status".to_string(), + values: vec!["200".to_string()], + on_miss: TagValueMismatchAction::Replace, + replacement: "other".to_string(), + }]; + + let mut kernel = TagFilterKernel::new(&entries, &value_allowlists); + + let mut counter = Metric::counter( + Context::from_static_parts("req.count", &["drop_me:1", "status:500", "env:prod"]), + 1.0, + ); + assert_eq!( + kernel.apply(&mut counter), + FilterMetricTagsOutcome::Modified { removed_tags: 2 } + ); + assert!(!counter.context().tags().has_tag(Tag::from("drop_me:1"))); + assert!(counter.context().tags().has_tag(Tag::from("status:other"))); + assert!(counter.context().tags().has_tag(Tag::from("env:prod"))); + + // Gauges are not eligible and remain untouched. + let mut gauge = Metric::gauge( + Context::from_static_parts("req.count", &["drop_me:1", "status:500"]), + 1.0, + ); + assert_eq!(kernel.apply(&mut gauge), FilterMetricTagsOutcome::RuleMiss); + assert!(gauge.context().tags().has_tag(Tag::from("drop_me:1"))); + } +} diff --git a/lib/saluki-transform-kernels/src/timestamp_split.rs b/lib/saluki-transform-kernels/src/timestamp_split.rs new file mode 100644 index 00000000000..339fca88787 --- /dev/null +++ b/lib/saluki-transform-kernels/src/timestamp_split.rs @@ -0,0 +1,125 @@ +//! Splitting metrics into timestamped passthrough and non-timestamped aggregation streams. + +use std::time::Duration; + +use saluki_core::data_model::event::metric::{Metric, MetricValues}; + +/// Fixed interval used to normalize timestamped counters into rates on the no-aggregation path. +pub const PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL: Duration = Duration::from_secs(10); + +/// Result of splitting a metric into timestamped passthrough and non-timestamped aggregate portions. +#[derive(Debug, PartialEq)] +pub struct TimestampSplitOutcome { + /// Timestamped portion converted for passthrough, if present and supported. + pub passthrough: Option, + + /// Non-timestamped portion destined for aggregation, if present. + pub aggregate: Option, + + /// Dropped timestamped portion when its value type cannot pass through without aggregation. + pub dropped_unsupported: Option, +} + +/// Splits `metric` into `(timestamped, non_timestamped)` without changing value types. +pub fn try_split_timestamped_values(mut metric: Metric) -> (Option, Option) { + if metric.values().all_timestamped() { + (Some(metric), None) + } else if metric.values().any_timestamped() { + let new_metric_values = metric.values_mut().split_timestamped(); + let new_metric = Metric::from_parts(metric.context().clone(), new_metric_values, metric.metadata().clone()); + + (Some(new_metric), Some(metric)) + } else { + (None, Some(metric)) + } +} + +/// Returns `true` if `values` can pass through the no-aggregation pipeline without aggregation. +/// +/// Only counters, rates, and gauges are supported; histograms, distributions, and sets require aggregation. +pub fn is_supported_passthrough_type(values: &MetricValues) -> bool { + matches!( + values, + MetricValues::Counter(_) | MetricValues::Rate(..) | MetricValues::Gauge(_) + ) +} + +/// Converts a counter into a rate using [`PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL`]. +/// +/// Non-counter values are returned unchanged. +pub fn counter_values_to_rate(values: MetricValues) -> MetricValues { + match values { + MetricValues::Counter(points) => MetricValues::rate(points, PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL), + values => values, + } +} + +/// Splits `metric` by timestamp state, validates supported passthrough types, and normalizes passthrough counters. +pub fn split_for_no_aggregation(metric: Metric) -> TimestampSplitOutcome { + let (timestamped, aggregate) = try_split_timestamped_values(metric); + let (passthrough, dropped_unsupported) = match timestamped { + Some(ts_metric) if is_supported_passthrough_type(ts_metric.values()) => { + let (context, values, metadata) = ts_metric.into_parts(); + let adjusted = counter_values_to_rate(values); + (Some(Metric::from_parts(context, adjusted, metadata)), None) + } + Some(unsupported) => (None, Some(unsupported)), + None => (None, None), + }; + + TimestampSplitOutcome { + passthrough, + aggregate, + dropped_unsupported, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn non_timestamped_metric_routes_to_aggregate() { + let metric = Metric::counter("requests", 5.0); + let outcome = split_for_no_aggregation(metric.clone()); + + assert_eq!(outcome.passthrough, None); + assert_eq!(outcome.aggregate, Some(metric)); + assert_eq!(outcome.dropped_unsupported, None); + } + + #[test] + fn timestamped_counter_routes_to_passthrough_as_rate() { + let metric = Metric::counter("requests", (1000, 5.0)); + let outcome = split_for_no_aggregation(metric); + + assert_eq!(outcome.aggregate, None); + assert_eq!(outcome.dropped_unsupported, None); + let passthrough = outcome.passthrough.expect("should route to passthrough"); + assert!(matches!( + passthrough.values(), + MetricValues::Rate(_, interval) if *interval == PASSTHROUGH_COUNTER_NORMALIZATION_INTERVAL + )); + } + + #[test] + fn timestamped_distribution_is_dropped_as_unsupported() { + let metric = Metric::distribution("latency", (1000, 1.5)); + let outcome = split_for_no_aggregation(metric); + + assert_eq!(outcome.passthrough, None); + assert_eq!(outcome.aggregate, None); + assert!(outcome.dropped_unsupported.is_some()); + } + + #[test] + fn mixed_metric_splits_both_ways() { + let mut metric = Metric::gauge("cpu", 10.0); + metric.values_mut().merge(MetricValues::gauge((2000, 20.0))); + + let outcome = split_for_no_aggregation(metric); + assert!(outcome.passthrough.is_some()); + assert!(outcome.aggregate.is_some()); + assert!(outcome.dropped_unsupported.is_none()); + } +}