Skip to main content

saluki_components/transforms/apm_stats/
mod.rs

1//! APM Stats transform.
2//!
3//! Aggregates traces into time-bucketed statistics, producing `TraceStats` events.
4
5use std::{
6    sync::Arc,
7    time::{Duration, SystemTime, UNIX_EPOCH},
8};
9
10use async_trait::async_trait;
11use datadog_agent_apm::semantics::SemanticRegistryProvider;
12use metrics::Counter;
13use saluki_core::{
14    accounting::{MemoryBounds, MemoryBoundsBuilder},
15    components::{transforms::*, BuildContext},
16    data_model::{
17        event::{
18            trace::{AttributeValue, AttributeValueExt, Trace},
19            trace_stats::{ClientStatsBucket, ClientStatsPayload, TraceStats},
20            Event, EventType,
21        },
22        origin::OriginTagCardinality,
23        tags::TagSet,
24    },
25    observability::ComponentMetricsExt as _,
26    topology::OutputDefinition,
27};
28use saluki_env::{
29    host::providers::BoxedHostProvider, workload::EntityId, EnvironmentProvider, HostProvider, WorkloadProvider,
30};
31use saluki_error::{ErrorContext as _, GenericError};
32use saluki_metrics::MetricsBuilder;
33use stringtheory::MetaString;
34use tokio::{select, time::interval};
35use tracing::{debug, error};
36
37use crate::common::datadog::get_tracer_hostname;
38use crate::common::datadog::version_data::ContainerVersionData;
39use crate::common::otlp::traces::normalize::normalized_tag_value;
40use crate::common::otlp::util::extract_trace_container_tags;
41use crate::config::AgentEnv;
42
43mod aggregation;
44pub(crate) use self::aggregation::{process_tags_hash, PayloadAggregationKey};
45
46mod peer_ip_quantize;
47
48pub(crate) mod peer_tags;
49
50mod span_concentrator;
51pub(crate) use self::span_concentrator::{InfraTags, SpanConcentrator};
52
53mod statsraw;
54
55mod weight;
56use self::weight::weight;
57
58/// Default flush interval for the APM stats transform.
59const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(10);
60
61/// Tag key for process tags in span meta.
62const TAG_PROCESS_TAGS: &str = "_dd.tags.process";
63
64/// Attribute key for the Git commit SHA, set on the tracer payload or in span meta.
65const TAG_GIT_COMMIT_SHA: &str = "_dd.git.commit.sha";
66
67/// Maximum number of `ClientGroupedStats` entries per `TraceStats` event.
68const MAX_STATS_GROUPS_PER_EVENT: usize = 4000;
69
70/// APM Stats transform configuration.
71///
72/// Aggregates incoming `Trace` events into time-bucketed statistics, emitting
73/// `TraceStats` events.
74pub struct ApmStatsTransformConfiguration {
75    /// Whether stats are computed separately per span kind.
76    pub compute_stats_by_span_kind: bool,
77
78    /// Whether stats are aggregated by peer tags.
79    pub peer_tags_aggregation: bool,
80
81    /// Custom span tags promoted to peer tags, in addition to those from the semantic registry.
82    pub peer_tags: Vec<MetaString>,
83
84    /// Environment used for traces whose spans and payload carry none.
85    pub agent_env: AgentEnv,
86
87    /// Hostname of emitted stats.
88    ///
89    /// If unset, stats carry an empty hostname. See [`with_environment_provider`](Self::with_environment_provider).
90    pub default_hostname: Option<String>,
91
92    /// Workload provider used to resolve container tags, if any.
93    pub workload_provider: Option<Arc<dyn WorkloadProvider + Send + Sync>>,
94
95    /// Provider of semantic mappings used to choose peer tag names for stats grouping.
96    ///
97    /// Peer tags describe the remote service or resource a span calls. The transform combines their names from the
98    /// registry with configured custom peer tags. With a subscribed provider, it checks for changed mappings before
99    /// each input event buffer; all spans in that buffer use the same key set.
100    pub semantic_registry: SemanticRegistryProvider,
101}
102
103impl ApmStatsTransformConfiguration {
104    /// Sets the default hostname using the environment provider.
105    pub async fn with_environment_provider<E>(mut self, env_provider: E) -> Result<Self, GenericError>
106    where
107        E: EnvironmentProvider<Host = BoxedHostProvider>,
108    {
109        let hostname = env_provider.host().get_hostname().await?;
110        self.default_hostname = Some(hostname);
111        Ok(self)
112    }
113}
114
115#[async_trait]
116impl TransformBuilder for ApmStatsTransformConfiguration {
117    async fn build(&self, context: BuildContext) -> Result<Box<dyn Transform + Send>, GenericError> {
118        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
119        let agent_hostname = MetaString::from(self.default_hostname.clone().unwrap_or_default());
120        let concentrator = SpanConcentrator::new(
121            self.compute_stats_by_span_kind,
122            self.peer_tags_aggregation,
123            &self.peer_tags,
124            self.semantic_registry.clone(),
125            now_nanos(),
126        );
127
128        Ok(Box::new(ApmStats {
129            concentrator,
130            flush_interval: DEFAULT_FLUSH_INTERVAL,
131            agent_env: self.agent_env.clone().into(),
132            agent_hostname,
133            workload_provider: self.workload_provider.clone(),
134            splits: metrics_builder.register_counter("component_stats_splits_total"),
135            future_clamps: metrics_builder.register_counter("component_stats_future_bucket_clamps_total"),
136        }))
137    }
138
139    fn input_event_type(&self) -> EventType {
140        EventType::Trace
141    }
142
143    fn outputs(&self) -> &[OutputDefinition<EventType>] {
144        static OUTPUTS: &[OutputDefinition<EventType>] = &[OutputDefinition::default_output(EventType::TraceStats)];
145        OUTPUTS
146    }
147}
148
149impl MemoryBounds for ApmStatsTransformConfiguration {
150    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
151        builder.minimum().with_single_value::<ApmStats>("component struct");
152        // TODO: Think about everything we need to account for here.
153    }
154}
155
156struct ApmStats {
157    concentrator: SpanConcentrator,
158    flush_interval: Duration,
159    agent_env: MetaString,
160    agent_hostname: MetaString,
161    workload_provider: Option<Arc<dyn WorkloadProvider + Send + Sync>>,
162    splits: Counter,
163    future_clamps: Counter,
164}
165
166impl ApmStats {
167    /// Splits flushed stats into events, counting a split whenever a flush needs more than one event.
168    fn split_flushed_stats(&self, client_payloads: Vec<ClientStatsPayload>) -> Vec<TraceStats> {
169        let events = split_into_trace_stats(client_payloads, MAX_STATS_GROUPS_PER_EVENT);
170        if events.len() > 1 {
171            self.splits.increment(1);
172        }
173        events
174    }
175
176    fn process_trace(&mut self, trace: &Trace) {
177        let root_span = trace
178            .spans()
179            .iter()
180            .find(|s| s.parent_id() == 0)
181            .or_else(|| trace.spans().first());
182
183        let trace_weight = root_span.map(weight).unwrap_or(1.0);
184
185        let process_tags = extract_process_tags(trace);
186
187        let infra_tags = self.build_infra_tags(trace, &process_tags);
188        let container_version = ContainerVersionData::from_tags(&infra_tags.container_tags);
189        let payload_key = self.build_payload_key(trace, &process_tags, container_version);
190
191        let origin = trace
192            .spans()
193            .first()
194            .and_then(|s| s.attributes.get("_dd.origin").and_then(AttributeValue::as_string))
195            .map(|s| s.as_ref())
196            .unwrap_or("");
197
198        let now = now_nanos();
199        for span in trace.spans() {
200            if let Some(stat_span) = self.concentrator.new_stat_span_from_span(span) {
201                self.concentrator
202                    .add_span(&stat_span, trace_weight, &payload_key, &infra_tags, origin, now);
203            }
204        }
205    }
206
207    fn build_infra_tags(&self, trace: &Trace, process_tags: &str) -> InfraTags {
208        let container_id = trace.payload.container_id.clone();
209        let mut container_tags = if container_id.is_empty() {
210            TagSet::default()
211        } else {
212            let mut tags = TagSet::default();
213            extract_trace_container_tags(trace.payload.resolved_container_tags(), &trace.attributes, &mut tags);
214            tags
215        };
216
217        if !container_id.is_empty() {
218            if let Some(workload_provider) = &self.workload_provider {
219                let entity_id = EntityId::Container(container_id.clone());
220                if let Some(tags) = workload_provider.get_tags_for_entity(&entity_id, OriginTagCardinality::Low) {
221                    container_tags.merge_shared(&tags);
222                }
223            }
224        }
225
226        InfraTags::new(container_id, container_tags, process_tags)
227    }
228
229    /// Builds the payload aggregation key of a trace.
230    ///
231    /// `container_version` supplies the version data that the trace itself leaves empty.
232    fn build_payload_key(
233        &self, trace: &Trace, process_tags: &str, container_version: ContainerVersionData<'_>,
234    ) -> PayloadAggregationKey {
235        let root_span = trace
236            .spans()
237            .iter()
238            .find(|s| s.parent_id() == 0)
239            .or_else(|| trace.spans().first());
240
241        // env fallback order mirrors get_trace_env (Go agent pkg/trace/traceutil/trace.go:GetEnv):
242        // root span attrs → all span attrs → trace.payload.env (ADP extension) → agent_env.
243        let env = root_span
244            .and_then(|s| {
245                s.attributes
246                    .get("env")
247                    .and_then(AttributeValue::as_string)
248                    .filter(|s| !s.is_empty())
249            })
250            .cloned()
251            .or_else(|| {
252                trace.spans().iter().find_map(|s| {
253                    s.attributes
254                        .get("env")
255                        .and_then(AttributeValue::as_string)
256                        .filter(|s| !s.is_empty())
257                        .cloned()
258                })
259            })
260            .unwrap_or_else(|| {
261                // The trace encoder normalizes the payload's env, so stats do the same to keep both on one env.
262                let payload_env = normalized_tag_value(&trace.payload.env);
263                if !payload_env.is_empty() {
264                    payload_env
265                } else {
266                    self.agent_env.clone()
267                }
268            });
269
270        let hostname = get_tracer_hostname(trace)
271            .cloned()
272            .unwrap_or_else(|| self.agent_hostname.clone());
273
274        // The root span's `version` attribute takes priority: for OTLP traces it already prefers the span's version
275        // over the resource's. The payload's version comes next, then the container's `version` tag.
276        let version = root_span
277            .and_then(|s| {
278                s.attributes
279                    .get("version")
280                    .and_then(AttributeValue::as_string)
281                    .filter(|s| !s.is_empty())
282            })
283            .cloned()
284            .unwrap_or_else(|| {
285                if !trace.payload.app_version.is_empty() {
286                    trace.payload.app_version.clone()
287                } else {
288                    MetaString::from(container_version.app_version)
289                }
290            });
291
292        let container_id = if !trace.payload.container_id.is_empty() {
293            trace.payload.container_id.clone()
294        } else {
295            root_span
296                .and_then(|s| s.attributes.get("_dd.container_id").and_then(AttributeValue::as_string))
297                .cloned()
298                .unwrap_or_default()
299        };
300
301        // The commit SHA set on the tracer payload wins over the root span's, and both win over the container's tag.
302        let git_commit_sha = trace
303            .attributes
304            .get(TAG_GIT_COMMIT_SHA)
305            .and_then(AttributeValue::as_string)
306            .filter(|s| !s.is_empty())
307            .or_else(|| {
308                root_span.and_then(|s| {
309                    s.attributes
310                        .get(TAG_GIT_COMMIT_SHA)
311                        .and_then(AttributeValue::as_string)
312                        .filter(|s| !s.is_empty())
313                })
314            })
315            .cloned()
316            .unwrap_or_else(|| MetaString::from(container_version.git_commit_sha));
317
318        let image_tag = root_span
319            .and_then(|s| {
320                s.attributes
321                    .get("_dd.image_tag")
322                    .and_then(AttributeValue::as_string)
323                    .filter(|s| !s.is_empty())
324            })
325            .cloned()
326            .unwrap_or_else(|| MetaString::from(container_version.image_tag));
327
328        let lang = if !trace.payload.language_name.is_empty() {
329            trace.payload.language_name.clone()
330        } else {
331            root_span
332                .and_then(|s| s.attributes.get("language").and_then(AttributeValue::as_string))
333                .cloned()
334                .unwrap_or_default()
335        };
336
337        PayloadAggregationKey {
338            env,
339            hostname,
340            version,
341            container_id,
342            git_commit_sha,
343            image_tag,
344            lang,
345            process_tags_hash: process_tags_hash(process_tags),
346        }
347    }
348}
349
350/// Splits stats payloads into multiple `TraceStats` events, each holding at most `max_entries_per_event` grouped
351/// entries. Each event becomes one outer stats payload when it is encoded.
352///
353/// This happens in two steps:
354///
355/// 1. A client payload with more than `max_entries_per_event` entries is divided into
356///    `ceil(entry_count / max_entries_per_event)` smaller client payloads, which is the fewest that can each stay
357///    within the limit. Its entries are dealt out to them round-robin, so they end up evenly sized, and each one
358///    keeps its entries in one bucket per time window.
359/// 2. The client payloads are then packed into events in order, without being divided again. A new event is started
360///    whenever the next client payload would push the current one past the limit.
361///
362/// If the stats need more than one event, every event is marked as part of a split flush.
363fn split_into_trace_stats(client_payloads: Vec<ClientStatsPayload>, max_entries_per_event: usize) -> Vec<TraceStats> {
364    if client_payloads.is_empty() {
365        return Vec::new();
366    }
367
368    // If the total number of grouped stats entries is below the specified threshold, then we don't do any splitting or
369    // collapsing or anything.
370    let total_grouped_entries = client_payloads.iter().map(count_grouped_entries).sum::<usize>();
371    if total_grouped_entries <= max_entries_per_event {
372        return vec![TraceStats::new(client_payloads)];
373    }
374
375    // The fewest events these entries can need. Whole client payloads are never divided while packing, so it can take
376    // more.
377    let mut finished_events = Vec::with_capacity(total_grouped_entries.div_ceil(max_entries_per_event));
378    let mut current_client_payloads = Vec::new();
379    let mut current_event_entries = 0;
380
381    // Adds a client payload to the event being built, closing that event first if the payload would not fit.
382    let mut add_to_event = |client_payload: ClientStatsPayload, entries: usize| {
383        if !current_client_payloads.is_empty() && current_event_entries + entries > max_entries_per_event {
384            finished_events.push(std::mem::take(&mut current_client_payloads));
385            current_event_entries = 0;
386        }
387        current_client_payloads.push(client_payload);
388        current_event_entries += entries;
389    };
390
391    for client_payload in client_payloads {
392        let client_payload_entries = count_grouped_entries(&client_payload);
393        if client_payload_entries <= max_entries_per_event {
394            add_to_event(client_payload, client_payload_entries);
395        } else {
396            for split_payload in split_client_payload(client_payload, max_entries_per_event) {
397                let split_payload_entries = count_grouped_entries(&split_payload);
398                add_to_event(split_payload, split_payload_entries);
399            }
400        }
401    }
402
403    if !current_client_payloads.is_empty() {
404        finished_events.push(current_client_payloads);
405    }
406
407    let is_split = finished_events.len() > 1;
408    finished_events
409        .into_iter()
410        .map(|payloads| TraceStats::new(payloads).with_split_payload(is_split))
411        .collect()
412}
413
414fn count_grouped_entries(client_payload: &ClientStatsPayload) -> usize {
415    client_payload.stats().iter().map(|b| b.stats().len()).sum()
416}
417
418/// Divides a client payload into `ceil(entry_count / max_entries)` client payloads, so that each holds at most
419/// `max_entries` grouped entries.
420///
421/// Entries are dealt out round-robin, so the resulting payloads differ in size by at most one entry, and each one has
422/// a single bucket per time window.
423fn split_client_payload(mut client_payload: ClientStatsPayload, max_entries: usize) -> Vec<ClientStatsPayload> {
424    let total_entries = count_grouped_entries(&client_payload);
425    if total_entries <= max_entries {
426        return vec![client_payload];
427    }
428
429    let payload_count = total_entries.div_ceil(max_entries);
430    let mut payload_buckets: Vec<Vec<ClientStatsBucket>> = vec![Vec::new(); payload_count];
431
432    let mut next_entry = 0;
433    for mut source_bucket in client_payload.take_stats() {
434        let entries = source_bucket.take_stats();
435
436        // Each split payload gets `entries.len() / payload_count` of this bucket's entries, and the first
437        // `entries.len() % payload_count` payloads in dealing order get one more, so a new bucket can be sized exactly.
438        let base = entries.len() / payload_count;
439        let extra = entries.len() % payload_count;
440        let first_payload = next_entry % payload_count;
441
442        for entry in entries {
443            let payload_index = next_entry % payload_count;
444            let buckets = &mut payload_buckets[payload_index];
445            next_entry += 1;
446
447            // The source bucket is now empty, so cloning it gives us a new bucket for the same time window.
448            let bucket_index = match buckets
449                .iter()
450                .position(|b| b.start() == source_bucket.start() && b.duration() == source_bucket.duration())
451            {
452                Some(index) => index,
453                None => {
454                    let dealing_order = (payload_index + payload_count - first_payload) % payload_count;
455                    let capacity = base + usize::from(dealing_order < extra);
456                    buckets.push(source_bucket.clone().with_stats(Vec::with_capacity(capacity)));
457                    buckets.len() - 1
458                }
459            };
460            buckets[bucket_index].stats_mut().push(entry);
461        }
462    }
463
464    payload_buckets
465        .into_iter()
466        .map(|buckets| client_payload.clone().with_stats(buckets))
467        .collect()
468}
469
470#[async_trait]
471impl Transform for ApmStats {
472    async fn run(mut self: Box<Self>, mut context: TransformContext) -> Result<(), GenericError> {
473        let mut health = context.take_health_handle();
474
475        let mut flush_ticker = interval(self.flush_interval);
476        flush_ticker.tick().await;
477
478        let mut final_flush = false;
479
480        health.mark_ready();
481        debug!("APM Stats transform started.");
482
483        loop {
484            select! {
485                _ = health.live() => continue,
486
487                _ = flush_ticker.tick() => {
488                    let stats_payloads = self.concentrator.flush(now_nanos(), final_flush);
489                    self.future_clamps.increment(self.concentrator.drain_future_clamps());
490                    if !stats_payloads.is_empty() {
491                        debug!(stats_payloads = stats_payloads.len(), "Flushing APM stats.");
492
493                        let events = self.split_flushed_stats(stats_payloads);
494                        let dispatcher = context.dispatcher().buffered()
495                            .error_context("Default output should be available.")?;
496
497                        if let Err(e) = dispatcher.send_all(events.into_iter().map(Event::TraceStats)).await {
498                            error!(error = %e, "Failed to dispatch events.");
499                        }
500                    }
501
502                    if final_flush {
503                        debug!("Final APM stats flush complete.");
504                        break;
505                    }
506                },
507
508                maybe_events = context.events().next(), if !final_flush => {
509                    match maybe_events {
510                        Some(events) => {
511                            // Use one peer tag key set for the whole buffer.
512                            self.concentrator.refresh_registry();
513                            for trace in events.into_events::<Trace>() {
514                                self.process_trace(&trace);
515                            }
516                        },
517                        None => {
518                            // We've reached the end of our input stream, so mark ourselves for a final flush and reset the
519                            // interval so it ticks immediately on the next loop iteration.
520                            final_flush = true;
521                            flush_ticker.reset_immediately();
522                            debug!("APM Stats transform stopping, triggering final flush...");
523                        }
524                    }
525                },
526            }
527        }
528
529        debug!("APM Stats transform stopped.");
530        Ok(())
531    }
532}
533
534/// Returns the current time as nanoseconds since Unix epoch.
535fn now_nanos() -> u64 {
536    SystemTime::now()
537        .duration_since(UNIX_EPOCH)
538        .unwrap_or_default()
539        .as_nanos() as u64
540}
541
542/// Extracts process tags from trace, checking both span and trace attributes.
543fn extract_process_tags(trace: &Trace) -> MetaString {
544    let root_span = trace
545        .spans()
546        .iter()
547        .find(|s| s.parent_id() == 0)
548        .or_else(|| trace.spans().first());
549    if let Some(span) = root_span {
550        if let Some(tags) = span
551            .attributes
552            .get(TAG_PROCESS_TAGS)
553            .and_then(AttributeValue::as_string)
554            .filter(|s| !s.is_empty())
555        {
556            return tags.clone();
557        }
558    }
559    if let Some(AttributeValue::String(tags)) = trace.attributes.get(TAG_PROCESS_TAGS) {
560        if !tags.is_empty() {
561            return tags.clone();
562        }
563    }
564    MetaString::empty()
565}
566
567#[cfg(test)]
568mod tests {
569    use datadog_agent_apm::semantics::test_util::TestRegistryPublisher;
570    use datadog_agent_apm::semantics::{test_util::registry_json, Registry};
571    use proptest::prelude::*;
572    use saluki_common::collections::FastHashMap;
573    use saluki_core::components::test_util::TestComponentDriver;
574    use saluki_core::data_model::event::trace::{AttributeValue, Span, TraceIngestInfo};
575    use saluki_core::data_model::event::trace_stats::ClientGroupedStats;
576    use saluki_core::data_model::event::trace_stats::ClientStatsBucket;
577    use saluki_env::workload::providers::TestWorkloadProvider;
578    use saluki_metrics::test::TestRecorder;
579
580    use super::aggregation::BUCKET_DURATION_NS;
581    use super::span_concentrator::METRIC_PARTIAL_VERSION;
582    use super::*;
583
584    /// Helper to align timestamp to bucket boundary
585    fn align_ts(ts: u64, bsize: u64) -> u64 {
586        ts - ts % bsize
587    }
588
589    /// Returns stats settings carrying the configuration defaults.
590    fn stats_configuration(agent_env: AgentEnv) -> ApmStatsTransformConfiguration {
591        ApmStatsTransformConfiguration {
592            compute_stats_by_span_kind: false,
593            peer_tags_aggregation: false,
594            peer_tags: Vec::new(),
595            agent_env,
596            default_hostname: None,
597            workload_provider: None,
598            semantic_registry: SemanticRegistryProvider::default(),
599        }
600    }
601
602    /// Creates a test span with the given parameters.
603    #[allow(clippy::too_many_arguments)]
604    fn test_span(
605        aligned_now: u64, span_id: u64, parent_id: u64, duration: u64, bucket_offset: u64, service: &str,
606        resource: &str, error: i32, meta: Option<FastHashMap<MetaString, MetaString>>,
607        metrics: Option<FastHashMap<MetaString, f64>>,
608    ) -> Span {
609        let bucket_start = aligned_now - bucket_offset * BUCKET_DURATION_NS;
610        let start = bucket_start - duration;
611
612        let mut attrs: FastHashMap<MetaString, AttributeValue> = FastHashMap::default();
613        if let Some(m) = meta {
614            attrs.extend(m.into_iter().map(|(k, v)| (k, AttributeValue::String(v))));
615        }
616        if let Some(m) = metrics {
617            attrs.extend(m.into_iter().map(|(k, v)| (k, AttributeValue::Float(v))));
618        }
619        Span::new(
620            service, "query", resource, "db", span_id, parent_id, start, duration, error,
621        )
622        .with_attributes(attrs)
623    }
624
625    /// Creates a simple measured span for basic tests
626    fn make_test_span(service: &str, name: &str, resource: &str) -> Span {
627        let mut attrs = FastHashMap::default();
628        attrs.insert(MetaString::from("_dd.measured"), AttributeValue::Float(1.0));
629        Span::new(service, name, resource, "web", 1, 0, 1000000000, 100000000, 0).with_attributes(attrs)
630    }
631
632    /// Creates a top-level span (`parent_id` = 0, has `_top_level` metric)
633    fn make_top_level_span(
634        aligned_now: u64, span_id: u64, duration: u64, bucket_offset: u64, service: &str, resource: &str, error: i32,
635        meta: Option<FastHashMap<MetaString, MetaString>>,
636    ) -> Span {
637        let mut metrics = FastHashMap::default();
638        metrics.insert(MetaString::from("_top_level"), 1.0);
639        test_span(
640            aligned_now,
641            span_id,
642            0,
643            duration,
644            bucket_offset,
645            service,
646            resource,
647            error,
648            meta,
649            Some(metrics),
650        )
651    }
652
653    #[tokio::test]
654    async fn run_refreshes_peer_tag_keys_before_each_buffer() {
655        use saluki_core::components::test_util::TestComponentDriver;
656
657        let now = now_nanos();
658        let (publisher, provider) = TestRegistryPublisher::new();
659        let config = ApmStatsTransformConfiguration {
660            compute_stats_by_span_kind: true,
661            peer_tags_aggregation: true,
662            semantic_registry: provider,
663            ..stats_configuration(AgentEnv::resolve(None, None, &[], &[]))
664        };
665        let (control, mut outputs) = TestComponentDriver::transform(config)
666            .await
667            .expect("transform should build");
668
669        // The buffer refresh must see a registry published after construction.
670        let remapped = registry_json(
671            r#"{"peer.service": {"fallbacks": [
672                {"name": "custom.remote.service", "provider": "otel", "type": "string"}]}}"#,
673        );
674        publisher.accept_registry(
675            Registry::from_json(&remapped).expect("remapped registry should parse"),
676            "remapped",
677        );
678
679        let mut meta = FastHashMap::default();
680        meta.insert(MetaString::from("span.kind"), MetaString::from("client"));
681        meta.insert(MetaString::from("custom.remote.service"), MetaString::from("billing"));
682        let span = make_top_level_span(
683            align_ts(now, BUCKET_DURATION_NS),
684            1,
685            100,
686            0,
687            "svc",
688            "resource",
689            0,
690            Some(meta),
691        );
692        control
693            .send_event(Event::Trace(Trace::new(vec![span], TraceIngestInfo::Datadog)))
694            .await;
695
696        // Closing the input makes the run loop flush and stop.
697        control.shutdown().await.expect("run should succeed");
698
699        let mut peer_tags = Vec::new();
700        for event in outputs.default_output().collect_events().await {
701            let Event::TraceStats(stats) = event else { continue };
702            for payload in stats.stats() {
703                for bucket in payload.stats() {
704                    for grouped in bucket.stats() {
705                        peer_tags.extend(grouped.peer_tags().iter().map(|tag| tag.to_string()));
706                    }
707                }
708            }
709        }
710        assert_eq!(peer_tags, ["custom.remote.service:billing"]);
711    }
712
713    #[tokio::test]
714    async fn traces_without_an_env_aggregate_under_the_agent_env() {
715        let agent_env = AgentEnv::resolve(None, Some("Prod"), &[], &[]);
716        let config = stats_configuration(agent_env);
717        let (control, mut outputs) = TestComponentDriver::transform(config)
718            .await
719            .expect("the transform should start");
720
721        let span = make_top_level_span(
722            align_ts(now_nanos(), BUCKET_DURATION_NS),
723            1,
724            100,
725            0,
726            "svc",
727            "resource",
728            0,
729            None,
730        );
731        control
732            .send_event(Event::Trace(Trace::new(vec![span], TraceIngestInfo::Datadog)))
733            .await;
734        // Shutting down flushes every bucket.
735        control.shutdown().await.expect("the transform should stop cleanly");
736
737        let mut envs = Vec::new();
738        for event in outputs.default_output().collect_events().await {
739            let Event::TraceStats(stats) = event else {
740                panic!("unexpected event: {event:?}");
741            };
742            envs.extend(stats.stats().iter().map(|payload| payload.env().to_string()));
743        }
744        assert_eq!(envs, ["prod"]);
745    }
746
747    #[test]
748    fn test_process_trace_creates_stats() {
749        let now = now_nanos();
750
751        let concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
752        let mut transform = ApmStats {
753            concentrator,
754            flush_interval: DEFAULT_FLUSH_INTERVAL,
755            agent_env: MetaString::from("none"),
756            agent_hostname: MetaString::default(),
757            workload_provider: None,
758            splits: Counter::noop(),
759            future_clamps: Counter::noop(),
760        };
761
762        let span = make_test_span("test-service", "test-operation", "test-resource");
763        let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
764
765        transform.process_trace(&trace);
766
767        // Flush and verify we got stats
768        let stats = transform.concentrator.flush(now + BUCKET_DURATION_NS * 2, true);
769        assert!(!stats.is_empty(), "Expected stats to be produced");
770    }
771
772    #[test]
773    fn test_weight_applied_to_stats() {
774        let now = now_nanos();
775
776        let concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
777        let mut transform = ApmStats {
778            concentrator,
779            flush_interval: DEFAULT_FLUSH_INTERVAL,
780            agent_env: MetaString::from("none"),
781            agent_hostname: MetaString::default(),
782            workload_provider: None,
783            splits: Counter::noop(),
784            future_clamps: Counter::noop(),
785        };
786
787        // Create a span with 0.5 sample rate (weight = 2.0)
788        let mut attrs = FastHashMap::default();
789        attrs.insert(MetaString::from("_dd.measured"), AttributeValue::Float(1.0));
790        attrs.insert(MetaString::from("_sample_rate"), AttributeValue::Float(0.5));
791
792        let span = Span::new(
793            "test-service",
794            "test-op",
795            "test-resource",
796            "web",
797            1,
798            0,
799            now,
800            100000000,
801            0,
802        )
803        .with_attributes(attrs);
804
805        let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
806        transform.process_trace(&trace);
807
808        let stats = transform.concentrator.flush(now + BUCKET_DURATION_NS * 2, true);
809        assert!(!stats.is_empty());
810
811        // The hits should be weighted (approximately 2 due to 0.5 sample rate)
812        let bucket = &stats[0].stats()[0];
813        let grouped = &bucket.stats()[0];
814        // With stochastic rounding, hits could be 1 or 2, but with weight 2.0 it should round to 2
815        assert!(grouped.hits() >= 1, "Expected weighted hits");
816    }
817
818    #[test]
819    fn test_force_flush() {
820        let now = now_nanos();
821        let aligned_now = align_ts(now, BUCKET_DURATION_NS);
822
823        let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
824
825        // Add a span
826        let span = make_top_level_span(aligned_now, 1, 50, 5, "A1", "resource1", 0, None);
827        let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
828
829        let payload_key = PayloadAggregationKey {
830            env: MetaString::from("test"),
831            hostname: MetaString::from("host"),
832            ..Default::default()
833        };
834        let infra_tags = InfraTags::default();
835
836        for span in trace.spans() {
837            if let Some(stat_span) = concentrator.new_stat_span_from_span(span) {
838                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
839            }
840        }
841
842        // ts=0 so that flush always considers buckets not old enough
843        let ts: u64 = 0;
844
845        // Without force flush, should skip the bucket
846        let stats = concentrator.flush(ts, false);
847        assert!(stats.is_empty(), "Non-force flush should return empty");
848
849        // With force flush, should flush buckets regardless of age
850        let stats = concentrator.flush(ts, true);
851        assert!(!stats.is_empty(), "Force flush should return stats");
852        assert_eq!(stats[0].stats().len(), 1, "Should have 1 bucket");
853    }
854
855    #[test]
856    fn test_ignores_partial_spans() {
857        let now = now_nanos();
858        let aligned_now = align_ts(now, BUCKET_DURATION_NS);
859
860        let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
861
862        // Create a partial span (has _dd.partial_version metric)
863        let mut metrics = FastHashMap::default();
864        metrics.insert(MetaString::from("_top_level"), 1.0);
865        metrics.insert(MetaString::from(METRIC_PARTIAL_VERSION), 830604.0);
866
867        let span = test_span(aligned_now, 1, 0, 50, 5, "A1", "resource1", 0, None, Some(metrics));
868        let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
869
870        let payload_key = PayloadAggregationKey {
871            env: MetaString::from("test"),
872            hostname: MetaString::from("tracer-hostname"),
873            ..Default::default()
874        };
875        let infra_tags = InfraTags::default();
876
877        for span in trace.spans() {
878            if let Some(stat_span) = concentrator.new_stat_span_from_span(span) {
879                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
880            }
881        }
882
883        // Partial spans should be ignored
884        let stats = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
885        assert!(stats.is_empty(), "Partial spans should be ignored");
886    }
887
888    #[test]
889    fn test_concentrator_stats_totals() {
890        let now = now_nanos();
891        let aligned_now = align_ts(now, BUCKET_DURATION_NS);
892
893        // Set oldestTs to allow old buckets
894        let oldest_ts = aligned_now - 2 * BUCKET_DURATION_NS;
895        let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), oldest_ts);
896
897        // Build spans spread over time windows
898        let spans = vec![
899            make_top_level_span(aligned_now, 1, 50, 5, "A1", "resource1", 0, None),
900            make_top_level_span(aligned_now, 2, 40, 4, "A1", "resource1", 0, None),
901            make_top_level_span(aligned_now, 3, 30, 3, "A1", "resource1", 0, None),
902            make_top_level_span(aligned_now, 4, 20, 2, "A1", "resource1", 0, None),
903            make_top_level_span(aligned_now, 5, 10, 1, "A1", "resource1", 0, None),
904            make_top_level_span(aligned_now, 6, 1, 0, "A1", "resource1", 0, None),
905        ];
906
907        let payload_key = PayloadAggregationKey {
908            env: MetaString::from("none"),
909            ..Default::default()
910        };
911        let infra_tags = InfraTags::default();
912
913        for span in &spans {
914            if let Some(stat_span) = concentrator.new_stat_span_from_span(span) {
915                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
916            }
917        }
918
919        // Flush all and collect totals
920        let all_stats = concentrator.flush(now + BUCKET_DURATION_NS * 10, true);
921
922        let mut total_duration: u64 = 0;
923        let mut total_hits: u64 = 0;
924        let mut total_errors: u64 = 0;
925        let mut total_top_level_hits: u64 = 0;
926
927        for payload in &all_stats {
928            for bucket in payload.stats() {
929                for grouped in bucket.stats() {
930                    total_duration += grouped.duration();
931                    total_hits += grouped.hits();
932                    total_errors += grouped.errors();
933                    total_top_level_hits += grouped.top_level_hits();
934                }
935            }
936        }
937
938        assert_eq!(total_duration, 50 + 40 + 30 + 20 + 10 + 1, "Wrong total duration");
939        assert_eq!(total_hits, 6, "Wrong total hits");
940        assert_eq!(total_top_level_hits, 6, "Wrong total top level hits");
941        assert_eq!(total_errors, 0, "Wrong total errors");
942    }
943
944    #[test]
945    fn test_root_tag() {
946        let now = now_nanos();
947        let aligned_now = align_ts(now, BUCKET_DURATION_NS);
948
949        let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
950
951        // Root span (parent_id = 0, top_level)
952        let mut root_metrics = FastHashMap::default();
953        root_metrics.insert(MetaString::from("_top_level"), 1.0);
954        let root_span = test_span(
955            aligned_now,
956            1,
957            0,
958            40,
959            10,
960            "A1",
961            "resource1",
962            0,
963            None,
964            Some(root_metrics),
965        );
966
967        // Non-root but top level span (has _top_level but parent_id != 0)
968        let mut top_level_metrics = FastHashMap::default();
969        top_level_metrics.insert(MetaString::from("_top_level"), 1.0);
970        let top_level_span = test_span(
971            aligned_now,
972            4,
973            1000,
974            10,
975            10,
976            "A1",
977            "resource1",
978            0,
979            None,
980            Some(top_level_metrics),
981        );
982
983        // Client span (non-root, non-top level, but has span.kind = client)
984        let mut client_meta = FastHashMap::default();
985        client_meta.insert(MetaString::from("span.kind"), MetaString::from("client"));
986        let client_span = test_span(aligned_now, 3, 2, 20, 10, "A1", "resource1", 0, Some(client_meta), None);
987
988        let spans = vec![root_span, top_level_span, client_span];
989
990        let payload_key = PayloadAggregationKey {
991            env: MetaString::from("none"),
992            ..Default::default()
993        };
994        let infra_tags = InfraTags::default();
995
996        for span in &spans {
997            if let Some(stat_span) = concentrator.new_stat_span_from_span(span) {
998                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
999            }
1000        }
1001
1002        let stats = concentrator.flush(now + BUCKET_DURATION_NS * 20, true);
1003        assert!(!stats.is_empty(), "Should have stats");
1004
1005        // Count grouped stats - should be split by IsTraceRoot
1006        let mut total_grouped = 0;
1007        let mut root_count = 0;
1008        let mut non_root_count = 0;
1009
1010        for payload in &stats {
1011            for bucket in payload.stats() {
1012                for grouped in bucket.stats() {
1013                    total_grouped += 1;
1014                    match grouped.is_trace_root() {
1015                        Some(true) => root_count += 1,
1016                        Some(false) => non_root_count += 1,
1017                        None => {}
1018                    }
1019                }
1020            }
1021        }
1022
1023        // We expect 3 grouped stats:
1024        // 1. Root span (is_trace_root = true)
1025        // 2. Non-root top-level span (is_trace_root = false)
1026        // 3. Client span (is_trace_root = false, span.kind = client)
1027        assert_eq!(total_grouped, 3, "Expected 3 grouped stats");
1028        assert_eq!(root_count, 1, "Expected 1 root span");
1029        assert_eq!(non_root_count, 2, "Expected 2 non-root spans");
1030    }
1031
1032    #[test]
1033    fn test_compute_stats_through_span_kind_check() {
1034        let now = now_nanos();
1035
1036        // Test with compute_stats_by_span_kind DISABLED
1037        {
1038            let mut concentrator = SpanConcentrator::new(false, true, &[], Default::default(), now);
1039
1040            let mut attrs = FastHashMap::default();
1041            attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
1042            let span = Span::new("myservice", "query", "GET /users", "web", 1, 0, now, 500, 0).with_attributes(attrs);
1043
1044            let payload_key = PayloadAggregationKey {
1045                env: MetaString::from("test"),
1046                ..Default::default()
1047            };
1048            let infra_tags = InfraTags::default();
1049
1050            if let Some(stat_span) = concentrator.new_stat_span_from_span(&span) {
1051                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1052            }
1053
1054            // Client span with span.kind=client but no _top_level or _dd.measured
1055            // Should NOT produce stats when compute_stats_by_span_kind is disabled
1056            let mut client_attrs = FastHashMap::default();
1057            client_attrs.insert(
1058                MetaString::from("span.kind"),
1059                AttributeValue::String(MetaString::from("client")),
1060            );
1061            let client_span = Span::new("myservice", "postgres.query", "SELECT ...", "db", 2, 1, now, 75, 0)
1062                .with_attributes(client_attrs);
1063
1064            if let Some(stat_span) = concentrator.new_stat_span_from_span(&client_span) {
1065                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1066            }
1067
1068            let stats = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
1069
1070            let mut count = 0;
1071            for payload in &stats {
1072                for bucket in payload.stats() {
1073                    count += bucket.stats().len();
1074                }
1075            }
1076
1077            // When disabled, only top_level span gets stats (client span has no top_level/measured)
1078            assert_eq!(count, 1, "Expected 1 stat when span kind check disabled");
1079        }
1080
1081        // Test with compute_stats_by_span_kind ENABLED
1082        {
1083            let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
1084
1085            let mut attrs = FastHashMap::default();
1086            attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
1087            let span = Span::new("myservice", "query", "GET /users", "web", 1, 0, now, 500, 0).with_attributes(attrs);
1088
1089            let payload_key = PayloadAggregationKey {
1090                env: MetaString::from("test"),
1091                ..Default::default()
1092            };
1093            let infra_tags = InfraTags::default();
1094
1095            if let Some(stat_span) = concentrator.new_stat_span_from_span(&span) {
1096                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1097            }
1098
1099            // Client span with span.kind=client
1100            // SHOULD produce stats when compute_stats_by_span_kind is enabled
1101            let mut client_attrs = FastHashMap::default();
1102            client_attrs.insert(
1103                MetaString::from("span.kind"),
1104                AttributeValue::String(MetaString::from("client")),
1105            );
1106            let client_span = Span::new("myservice", "postgres.query", "SELECT ...", "db", 2, 1, now, 75, 0)
1107                .with_attributes(client_attrs);
1108
1109            if let Some(stat_span) = concentrator.new_stat_span_from_span(&client_span) {
1110                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1111            }
1112
1113            let stats = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
1114
1115            let mut count = 0;
1116            for payload in &stats {
1117                for bucket in payload.stats() {
1118                    count += bucket.stats().len();
1119                }
1120            }
1121
1122            // When enabled, both spans get stats
1123            assert_eq!(count, 2, "Expected 2 stats when span kind check enabled");
1124        }
1125    }
1126
1127    #[test]
1128    fn test_peer_tags() {
1129        let now = now_nanos();
1130
1131        // Test without peer tags aggregation enabled
1132        {
1133            let mut concentrator = SpanConcentrator::new(true, false, &[], Default::default(), now);
1134
1135            let mut attrs = FastHashMap::default();
1136            attrs.insert(
1137                MetaString::from("span.kind"),
1138                AttributeValue::String(MetaString::from("client")),
1139            );
1140            attrs.insert(
1141                MetaString::from("db.instance"),
1142                AttributeValue::String(MetaString::from("i-1234")),
1143            );
1144            attrs.insert(
1145                MetaString::from("db.system"),
1146                AttributeValue::String(MetaString::from("postgres")),
1147            );
1148            attrs.insert(MetaString::from("_dd.measured"), AttributeValue::Float(1.0));
1149            let client_span =
1150                Span::new("myservice", "postgres.query", "SELECT ...", "db", 2, 1, now, 75, 0).with_attributes(attrs);
1151
1152            let payload_key = PayloadAggregationKey {
1153                env: MetaString::from("test"),
1154                ..Default::default()
1155            };
1156            let infra_tags = InfraTags::default();
1157
1158            if let Some(stat_span) = concentrator.new_stat_span_from_span(&client_span) {
1159                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1160            }
1161
1162            let stats = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
1163
1164            // Without peer tags aggregation, peer_tags should be empty
1165            for payload in &stats {
1166                for bucket in payload.stats() {
1167                    for grouped in bucket.stats() {
1168                        assert!(
1169                            grouped.peer_tags().is_empty(),
1170                            "Peer tags should be empty when peer_tags_aggregation is false"
1171                        );
1172                    }
1173                }
1174            }
1175        }
1176
1177        // Test with peer tags aggregation enabled
1178        {
1179            // Note: BASE_PEER_TAGS already includes db.instance and db.system
1180            let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
1181
1182            let mut attrs = FastHashMap::default();
1183            attrs.insert(
1184                MetaString::from("span.kind"),
1185                AttributeValue::String(MetaString::from("client")),
1186            );
1187            attrs.insert(
1188                MetaString::from("db.instance"),
1189                AttributeValue::String(MetaString::from("i-1234")),
1190            );
1191            attrs.insert(
1192                MetaString::from("db.system"),
1193                AttributeValue::String(MetaString::from("postgres")),
1194            );
1195            attrs.insert(MetaString::from("_dd.measured"), AttributeValue::Float(1.0));
1196            let client_span =
1197                Span::new("myservice", "postgres.query", "SELECT ...", "db", 2, 1, now, 75, 0).with_attributes(attrs);
1198
1199            let payload_key = PayloadAggregationKey {
1200                env: MetaString::from("test"),
1201                ..Default::default()
1202            };
1203            let infra_tags = InfraTags::default();
1204
1205            if let Some(stat_span) = concentrator.new_stat_span_from_span(&client_span) {
1206                concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1207            }
1208
1209            let stats = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
1210
1211            // With peer tags aggregation, client span should have peer_tags
1212            let mut found_client_with_peer_tags = false;
1213            for payload in &stats {
1214                for bucket in payload.stats() {
1215                    for grouped in bucket.stats() {
1216                        if grouped.resource() == "SELECT ..." {
1217                            assert!(!grouped.peer_tags().is_empty(), "Client span should have peer tags");
1218                            // Check that peer tags contain db.instance and db.system
1219                            let peer_tags: Vec<&str> = grouped.peer_tags().iter().map(|s| s.as_ref()).collect();
1220                            assert!(
1221                                peer_tags.iter().any(|t| t.starts_with("db.instance:")),
1222                                "Should have db.instance peer tag"
1223                            );
1224                            assert!(
1225                                peer_tags.iter().any(|t| t.starts_with("db.system:")),
1226                                "Should have db.system peer tag"
1227                            );
1228                            found_client_with_peer_tags = true;
1229                        }
1230                    }
1231                }
1232            }
1233            assert!(
1234                found_client_with_peer_tags,
1235                "Should have found client span with peer tags"
1236            );
1237        }
1238    }
1239
1240    #[test]
1241    fn test_concentrator_oldest_ts() {
1242        let now = now_nanos();
1243        let aligned_now = align_ts(now, BUCKET_DURATION_NS);
1244
1245        // Test "cold" scenario - all spans in the past should end up in current bucket
1246        {
1247            // Start concentrator at current time (cold start)
1248            let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
1249
1250            // Build spans spread over many time windows (all in the past)
1251            let spans = vec![
1252                make_top_level_span(aligned_now, 1, 50, 5, "A1", "resource1", 0, None),
1253                make_top_level_span(aligned_now, 2, 40, 4, "A1", "resource1", 0, None),
1254                make_top_level_span(aligned_now, 3, 30, 3, "A1", "resource1", 0, None),
1255                make_top_level_span(aligned_now, 4, 20, 2, "A1", "resource1", 0, None),
1256                make_top_level_span(aligned_now, 5, 10, 1, "A1", "resource1", 0, None),
1257                make_top_level_span(aligned_now, 6, 1, 0, "A1", "resource1", 0, None),
1258            ];
1259
1260            let payload_key = PayloadAggregationKey {
1261                env: MetaString::from("none"),
1262                ..Default::default()
1263            };
1264            let infra_tags = InfraTags::default();
1265
1266            for span in &spans {
1267                if let Some(stat_span) = concentrator.new_stat_span_from_span(span) {
1268                    concentrator.add_span(&stat_span, 1.0, &payload_key, &infra_tags, "", now);
1269                }
1270            }
1271
1272            // Flush multiple times without force
1273            let mut flush_time = now;
1274            let buffer_len = 2; // DEFAULT_BUFFER_LEN
1275
1276            for _ in 0..buffer_len {
1277                let stats = concentrator.flush(flush_time, false);
1278                assert!(stats.is_empty(), "Should not flush before buffer fills");
1279                flush_time += BUCKET_DURATION_NS;
1280            }
1281
1282            // After buffer_len flushes, should get aggregated stats
1283            let stats = concentrator.flush(flush_time, false);
1284            assert!(!stats.is_empty(), "Should flush after buffer fills");
1285
1286            // All spans should be aggregated into one bucket (oldest bucket aggregates old data)
1287            let mut total_hits: u64 = 0;
1288            let mut total_duration: u64 = 0;
1289            for payload in &stats {
1290                for bucket in payload.stats() {
1291                    for grouped in bucket.stats() {
1292                        total_hits += grouped.hits();
1293                        total_duration += grouped.duration();
1294                    }
1295                }
1296            }
1297
1298            assert_eq!(total_hits, 6, "All 6 spans should be counted");
1299            assert_eq!(
1300                total_duration,
1301                50 + 40 + 30 + 20 + 10 + 1,
1302                "Total duration should match"
1303            );
1304        }
1305    }
1306
1307    #[test]
1308    fn test_compute_stats_for_span_kind() {
1309        use super::span_concentrator::compute_stats_for_span_kind;
1310
1311        // Valid span kinds (case insensitive)
1312        assert!(compute_stats_for_span_kind("server"));
1313        assert!(compute_stats_for_span_kind("consumer"));
1314        assert!(compute_stats_for_span_kind("client"));
1315        assert!(compute_stats_for_span_kind("producer"));
1316
1317        // Uppercase
1318        assert!(compute_stats_for_span_kind("SERVER"));
1319        assert!(compute_stats_for_span_kind("CONSUMER"));
1320        assert!(compute_stats_for_span_kind("CLIENT"));
1321        assert!(compute_stats_for_span_kind("PRODUCER"));
1322
1323        // Mixed case
1324        assert!(compute_stats_for_span_kind("SErVER"));
1325        assert!(compute_stats_for_span_kind("COnSUMER"));
1326        assert!(compute_stats_for_span_kind("CLiENT"));
1327        assert!(compute_stats_for_span_kind("PRoDUCER"));
1328
1329        // Invalid span kinds
1330        assert!(!compute_stats_for_span_kind("internal"));
1331        assert!(!compute_stats_for_span_kind("INTERNAL"));
1332        assert!(!compute_stats_for_span_kind("INtERNAL"));
1333        assert!(!compute_stats_for_span_kind(""));
1334    }
1335
1336    #[test]
1337    fn test_extract_process_tags() {
1338        // Test with no process tags
1339        {
1340            let span = Span::default();
1341            let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1342            let process_tags = extract_process_tags(&trace);
1343            assert!(process_tags.is_empty(), "Should be empty when no _dd.tags.process");
1344        }
1345
1346        // Test with process tags in first span meta
1347        {
1348            let mut attrs = FastHashMap::default();
1349            attrs.insert(
1350                MetaString::from(TAG_PROCESS_TAGS),
1351                AttributeValue::String(MetaString::from("a:1,b:2,c:3")),
1352            );
1353            let span = Span::default().with_attributes(attrs);
1354            let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1355            let process_tags = extract_process_tags(&trace);
1356            assert_eq!(process_tags, "a:1,b:2,c:3");
1357        }
1358
1359        // Test with empty process tags
1360        {
1361            let mut attrs = FastHashMap::default();
1362            attrs.insert(
1363                MetaString::from(TAG_PROCESS_TAGS),
1364                AttributeValue::String(MetaString::from("")),
1365            );
1366            let span = Span::default().with_attributes(attrs);
1367            let trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1368            let process_tags = extract_process_tags(&trace);
1369            assert!(
1370                process_tags.is_empty(),
1371                "Should be empty when _dd.tags.process is empty string"
1372            );
1373        }
1374
1375        // Test with empty trace
1376        {
1377            let trace = Trace::new(vec![], TraceIngestInfo::Datadog);
1378            let process_tags = extract_process_tags(&trace);
1379            assert!(process_tags.is_empty(), "Should be empty when trace has no spans");
1380        }
1381    }
1382
1383    #[test]
1384    fn test_process_tags_hash_computation() {
1385        use super::aggregation::process_tags_hash;
1386
1387        // Empty string should return 0
1388        assert_eq!(process_tags_hash(""), 0);
1389
1390        // Same tags should produce same hash
1391        let hash1 = process_tags_hash("a:1,b:2,c:3");
1392        let hash2 = process_tags_hash("a:1,b:2,c:3");
1393        assert_eq!(hash1, hash2);
1394
1395        // Different tags should produce different hash
1396        let hash3 = process_tags_hash("a:1,b:2");
1397        assert_ne!(hash1, hash3);
1398    }
1399
1400    // Helper to create a ClientGroupedStats for testing
1401    fn make_grouped_stats(service: &str, resource: &str) -> ClientGroupedStats {
1402        ClientGroupedStats::new(service, "operation", resource)
1403            .with_hits(1)
1404            .with_duration(100)
1405    }
1406
1407    // Helper to create a ClientStatsBucket with N stats
1408    fn make_bucket_with_stats(n: usize) -> ClientStatsBucket {
1409        let stats: Vec<ClientGroupedStats> = (0..n)
1410            .map(|i| make_grouped_stats("service", &format!("resource-{}", i)))
1411            .collect();
1412        ClientStatsBucket::new(1000, 10_000_000_000, stats)
1413    }
1414
1415    // Helper to create a ClientStatsPayload with specified buckets
1416    fn make_payload_with_buckets(hostname: &str, buckets: Vec<ClientStatsBucket>) -> ClientStatsPayload {
1417        ClientStatsPayload::new(hostname, "test-env", "1.0.0")
1418            .with_stats(buckets)
1419            .with_container_id("container-123")
1420            .with_lang("rust")
1421    }
1422
1423    // Helper to count total ClientGroupedStats across all payloads in a TraceStats
1424    fn count_grouped_stats(trace_stats: &TraceStats) -> usize {
1425        trace_stats
1426            .stats()
1427            .iter()
1428            .flat_map(|p| p.stats())
1429            .map(|b| b.stats().len())
1430            .sum()
1431    }
1432
1433    #[test]
1434    fn test_split_into_trace_stats_empty_input() {
1435        let result = split_into_trace_stats(vec![], 100);
1436        assert!(result.is_empty());
1437    }
1438
1439    #[test]
1440    fn test_split_into_trace_stats_no_split_needed() {
1441        // 50 stats with max 100 - no split needed
1442        let bucket = make_bucket_with_stats(50);
1443        let payload = make_payload_with_buckets("host1", vec![bucket]);
1444
1445        let result = split_into_trace_stats(vec![payload], 100);
1446
1447        assert_eq!(result.len(), 1);
1448        assert_eq!(count_grouped_stats(&result[0]), 50);
1449    }
1450
1451    #[test]
1452    fn test_split_into_trace_stats_exact_threshold() {
1453        // Exactly 100 stats with max 100 - no split needed
1454        let bucket = make_bucket_with_stats(100);
1455        let payload = make_payload_with_buckets("host1", vec![bucket]);
1456
1457        let result = split_into_trace_stats(vec![payload], 100);
1458
1459        assert_eq!(result.len(), 1);
1460        assert_eq!(count_grouped_stats(&result[0]), 100);
1461    }
1462
1463    #[test]
1464    fn test_split_into_trace_stats_splits_single_bucket() {
1465        // 250 stats in one bucket with max 100 - should split into 3 evenly sized TraceStats
1466        let bucket = make_bucket_with_stats(250);
1467        let payload = make_payload_with_buckets("host1", vec![bucket]);
1468
1469        let result = split_into_trace_stats(vec![payload], 100);
1470
1471        assert_eq!(result.len(), 3);
1472        assert_eq!(count_grouped_stats(&result[0]), 84);
1473        assert_eq!(count_grouped_stats(&result[1]), 83);
1474        assert_eq!(count_grouped_stats(&result[2]), 83);
1475
1476        // Total should be preserved
1477        let total: usize = result.iter().map(count_grouped_stats).sum();
1478        assert_eq!(total, 250);
1479    }
1480
1481    #[test]
1482    fn test_split_into_trace_stats_splits_across_payloads() {
1483        // Two payloads with 60 stats each, max 100 - each payload stays whole, so we get 2 TraceStats
1484        let payload1 = make_payload_with_buckets("host1", vec![make_bucket_with_stats(60)]);
1485        let payload2 = make_payload_with_buckets("host2", vec![make_bucket_with_stats(60)]);
1486
1487        let result = split_into_trace_stats(vec![payload1, payload2], 100);
1488
1489        assert_eq!(result.len(), 2);
1490        assert_eq!(count_grouped_stats(&result[0]), 60);
1491        assert_eq!(count_grouped_stats(&result[1]), 60);
1492    }
1493
1494    #[test]
1495    fn test_split_into_trace_stats_splits_single_payload_multiple_buckets() {
1496        // One payload with two buckets (70 + 80 = 150 stats), max 100
1497        let bucket1 = make_bucket_with_stats(70);
1498        let bucket2 = make_bucket_with_stats(80);
1499        let payload = make_payload_with_buckets("host1", vec![bucket1, bucket2]);
1500
1501        let result = split_into_trace_stats(vec![payload], 100);
1502
1503        assert_eq!(result.len(), 2);
1504        let total: usize = result.iter().map(count_grouped_stats).sum();
1505        assert_eq!(total, 150);
1506    }
1507
1508    #[test]
1509    fn test_split_into_trace_stats_preserves_metadata() {
1510        let bucket = make_bucket_with_stats(250);
1511        let payload = ClientStatsPayload::new("test-host", "prod", "2.0.0")
1512            .with_stats(vec![bucket])
1513            .with_container_id("container-abc")
1514            .with_lang("go")
1515            .with_git_commit_sha("abc123")
1516            .with_image_tag("v1.2.3")
1517            .with_process_tags_hash(12345)
1518            .with_process_tags("tag1,tag2");
1519
1520        let result = split_into_trace_stats(vec![payload], 100);
1521
1522        // All split payloads should have the same metadata
1523        for trace_stats in &result {
1524            for p in trace_stats.stats() {
1525                assert_eq!(p.hostname(), "test-host");
1526                assert_eq!(p.env(), "prod");
1527                assert_eq!(p.version(), "2.0.0");
1528                assert_eq!(p.container_id(), "container-abc");
1529                assert_eq!(p.lang(), "go");
1530                assert_eq!(p.git_commit_sha(), "abc123");
1531                assert_eq!(p.image_tag(), "v1.2.3");
1532                assert_eq!(p.process_tags_hash(), 12345);
1533                assert_eq!(p.process_tags(), "tag1,tag2");
1534            }
1535        }
1536    }
1537
1538    #[test]
1539    fn test_split_into_trace_stats_preserves_bucket_metadata() {
1540        // Create a bucket with specific start/duration/time_shift
1541        let stats: Vec<ClientGroupedStats> = (0..150)
1542            .map(|i| make_grouped_stats("svc", &format!("res-{}", i)))
1543            .collect();
1544        let bucket = ClientStatsBucket::new(999_000_000, 10_000_000_000, stats).with_agent_time_shift(42);
1545        let payload = make_payload_with_buckets("host1", vec![bucket]);
1546
1547        let result = split_into_trace_stats(vec![payload], 100);
1548
1549        // All split buckets should have the same start/duration/time_shift
1550        for trace_stats in &result {
1551            for p in trace_stats.stats() {
1552                for b in p.stats() {
1553                    assert_eq!(b.start(), 999_000_000);
1554                    assert_eq!(b.duration(), 10_000_000_000);
1555                    assert_eq!(b.agent_time_shift(), 42);
1556                }
1557            }
1558        }
1559    }
1560
1561    #[test]
1562    fn test_split_into_trace_stats_handles_empty_bucket() {
1563        let empty_bucket = ClientStatsBucket::new(1000, 10_000_000_000, vec![]);
1564        let payload = make_payload_with_buckets("host1", vec![empty_bucket]);
1565
1566        let result = split_into_trace_stats(vec![payload], 100);
1567
1568        assert_eq!(result.len(), 1);
1569        assert_eq!(count_grouped_stats(&result[0]), 0);
1570    }
1571
1572    #[test]
1573    fn test_split_into_trace_stats_large_split() {
1574        // 10,000 stats with max 4000 - should produce 3 evenly sized TraceStats
1575        let bucket = make_bucket_with_stats(10_000);
1576        let payload = make_payload_with_buckets("host1", vec![bucket]);
1577
1578        let result = split_into_trace_stats(vec![payload], 4000);
1579
1580        assert_eq!(result.len(), 3);
1581        assert_eq!(count_grouped_stats(&result[0]), 3334);
1582        assert_eq!(count_grouped_stats(&result[1]), 3333);
1583        assert_eq!(count_grouped_stats(&result[2]), 3333);
1584    }
1585
1586    #[test]
1587    fn split_flushed_stats_counts_one_split_per_split_flush() {
1588        let recorder = TestRecorder::default();
1589        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
1590        let now = now_nanos();
1591        let transform = ApmStats {
1592            concentrator: SpanConcentrator::new(true, true, &[], Default::default(), now),
1593            flush_interval: DEFAULT_FLUSH_INTERVAL,
1594            agent_env: MetaString::default(),
1595            agent_hostname: MetaString::default(),
1596            workload_provider: None,
1597            splits: MetricsBuilder::default().register_counter("component_stats_splits_total"),
1598            future_clamps: Counter::noop(),
1599        };
1600        let flush = |groups: usize| vec![make_payload_with_buckets("host1", vec![make_bucket_with_stats(groups)])];
1601
1602        // A flush that fits in one event is not a split.
1603        assert_eq!(
1604            transform.split_flushed_stats(flush(MAX_STATS_GROUPS_PER_EVENT)).len(),
1605            1
1606        );
1607        assert_eq!(recorder.counter("component_stats_splits_total"), Some(0));
1608
1609        // A flush is counted once however many events it splits into.
1610        assert_eq!(transform.split_flushed_stats(flush(9000)).len(), 3);
1611        assert_eq!(transform.split_flushed_stats(flush(4001)).len(), 2);
1612        assert_eq!(recorder.counter("component_stats_splits_total"), Some(2));
1613    }
1614
1615    #[test]
1616    fn split_into_trace_stats_marks_and_balances_by_group_count() {
1617        // The sizes the backend sees for a single client payload, using the production limit.
1618        let cases: [(usize, &[usize]); 4] = [
1619            (1, &[1]),
1620            (4000, &[4000]),
1621            (4001, &[2001, 2000]),
1622            (9000, &[3000, 3000, 3000]),
1623        ];
1624        for (groups, expected) in cases {
1625            let payload = make_payload_with_buckets("host1", vec![make_bucket_with_stats(groups)]);
1626
1627            let result = split_into_trace_stats(vec![payload], MAX_STATS_GROUPS_PER_EVENT);
1628
1629            let sizes: Vec<usize> = result.iter().map(count_grouped_stats).collect();
1630            assert_eq!(sizes, expected, "unexpected event sizes for {groups} groups");
1631            for event in &result {
1632                assert_eq!(
1633                    event.is_split_payload(),
1634                    expected.len() > 1,
1635                    "split flag for {groups} groups"
1636                );
1637            }
1638        }
1639    }
1640
1641    #[test]
1642    fn split_into_trace_stats_balances_entries_with_one_bucket_per_window() {
1643        // 15 entries over three buckets of the same time window, max 12: two events of 8 and 7 entries, each with a
1644        // single client payload holding a single bucket.
1645        let buckets = vec![
1646            make_bucket_with_stats(5),
1647            make_bucket_with_stats(5),
1648            make_bucket_with_stats(5),
1649        ];
1650        let payload = make_payload_with_buckets("host1", buckets);
1651
1652        let result = split_into_trace_stats(vec![payload.clone()], 12);
1653
1654        assert_eq!(result.len(), 2);
1655        for (event, expected_entries) in result.iter().zip([8, 7]) {
1656            assert!(event.is_split_payload());
1657            assert_eq!(event.stats().len(), 1);
1658            assert_eq!(event.stats()[0].stats().len(), 1);
1659            assert_eq!(count_grouped_stats(event), expected_entries);
1660
1661            let metadata_only = event.stats()[0].clone().with_stats(Vec::new());
1662            assert_eq!(metadata_only, payload.clone().with_stats(Vec::new()));
1663        }
1664    }
1665
1666    #[test]
1667    fn split_into_trace_stats_keeps_one_bucket_per_window_for_each_split_payload() {
1668        // Two windows of 300 entries each, max 400: two split payloads, each holding one bucket for each window.
1669        let window_a = ClientStatsBucket::new(
1670            1000,
1671            10,
1672            (0..300).map(|i| make_grouped_stats("a", &i.to_string())).collect(),
1673        );
1674        let window_b = ClientStatsBucket::new(
1675            2000,
1676            10,
1677            (0..300).map(|i| make_grouped_stats("b", &i.to_string())).collect(),
1678        );
1679        let payload = make_payload_with_buckets("host1", vec![window_a, window_b]);
1680
1681        let result = split_into_trace_stats(vec![payload], 400);
1682
1683        assert_eq!(result.len(), 2);
1684        for event in &result {
1685            assert_eq!(event.stats().len(), 1);
1686            let windows: Vec<(u64, u64)> = event.stats()[0]
1687                .stats()
1688                .iter()
1689                .map(|b| (b.start(), b.duration()))
1690                .collect();
1691            assert_eq!(windows, [(1000, 10), (2000, 10)]);
1692            assert_eq!(count_grouped_stats(event), 300);
1693        }
1694    }
1695
1696    #[test]
1697    fn split_into_trace_stats_no_split_leaves_buckets_and_flag_unset() {
1698        let buckets = vec![
1699            make_bucket_with_stats(5),
1700            make_bucket_with_stats(5),
1701            make_bucket_with_stats(5),
1702        ];
1703        let payload = make_payload_with_buckets("host1", buckets);
1704
1705        let result = split_into_trace_stats(vec![payload], 1337);
1706
1707        assert_eq!(result.len(), 1);
1708        assert!(!result[0].is_split_payload());
1709        let bucket_sizes: Vec<usize> = result[0].stats()[0].stats().iter().map(|b| b.stats().len()).collect();
1710        assert_eq!(bucket_sizes, [5, 5, 5]);
1711    }
1712
1713    // Property test strategies
1714
1715    /// Strategy to generate arbitrary ClientGroupedStats.
1716    fn arb_grouped_stats() -> impl Strategy<Value = ClientGroupedStats> {
1717        (0..100u64, 0..1000u64).prop_map(|(hits, duration)| {
1718            ClientGroupedStats::new("service", "operation", "resource")
1719                .with_hits(hits)
1720                .with_duration(duration)
1721        })
1722    }
1723
1724    /// Strategy to generate a bucket with 0..=max_stats_per_bucket grouped stats.
1725    fn arb_bucket(max_stats_per_bucket: usize) -> impl Strategy<Value = ClientStatsBucket> {
1726        proptest::collection::vec(arb_grouped_stats(), 0..=max_stats_per_bucket)
1727            .prop_map(|stats| ClientStatsBucket::new(1000, 10_000_000_000, stats))
1728    }
1729
1730    /// Strategy to generate a payload with 1..=max_buckets buckets.
1731    fn arb_payload(max_buckets: usize, max_stats_per_bucket: usize) -> impl Strategy<Value = ClientStatsPayload> {
1732        proptest::collection::vec(arb_bucket(max_stats_per_bucket), 1..=max_buckets)
1733            .prop_map(|buckets| ClientStatsPayload::new("host", "env", "1.0.0").with_stats(buckets))
1734    }
1735
1736    /// Strategy to generate test inputs for the split function.
1737    ///
1738    /// Parameters:
1739    /// - `num_payloads`: 1..=10
1740    /// - `num_buckets_per_payload`: 1..=5
1741    /// - `num_stats_per_bucket`: 0..=500
1742    /// - `max_entries_per_event`: 1..=1000 (never zero)
1743    fn arb_split_inputs() -> impl Strategy<Value = (Vec<ClientStatsPayload>, usize)> {
1744        let payloads_strategy = proptest::collection::vec(arb_payload(5, 500), 1..=10);
1745        let max_entries_strategy = 1..=1000usize;
1746
1747        (payloads_strategy, max_entries_strategy)
1748    }
1749
1750    // Mirrors Go agent behavior: for OTLP traces the version on the root span's meta["version"]
1751    // (set with span-over-resource precedence by otel_span_to_dd_span) should win over the
1752    // resource-level version carried in payload.app_version.
1753    // See: pkg/trace/version/version.go:GetAppVersionFromTrace and pkg/trace/api/otlp.go.
1754    #[test]
1755    fn test_version_span_beats_resource_for_otlp() {
1756        let now = now_nanos();
1757        let concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
1758        let transform = ApmStats {
1759            concentrator,
1760            flush_interval: DEFAULT_FLUSH_INTERVAL,
1761            agent_env: MetaString::default(),
1762            agent_hostname: MetaString::default(),
1763            workload_provider: None,
1764            splits: Counter::noop(),
1765            future_clamps: Counter::noop(),
1766        };
1767
1768        // Root span carries a span-level version attribute (set by otel_span_to_dd_span with
1769        // span-over-resource precedence).
1770        let mut attrs = FastHashMap::default();
1771        attrs.insert(
1772            MetaString::from("version"),
1773            AttributeValue::String(MetaString::from("span-v2")),
1774        );
1775        let root_span = Span::new("svc", "op", "res", "web", 1, 0, now, 1_000_000, 0).with_attributes(attrs);
1776
1777        let mut trace = Trace::new(vec![root_span], TraceIngestInfo::Datadog);
1778        // Simulate OTLP resource extraction: payload.app_version comes from resource attrs only.
1779        trace.payload.app_version = MetaString::from("resource-v1");
1780
1781        let key = transform.build_payload_key(&trace, "", ContainerVersionData::default());
1782
1783        // The Go agent resolves version from root_span.meta["version"] first, which carries
1784        // span-over-resource precedence. The span attribute ("span-v2") must win.
1785        assert_eq!(
1786            key.version.as_ref(),
1787            "span-v2",
1788            "span-level version must take precedence over resource-level payload.app_version for OTLP traces"
1789        );
1790    }
1791
1792    // Span conversion extracts no peer tag keys of its own, so a peer tag set only on the OTLP resource reaches span
1793    // meta through the generic resource-attribute loop, and the concentrator reads it from there.
1794    #[test]
1795    fn peer_tag_set_only_on_otlp_resource_reaches_stats() {
1796        use otlp_protos::opentelemetry::proto::common::v1::{any_value::Value, AnyValue, KeyValue};
1797        use otlp_protos::opentelemetry::proto::resource::v1::Resource;
1798        use otlp_protos::opentelemetry::proto::trace::v1::span::SpanKind;
1799        use otlp_protos::opentelemetry::proto::trace::v1::{ResourceSpans, ScopeSpans, Span as OtlpSpan};
1800        use saluki_core::data_model::event::Event;
1801
1802        use crate::common::otlp::origin::OtlpOriginTagResolver;
1803        use crate::common::otlp::traces::translator::{traces_settings, OtlpTracesTranslator};
1804        use crate::common::otlp::Metrics;
1805
1806        let now = now_nanos();
1807        let client_span = OtlpSpan {
1808            trace_id: vec![1; 16],
1809            span_id: vec![2; 8],
1810            name: "SELECT ...".to_string(),
1811            kind: SpanKind::Client as i32,
1812            start_time_unix_nano: now - 1_000_000,
1813            end_time_unix_nano: now,
1814            ..Default::default()
1815        };
1816        let resource_spans = ResourceSpans {
1817            resource: Some(Resource {
1818                attributes: vec![KeyValue {
1819                    key: "db.instance".to_string(),
1820                    value: Some(AnyValue {
1821                        value: Some(Value::StringValue("i-1234".to_string())),
1822                    }),
1823                }],
1824                ..Default::default()
1825            }),
1826            scope_spans: vec![ScopeSpans {
1827                spans: vec![client_span],
1828                ..Default::default()
1829            }],
1830            ..Default::default()
1831        };
1832
1833        let mut translator = OtlpTracesTranslator::new(
1834            traces_settings(),
1835            5000,
1836            SemanticRegistryProvider::default(),
1837            OtlpOriginTagResolver::new(Arc::new(TestWorkloadProvider::new())),
1838        );
1839        let trace = translator
1840            .translate_spans(resource_spans, &Metrics::for_tests())
1841            .find_map(Event::try_into_trace)
1842            .expect("the client span should translate into a trace");
1843        let span = &trace.spans()[0];
1844        assert_eq!(
1845            span.attributes.get("db.instance").and_then(AttributeValue::as_string),
1846            Some(&MetaString::from("i-1234")),
1847            "a resource-only peer tag must reach span meta"
1848        );
1849
1850        let mut concentrator = SpanConcentrator::new(true, true, &[], Default::default(), now);
1851        let payload_key = PayloadAggregationKey {
1852            env: MetaString::from("test"),
1853            ..Default::default()
1854        };
1855        let stat_span = concentrator
1856            .new_stat_span_from_span(span)
1857            .expect("a client span with a peer tag should produce stats");
1858        concentrator.add_span(&stat_span, 1.0, &payload_key, &InfraTags::default(), "", now);
1859
1860        let payloads = concentrator.flush(now + BUCKET_DURATION_NS * 3, true);
1861        let peer_tags: Vec<String> = payloads
1862            .iter()
1863            .flat_map(|payload| payload.stats())
1864            .flat_map(|bucket| bucket.stats())
1865            .flat_map(|grouped| grouped.peer_tags().iter().map(|tag| tag.to_string()))
1866            .collect();
1867        assert_eq!(peer_tags, ["db.instance:i-1234"]);
1868    }
1869
1870    fn transform_with_workload_provider(workload_provider: Option<TestWorkloadProvider>) -> ApmStats {
1871        let now = now_nanos();
1872        ApmStats {
1873            concentrator: SpanConcentrator::new(true, true, &[], Default::default(), now),
1874            flush_interval: DEFAULT_FLUSH_INTERVAL,
1875            agent_env: MetaString::from("none"),
1876            agent_hostname: MetaString::default(),
1877            workload_provider: workload_provider
1878                .map(|provider| Arc::new(provider) as Arc<dyn WorkloadProvider + Send + Sync>),
1879            splits: Counter::noop(),
1880            future_clamps: Counter::noop(),
1881        }
1882    }
1883
1884    fn string_attributes(pairs: &[(&str, &str)]) -> FastHashMap<MetaString, AttributeValue> {
1885        pairs
1886            .iter()
1887            .map(|(k, v)| (MetaString::from(*k), AttributeValue::String(MetaString::from(*v))))
1888            .collect()
1889    }
1890
1891    const CONTAINER_VERSION: ContainerVersionData<'static> = ContainerVersionData {
1892        git_commit_sha: "container-sha",
1893        image_tag: "container-image",
1894        app_version: "container-v",
1895    };
1896
1897    #[test]
1898    fn version_data_falls_back_to_container_tags() {
1899        let transform = transform_with_workload_provider(None);
1900        let trace = Trace::new(vec![make_test_span("svc", "op", "res")], TraceIngestInfo::Datadog);
1901
1902        let key = transform.build_payload_key(&trace, "", CONTAINER_VERSION);
1903        assert_eq!(key.version, "container-v");
1904        assert_eq!(key.git_commit_sha, "container-sha");
1905        assert_eq!(key.image_tag, "container-image");
1906    }
1907
1908    #[test]
1909    fn trace_version_data_wins_over_container_tags() {
1910        let transform = transform_with_workload_provider(None);
1911
1912        // The payload version and the root span's image tag and commit SHA win over the container's tags.
1913        let span = make_test_span("svc", "op", "res").with_attributes(string_attributes(&[
1914            (TAG_GIT_COMMIT_SHA, "span-sha"),
1915            ("_dd.image_tag", "span-image"),
1916        ]));
1917        let mut trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1918        trace.payload.app_version = MetaString::from("payload-v");
1919        let key = transform.build_payload_key(&trace, "", CONTAINER_VERSION);
1920        assert_eq!(key.version, "payload-v");
1921        assert_eq!(key.git_commit_sha, "span-sha");
1922        assert_eq!(key.image_tag, "span-image");
1923
1924        // The commit SHA set on the tracer payload wins over the root span's.
1925        trace.attributes = Arc::new(string_attributes(&[(TAG_GIT_COMMIT_SHA, "payload-sha")]));
1926        let key = transform.build_payload_key(&trace, "", CONTAINER_VERSION);
1927        assert_eq!(key.git_commit_sha, "payload-sha");
1928
1929        // Empty trace values don't hide the container's tags.
1930        let span = make_test_span("svc", "op", "res").with_attributes(string_attributes(&[
1931            ("version", ""),
1932            (TAG_GIT_COMMIT_SHA, ""),
1933            ("_dd.image_tag", ""),
1934        ]));
1935        let mut trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1936        trace.attributes = Arc::new(string_attributes(&[(TAG_GIT_COMMIT_SHA, "")]));
1937        let key = transform.build_payload_key(&trace, "", CONTAINER_VERSION);
1938        assert_eq!(key.version, "container-v");
1939        assert_eq!(key.git_commit_sha, "container-sha");
1940        assert_eq!(key.image_tag, "container-image");
1941    }
1942
1943    #[test]
1944    fn stats_carry_version_data_from_the_workload_provider() {
1945        let provider = TestWorkloadProvider::with_entity(
1946            EntityId::Container(MetaString::from("cid-1")),
1947            &["git.commit.sha:abc123", "image_tag:1.2.3", "version:v4"],
1948        );
1949        let mut transform = transform_with_workload_provider(Some(provider));
1950
1951        let now = now_nanos();
1952        let mut attrs = FastHashMap::default();
1953        attrs.insert(MetaString::from("_dd.measured"), AttributeValue::Float(1.0));
1954        let span = Span::new("svc", "op", "res", "web", 1, 0, now, 100_000_000, 0).with_attributes(attrs);
1955        let mut trace = Trace::new(vec![span], TraceIngestInfo::Datadog);
1956        trace.payload.container_id = MetaString::from("cid-1");
1957        transform.process_trace(&trace);
1958
1959        let stats = transform.concentrator.flush(now + BUCKET_DURATION_NS * 2, true);
1960        assert_eq!(stats.len(), 1);
1961        assert_eq!(stats[0].version(), "v4");
1962        assert_eq!(stats[0].git_commit_sha(), "abc123");
1963        assert_eq!(stats[0].image_tag(), "1.2.3");
1964    }
1965
1966    #[test]
1967    fn stats_normalize_the_payload_env_like_the_trace_encoder() {
1968        let transform = transform_with_workload_provider(None);
1969        let key_for = |payload_env: &str| {
1970            let mut trace = Trace::new(vec![make_test_span("svc", "op", "res")], TraceIngestInfo::Datadog);
1971            trace.payload.env = MetaString::from(payload_env);
1972            transform
1973                .build_payload_key(&trace, "", ContainerVersionData::default())
1974                .env
1975                .to_string()
1976        };
1977
1978        assert_eq!(key_for("Prod Env"), "prod_env");
1979        assert_eq!(key_for("prod"), "prod");
1980        // A payload env that normalizes to nothing falls back to the agent's.
1981        assert_eq!(key_for("!!!"), "none");
1982        assert_eq!(key_for(""), "none");
1983    }
1984
1985    #[test]
1986    fn hostname_prefers_payload_then_root_span_then_agent() {
1987        let now = now_nanos();
1988        let transform = ApmStats {
1989            concentrator: SpanConcentrator::new(true, true, &[], Default::default(), now),
1990            flush_interval: DEFAULT_FLUSH_INTERVAL,
1991            agent_env: MetaString::default(),
1992            agent_hostname: MetaString::from("agent-host"),
1993            workload_provider: None,
1994            splits: Counter::noop(),
1995            future_clamps: Counter::noop(),
1996        };
1997        let trace_with = |payload_hostname: &str, root_hostname: Option<&str>| {
1998            let mut attrs = FastHashMap::default();
1999            if let Some(root_hostname) = root_hostname {
2000                attrs.insert(
2001                    MetaString::from("_dd.hostname"),
2002                    AttributeValue::String(MetaString::from(root_hostname)),
2003                );
2004            }
2005            let root_span = Span::new("svc", "op", "res", "web", 1, 0, now, 1_000_000, 0).with_attributes(attrs);
2006            let mut trace = Trace::new(vec![root_span], TraceIngestInfo::Datadog);
2007            trace.payload.hostname = MetaString::from(payload_hostname);
2008            trace
2009        };
2010        let hostname = |trace: &Trace| {
2011            transform
2012                .build_payload_key(trace, "", ContainerVersionData::default())
2013                .hostname
2014                .to_string()
2015        };
2016
2017        // The payload hostname beats the root span's `_dd.hostname`.
2018        assert_eq!(hostname(&trace_with("payload-host", Some("root-host"))), "payload-host");
2019        assert_eq!(hostname(&trace_with("", Some("root-host"))), "root-host");
2020        assert_eq!(hostname(&trace_with("", None)), "agent-host");
2021    }
2022
2023    #[test]
2024    fn otlp_trace_without_a_hostname_is_attributed_to_the_configured_hostname() {
2025        let now = now_nanos();
2026        let transform = ApmStats {
2027            concentrator: SpanConcentrator::new(true, true, &[], Default::default(), now),
2028            flush_interval: DEFAULT_FLUSH_INTERVAL,
2029            agent_env: MetaString::default(),
2030            agent_hostname: MetaString::from("agent-host"),
2031            workload_provider: None,
2032            splits: Counter::noop(),
2033            future_clamps: Counter::noop(),
2034        };
2035
2036        // A serverless OTLP resource reports no hostname, so its stats use the configured one. The trace payload
2037        // itself stays empty.
2038        let span = Span::new("svc", "op", "res", "web", 1, 0, now, 1_000_000, 0);
2039        let trace = Trace::new(
2040            vec![span],
2041            TraceIngestInfo::Otlp {
2042                receiver_sampling_rate: 1.0,
2043            },
2044        );
2045        let key = transform.build_payload_key(&trace, "", ContainerVersionData::default());
2046        assert_eq!(key.hostname.as_ref(), "agent-host");
2047    }
2048
2049    proptest! {
2050        #[test]
2051        #[cfg_attr(miri, ignore)]
2052        fn property_test_split_respects_max_entries((payloads, max_entries_per_event) in arb_split_inputs()) {
2053            let input_total: usize = payloads.iter().flat_map(|p| p.stats()).map(|b| b.stats().len()).sum();
2054
2055            let result = split_into_trace_stats(payloads, max_entries_per_event);
2056
2057            // Property 1: No TraceStats should exceed max_entries_per_event
2058            for trace_stats in &result {
2059                let count = count_grouped_stats(trace_stats);
2060                prop_assert!(
2061                    count <= max_entries_per_event,
2062                    "TraceStats has {} grouped stats, exceeds max of {}",
2063                    count,
2064                    max_entries_per_event
2065                );
2066            }
2067
2068            // Property 2: Total stats should be preserved
2069            let output_total: usize = result.iter().map(count_grouped_stats).sum();
2070            prop_assert_eq!(input_total, output_total, "Total stats count should be preserved");
2071
2072            // Property 3: Events are marked as split exactly when there is more than one of them
2073            for trace_stats in &result {
2074                prop_assert_eq!(trace_stats.is_split_payload(), result.len() > 1);
2075            }
2076        }
2077    }
2078}