Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 71 additions & 1 deletion lib/datadog-agent/metrics-v3/src/interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -110,6 +114,72 @@ impl Interner {
}
}

const PINNED_SYMBOL_SLOTS: usize = 512;
const PINNED_SYMBOL_PROBES: usize = 4;

/// A reference that keeps a cached symbol's text alive and immutable at the same address.
pub type SymbolOwner = Arc<dyn Any + Send + Sync>;

#[derive(Debug)]
struct PinnedSymbol {
hint: SymbolHint,
address: usize,
len: usize,
id: i64,
_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 {
Comment thread
blt marked this conversation as resolved.
Resolved
slots: Vec<Option<PinnedSymbol>>,
}

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 {
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::*;
Expand Down
1 change: 1 addition & 0 deletions lib/datadog-agent/metrics-v3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
113 changes: 107 additions & 6 deletions lib/datadog-agent/metrics-v3/src/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
};

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -513,15 +514,25 @@ impl V3Writer {
self.intern_tag_ids()
}

fn intern_unique_tagset<'a>(&mut self, tags: impl Iterator<Item = (&'a str, Option<(usize, u32)>)>) -> i64 {
fn intern_unique_tagset<'a, F: FnMut() -> SymbolOwner>(
&mut self, tags: impl Iterator<Item = (&'a str, Option<(usize, u32)>)>, mut retain_owner: Option<F>,
) -> i64 {
self.tag_ids.clear();
self.tag_epoch = self.tag_epoch.wrapping_add(1);
if self.tag_epoch == 0 {
self.tag_epochs.fill(0);
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);
Expand Down Expand Up @@ -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<Item = (&'t str, Option<(usize, u32)>)>) {
let tagset_id = self.writer.intern_unique_tagset(tags);
let tagset_id = self.writer.intern_unique_tagset(tags, None::<fn() -> 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>(
Comment thread
blt marked this conversation as resolved.
Resolved
&mut self, tags: impl Iterator<Item = (&'t str, Option<(usize, u32)>)>,
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;
}

Expand Down Expand Up @@ -873,6 +896,36 @@ fn append_len(dst: &mut Vec<u8>, 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]) {
Comment thread
blt marked this conversation as resolved.
Resolved
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) {
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 {
Expand All @@ -894,6 +947,8 @@ fn delta_encode_i32(s: &mut [i32]) {

#[cfg(test)]
mod tests {
use std::sync::Arc;

use super::*;

#[test]
Expand Down Expand Up @@ -978,6 +1033,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();
Expand Down Expand Up @@ -1260,4 +1333,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());
}
}
22 changes: 17 additions & 5 deletions lib/saluki-components/src/encoders/datadog/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<str>,
Expand All @@ -1722,20 +1726,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() >= MIN_CONTEXT_TAGS_FOR_PINNED_SYMBOLS {
let mut symbol_owner: Option<SymbolOwner> = 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
enhancements:
- |
Reduce V3 metric encoding work for recurring instrumented tags.