From 03c28411fa2fab4d645ac293c589955268fe3682 Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 03:48:32 +0000 Subject: [PATCH 1/2] enhancement(metrics-v3): map packed tag symbols directly to payload IDs Even with arena dictionaries, the V3 writer hashes every tag string to find its payload ID. On the 50-tag workload, each metric carries 50 tags, so the writer hashes 50 strings per metric on every flush. Packed contexts already hold a `SymbolTable` ID for each recurring tag. This change maps packed symbol IDs directly to V3 tag IDs through a small cache. The writer holds a reference on each mapped symbol, so a reclaimed ID cannot alias a different tag. Tags without a usable symbol still intern by text. Stripped `optimized-release` Tier 1 runs on 50-tag show cgroup CPU falling 6.32% and peak memory falling 6.9 MiB. - [ ] Bug fix - [ ] New feature - [ ] Non-functional - [x] Performance - `cargo check --locked --workspace --tests` - `cargo test --locked -p datadog-agent-metrics-v3 --lib pinned_tags_share_dictionary_ids_without_aliasing_recycled_symbol_hints` - Tier 1 runs use stripped `optimized-release` builds against base `18f587f5f6` in cgroup v2, in default unbounded mode. - 50-tag holds 1,000,000 gauges that each carry 50 tags drawn from a 100-tag shared pool. - Requires: the V3 arena writer, and packed `Context` symbol IDs. - Required by: none. - Release note: `releasenotes/notes/v3-packed-symbol-ids-53e4988c02026291.yaml` - Context & Tag Density: pack contexts into one allocation and drop unused cache overhead. - Dense Aggregation: replace 177 B buckets with per-kind typed pages. - Resumable Flush: shrink metric buffers and interleave bounded flush chunks. - Idle Pipeline Bypass: skip inactive transforms and borrow client telemetry. - **`300m` CPU:** cut encoder, codec and worker-pool hot-path cost. - PR TBD: reuse V3 dictionary arenas and frame payloads in one pass - **Current:** map packed tag symbols directly to V3 payload IDs - PR TBD: reuse the `zstd` context and gate per-column recompression - PR TBD: parse DogStatsD metrics in one pass and fast-path singleton scalars - PR TBD: classify and deduplicate metric tags on the stack - PR TBD: size the dedicated topology worker pool to available CPUs - Memory Admission: enforce opt-in configured memory limits with idle reclaim and counted drops. --- lib/datadog-agent/metrics-v3/src/interner.rs | 64 +++++++++- lib/datadog-agent/metrics-v3/src/writer.rs | 109 +++++++++++++++++- .../src/encoders/datadog/metrics/mod.rs | 18 ++- ...v3-packed-symbol-ids-53e4988c02026291.yaml | 3 + 4 files changed, 182 insertions(+), 12 deletions(-) create mode 100644 releasenotes/notes/v3-packed-symbol-ids-53e4988c02026291.yaml diff --git a/lib/datadog-agent/metrics-v3/src/interner.rs b/lib/datadog-agent/metrics-v3/src/interner.rs index 39c47e07799..b5272ba1d34 100644 --- a/lib/datadog-agent/metrics-v3/src/interner.rs +++ b/lib/datadog-agent/metrics-v3/src/interner.rs @@ -8,7 +8,11 @@ //! This avoids a second copy of each key but requires the caller to keep indexed ranges intact until reset. //! Reset both the index and arena between payloads to reuse their allocations and start IDs again at 1. -use std::hash::{BuildHasher, Hash}; +use std::{ + any::Any, + hash::{BuildHasher, Hash}, + sync::Arc, +}; use hashbrown::{hash_table::Entry, HashTable}; @@ -110,6 +114,64 @@ impl Interner { } } +const PINNED_SYMBOL_SLOTS: usize = 512; +const PINNED_SYMBOL_PROBES: usize = 4; + +pub(crate) type SymbolOwner = Arc; + +#[derive(Debug)] +struct PinnedSymbol { + hint: SymbolHint, + address: usize, + len: usize, + id: i64, + _owner: SymbolOwner, +} + +#[derive(Debug, Default)] +pub(crate) struct PinnedSymbols { + slots: Vec>, +} + +impl PinnedSymbols { + pub fn intern( + &mut self, hint: SymbolHint, text: &str, intern: impl FnOnce() -> i64, retain: impl FnOnce() -> SymbolOwner, + ) -> i64 { + if self.slots.is_empty() { + self.slots.resize_with(PINNED_SYMBOL_SLOTS, || None); + } + let (_, symbol) = hint; + let mixed = (symbol ^ symbol.rotate_right(15)).wrapping_mul(0x9e37_79b9); + let start = (mixed >> (u32::BITS - PINNED_SYMBOL_SLOTS.ilog2())) as usize; + let address = text.as_ptr().addr(); + let mut destination = start; + for probe in 0..PINNED_SYMBOL_PROBES { + let idx = (start + probe) & (PINNED_SYMBOL_SLOTS - 1); + match &self.slots[idx] { + Some(slot) if slot.hint == hint && slot.address == address && slot.len == text.len() => return slot.id, + Some(_) => {} + None => { + destination = idx; + break; + } + } + } + let id = intern(); + self.slots[destination] = Some(PinnedSymbol { + hint, + address, + len: text.len(), + id, + _owner: retain(), + }); + id + } + + pub fn clear(&mut self) { + self.slots.iter_mut().for_each(|slot| *slot = None); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/lib/datadog-agent/metrics-v3/src/writer.rs b/lib/datadog-agent/metrics-v3/src/writer.rs index 72b97e43d81..e4a2e351577 100644 --- a/lib/datadog-agent/metrics-v3/src/writer.rs +++ b/lib/datadog-agent/metrics-v3/src/writer.rs @@ -23,7 +23,7 @@ use crate::{ TYPES_FIELD_NUMBER, UNIT_REFS_FIELD_NUMBER, VALS_FLOAT32_FIELD_NUMBER, VALS_FLOAT64_FIELD_NUMBER, VALS_SINT64_FIELD_NUMBER, }, - interner::Interner, + interner::{Interner, PinnedSymbols, SymbolOwner}, types::{value_type_for_values, V3MetricType, V3ValueType}, }; @@ -148,6 +148,7 @@ pub struct V3Writer { // Each interner assigns IDs within one dictionary and points into its backing storage by offset. name_interner: Interner, tag_interner: Interner, + tag_symbols: PinnedSymbols, tagset_interner: Interner, resource_str_interner: Interner, resource_interner: Interner, @@ -269,6 +270,7 @@ impl V3Writer { pub fn clear(&mut self) { self.name_interner.clear(); self.tag_interner.clear(); + self.tag_symbols.clear(); self.tagset_interner.clear(); self.resource_str_interner.clear(); self.resource_interner.clear(); @@ -328,8 +330,7 @@ impl V3Writer { let mut tagsets = data.dict_tagsets.as_mut_slice(); while let Some((&mut len, rest)) = tagsets.split_first_mut() { let (ids, remaining) = rest.split_at_mut(len as usize); - ids.sort_unstable(); - delta_encode(ids); + sort_and_delta_tagset(ids); tagsets = remaining; } } @@ -513,7 +514,9 @@ impl V3Writer { self.intern_tag_ids() } - fn intern_unique_tagset<'a>(&mut self, tags: impl Iterator)>) -> i64 { + fn intern_unique_tagset<'a, F: FnMut() -> SymbolOwner>( + &mut self, tags: impl Iterator)>, mut retain_owner: Option, + ) -> i64 { self.tag_ids.clear(); self.tag_epoch = self.tag_epoch.wrapping_add(1); if self.tag_epoch == 0 { @@ -521,7 +524,15 @@ impl V3Writer { self.tag_epoch = 1; } for (tag, hint) in tags { - let id = intern_string_with_hint(&mut self.tag_interner, &mut self.data.dict_tags_bytes, tag, hint); + let interner = &mut self.tag_interner; + let arena = &mut self.data.dict_tags_bytes; + let id = match (hint, retain_owner.as_mut()) { + (Some(hint), Some(retain)) => { + self.tag_symbols + .intern(hint, tag, || intern_string(interner, arena, tag), retain) + } + _ => intern_string_with_hint(interner, arena, tag, hint), + }; let idx = id as usize; if idx >= self.tag_epochs.len() { self.tag_epochs.resize(idx + 1, 0); @@ -616,7 +627,19 @@ impl<'a> V3MetricBuilder<'a> { /// /// Each tag can carry an optional `(table, id)` packed symbol cache hint. pub fn set_unique_tags<'t>(&mut self, tags: impl Iterator)>) { - let tagset_id = self.writer.intern_unique_tagset(tags); + let tagset_id = self.writer.intern_unique_tagset(tags, None:: SymbolOwner>); + self.writer.data.tags[self.metric_idx] = tagset_id; + } + + /// Sets unique tags and maps retained packed symbols directly to V3 tag IDs. + /// + /// The owner returned by `retain_owner` must keep the hinted strings alive and immutable. The callback runs only + /// when a symbol enters the cache. Owners are dropped on cache replacement or writer reset. + pub fn set_unique_tags_with_symbols<'t>( + &mut self, tags: impl Iterator)>, + retain_owner: impl FnMut() -> SymbolOwner, + ) { + let tagset_id = self.writer.intern_unique_tagset(tags, Some(retain_owner)); self.writer.data.tags[self.metric_idx] = tagset_id; } @@ -873,6 +896,32 @@ fn append_len(dst: &mut Vec, mut len: usize) { } } +fn sort_and_delta_tagset(ids: &mut [i64]) { + if ids.len() >= 32 { + let mut bits = 0u128; + for &id in &*ids { + if id as u64 >= u64::from(u128::BITS) { + bits = 0; + break; + } + bits |= 1 << id; + } + // The general setter can contain duplicate IDs; keep them in the normal sorting path. + if bits.count_ones() as usize == ids.len() { + let mut previous = 0; + for id in ids { + let next = i64::from(bits.trailing_zeros()); + *id = next - previous; + previous = next; + bits &= bits.wrapping_sub(1); + } + return; + } + } + ids.sort_unstable(); + delta_encode(ids); +} + // Work backward so each subtraction reads the preceding absolute value before overwriting it. fn delta_encode(s: &mut [i64]) { if s.len() < 2 { @@ -894,6 +943,8 @@ fn delta_encode_i32(s: &mut [i32]) { #[cfg(test)] mod tests { + use std::sync::Arc; + use super::*; #[test] @@ -978,6 +1029,24 @@ mod tests { assert_eq!(data, vec![42]); } + #[test] + fn large_tagsets_encode_sorted_ids_and_preserve_duplicates() { + let unique: Vec<_> = (0..128).rev().step_by(2).collect(); + for extra in [None, Some(127), Some(128)] { + let mut ids = unique.clone(); + ids.extend(extra); + let mut expected = ids.clone(); + expected.sort_unstable(); + sort_and_delta_tagset(&mut ids); + let mut decoded = 0; + for delta in &mut ids { + decoded += *delta; + *delta = decoded; + } + assert_eq!(ids, expected); + } + } + #[test] fn intern_string_prefixes_length() { let mut buf = Vec::new(); @@ -1260,4 +1329,32 @@ mod tests { } assert_eq!(writer.finish().unwrap().payload, fresh.finalize().unwrap().payload); } + + #[test] + fn pinned_tags_share_dictionary_ids_without_aliasing_recycled_symbol_hints() { + let mut writer = V3Writer::new(); + let mut exact = V3Writer::new(); + let first = Arc::new("env:prod".to_owned()); + let second = Arc::new("env:test".to_owned()); + let first_weak = Arc::downgrade(&first); + let hint = Some((1, 42)); + for (tag, retain) in [(&first, true), (&first, false), (&second, true)] { + let mut metric = writer.write(V3MetricType::Gauge, "metric"); + metric.set_unique_tags_with_symbols([(tag.as_str(), hint), (tag.as_str(), None)].into_iter(), || { + assert!(retain, "a repeated symbol must not retain another reference"); + Arc::clone(tag) as SymbolOwner + }); + metric.add_point(1, 1.0); + metric.close(); + + let mut metric = exact.write(V3MetricType::Gauge, "metric"); + metric.set_tags([tag.as_str()].into_iter()); + metric.add_point(1, 1.0); + metric.close(); + } + drop(first); + assert!(first_weak.upgrade().is_some()); + assert_eq!(writer.finish().unwrap().payload, exact.finish().unwrap().payload); + assert!(first_weak.upgrade().is_none()); + } } diff --git a/lib/saluki-components/src/encoders/datadog/metrics/mod.rs b/lib/saluki-components/src/encoders/datadog/metrics/mod.rs index f811ad5cc66..8816a9110c1 100644 --- a/lib/saluki-components/src/encoders/datadog/metrics/mod.rs +++ b/lib/saluki-components/src/encoders/datadog/metrics/mod.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, collections::VecDeque, ops::Range, sync::Arc, time::Duration}; +use std::{any::Any, collections::HashMap, collections::VecDeque, ops::Range, sync::Arc, time::Duration}; use async_trait::async_trait; use ddsketch::DDSketch; @@ -1722,20 +1722,28 @@ fn write_metric_to_v3( let mut builder = writer.write_with_symbol_id(metric_type, name, hint); let mut promoted_tags = SmallVec::<[(&str, bool); 4]>::new(); - let tags = context - .tags() + let context_tags = context.tags(); + let tags = context_tags .tags_with_symbol_ids() .map(|(tag, hint)| (tag, hint, false)) .chain(additional_tags.into_iter().map(|tag| (tag.as_str(), None, false))) .chain(context.origin_tags().into_iter().map(|tag| (tag.as_str(), None, true))); - builder.set_unique_tags(tags.filter_map(|(tag, hint, is_origin)| { + let tags = tags.filter_map(|(tag, hint, is_origin)| { if !is_sketch && (is_v3_series_device_tag(tag) || is_v3_series_resource_tag(tag)) { promoted_tags.push((tag, is_origin)); None } else { Some((tag, hint)) } - })); + }); + if context_tags.len() >= 32 { + let mut symbol_owner: Option> = None; + builder.set_unique_tags_with_symbols(tags, || { + Arc::clone(symbol_owner.get_or_insert_with(|| Arc::new(context.clone()))) + }); + } else { + builder.set_unique_tags(tags); + } let host = context.host().filter(|host| !host.is_empty()); let mut resources = SmallVec::<[(&str, &str); 4]>::new(); diff --git a/releasenotes/notes/v3-packed-symbol-ids-53e4988c02026291.yaml b/releasenotes/notes/v3-packed-symbol-ids-53e4988c02026291.yaml new file mode 100644 index 00000000000..0e67e255b80 --- /dev/null +++ b/releasenotes/notes/v3-packed-symbol-ids-53e4988c02026291.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Reduce V3 metric encoding work for recurring instrumented tags. From 737e4acc2a51c4c9815fb5e14e8c693e6ded1826 Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 23:46:40 +0000 Subject: [PATCH 2/2] docs(metrics-v3): clarify pinned symbol ownership and fast-path thresholds --- lib/datadog-agent/metrics-v3/src/interner.rs | 10 +++++++++- lib/datadog-agent/metrics-v3/src/lib.rs | 1 + lib/datadog-agent/metrics-v3/src/writer.rs | 6 +++++- .../src/encoders/datadog/metrics/mod.rs | 12 ++++++++---- .../src/encoders/datadog/metrics/v3/mod.rs | 2 +- 5 files changed, 24 insertions(+), 7 deletions(-) diff --git a/lib/datadog-agent/metrics-v3/src/interner.rs b/lib/datadog-agent/metrics-v3/src/interner.rs index b5272ba1d34..ed69aaf4a87 100644 --- a/lib/datadog-agent/metrics-v3/src/interner.rs +++ b/lib/datadog-agent/metrics-v3/src/interner.rs @@ -117,7 +117,8 @@ impl Interner { const PINNED_SYMBOL_SLOTS: usize = 512; const PINNED_SYMBOL_PROBES: usize = 4; -pub(crate) type SymbolOwner = Arc; +/// A reference that keeps a cached symbol's text alive and immutable at the same address. +pub type SymbolOwner = Arc; #[derive(Debug)] struct PinnedSymbol { @@ -128,12 +129,19 @@ struct PinnedSymbol { _owner: SymbolOwner, } +/// Maps retained symbols to payload IDs using their hint, address, and length. +/// +/// Each occupied slot owns a reference that keeps the text alive and immutable at that address until replacement or +/// reset. Unlike `Interner::intern_symbol`, this cache can therefore reuse an ID without comparing the arena bytes. #[derive(Debug, Default)] pub(crate) struct PinnedSymbols { slots: Vec>, } impl PinnedSymbols { + /// Returns the cached ID or interns the text and retains an owner for the new entry. + /// + /// The owner from `retain` must keep `text` alive and immutable at this address while the slot is occupied. pub fn intern( &mut self, hint: SymbolHint, text: &str, intern: impl FnOnce() -> i64, retain: impl FnOnce() -> SymbolOwner, ) -> i64 { diff --git a/lib/datadog-agent/metrics-v3/src/lib.rs b/lib/datadog-agent/metrics-v3/src/lib.rs index d7f3d79c389..3a9d6b34e4a 100644 --- a/lib/datadog-agent/metrics-v3/src/lib.rs +++ b/lib/datadog-agent/metrics-v3/src/lib.rs @@ -15,5 +15,6 @@ mod types; mod writer; pub use constants::COLUMN_NAMES; +pub use interner::SymbolOwner; pub use types::V3MetricType; pub use writer::{V3EncodeError, V3EncodedMetrics, V3EncoderStats, V3MetricBuilder, V3ValueEncodingStats, V3Writer}; diff --git a/lib/datadog-agent/metrics-v3/src/writer.rs b/lib/datadog-agent/metrics-v3/src/writer.rs index e4a2e351577..e9a952ed5cf 100644 --- a/lib/datadog-agent/metrics-v3/src/writer.rs +++ b/lib/datadog-agent/metrics-v3/src/writer.rs @@ -896,8 +896,12 @@ fn append_len(dst: &mut Vec, mut len: usize) { } } +// Use the bitset for longer tagsets, where it avoids more of the work of comparison sorting. +const MIN_TAGSET_BITSET_LEN: usize = 32; + fn sort_and_delta_tagset(ids: &mut [i64]) { - if ids.len() >= 32 { + if ids.len() >= MIN_TAGSET_BITSET_LEN { + // Sort and delta-encode distinct IDs below 128 using a bitset. let mut bits = 0u128; for &id in &*ids { if id as u64 >= u64::from(u128::BITS) { diff --git a/lib/saluki-components/src/encoders/datadog/metrics/mod.rs b/lib/saluki-components/src/encoders/datadog/metrics/mod.rs index 8816a9110c1..a2e8c6b9106 100644 --- a/lib/saluki-components/src/encoders/datadog/metrics/mod.rs +++ b/lib/saluki-components/src/encoders/datadog/metrics/mod.rs @@ -1,4 +1,4 @@ -use std::{any::Any, collections::HashMap, collections::VecDeque, ops::Range, sync::Arc, time::Duration}; +use std::{collections::HashMap, collections::VecDeque, ops::Range, sync::Arc, time::Duration}; use async_trait::async_trait; use ddsketch::DDSketch; @@ -37,7 +37,7 @@ use tracing::{debug, error, warn}; use url::Url; use self::v3::{ - V3EncodedMetrics, V3EncodedRequest, V3EncoderStats, V3MetricType, V3PayloadLimits, V3PayloadRequest, + SymbolOwner, V3EncodedMetrics, V3EncodedRequest, V3EncoderStats, V3MetricType, V3PayloadLimits, V3PayloadRequest, V3PayloadSplitReason, V3SerializerTelemetry, V3Writer, }; use crate::{ @@ -1705,6 +1705,10 @@ pub(super) fn metric_has_emittable_values(metric: &Metric) -> bool { } } +// Retain symbols only for longer tag lists, where avoiding repeated text hashing offsets the cost of pinning. +// This counts all context tags, including device and resource tags promoted out of the V3 tagset. +const MIN_CONTEXT_TAGS_FOR_PINNED_SYMBOLS: usize = 32; + fn write_metric_to_v3( writer: &mut V3Writer, metric: &Metric, additional_tags: &SharedTagSet, promoted_tags_deduplicator: &mut ReusableDeduplicator, @@ -1736,8 +1740,8 @@ fn write_metric_to_v3( Some((tag, hint)) } }); - if context_tags.len() >= 32 { - let mut symbol_owner: Option> = None; + if context_tags.len() >= MIN_CONTEXT_TAGS_FOR_PINNED_SYMBOLS { + let mut symbol_owner: Option = None; builder.set_unique_tags_with_symbols(tags, || { Arc::clone(symbol_owner.get_or_insert_with(|| Arc::new(context.clone()))) }); diff --git a/lib/saluki-components/src/encoders/datadog/metrics/v3/mod.rs b/lib/saluki-components/src/encoders/datadog/metrics/v3/mod.rs index 81c51264f26..668a7bb50a2 100644 --- a/lib/saluki-components/src/encoders/datadog/metrics/v3/mod.rs +++ b/lib/saluki-components/src/encoders/datadog/metrics/v3/mod.rs @@ -19,6 +19,6 @@ mod payload; mod telemetry; pub(crate) use datadog_agent_metrics_v3::V3EncoderStats; -pub use datadog_agent_metrics_v3::{V3EncodedMetrics, V3MetricType, V3Writer}; +pub use datadog_agent_metrics_v3::{SymbolOwner, V3EncodedMetrics, V3MetricType, V3Writer}; pub(super) use payload::{V3EncodedRequest, V3PayloadLimits, V3PayloadRequest}; pub(crate) use telemetry::{V3PayloadSplitReason, V3SerializerTelemetry};