Skip to main content

saluki_components/sources/dogstatsd/
origin.rs

1use std::sync::Arc;
2
3use saluki_core::data_model::{
4    origin::{OriginTagCardinality, OriginTagsResolver, RawOrigin},
5    tags::SharedTagSet,
6};
7use saluki_env::{
8    workload::{origin::ResolvedOrigin, EntityId},
9    WorkloadProvider,
10};
11use tracing::trace;
12
13use super::{replay::CapturedTaggerHandle, tags::WellKnownTags};
14
15const REPLAY_PROCESS_ID_MARKER: u32 = 1u32 << 31;
16
17#[derive(Clone, Debug, Eq, PartialEq)]
18pub(super) enum ProcessOrigin {
19    Pinned(Option<EntityId>),
20    Unpinned(u32),
21    Replay(u32),
22}
23
24impl ProcessOrigin {
25    pub(super) fn container_entity_id(&self) -> Option<&EntityId> {
26        match self {
27            Self::Pinned(entity_id) => entity_id.as_ref(),
28            Self::Unpinned(_) | Self::Replay(_) => None,
29        }
30    }
31}
32
33pub(super) fn mark_replay_process_id(process_id: u32) -> u32 {
34    process_id | REPLAY_PROCESS_ID_MARKER
35}
36
37fn captured_process_id_from_replay(process_id: u32) -> Option<u32> {
38    if process_id & REPLAY_PROCESS_ID_MARKER != 0 {
39        Some(process_id & !REPLAY_PROCESS_ID_MARKER)
40    } else {
41        None
42    }
43}
44
45/// Origin enrichment configuration.
46///
47/// Origin enrichment controls the when and how of enriching metrics ingested via DogStatsD based on various sources of
48/// "origin" information, such as specific metric tags or UDS socket credentials. Enrichment involves adding additional
49/// metric tags that describe the origin of the metric, such as the Kubernetes pod or container.
50#[derive(Clone)]
51#[cfg_attr(test, derive(Debug, PartialEq))]
52pub struct OriginEnrichmentConfiguration {
53    /// Whether or not to enable origin detection.
54    ///
55    /// If disabled, no origin tags will be added to events even if the origin information is detected.
56    pub enabled: bool,
57
58    /// Whether or not a client-provided entity ID should take precedence over automatically detected origin metadata.
59    ///
60    /// When a client-provided entity ID is specified, and an origin process ID has automatically been detected, setting
61    /// this to `true` will cause the origin process ID to be ignored. This only applies when
62    /// `origin_detection_unified` is `false`.
63    pub entity_id_precedence: bool,
64
65    /// The cardinality of tags to enrich metrics with, when the payload doesn't specify one itself.
66    pub tag_cardinality: OriginTagCardinality,
67
68    /// Whether or not to use the unified origin detection behavior.
69    ///
70    /// When set to `true`, all detected entity IDs -- UDS Origin Detection, `dd.internal.entity_id`, container ID from
71    /// DogStatsD payload -- will be used for querying tags to enrich with. When set to `false`, the original precedence
72    /// behavior will be used, which enriches with the entity ID detected via Origin Detection first, and then
73    /// potentially again with either the client-provided entity ID (`dd.internal.entity_id`) or the container ID from
74    /// the DogStatsD payload, with the client-provided entity ID taking precedence. An entity ID detected via Origin
75    /// Detection is only used when no client-provided entity ID was present, or when `entity_id_precedence` is
76    /// `false`.
77    pub origin_detection_unified: bool,
78
79    /// Whether or not to opt out of origin detection for DogStatsD metrics.
80    ///
81    /// When set to `true`, and the metric explicitly denotes a cardinality of `"none"`, origin enrichment will be
82    /// skipped. This is only applicable to DogStatsD metrics when unified origin detection behavior isn't enabled.
83    pub origin_detection_optout: bool,
84
85    /// Whether or not to parse client-provided origin fields from DogStatsD payloads.
86    ///
87    /// When enabled, the `c:` (Local Data), `e:` (External Data), and `card:` (Cardinality) protocol fields are
88    /// parsed and used for origin enrichment.
89    pub origin_detection_client: bool,
90}
91
92#[cfg(test)]
93impl OriginEnrichmentConfiguration {
94    /// Creates a fixture configuration with origin detection disabled, for tests that exercise enrichment behavior
95    /// rather than configuration.
96    pub(super) fn for_test() -> Self {
97        Self {
98            enabled: false,
99            entity_id_precedence: false,
100            tag_cardinality: OriginTagCardinality::Low,
101            origin_detection_unified: false,
102            origin_detection_optout: true,
103            origin_detection_client: false,
104        }
105    }
106}
107
108#[derive(Clone)]
109pub(super) struct DogStatsDOriginTagResolver {
110    config: OriginEnrichmentConfiguration,
111    workload_provider: Arc<dyn WorkloadProvider + Send + Sync>,
112    captured_tagger: CapturedTaggerHandle,
113}
114
115impl DogStatsDOriginTagResolver {
116    pub fn new(
117        config: OriginEnrichmentConfiguration, workload_provider: Arc<dyn WorkloadProvider + Send + Sync>,
118        captured_tagger: CapturedTaggerHandle,
119    ) -> Self {
120        Self {
121            config,
122            workload_provider,
123            captured_tagger,
124        }
125    }
126
127    fn collect_origin_tags_with_process_entity(
128        &self, origin: &ResolvedOrigin, process_entity_id: Option<&EntityId>,
129    ) -> SharedTagSet {
130        let mut collected_tags = SharedTagSet::default();
131
132        if !self.config.enabled {
133            return collected_tags;
134        }
135
136        // Examine the various possible entity ID values, and based on their state, use one or more of them to grab any
137        // enriched tags attached to the entities. We evalulate a number of possible entity IDs:
138        //
139        // - sender entity (resolved from UDS socket credentials when the packet is received)
140        // - Local Data-based container ID (extracted from special "container ID" extension in DogStatsD protocol; also known as Local Data)
141        // - Local Data-based pod UID (extracted from `dd.internal.entity_id` tag)
142        // - External Data-based container ID (derived from pod UID and container name in External Data)
143        // - External Data-based pod UID (raw pod UID from External Data)
144        let maybe_process_entity_id = process_entity_id;
145        let maybe_local_container_id = origin.local_data();
146        let maybe_local_pod_uid = origin.pod_uid();
147        let maybe_external_container_id = origin.resolved_external_data().map(|red| red.container_entity_id());
148        let maybe_external_pod_uid = origin.resolved_external_data().map(|red| red.pod_entity_id());
149
150        let tag_cardinality = origin.cardinality().unwrap_or(self.config.tag_cardinality);
151
152        if !self.config.origin_detection_unified {
153            if self.config.origin_detection_optout && tag_cardinality == OriginTagCardinality::None {
154                trace!("Skipping origin enrichment for DogStatsD metric with cardinality 'none'.");
155                return collected_tags;
156            }
157
158            // If we discovered an entity ID from socket credentials, and no client-provided entity ID was provided (or
159            // it was, but entity ID precedence is disabled), then try to get tags for the detected entity ID.
160            if let Some(entity_id) = maybe_process_entity_id {
161                if maybe_local_pod_uid.is_none() || !self.config.entity_id_precedence {
162                    if let Some(tags) = self.workload_provider.get_tags_for_entity(entity_id, tag_cardinality) {
163                        collected_tags.extend_from_shared(&tags);
164                    } else {
165                        trace!(
166                            ?entity_id,
167                            cardinality = tag_cardinality.as_str(),
168                            "No tags found for entity."
169                        );
170                    }
171                }
172            }
173
174            // If we have a client-provided entity ID, try to get tags for the entity based on those. A client-provided
175            // entity ID takes precedence over the container ID.
176            let maybe_entity_id = maybe_local_pod_uid.or(maybe_local_container_id);
177            if let Some(entity_id) = maybe_entity_id {
178                if let Some(tags) = self.workload_provider.get_tags_for_entity(entity_id, tag_cardinality) {
179                    collected_tags.extend_from_shared(&tags);
180                } else {
181                    trace!(
182                        ?entity_id,
183                        cardinality = tag_cardinality.as_str(),
184                        "No tags found for entity."
185                    );
186                }
187            }
188        } else {
189            if tag_cardinality == OriginTagCardinality::None {
190                trace!("Skipping origin enrichment for metric with cardinality 'none'.");
191                return collected_tags;
192            }
193
194            // Evaluate all available entity IDs in order of priority: Local Data-based container ID, sender entity,
195            // External Data-based container ID, Local Data-based pod UID, and External Data-based pod UID.
196            //
197            // As soon as the first set of tags for an entity ID is found, we skip the remaining entity IDs.
198            let maybe_entity_ids = &[
199                maybe_local_container_id,
200                maybe_process_entity_id,
201                maybe_external_container_id,
202                maybe_local_pod_uid,
203                maybe_external_pod_uid,
204            ];
205            for entity_id in maybe_entity_ids.iter().flatten() {
206                if let Some(tags) = self.workload_provider.get_tags_for_entity(entity_id, tag_cardinality) {
207                    if !tags.is_empty() {
208                        collected_tags.extend_from_shared(&tags);
209                        break;
210                    }
211                } else {
212                    trace!(
213                        ?entity_id,
214                        cardinality = tag_cardinality.as_str(),
215                        "No tags found for entity."
216                    );
217                }
218            }
219        }
220
221        collected_tags
222    }
223
224    fn collect_origin_tags(&self, origin: &ResolvedOrigin) -> SharedTagSet {
225        self.collect_origin_tags_with_process_entity(origin, origin.process_id())
226    }
227
228    pub(super) fn resolve_origin_tags_with_process_origin(
229        &self, mut origin: RawOrigin<'_>, process_origin: Option<&ProcessOrigin>,
230    ) -> SharedTagSet {
231        match process_origin {
232            Some(ProcessOrigin::Replay(process_id)) => {
233                origin.set_process_id(mark_replay_process_id(*process_id));
234                self.resolve_origin_tags(origin)
235            }
236            Some(ProcessOrigin::Unpinned(process_id)) => {
237                origin.set_process_id(*process_id);
238                self.resolve_origin_tags(origin)
239            }
240            Some(ProcessOrigin::Pinned(process_entity_id)) => {
241                let resolved_origin = self
242                    .workload_provider
243                    .get_resolved_origin(origin.clone())
244                    .unwrap_or_else(|| ResolvedOrigin::from_parts(origin.cardinality(), None, None, None, None));
245                self.collect_origin_tags_with_process_entity(&resolved_origin, process_entity_id.as_ref())
246            }
247            None => self.resolve_origin_tags(origin),
248        }
249    }
250}
251
252impl OriginTagsResolver for DogStatsDOriginTagResolver {
253    fn resolve_origin_tags(&self, origin: RawOrigin<'_>) -> SharedTagSet {
254        // Replay traffic is tagged by setting the marker bit on the origin process ID. It bypasses the live enrichment
255        // pipeline entirely: the captured `TaggerState` already contains fully-resolved tags per entity, so the
256        // resolver's entity-ID-walking logic has nothing to add.
257        if let Some(captured_process_id) = origin.process_id().and_then(captured_process_id_from_replay) {
258            if let Some(store) = self.captured_tagger.current() {
259                let cardinality = origin.cardinality().unwrap_or(self.config.tag_cardinality);
260                return store
261                    .lookup(captured_process_id as i32, cardinality)
262                    .unwrap_or_default();
263            }
264            trace!(?origin, "Replay-flagged origin but no captured tagger available.");
265            return SharedTagSet::default();
266        }
267
268        match self.workload_provider.get_resolved_origin(origin.clone()) {
269            Some(resolved_origin) => self.collect_origin_tags(&resolved_origin),
270            None => {
271                trace!(?origin, "No resolved origin found for origin.");
272                SharedTagSet::default()
273            }
274        }
275    }
276}
277
278/// Builds a `RawOrigin` from the origin fields of a DogStatsD packet and its well-known tags.
279///
280/// Metric, event, and service check packets all carry the same origin fields.
281pub fn origin_from_packet<'a>(
282    local_data: Option<&'a str>, external_data: Option<&'a str>, cardinality: Option<OriginTagCardinality>,
283    well_known_tags: &WellKnownTags<'a>,
284) -> RawOrigin<'a> {
285    let cardinality = cardinality.or(well_known_tags.cardinality);
286
287    let mut origin = RawOrigin::default();
288    origin.set_pod_uid(well_known_tags.pod_uid);
289    origin.set_local_data(local_data);
290    origin.set_external_data(external_data);
291    origin.set_cardinality(cardinality);
292    origin
293}
294
295#[cfg(test)]
296mod tests {
297    use std::collections::HashMap;
298
299    use saluki_core::data_model::tags::{RawTags, TagSet};
300    use saluki_env::workload::{origin::ResolvedExternalData, providers::TestWorkloadProvider, EntityId};
301    use stringtheory::MetaString;
302
303    use super::*;
304
305    static EID_PID: EntityId = EntityId::ContainerPid(12345);
306    static EID_LOCAL_CID: EntityId = EntityId::Container(MetaString::from_static("local-cid"));
307    static EID_EXTERNAL_CID_VALID: EntityId = EntityId::Container(MetaString::from_static("external-cid"));
308    static EID_EXTERNAL_CID_INVALID: EntityId = EntityId::Container(MetaString::from_static("invalid-external-cid"));
309    static EID_LOCAL_POD: EntityId = EntityId::PodUid(MetaString::from_static("local-pod-uid"));
310    static EID_EXTERNAL_POD: EntityId = EntityId::PodUid(MetaString::from_static("external-pod-uid"));
311
312    /// The tag the default workload provider holds for each entity. `EID_EXTERNAL_CID_INVALID` has none.
313    static ENTITY_TAGS: [(&EntityId, &str); 5] = [
314        (&EID_PID, "tag_source:pid"),
315        (&EID_LOCAL_CID, "tag_source:local-cid"),
316        (&EID_EXTERNAL_CID_VALID, "tag_source:external-cid"),
317        (&EID_LOCAL_POD, "tag_source:local-pod"),
318        (&EID_EXTERNAL_POD, "tag_source:external-pod"),
319    ];
320
321    fn single_tag(tag: &str) -> SharedTagSet {
322        let mut tag_set = TagSet::default();
323        tag_set.insert_tag(tag);
324        tag_set.into_shared()
325    }
326
327    fn tags_for_entity(entity_id: &EntityId) -> SharedTagSet {
328        ENTITY_TAGS
329            .iter()
330            .find(|(id, _)| *id == entity_id)
331            .map(|(_, tag)| single_tag(tag))
332            .unwrap_or_default()
333    }
334
335    fn origin(
336        maybe_process_id: Option<&EntityId>, maybe_local_container_id: Option<&EntityId>,
337        maybe_local_pod_uid: Option<&EntityId>, maybe_external_data: Option<&ResolvedExternalData>,
338    ) -> ResolvedOrigin {
339        ResolvedOrigin::from_parts(
340            None,
341            maybe_process_id.cloned(),
342            maybe_local_container_id.cloned(),
343            maybe_local_pod_uid.cloned(),
344            maybe_external_data.cloned(),
345        )
346    }
347
348    fn build_tags_resolver_with_default_tags(config: OriginEnrichmentConfiguration) -> DogStatsDOriginTagResolver {
349        let mut workload_provider = TestWorkloadProvider::new();
350        for (entity_id, tag) in ENTITY_TAGS {
351            workload_provider.add_entity_shared_tags(entity_id.clone(), single_tag(tag));
352        }
353
354        DogStatsDOriginTagResolver::new(config, Arc::new(workload_provider), CapturedTaggerHandle::new())
355    }
356
357    /// Builds a resolver with origin detection enabled at `tag_cardinality`.
358    fn enabled_resolver(
359        tag_cardinality: OriginTagCardinality, workload_provider: TestWorkloadProvider,
360        captured_tagger: CapturedTaggerHandle,
361    ) -> DogStatsDOriginTagResolver {
362        let config = OriginEnrichmentConfiguration {
363            enabled: true,
364            tag_cardinality,
365            ..OriginEnrichmentConfiguration::for_test()
366        };
367        DogStatsDOriginTagResolver::new(config, Arc::new(workload_provider), captured_tagger)
368    }
369
370    #[test]
371    fn packet_cardinality_takes_precedence_over_cardinality_tag() {
372        // The cardinality specified in a packet (`|card:high`, etc) takes precedence over the cardinality specified via
373        // the deprecated `dd.internal.card` tag.
374        let cases = [
375            (
376                "dd.internal.card:high",
377                OriginTagCardinality::High,
378                OriginTagCardinality::Low,
379            ),
380            (
381                "dd.internal.card:low",
382                OriginTagCardinality::Low,
383                OriginTagCardinality::Orchestrator,
384            ),
385            (
386                "dd.internal.card:orchestrator",
387                OriginTagCardinality::Orchestrator,
388                OriginTagCardinality::Low,
389            ),
390        ];
391
392        for (tag, tag_cardinality, packet_cardinality) in cases {
393            let raw_tags = RawTags::new(tag, usize::MAX, usize::MAX);
394            let (well_known_tags, _) = WellKnownTags::split_raw_tags(&raw_tags);
395            assert_eq!(well_known_tags.cardinality, Some(tag_cardinality), "{tag}");
396            assert_ne!(packet_cardinality, tag_cardinality, "{tag}");
397
398            assert_eq!(
399                origin_from_packet(None, None, Some(packet_cardinality), &well_known_tags).cardinality(),
400                Some(packet_cardinality),
401                "{tag} with packet cardinality"
402            );
403            assert_eq!(
404                origin_from_packet(None, None, None, &well_known_tags).cardinality(),
405                Some(tag_cardinality),
406                "{tag} without packet cardinality"
407            );
408        }
409    }
410
411    #[test]
412    fn origin_detection_legacy_precedence() {
413        let mut pid_plus_local_pod_tags = tags_for_entity(&EID_PID);
414        pid_plus_local_pod_tags.extend_from_shared(&tags_for_entity(&EID_LOCAL_POD));
415
416        let mut pid_plus_local_cid_tags = tags_for_entity(&EID_PID);
417        pid_plus_local_cid_tags.extend_from_shared(&tags_for_entity(&EID_LOCAL_CID));
418
419        let cases = [
420            // We only have the process ID, so entity ID precedence should be irrelevant.
421            (
422                false,
423                origin(Some(&EID_PID), None, None, None),
424                tags_for_entity(&EID_PID),
425            ),
426            (
427                true,
428                origin(Some(&EID_PID), None, None, None),
429                tags_for_entity(&EID_PID),
430            ),
431            // We have both the process ID and local pod UID, but entity ID precedence is disabled, so we get the
432            // process ID and local pod UID tags.
433            (
434                false,
435                origin(Some(&EID_PID), None, Some(&EID_LOCAL_POD), None),
436                pid_plus_local_pod_tags.clone(),
437            ),
438            // We have both the process ID and local pod UID, but entity ID precedence is enabled, so we should only get
439            // the local pod UID tags.
440            (
441                true,
442                origin(Some(&EID_PID), None, Some(&EID_LOCAL_POD), None),
443                tags_for_entity(&EID_LOCAL_POD),
444            ),
445            // We have the process ID, local container ID, and local pod UID, but entity ID precedence is disabled, so
446            // we should get the process ID and local pod UID tags.
447            (
448                false,
449                origin(Some(&EID_PID), Some(&EID_LOCAL_CID), Some(&EID_LOCAL_POD), None),
450                pid_plus_local_pod_tags,
451            ),
452            // We have the process ID, local container ID, and local pod UID, but entity ID precedence is enabled, so we
453            // should only get the local pod UID tags.
454            (
455                true,
456                origin(Some(&EID_PID), Some(&EID_LOCAL_CID), Some(&EID_LOCAL_POD), None),
457                tags_for_entity(&EID_LOCAL_POD),
458            ),
459            // We only have the process ID and local container ID, so entity ID precedence should be irrelevant, and so
460            // we should get the process ID and local container ID tags.
461            (
462                false,
463                origin(Some(&EID_PID), Some(&EID_LOCAL_CID), None, None),
464                pid_plus_local_cid_tags.clone(),
465            ),
466            (
467                true,
468                origin(Some(&EID_PID), Some(&EID_LOCAL_CID), None, None),
469                pid_plus_local_cid_tags,
470            ),
471        ];
472
473        for (entity_id_precedence, resolved_origin, expected_tags) in cases {
474            let tag_resolver_config = OriginEnrichmentConfiguration {
475                enabled: true,
476                entity_id_precedence,
477                tag_cardinality: OriginTagCardinality::High,
478                origin_detection_unified: false,
479                origin_detection_optout: false,
480                origin_detection_client: false,
481            };
482
483            let origin_tags_resolver = build_tags_resolver_with_default_tags(tag_resolver_config);
484
485            let actual_tags = origin_tags_resolver.collect_origin_tags(&resolved_origin);
486            assert_eq!(
487                actual_tags, expected_tags,
488                "failed to resolve the expected tags for origin {:?}",
489                resolved_origin
490            );
491        }
492    }
493
494    #[test]
495    fn origin_detection_unified_precedence() {
496        // We craft a "valid" and "invalid" variant for External Data, where the invalid one has a container ID with no tags
497        // assigned to it, which lets us exercise the tags resolver logic for when we have a pod UID through External Data,
498        // but not a container ID (or a container ID with no tags attached).
499        //
500        // We have to do it this way because we pass both External Data-based entity IDs through `ResolvedExternalData` when
501        // creating `ResolvedOrigin`, so we can't pass them separately.
502        let ext_data_valid = ResolvedExternalData::new(EID_EXTERNAL_POD.clone(), EID_EXTERNAL_CID_VALID.clone());
503        let ext_data_invalid = ResolvedExternalData::new(EID_EXTERNAL_POD.clone(), EID_EXTERNAL_CID_INVALID.clone());
504
505        let tag_resolver_config = OriginEnrichmentConfiguration {
506            enabled: true,
507            entity_id_precedence: false,
508            tag_cardinality: OriginTagCardinality::High,
509            origin_detection_unified: true,
510            origin_detection_optout: false,
511            origin_detection_client: false,
512        };
513
514        let origin_tags_resolver = build_tags_resolver_with_default_tags(tag_resolver_config);
515
516        // We craft our test cases to ensure that we always take the tags of the highest precedence entity ID available,
517        // and don't take any other tags.
518        let cases = [
519            // Cases where we're only setting a single entity ID. This is the happy path.
520            (origin(Some(&EID_PID), None, None, None), tags_for_entity(&EID_PID)),
521            (
522                origin(None, Some(&EID_LOCAL_CID), None, None),
523                tags_for_entity(&EID_LOCAL_CID),
524            ),
525            (
526                origin(None, None, Some(&EID_LOCAL_POD), None),
527                tags_for_entity(&EID_LOCAL_POD),
528            ),
529            (
530                origin(None, None, None, Some(&ext_data_valid)),
531                tags_for_entity(&EID_EXTERNAL_CID_VALID),
532            ),
533            (
534                origin(None, None, None, Some(&ext_data_invalid)),
535                tags_for_entity(&EID_EXTERNAL_POD),
536            ),
537            // Cases where we have multiple entity IDs to choose from. We work our way backwards here.
538            (
539                origin(
540                    Some(&EID_PID),
541                    Some(&EID_LOCAL_CID),
542                    Some(&EID_LOCAL_POD),
543                    Some(&ext_data_valid),
544                ),
545                tags_for_entity(&EID_LOCAL_CID),
546            ),
547            (
548                origin(Some(&EID_PID), None, Some(&EID_LOCAL_POD), Some(&ext_data_valid)),
549                tags_for_entity(&EID_PID),
550            ),
551            (
552                origin(None, None, Some(&EID_LOCAL_POD), Some(&ext_data_valid)),
553                tags_for_entity(&EID_EXTERNAL_CID_VALID),
554            ),
555            (
556                origin(None, None, Some(&EID_LOCAL_POD), Some(&ext_data_invalid)),
557                tags_for_entity(&EID_LOCAL_POD),
558            ),
559            (
560                origin(None, None, None, Some(&ext_data_invalid)),
561                tags_for_entity(&EID_EXTERNAL_POD),
562            ),
563        ];
564
565        for (resolved_origin, expected_tags) in cases {
566            let actual_tags = origin_tags_resolver.collect_origin_tags(&resolved_origin);
567            assert_eq!(
568                actual_tags, expected_tags,
569                "failed to resolve the expected tags for origin {:?}",
570                resolved_origin
571            );
572        }
573    }
574
575    #[test]
576    fn origin_detection_disabled() {
577        // When origin detection is disabled, no tags should be resolved even if we do have mapped tags for the given
578        // resolved origin.
579        let tag_resolver_config = OriginEnrichmentConfiguration::for_test();
580        assert!(!tag_resolver_config.enabled);
581
582        let origin_tags_resolver = build_tags_resolver_with_default_tags(tag_resolver_config);
583
584        let resolved_origin = origin(Some(&EID_PID), None, None, None);
585        let actual_tags = origin_tags_resolver.collect_origin_tags(&resolved_origin);
586        assert!(actual_tags.is_empty());
587    }
588
589    #[test]
590    fn resolve_origin_tags_dispatches_to_captured_store_when_replay_flag_set() {
591        use datadog_protos::agent::{Entity as ProtoEntity, TaggerState};
592
593        // Build a captured store with a single entity keyed by PID 7777.
594        let mut entities = HashMap::new();
595        entities.insert(
596            "container_id://captured-container".to_string(),
597            ProtoEntity {
598                low_cardinality_tags: vec!["env:captured".into(), "service:replayed".into()],
599                ..Default::default()
600            },
601        );
602        let mut pid_map = HashMap::new();
603        pid_map.insert(7777, "container_id://captured-container".to_string());
604        let state = TaggerState {
605            state: entities,
606            pid_map,
607            duration: 0,
608        };
609        let captured_tagger = CapturedTaggerHandle::new();
610        captured_tagger.set_current(Some(super::super::replay::CapturedTaggerStore::from_tagger_state(
611            state,
612        )));
613
614        // Build a resolver whose live workload provider is empty; if the replay path is wired wrong, we'd get
615        // no tags. If it's wired right, we get the captured tags.
616        let resolver = enabled_resolver(OriginTagCardinality::Low, TestWorkloadProvider::new(), captured_tagger);
617
618        let mut origin = RawOrigin::default();
619        origin.set_process_id(mark_replay_process_id(7777));
620        origin.set_cardinality(OriginTagCardinality::Low);
621
622        let tags = resolver.resolve_origin_tags(origin);
623        let tag_strs: Vec<String> = tags.into_iter().map(|t| t.as_str().to_string()).collect();
624        assert!(tag_strs.contains(&"env:captured".to_string()));
625        assert!(tag_strs.contains(&"service:replayed".to_string()));
626    }
627
628    #[test]
629    fn resolve_origin_tags_returns_empty_when_replay_flag_set_but_no_captured_store() {
630        // If the replay flag is set but no captured store is current, the resolver returns an empty tag set
631        // (no fallback to the live tagger). This guards against accidentally serving live tags for replay packets.
632        let resolver = enabled_resolver(
633            OriginTagCardinality::Low,
634            TestWorkloadProvider::new(),
635            CapturedTaggerHandle::new(),
636        );
637
638        let mut origin = RawOrigin::default();
639        origin.set_process_id(mark_replay_process_id(7777));
640
641        let tags = resolver.resolve_origin_tags(origin);
642        assert!(
643            tags.is_empty(),
644            "replay path with no captured store must return empty tags"
645        );
646    }
647
648    #[test]
649    fn resolve_origin_tags_live_path_resolves_tags_via_workload_provider() {
650        // Exercises the real, non-replay production entry point: `resolve_origin_tags` asks the workload provider to
651        // resolve the raw origin, then walks the resolved entity IDs to collect tags. Every other test either drives
652        // the internal `collect_origin_tags` directly or takes the replay bypass, so this is the only coverage of the
653        // live `get_resolved_origin` -> `collect_origin_tags` path through the trait method.
654        let mut workload_provider = TestWorkloadProvider::new();
655        workload_provider.add_entity_shared_tags(EntityId::ContainerPid(4242), single_tag("tag_source:live-pid"));
656        let resolver = enabled_resolver(
657            OriginTagCardinality::High,
658            workload_provider,
659            CapturedTaggerHandle::new(),
660        );
661
662        // A plain process ID (no replay marker bit) resolves to `EntityId::ContainerPid(4242)` via the live path.
663        let mut origin = RawOrigin::default();
664        origin.set_process_id(4242);
665
666        let tags = resolver.resolve_origin_tags(origin);
667        assert_eq!(tags, single_tag("tag_source:live-pid"));
668    }
669
670    #[test]
671    fn resolve_origin_tags_uses_pinned_process_entity() {
672        let pinned_entity = EntityId::Container(MetaString::from_static("original-container"));
673        let workload_provider =
674            TestWorkloadProvider::with_entity(pinned_entity.clone(), &["tag_source:pinned-container"]);
675        let resolver = enabled_resolver(
676            OriginTagCardinality::High,
677            workload_provider,
678            CapturedTaggerHandle::new(),
679        );
680        let process_origin = ProcessOrigin::Pinned(Some(pinned_entity));
681
682        let tags = resolver.resolve_origin_tags_with_process_origin(RawOrigin::default(), Some(&process_origin));
683
684        assert_eq!(tags, single_tag("tag_source:pinned-container"));
685    }
686
687    #[test]
688    fn resolve_origin_tags_live_path_returns_empty_when_origin_unresolved() {
689        // When the workload provider can't resolve the origin (here, an empty origin resolves to `None`), the live
690        // path returns an empty tag set rather than falling through to anything else.
691        let resolver = enabled_resolver(
692            OriginTagCardinality::High,
693            TestWorkloadProvider::new(),
694            CapturedTaggerHandle::new(),
695        );
696
697        let tags = resolver.resolve_origin_tags(RawOrigin::default());
698        assert!(tags.is_empty(), "unresolved origin must produce no tags");
699    }
700}