From 3e300eee69e7505ace052cd0e43d0e7f8abea40b Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 03:49:58 +0000 Subject: [PATCH 1/2] enhancement(dogstatsd): classify and deduplicate metric tags on the stack ## Summary The DogStatsD codec checks every tag against four well-known prefixes with separate `starts_with` calls. It collects regular tags in a `SmallVec` with 32 inline slots, so a 50-tag line spills to the heap. The resolver then hashes each tag into a heap `PrehashedHashSet` to skip duplicates, and packing deduplicates the same tags again. This change dispatches on the first byte of each tag, so most tags skip every prefix check. Regular tags get 64 inline slots. Tag sets that fit deduplicate in a stack table kept at most half full, and larger sets use reusable scratch storage. When all tag hashes are distinct, packing skips its second deduplication pass. Stripped `optimized-release` Tier 1 runs show cgroup CPU falling 4.09% on SMP-500, 4.04% on 1M RUM and 7.50% on 50-tag. ## Change Type - [ ] Bug fix - [ ] New feature - [ ] Non-functional - [x] Performance ## How did you test this PR? - `cargo check --locked --workspace --tests` - `cargo test --locked -p saluki-core --lib context_hash_matches_hash_set_deduplication` - Tier 1 runs use stripped `optimized-release` builds against base `18f587f5f6` in cgroup v2, in default unbounded mode. - SMP-500 is the Saluki Single Machine Performance 3,000-context UDS case at 500 MiB/s. - 1M RUM holds 1,000,000 gauges that each carry one unique 51 B UUID tag and 4 to 10 shared tags. - 50-tag holds 1,000,000 gauges that each carry 50 tags drawn from a 100-tag shared pool. ## References - Requires: packed `Context` storage. - Required by: none. - Release note: `releasenotes/notes/dogstatsd-stack-tag-hashing-3681dfabf7d05702.yaml` ### Series overview - 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 - PR TBD: 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 - **Current:** 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. --- .../src/sources/dogstatsd/tags.rs | 92 ++++--- .../data_model/event/metric/context/hash.rs | 238 +++++++++++++----- .../data_model/event/metric/context/packed.rs | 9 +- .../event/metric/context/resolver.rs | 14 +- ...sd-stack-tag-hashing-3681dfabf7d05702.yaml | 3 + 5 files changed, 241 insertions(+), 115 deletions(-) create mode 100644 releasenotes/notes/dogstatsd-stack-tag-hashing-3681dfabf7d05702.yaml diff --git a/lib/saluki-components/src/sources/dogstatsd/tags.rs b/lib/saluki-components/src/sources/dogstatsd/tags.rs index e274bfa2573..127d74276f7 100644 --- a/lib/saluki-components/src/sources/dogstatsd/tags.rs +++ b/lib/saluki-components/src/sources/dogstatsd/tags.rs @@ -1,30 +1,19 @@ use saluki_core::{ constants::datadog::*, - data_model::{ - origin::OriginTagCardinality, - tags::{BorrowedTag, RawTags}, - }, + data_model::{origin::OriginTagCardinality, tags::RawTags}, }; use smallvec::SmallVec; /// Regular (non-well-known) tags from a DogStatsD payload. /// -/// As an optimization, up to 32 tags are stored inline without allocating. This isn't a limit on the number of tags: -/// any beyond that are stored on the heap. -pub type RegularTags<'a> = SmallVec<[&'a str; 32]>; - -/// Returns `true` if the given tag is a well-known tag. -fn is_well_known_tag(tag: &str) -> bool { - tag.starts_with(HOST_TAG_KEY_SUFFIXED) - || tag.starts_with(ENTITY_ID_TAG_KEY_SUFFIXED) - || tag.starts_with(JMX_CHECK_NAME_TAG_KEY_SUFFIXED) - || tag.starts_with(CARDINALITY_TAG_KEY_SUFFIXED) -} +/// Keeps up to 64 tag references inline without allocating. The inline capacity is not a limit on tag count. +/// Larger lists move to heap storage. +pub type RegularTags<'a> = SmallVec<[&'a str; 64]>; /// Well-known tags shared across DogStatsD payloads. /// -/// Well-known tags are tags which are generally set by the DogStatsD client to convey structured information -/// about the source of the metric, event, or service check. +/// The DogStatsD client uses well-known keys to carry a hostname, entity ID, JMX check name, or cardinality hint. +/// These values describe the payload or its origin instead of appearing as regular tags. #[derive(Default)] pub struct WellKnownTags<'a> { pub hostname: Option<&'a str>, @@ -36,38 +25,45 @@ pub struct WellKnownTags<'a> { impl<'a> WellKnownTags<'a> { /// Splits the raw tags of a DogStatsD payload into well-known tags and regular tags. /// - /// Any tag with a well-known tag key is excluded from the regular tags, even if its value is ignored. All fields - /// of the well-known tags default to `None`. + /// A tag with a well-known key stays out of the regular list even if the parser ignores its value. + /// Each well-known field starts as `None`. /// - /// The raw tags are walked exactly once, so callers can iterate over the regular tags as many times as needed - /// (such as for both hashing and building a context) without re-parsing the raw tags. + /// The split scans the raw tags once. The caller can reuse the regular tags for hashing and context creation + /// without parsing the payload again. pub fn split_raw_tags(tags: &'a RawTags<'_>) -> (Self, RegularTags<'a>) { let mut well_known_tags = Self::default(); let mut regular_tags = RegularTags::new(); for tag in tags.iter() { - if !is_well_known_tag(tag) { - regular_tags.push(tag); - continue; - } - - match BorrowedTag::from(tag).name_and_value() { - (HOST_TAG_KEY, Some(hostname)) => { - well_known_tags.hostname = Some(hostname); - } - (ENTITY_ID_TAG_KEY, Some(entity_id)) if entity_id != ENTITY_ID_IGNORE_VALUE => { - well_known_tags.pod_uid = Some(entity_id); - } - (JMX_CHECK_NAME_TAG_KEY, Some(name)) => { - well_known_tags.jmx_check_name = Some(name); + // The first byte selects which well-known prefixes can match. A full prefix match includes the colon. + match tag.as_bytes().first() { + Some(b'h') => { + if let Some(hostname) = tag.strip_prefix(HOST_TAG_KEY_SUFFIXED) { + well_known_tags.hostname = Some(hostname); + continue; + } } - (CARDINALITY_TAG_KEY, Some(value)) => { - if let Ok(card) = OriginTagCardinality::try_from(value) { - well_known_tags.cardinality = Some(card); + Some(b'd') => { + if let Some(entity_id) = tag.strip_prefix(ENTITY_ID_TAG_KEY_SUFFIXED) { + if entity_id != ENTITY_ID_IGNORE_VALUE { + well_known_tags.pod_uid = Some(entity_id); + } + continue; + } + if let Some(name) = tag.strip_prefix(JMX_CHECK_NAME_TAG_KEY_SUFFIXED) { + well_known_tags.jmx_check_name = Some(name); + continue; + } + if let Some(value) = tag.strip_prefix(CARDINALITY_TAG_KEY_SUFFIXED) { + if let Ok(card) = OriginTagCardinality::try_from(value) { + well_known_tags.cardinality = Some(card); + } + continue; } } _ => {} } + regular_tags.push(tag); } (well_known_tags, regular_tags) @@ -145,4 +141,24 @@ mod tests { assert_eq!(wkt.cardinality, None); assert_eq!(wkt.jmx_check_name, Some("check")); } + + #[test] + fn well_known_tag_values_keep_suffixes_and_ignore_invalid_overrides() { + let tags = format!( + "host:old,host:new:port,dd.internal.entity_id:pod,dd.internal.entity_id:{ENTITY_ID_IGNORE_VALUE},\ + dd.internal.card:low,dd.internal.card:bad,dd.internal.jmx_check_name:,dd.internal.jmx_check_name:x:y,\ + ,dd.internal.card.extra:keep,jmx_check_name:keep" + ); + let tags = RawTags::new(&tags, usize::MAX, usize::MAX); + let (wkt, regular_tags) = WellKnownTags::split_raw_tags(&tags); + + assert_eq!(wkt.hostname, Some("new:port")); + assert_eq!(wkt.pod_uid, Some("pod")); + assert_eq!(wkt.cardinality, Some(OriginTagCardinality::Low)); + assert_eq!(wkt.jmx_check_name, Some("x:y")); + assert_eq!( + regular_tags.as_slice(), + ["", "dd.internal.card.extra:keep", "jmx_check_name:keep"] + ); + } } diff --git a/lib/saluki-core/src/data_model/event/metric/context/hash.rs b/lib/saluki-core/src/data_model/event/metric/context/hash.rs index 1ed02b9f0e9..9ea21a46155 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/hash.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/hash.rs @@ -5,21 +5,14 @@ use saluki_common::{ hash::{get_fast_hasher, hash_single_fast}, }; -/// Hashes a metric context. -/// -/// Takes a metric name, an iterator of tags, and an iterator of origin tags, and returns a tuple containing a unique -/// hash key for the overall context, and a unique hash key for the non-origin tags by themselves. -/// -/// All tags are hashed in an order-oblivious (XOR) manner, which allows tags to be hashed in any order while still -/// resulting in the same overall hash. This function is _not_ oblivious to the actual tag values themselves, though, so -/// differences such as case (lower vs upper) or leading/trailing whitespace will influence the resulting hash. +const MEDIUM_TAG_CAPACITY: usize = 64; + +/// Returns hash keys for the metric context and its non-origin tag set. /// -/// If a tag is seen more than once, it will be ignored and not included in the overall hash. This function allocates a -/// hash set in order to track which tags have already been hashed, so it's preferable to allocate a single -/// [`PrehashedHashSet`] and use it with [`hash_context_with_host_and_seen`] in order to amortize the cost of allocating -/// the hash set. +/// Tag order and duplicate tags do not affect either key. Tags and origin tags deduplicate separately. +/// Tag values remain case-sensitive and whitespace-sensitive. The hash keys can collide. /// -/// Returns a hash that uniquely identifies the combination of name, tags, and origin of the value. +/// Small and medium tag sets use stack storage. Large sets can allocate temporary storage for deduplication. pub fn hash_context(name: &str, tags: I, origin_tags: I2) -> (ContextKey, TagSetKey) where I: IntoIterator, @@ -28,26 +21,14 @@ where T2: AsRef, { let mut seen = PrehashedHashSet::default(); - hash_context_with_host_and_seen(name, None, tags, origin_tags, &mut seen) + let (context, tagset, _) = hash_context_with_host_and_seen(name, None, tags, origin_tags, &mut seen); + (context, tagset) } -/// Hashes a metric context with an explicit host dimension, using a provided set to track duplicate tags. -/// -/// Takes a metric name, optional host, an iterator of tags, and an iterator of origin tags, and returns a tuple -/// containing a unique hash key for the overall context, and a unique hash key for the non-origin tags by themselves. -/// The host is considered part of overall context identity, but not part of the non-origin tag set. -/// -/// All tags are hashed in an order-oblivious (XOR) manner, which allows tags to be hashed in any order while still -/// resulting in the same overall hash. This function is _not_ oblivious to the actual tag values themselves, though, so -/// differences such as case (lower vs upper) or leading/trailing whitespace will influence the resulting hash. The host -/// and metric name are order-dependent scalar context fields, not tags. -/// -/// If a tag is seen more than once, it will be ignored and not included in the overall hash. This function requires the -/// caller to provide the hash set used for tracking duplicates, and is more efficient than `hash_context` which -/// allocates a new hash set each time. +/// Returns hash keys for the metric context with a host and for its non-origin tag set. /// -/// Returns a hash that uniquely identifies the combination of name, host, tags, and origin of the value. An unset host -/// and an explicitly empty host are distinct contexts. +/// The metric name and host affect only the context key. An unset host and an explicitly empty host are distinct. +/// Tag order and duplicate tags do not affect either key. Tags and origin tags deduplicate separately. pub fn hash_context_with_host( name: &str, host: Option<&str>, tags: I, origin_tags: I2, ) -> (ContextKey, TagSetKey) @@ -58,67 +39,136 @@ where T2: AsRef, { let mut seen = PrehashedHashSet::default(); - hash_context_with_host_and_seen(name, host, tags, origin_tags, &mut seen) + let (context, tagset, _) = hash_context_with_host_and_seen(name, host, tags, origin_tags, &mut seen); + (context, tagset) } +/// Computes both keys and reports whether the non-origin tag hashes can represent duplicates. +/// +/// A repeated hash can be a duplicate tag or a collision. Distinct hashes rule out duplicate tags. +/// Reuse a `PrehashedHashSet` across contexts to amortize the allocation when a tag set outgrows the stack tables. pub(super) fn hash_context_with_host_and_seen( name: &str, host: Option<&str>, tags: I, origin_tags: I2, seen: &mut PrehashedHashSet, -) -> (ContextKey, TagSetKey) +) -> (ContextKey, TagSetKey, bool) where I: IntoIterator, T: AsRef, I2: IntoIterator, T2: AsRef, { - seen.clear(); - let mut hasher = get_fast_hasher(); - // Hash the metric name and host. + // Hash the name and host as separate scalar fields. Do not XOR them with tag hashes. name.hash(&mut hasher); host.hash(&mut hasher); - // Hash the metric tags individually and XOR their hashes together, which allows us to be order-oblivious: - let mut combined_tags_hash = 0; + let (combined_tags_hash, tags_may_repeat) = hash_tags(tags, seen); + hasher.write_u64(combined_tags_hash); - for tag in tags { - let tag_hash = hash_single_fast(tag.as_ref()); + // Origin tags contribute their own order-independent hash. They do not affect the non-origin tag set key. + hasher.write_u64(hash_tags(origin_tags, seen).0); - // If we've already seen this tag before, skip combining it again. - if !seen.insert(tag_hash) { - continue; - } + let context_key = ContextKey { hash: hasher.finish() }; + let tagset_key = TagSetKey { + hash: combined_tags_hash, + }; - combined_tags_hash ^= tag_hash; - } + (context_key, tagset_key, tags_may_repeat) +} - hasher.write_u64(combined_tags_hash); +/// XORs each distinct tag hash once so tag order does not matter and duplicates cannot cancel a hash. +/// +/// An array scans up to 16 distinct hashes. A stack table handles up to 64 distinct nonzero hashes. +/// The iterator's lower bound can skip a small path. Unknown-length iterators promote as needed. +/// The heap fallback reuses the caller's set and inserts the hashes directly without hashing the strings again. +#[inline] +fn hash_tags(tags: I, seen: &mut PrehashedHashSet) -> (u64, bool) +where + I: IntoIterator, + T: AsRef, +{ + const INLINE_CAPACITY: usize = 16; + + let mut hashes = tags.into_iter().map(|tag| hash_single_fast(tag.as_ref())); + let mut combined = 0; + let mut may_repeat = false; + + let lower_bound = hashes.size_hint().0; + if lower_bound <= INLINE_CAPACITY { + let mut inline = [0; INLINE_CAPACITY]; + let mut len = 0; + for hash in hashes.by_ref() { + if inline[..len].contains(&hash) { + may_repeat = true; + continue; + } + if len == INLINE_CAPACITY { + let (combined, repeats) = + hash_medium_tags(inline.into_iter().chain(std::iter::once(hash)).chain(hashes), seen); + return (combined, may_repeat || repeats); + } + combined ^= hash; + inline[len] = hash; + len += 1; + } + return (combined, may_repeat); + } + if lower_bound <= MEDIUM_TAG_CAPACITY { + return hash_medium_tags(hashes, seen); + } - // Finally, hash the origin tags. - // - // We also hash these in an order-oblivious manner. seen.clear(); - let mut combined_origin_tags_hash = 0; - - for tag in origin_tags { - let tag_hash = hash_single_fast(tag.as_ref()); - - // If we've already seen this tag before, skip combining it again. - if !seen.insert(tag_hash) { - continue; + for hash in hashes { + if seen.insert(hash) { + combined ^= hash; + } else { + may_repeat = true; } - - combined_origin_tags_hash ^= tag_hash; } - hasher.write_u64(combined_origin_tags_hash); - - let context_key = ContextKey { hash: hasher.finish() }; - let tagset_key = TagSetKey { - hash: combined_tags_hash, - }; + (combined, may_repeat) +} - (context_key, tagset_key) +// Keep the stack table at most half full. XOR ignores zero, so zero can also mark empty slots. +fn hash_medium_tags(mut hashes: impl Iterator, seen: &mut PrehashedHashSet) -> (u64, bool) { + const BUCKETS: usize = MEDIUM_TAG_CAPACITY * 2; + let mut slots = [0; BUCKETS]; + let mut combined = 0; + let mut len = 0; + let mut may_repeat = false; + for hash in hashes.by_ref() { + let mut index = hash as usize & (BUCKETS - 1); + loop { + let slot = &mut slots[index]; + if *slot == hash { + may_repeat = true; + break; + } + if *slot == 0 { + *slot = hash; + combined ^= hash; + len += 1; + break; + } + index = (index + 1) & (BUCKETS - 1); + } + if len == MEDIUM_TAG_CAPACITY { + if let Some(next) = hashes.next() { + // Transfer the hashes already counted so the remaining tags cannot XOR them in again. + seen.clear(); + seen.extend(slots.into_iter().filter(|&slot| slot != 0)); + for hash in std::iter::once(next).chain(hashes) { + if seen.insert(hash) { + combined ^= hash; + } else { + may_repeat = true; + } + } + } + break; + } + } + (combined, may_repeat) } /// A compact hash key that identifies a metric context. @@ -133,3 +183,59 @@ pub struct ContextKey { pub struct TagSetKey { hash: u64, } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn context_hash_matches_hash_set_deduplication() { + fn baseline_tags(tags: &[String]) -> u64 { + tags.iter() + .map(|tag| hash_single_fast(tag.as_str())) + .collect::>() + .into_iter() + .fold(0, |combined, hash| combined ^ hash) + } + + let name = "sample.metric"; + let mut seen = PrehashedHashSet::default(); + for (regular_count, origin_count) in [(0, 0), (16, 17), (17, 16), (50, 63), (64, 65), (2, 1)] { + let build_tags = |count| { + let mut tags: Vec<_> = (0..count).map(|i| format!("tag:{i}")).collect(); + if let Some(first) = tags.first() { + tags.push(first.clone()); + } + tags + }; + let tags = build_tags(regular_count); + let mut origin_tags = build_tags(origin_count); + origin_tags.reverse(); + + for host in [None, Some(""), Some("my-host")] { + let tags_hash = baseline_tags(&tags); + let mut hasher = get_fast_hasher(); + name.hash(&mut hasher); + host.hash(&mut hasher); + hasher.write_u64(tags_hash); + hasher.write_u64(baseline_tags(&origin_tags)); + + let (context_key, tagset_key, may_repeat) = + hash_context_with_host_and_seen(name, host, &tags, &origin_tags, &mut seen); + assert_eq!(context_key.hash, hasher.finish()); + assert_eq!(tagset_key.hash, tags_hash); + assert_eq!(may_repeat, regular_count != 0); + + // Filters hide the length, forcing large inputs to spill from the stack while hashing. + let streaming = hash_context_with_host_and_seen( + name, + host, + tags.iter().filter(|_| true), + origin_tags.iter().filter(|_| true), + &mut seen, + ); + assert_eq!(streaming, (context_key, tagset_key, may_repeat)); + } + } + } +} diff --git a/lib/saluki-core/src/data_model/event/metric/context/packed.rs b/lib/saluki-core/src/data_model/event/metric/context/packed.rs index 49d64041904..295c318a89a 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/packed.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/packed.rs @@ -473,13 +473,14 @@ impl Packed { }; let name_symbol = intern(name); let host_symbol = host.and_then(intern); - let mut prepared: SmallVec<[(&str, Option>); INLINE_TAG_CAPACITY]> = SmallVec::new(); + let tags = tags.into_iter(); + let min_tags = tags.size_hint().0; + let mut prepared = SmallVec::<[(&str, Option>); INLINE_TAG_CAPACITY]>::with_capacity(min_tags); let mut ids = 0; let mut all_inline_bytes = 0; let mut tag_bytes = 0; - let tags = tags.into_iter(); - let mut seen = (metadata.deduplicate && tags.size_hint().0 > INLINE_TAG_CAPACITY) - .then(HashSet::<&str, FastBuildHasher>::default); + let mut seen = (metadata.deduplicate && min_tags > INLINE_TAG_CAPACITY) + .then(|| HashSet::<&str, FastBuildHasher>::with_capacity_and_hasher(min_tags, FastBuildHasher::default())); for text in tags { if metadata.deduplicate { let duplicate = match &mut seen { diff --git a/lib/saluki-core/src/data_model/event/metric/context/resolver.rs b/lib/saluki-core/src/data_model/event/metric/context/resolver.rs index b76f49c96c7..2fc6977df2f 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/resolver.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/resolver.rs @@ -471,7 +471,7 @@ impl ContextResolver { fn create_context_key_with_host( &mut self, name: N, host: Option<&H>, tags: I, origin_tags: I2, - ) -> (ContextKey, TagSetKey) + ) -> (ContextKey, TagSetKey, bool) where N: AsRef, H: AsRef, @@ -490,7 +490,7 @@ impl ContextResolver { } fn create_context( - &self, keys: (ContextKey, TagSetKey), name: N, host: Option, tags: I, origin: SharedTagSet, + &self, keys: (ContextKey, TagSetKey, bool), name: N, host: Option, tags: I, origin: SharedTagSet, ) -> Option where N: AsRef + CheapMetaString, @@ -498,7 +498,7 @@ impl ContextResolver { I: IntoIterator, T: AsRef + CheapMetaString, { - let (key, tagset_key) = keys; + let (key, tagset_key, tags_may_repeat) = keys; let origin = TagSet::from(origin); let inner = if self.use_packed_strings { // Packed contexts own their tags and bypass the tag-set cache. @@ -512,7 +512,7 @@ impl ContextResolver { domain: Some(&self.domain), tracked: true, metadata: TagMetadata { - deduplicate: true, + deduplicate: tags_may_repeat, ..TagMetadata::default() }, lease: None, @@ -689,9 +689,9 @@ impl ContextResolver { I: IntoIterator + Clone, T: AsRef + CheapMetaString, { - let (context_key, tagset_key) = - self.create_context_key_with_host(&name, host.as_ref(), tags.clone(), &origin_tags); - let create = || self.create_context((context_key, tagset_key), name, host, tags, origin_tags); + let keys = self.create_context_key_with_host(&name, host.as_ref(), tags.clone(), &origin_tags); + let context_key = keys.0; + let create = || self.create_context(keys, name, host, tags, origin_tags); // Fast path to avoid looking up the context in the cache if caching is disabled. let Some(cache) = &self.context_cache else { diff --git a/releasenotes/notes/dogstatsd-stack-tag-hashing-3681dfabf7d05702.yaml b/releasenotes/notes/dogstatsd-stack-tag-hashing-3681dfabf7d05702.yaml new file mode 100644 index 00000000000..1e7237d5a2f --- /dev/null +++ b/releasenotes/notes/dogstatsd-stack-tag-hashing-3681dfabf7d05702.yaml @@ -0,0 +1,3 @@ +enhancements: + - | + Reduce allocation overhead when DogStatsD classifies and deduplicates common tag sets. From 2850a6e1aad4e5eb5e2cbf7ca2b6a4c945b4d5a9 Mon Sep 17 00:00:00 2001 From: "Brian L. Troutwine" Date: Thu, 26 Nov 2026 23:48:21 +0000 Subject: [PATCH 2/2] docs(context): clarify tag hash deduplication --- .../data_model/event/metric/context/hash.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/saluki-core/src/data_model/event/metric/context/hash.rs b/lib/saluki-core/src/data_model/event/metric/context/hash.rs index 9ea21a46155..76865edcdcc 100644 --- a/lib/saluki-core/src/data_model/event/metric/context/hash.rs +++ b/lib/saluki-core/src/data_model/event/metric/context/hash.rs @@ -1,4 +1,7 @@ -use std::hash::{Hash as _, Hasher as _}; +use std::{ + hash::{Hash as _, Hasher as _}, + iter::once, +}; use saluki_common::{ collections::PrehashedHashSet, @@ -9,10 +12,8 @@ const MEDIUM_TAG_CAPACITY: usize = 64; /// Returns hash keys for the metric context and its non-origin tag set. /// -/// Tag order and duplicate tags do not affect either key. Tags and origin tags deduplicate separately. +/// Tag order and duplicate tags do not affect either key. Tags and origin tags are deduplicated separately. /// Tag values remain case-sensitive and whitespace-sensitive. The hash keys can collide. -/// -/// Small and medium tag sets use stack storage. Large sets can allocate temporary storage for deduplication. pub fn hash_context(name: &str, tags: I, origin_tags: I2) -> (ContextKey, TagSetKey) where I: IntoIterator, @@ -28,7 +29,7 @@ where /// Returns hash keys for the metric context with a host and for its non-origin tag set. /// /// The metric name and host affect only the context key. An unset host and an explicitly empty host are distinct. -/// Tag order and duplicate tags do not affect either key. Tags and origin tags deduplicate separately. +/// Tag order and duplicate tags do not affect either key. Tags and origin tags are deduplicated separately. pub fn hash_context_with_host( name: &str, host: Option<&str>, tags: I, origin_tags: I2, ) -> (ContextKey, TagSetKey) @@ -76,10 +77,10 @@ where (context_key, tagset_key, tags_may_repeat) } -/// XORs each distinct tag hash once so tag order does not matter and duplicates cannot cancel a hash. +/// Combines each distinct tag hash once with XOR. Tag order does not matter, and duplicates cannot cancel a hash. /// /// An array scans up to 16 distinct hashes. A stack table handles up to 64 distinct nonzero hashes. -/// The iterator's lower bound can skip a small path. Unknown-length iterators promote as needed. +/// The lower bound of the iterator can skip a small path. Iterators of unknown length use larger storage as needed. /// The heap fallback reuses the caller's set and inserts the hashes directly without hashing the strings again. #[inline] fn hash_tags(tags: I, seen: &mut PrehashedHashSet) -> (u64, bool) @@ -103,8 +104,7 @@ where continue; } if len == INLINE_CAPACITY { - let (combined, repeats) = - hash_medium_tags(inline.into_iter().chain(std::iter::once(hash)).chain(hashes), seen); + let (combined, repeats) = hash_medium_tags(inline.into_iter().chain(once(hash)).chain(hashes), seen); return (combined, may_repeat || repeats); } combined ^= hash; @@ -157,7 +157,7 @@ fn hash_medium_tags(mut hashes: impl Iterator, seen: &mut PrehashedH // Transfer the hashes already counted so the remaining tags cannot XOR them in again. seen.clear(); seen.extend(slots.into_iter().filter(|&slot| slot != 0)); - for hash in std::iter::once(next).chain(hashes) { + for hash in once(next).chain(hashes) { if seen.insert(hash) { combined ^= hash; } else {