Skip to main content

saluki_components/transforms/trace_sampler/
mod.rs

1//! Decides which incoming traces to forward before they reach the backend.
2//!
3//! The transform honors user sampling decisions and can keep traces through probabilistic,
4//! priority, error, and rare sampling. It also handles OTLP sampling metadata. When given an
5//! `APM_SAMPLING` subscription, it updates priority and error sampler targets and the rare sampler
6//! switch before processing each buffer. Without a subscription, it uses local configuration.
7//!
8//! TODO: Add trace metrics from `datadog-agent/pkg/trace/sampler/metrics.go`.
9
10use std::collections::HashMap;
11use std::sync::{Arc, LazyLock};
12
13use async_trait::async_trait;
14use datadog_agent_apm::sampling::{RemoteSampling, SamplerSettings, TraceSamplingSubscription};
15use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
16use saluki_core::data_model::event::trace::AttributeValueExt;
17use saluki_core::{
18    components::{transforms::*, BuildContext},
19    data_model::event::{
20        trace::{AttributeValue, Span, Trace, TraceIngestInfo},
21        EventType,
22    },
23    topology::{EventsBuffer, OutputDefinition},
24};
25use saluki_error::GenericError;
26use stringtheory::MetaString;
27use tokio::select;
28use tracing::{debug, warn};
29
30mod catalog;
31mod core_sampler;
32mod errors;
33mod event_processor;
34mod priority_sampler;
35mod probabilistic;
36mod rare_sampler;
37mod score_sampler;
38mod signature;
39mod telemetry;
40
41use self::event_processor::EventProcessor;
42use self::probabilistic::PROB_RATE_KEY;
43use self::telemetry::{DecisionWindow, WINDOW};
44use crate::common::datadog::{
45    compute_top_level, get_root_span_index, get_trace_env, sample_by_rate, DECISION_MAKER_MANUAL,
46    DECISION_MAKER_PROBABILISTIC, KEY_ANALYZED_SPANS, SAMPLING_PRIORITY_METRIC_KEY, TAG_DECISION_MAKER, TAG_ORIGIN,
47};
48use crate::config::AgentEnv;
49
50// Sampling priority constants (matching datadog-agent)
51const PRIORITY_AUTO_DROP: i32 = 0;
52const PRIORITY_AUTO_KEEP: i32 = 1;
53const PRIORITY_USER_KEEP: i32 = 2;
54
55// Single Span Sampling key
56const KEY_SPAN_SAMPLING_MECHANISM: &str = "_dd.span_sampling.mechanism";
57
58/// Configuration for the trace sampler transform.
59#[derive(Debug)]
60pub struct TraceSamplerConfiguration {
61    /// Whether the probabilistic sampler decides traces, in place of the priority, error, and rare samplers.
62    pub probabilistic_sampler_enabled: bool,
63
64    /// Seed mixed into the trace-ID hash before probabilistic sampling.
65    pub probabilistic_hash_seed: u32,
66
67    /// Whether the probabilistic sampler hashes the full 128-bit trace ID instead of its low 64 bits.
68    pub probabilistic_full_trace_id: bool,
69
70    /// Percentage of traces the probabilistic sampler keeps.
71    pub sampling_percentage: f64,
72
73    /// Whether error traces are sampled independently of the base sampler.
74    pub error_sampling_enabled: bool,
75
76    /// Whether Error Tracking standalone mode is enabled.
77    pub error_tracking_standalone: bool,
78
79    /// Target number of error traces sampled per second.
80    pub errors_per_second: f64,
81
82    /// Target number of traces sampled per second.
83    pub target_traces_per_second: f64,
84
85    /// Multiplier applied to every learned keep-rate of the adaptive samplers.
86    pub extra_sample_rate: f64,
87
88    /// Maximum number of service signatures the priority sampler tracks rates for. If set to `0`, the catalog's
89    /// default size applies.
90    pub max_catalog_entries: usize,
91
92    /// Environment the priority sampler uses for traces without one, and used to select a remote `by_env` entry.
93    pub agent_env: AgentEnv,
94
95    /// Whether the rare sampler is enabled.
96    pub rare_sampler_enabled: bool,
97
98    /// Target number of rare traces sampled per second.
99    pub rare_sampler_tps: f64,
100
101    /// Cooldown, in seconds, before a signature may be sampled again by the rare sampler.
102    pub rare_sampler_cooldown_secs: f64,
103
104    /// Maximum number of distinct signatures the rare sampler tracks.
105    pub rare_sampler_cardinality: usize,
106
107    /// Whether spans are marked top-level by their span kind.
108    pub compute_top_level_by_span_kind: bool,
109
110    /// Event extraction rates by service and operation name. Takes precedence over `analyzed_rate_by_service` when
111    /// non-empty.
112    pub analyzed_spans_by_service: HashMap<String, HashMap<String, f64>>,
113
114    /// Event extraction rates by service, for the deprecated analytics configuration.
115    ///
116    /// Rates are ignored when `analyzed_spans_by_service` is non-empty. Building the sampler logs a deprecation warning
117    /// whenever this map is non-empty, even when its rates are ignored.
118    pub analyzed_rate_by_service: HashMap<String, f64>,
119
120    /// Upper bound on the average number of extracted events sampled per second.
121    pub max_events_per_second: f64,
122
123    /// Remote `APM_SAMPLING` updates, or an inert subscription when remote sampling is not configured.
124    ///
125    /// Only priority and error sampling targets and rare sampling can change. For each field left unset by the remote
126    /// configuration, the sampler uses its local setting.
127    pub remote_sampling: TraceSamplingSubscription,
128}
129
130impl TraceSamplerConfiguration {
131    fn build_sampler(&self) -> TraceSampler {
132        let telemetry = DecisionWindow::new();
133        let event_processor = EventProcessor::new(
134            &self.analyzed_spans_by_service,
135            &self.analyzed_rate_by_service,
136            self.max_events_per_second,
137        );
138        TraceSampler {
139            sampling_rate: self.sampling_percentage / 100.0,
140            error_sampling_enabled: self.error_sampling_enabled,
141            error_tracking_standalone: self.error_tracking_standalone,
142            probabilistic_sampler_enabled: self.probabilistic_sampler_enabled,
143            probabilistic: probabilistic::ProbabilisticSampler::new(
144                self.probabilistic_hash_seed,
145                self.probabilistic_full_trace_id,
146            ),
147            error_sampler: errors::ErrorsSampler::new(self.errors_per_second, self.extra_sample_rate),
148            priority_sampler: priority_sampler::PrioritySampler::new(
149                self.agent_env.clone().into(),
150                self.extra_sample_rate,
151                self.target_traces_per_second,
152                self.max_catalog_entries,
153            ),
154            no_priority_sampler: score_sampler::NoPrioritySampler::new(
155                self.target_traces_per_second,
156                self.extra_sample_rate,
157            ),
158            rare_sampler: rare_sampler::RareSampler::new(
159                self.rare_sampler_enabled,
160                self.rare_sampler_tps,
161                std::time::Duration::from_secs_f64(self.rare_sampler_cooldown_secs),
162                self.rare_sampler_cardinality,
163                telemetry.counters().clone(),
164            ),
165            event_processor,
166            telemetry,
167            compute_top_level_by_span_kind: self.compute_top_level_by_span_kind,
168            static_settings: SamplerSettings {
169                target_traces_per_second: self.target_traces_per_second,
170                errors_per_second: self.errors_per_second,
171                rare_sampler_enabled: self.rare_sampler_enabled,
172            },
173            agent_env: self.agent_env.clone().into(),
174            remote_sampling: self.remote_sampling.clone(),
175            applied_sampling: None,
176        }
177    }
178}
179
180#[async_trait]
181impl TransformBuilder for TraceSamplerConfiguration {
182    fn input_event_type(&self) -> EventType {
183        EventType::Trace
184    }
185
186    fn outputs(&self) -> &[OutputDefinition<EventType>] {
187        static OUTPUTS: LazyLock<Vec<OutputDefinition<EventType>>> = LazyLock::new(|| {
188            vec![
189                OutputDefinition::default_output(EventType::Trace),
190                OutputDefinition::named_output("metrics", EventType::Metric),
191            ]
192        });
193        &OUTPUTS
194    }
195
196    async fn build(&self, _context: BuildContext) -> Result<Box<dyn Transform + Send>, GenericError> {
197        if !self.analyzed_rate_by_service.is_empty() {
198            warn!("analyzed_rate_by_service is deprecated, please use analyzed_spans instead");
199        }
200        Ok(Box::new(self.build_sampler()))
201    }
202}
203
204impl MemoryBounds for TraceSamplerConfiguration {
205    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
206        builder.minimum().with_single_value::<TraceSampler>("component struct");
207
208        // The catalog holds a hash map slot plus one LRU slab entry per tracked signature. A
209        // configured 0 selects the default cap, matching the catalog's own resolution.
210        let catalog_capacity = if self.max_catalog_entries == 0 {
211            catalog::MAX_CATALOG_ENTRIES
212        } else {
213            self.max_catalog_entries
214        };
215        builder
216            .minimum()
217            .with_map::<signature::ServiceSignature, u32>("priority sampler catalog map", catalog_capacity)
218            .with_map::<signature::ServiceSignature, signature::Signature>(
219                "priority sampler catalog entries",
220                catalog_capacity,
221            );
222
223        // Decision keys span the same (service, env) universe as the catalog, across a handful
224        // of samplers. The window resets every ten seconds, so steady-state growth follows active
225        // combinations; within a window, growth is capped at the telemetry's decision-key limit,
226        // with excess combinations rolled into one bucket per sampler.
227        builder
228            .minimum()
229            .with_map::<telemetry::DecisionKey, telemetry::DecisionCounts>("sampler decision window", catalog_capacity);
230
231        // Event extraction rates are bounded by their configured size, plus one nested operation
232        // map per configured service.
233        let analyzed_operations: usize = self.analyzed_spans_by_service.values().map(|ops| ops.len()).sum();
234        builder
235            .minimum()
236            .with_map::<String, HashMap<String, f64>>(
237                "analyzed spans service rates",
238                self.analyzed_spans_by_service.len(),
239            )
240            .with_map::<String, f64>("analyzed spans operation rates", analyzed_operations)
241            .with_map::<String, f64>("legacy analyzed service rates", self.analyzed_rate_by_service.len());
242    }
243}
244
245pub struct TraceSampler {
246    sampling_rate: f64,
247    error_tracking_standalone: bool,
248    error_sampling_enabled: bool,
249    probabilistic_sampler_enabled: bool,
250    probabilistic: probabilistic::ProbabilisticSampler,
251    compute_top_level_by_span_kind: bool,
252    error_sampler: errors::ErrorsSampler,
253    priority_sampler: priority_sampler::PrioritySampler,
254    no_priority_sampler: score_sampler::NoPrioritySampler,
255    rare_sampler: rare_sampler::RareSampler,
256    event_processor: EventProcessor,
257    telemetry: DecisionWindow,
258    /// Local settings used when a remote configuration leaves a field unset.
259    static_settings: SamplerSettings,
260    /// Agent environment, used to select a remote `by_env` entry.
261    agent_env: MetaString,
262    remote_sampling: TraceSamplingSubscription,
263    /// Last update handled, so each buffer does not reapply the same settings.
264    applied_sampling: Option<Arc<RemoteSampling>>,
265}
266
267/// The outcome of evaluating a trace against the configured samplers.
268struct SamplerOutcome {
269    /// Whether the trace should be kept.
270    keep: bool,
271    /// The final sampling priority.
272    priority: i32,
273    /// The decision maker tag value for the deciding sampler, if any.
274    decision_maker: &'static str,
275    /// The index of the root span the samplers evaluated against, when one was found.
276    root_span_idx: Option<usize>,
277    /// The sampler that decided the trace.
278    sampler: telemetry::SamplerName,
279    /// Whether the samplers decided without short-circuiting, so event extraction should run.
280    extract_events: bool,
281}
282
283impl SamplerOutcome {
284    const fn new(
285        keep: bool, priority: i32, decision_maker: &'static str, root_span_idx: Option<usize>,
286        sampler: telemetry::SamplerName, extract_events: bool,
287    ) -> Self {
288        Self {
289            keep,
290            priority,
291            decision_maker,
292            root_span_idx,
293            sampler,
294            extract_events,
295        }
296    }
297}
298
299impl TraceSampler {
300    /// Applies the latest accepted remote sampling configuration, if it has changed.
301    ///
302    /// Unset fields use local settings, not previous remote values. When the assignment becomes
303    /// empty, the subscription keeps reporting the last configuration, as the Datadog Agent does. A newly published
304    /// configuration can have the same values after a worker restart; applying it again preserves
305    /// learned sampling rates and the rare sampler's record of seen span signatures.
306    fn apply_remote_sampling(&mut self) {
307        let Some(current) = self.remote_sampling.current() else {
308            return;
309        };
310        if self
311            .applied_sampling
312            .as_ref()
313            .is_some_and(|applied| Arc::ptr_eq(applied, &current))
314        {
315            return;
316        }
317        if let RemoteSampling::Remote { id, config } = &*current {
318            let settings = config.resolve(&self.agent_env, &self.static_settings);
319            debug!(config_id = %id, ?settings, "Applying remote sampling configuration.");
320            // The Datadog Agent does not update the no-priority sampler from this product.
321            self.priority_sampler
322                .update_target_tps(settings.target_traces_per_second);
323            self.error_sampler.update_target_tps(settings.errors_per_second);
324            self.rare_sampler.set_enabled(settings.rare_sampler_enabled);
325        }
326        self.applied_sampling = Some(current);
327    }
328
329    /// Applies pending sampling settings, then samples every trace in the buffer with those settings.
330    fn process_buffer(&mut self, events: &mut EventsBuffer) {
331        self.apply_remote_sampling();
332        events.retain_events::<Trace, _>(|trace| self.process_trace(trace));
333    }
334
335    /// Find the root span index of a trace.
336    fn get_root_span_index(&self, trace: &Trace) -> Option<usize> {
337        // The shared root finder, so every consumer anchors metadata to identical root spans.
338        get_root_span_index(trace.spans())
339    }
340
341    /// Check for user-set sampling priority in trace
342    fn get_user_priority(&self, trace: &Trace, root_span_idx: usize) -> Option<i32> {
343        // First check trace-level sampling priority (last-seen priority from OTLP ingest)
344        if let Some(priority) = trace.priority {
345            return Some(priority);
346        }
347
348        if trace.spans().is_empty() {
349            return None;
350        }
351
352        // Fall back to checking spans (for compatibility with non-OTLP traces)
353        // Prefer the root span (common case), but fall back to scanning all spans to be robust to ordering.
354        if let Some(root) = trace.spans().get(root_span_idx) {
355            if let Some(p) = root
356                .attributes
357                .get(SAMPLING_PRIORITY_METRIC_KEY)
358                .and_then(AttributeValue::as_num)
359            {
360                return Some(p as i32);
361            }
362        }
363        let spans = trace.spans();
364        spans.iter().find_map(|span| {
365            span.attributes
366                .get(SAMPLING_PRIORITY_METRIC_KEY)
367                .and_then(AttributeValue::as_num)
368                .map(|p| p as i32)
369        })
370    }
371
372    /// Returns `true` if the given trace ID should be probabilistically sampled.
373    fn sample_probabilistic(&self, trace_id_high: u64, trace_id_low: u64) -> bool {
374        self.probabilistic
375            .sample(trace_id_high, trace_id_low, self.sampling_rate)
376    }
377
378    /// Returns `true` if the trace contains a span with an error.
379    fn trace_contains_error(&self, trace: &Trace, consider_exception_span_events: bool) -> bool {
380        trace.spans().iter().any(|span| {
381            span.error() != 0 || (consider_exception_span_events && self.span_contains_exception_span_event(span))
382        })
383    }
384
385    /// Returns `true` if the span has exception span events.
386    ///
387    /// This checks for the `_dd.span_events.has_exception` meta field set to `"true"`.
388    fn span_contains_exception_span_event(&self, span: &Span) -> bool {
389        if let Some(has_exception) = span
390            .attributes
391            .get("_dd.span_events.has_exception")
392            .and_then(AttributeValue::as_string)
393        {
394            return has_exception == "true";
395        }
396        false
397    }
398
399    /// Computes the OTLP pre-sampling priority and decision maker for a trace, mirroring
400    /// `OTLPReceiver.createChunks` in DDA which runs before `runSamplersV1`.
401    ///
402    /// Returns `Some((priority, dm))` for OTLP traces when the probabilistic sampler is disabled,
403    /// or `None` if pre-sampling doesn't apply.
404    ///
405    /// See: https://github.com/DataDog/datadog-agent/blob/be33ac1490c4a34602cbc65a211406b73ad6d00b/pkg/trace/api/otlp.go#L561-L585
406    fn otlp_pre_sample(&mut self, trace: &mut Trace, root_span_idx: usize) -> Option<(i32, &'static str)> {
407        let TraceIngestInfo::Otlp { receiver_sampling_rate } = trace.ingest_info() else {
408            return None;
409        };
410        if self.probabilistic_sampler_enabled {
411            return None;
412        }
413        let (priority, dm) = if let Some(user_priority) = self.get_user_priority(trace, root_span_idx) {
414            (user_priority, DECISION_MAKER_MANUAL)
415        } else {
416            let root_trace_id = trace.trace_id_low;
417            if sample_by_rate(root_trace_id, receiver_sampling_rate) {
418                (PRIORITY_AUTO_KEEP, DECISION_MAKER_PROBABILISTIC)
419            } else {
420                (PRIORITY_AUTO_DROP, DECISION_MAKER_PROBABILISTIC)
421            }
422        };
423        if priority == PRIORITY_AUTO_KEEP {
424            if let Some(root_span) = trace.spans_mut().get_mut(root_span_idx) {
425                root_span.attributes.remove(PROB_RATE_KEY);
426            }
427        }
428        Some((priority, dm))
429    }
430
431    /// Retains only the analyzed-marker spans of a dropped trace and forwards it as events.
432    fn forward_analyzed_spans(&self, trace: &mut Trace, priority: i32) -> bool {
433        let retained = trace.retain_spans(|_, span| span.attributes.contains_key(KEY_ANALYZED_SPANS));
434        if retained > 0 {
435            trace.dropped_trace = true;
436            trace.priority = Some(priority);
437            true
438        } else {
439            false
440        }
441    }
442
443    /// Apply Single Span Sampling to the trace
444    /// Returns true if the trace was modified
445    fn single_span_sampling(&self, trace: &mut Trace) -> bool {
446        let retained = trace.retain_spans(|_, span| span.attributes.contains_key(KEY_SPAN_SAMPLING_MECHANISM));
447        if retained > 0 {
448            trace.dropped_trace = false;
449            trace.priority = Some(PRIORITY_USER_KEEP);
450            true
451        } else {
452            false
453        }
454    }
455
456    /// Evaluates the given trace against all configured samplers.
457    fn run_samplers(&mut self, trace: &mut Trace) -> SamplerOutcome {
458        let outcome = self.run_samplers_inner(trace);
459
460        // Unclaimed decisions carry no sampler identity, so recording them would inflate a
461        // series that exists only to expose attribution gaps; empty and rootless traces are the
462        // only unclaimed cases.
463        if outcome.sampler != telemetry::SamplerName::Unknown {
464            let (service, env) = self.decision_dimensions(trace, outcome.root_span_idx);
465            self.telemetry
466                .record_decision(outcome.keep, outcome.sampler, outcome.priority, service, env);
467        }
468
469        outcome
470    }
471
472    /// Reads the service and env dimensions a decision is recorded under.
473    fn decision_dimensions(&self, trace: &Trace, root_span_idx: Option<usize>) -> (MetaString, MetaString) {
474        match root_span_idx {
475            Some(root_span_idx) => {
476                let service = trace
477                    .spans()
478                    .get(root_span_idx)
479                    .map(|span| MetaString::from(span.service()))
480                    .unwrap_or_default();
481                let env = get_trace_env(trace, root_span_idx).cloned().unwrap_or_default();
482                (service, env)
483            }
484            None => (MetaString::empty(), MetaString::empty()),
485        }
486    }
487
488    fn run_samplers_inner(&mut self, trace: &mut Trace) -> SamplerOutcome {
489        // The name starts unclaimed; whichever sampler decides the trace claims it, so every
490        // decision is recorded under exactly one sampler.
491        let mut sampler_name = telemetry::SamplerName::Unknown;
492
493        // logic taken from: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/agent/agent.go#L1066
494        // Empty trace check
495        if trace.spans().is_empty() {
496            return SamplerOutcome::new(false, PRIORITY_AUTO_DROP, "", None, sampler_name, false);
497        }
498
499        let Some(root_span_idx) = self.get_root_span_index(trace) else {
500            return SamplerOutcome::new(false, PRIORITY_AUTO_DROP, "", None, sampler_name, false);
501        };
502
503        // ETS: only sample traces containing errors (including exception span events); skip all other samplers.
504        // logic taken from: https://github.com/DataDog/datadog-agent/blob/be33ac1490c4a34602cbc65a211406b73ad6d00/pkg/trace/agent/agent.go#L1068
505        if self.error_tracking_standalone {
506            sampler_name = telemetry::SamplerName::Error;
507            let otlp_pre_sample = self.otlp_pre_sample(trace, root_span_idx);
508            if self.trace_contains_error(trace, true) {
509                let now = std::time::SystemTime::now();
510                let keep = self.error_sampler.sample_error(now, trace, root_span_idx);
511                let default_priority = if keep { PRIORITY_AUTO_KEEP } else { PRIORITY_AUTO_DROP };
512                let (priority, dm) = otlp_pre_sample.unwrap_or((default_priority, ""));
513                return SamplerOutcome::new(keep, priority, dm, Some(root_span_idx), sampler_name, false);
514            }
515            let (pre_priority, pre_dm) = otlp_pre_sample.unwrap_or((PRIORITY_AUTO_DROP, ""));
516            return SamplerOutcome::new(false, pre_priority, pre_dm, Some(root_span_idx), sampler_name, false);
517        }
518
519        // Run the rare sampler early, before all other samplers. This mirrors the Go agent behavior
520        // where the rare sampler runs first to catch traces that would otherwise be dropped entirely.
521        // logic taken from: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/agent/agent.go#L1078
522        let rare = self.rare_sampler.sample(trace, root_span_idx);
523
524        // Modern path: ProbabilisticSamplerEnabled = true
525        if self.probabilistic_sampler_enabled {
526            sampler_name = telemetry::SamplerName::Probabilistic;
527            let mut prob_keep = false;
528            let mut decision_maker = "";
529
530            if rare {
531                // Rare sampler wins over probabilistic sampling.
532                sampler_name = telemetry::SamplerName::Rare;
533                prob_keep = true;
534            } else {
535                if self.sample_probabilistic(trace.trace_id_high, trace.trace_id_low) {
536                    decision_maker = DECISION_MAKER_PROBABILISTIC;
537                    prob_keep = true;
538
539                    if let Some(root_span) = trace.spans_mut().get_mut(root_span_idx) {
540                        root_span.attributes.insert(
541                            MetaString::from_static(PROB_RATE_KEY),
542                            AttributeValue::Float(self.sampling_rate),
543                        );
544                    }
545                } else if self.error_sampling_enabled && self.trace_contains_error(trace, false) {
546                    sampler_name = telemetry::SamplerName::Error;
547                    let now = std::time::SystemTime::now();
548                    prob_keep = self.error_sampler.sample_error(now, trace, root_span_idx);
549                }
550            }
551
552            let priority = if prob_keep {
553                PRIORITY_AUTO_KEEP
554            } else {
555                PRIORITY_AUTO_DROP
556            };
557
558            return SamplerOutcome::new(
559                prob_keep,
560                priority,
561                decision_maker,
562                Some(root_span_idx),
563                sampler_name,
564                true,
565            );
566        }
567
568        // Read once here, where the samplers below consume it; every path above returns without
569        // needing it.
570        let now = std::time::SystemTime::now();
571        let user_priority = self.get_user_priority(trace, root_span_idx);
572        if let Some(priority) = user_priority {
573            sampler_name = telemetry::SamplerName::Priority;
574            if Self::trace_chunk_contains_probability_sampling(trace) {
575                // Traces already sampled probabilistically upstream count under the probabilistic
576                // sampler; the priority sampler still decides them.
577                sampler_name = telemetry::SamplerName::Probabilistic;
578            }
579            if priority < PRIORITY_AUTO_DROP {
580                // Manual drop: short-circuit and skip other samplers.
581                return SamplerOutcome::new(false, priority, "", Some(root_span_idx), sampler_name, false);
582            }
583
584            if rare {
585                sampler_name = telemetry::SamplerName::Rare;
586                return SamplerOutcome::new(true, priority, "", Some(root_span_idx), sampler_name, true);
587            }
588
589            if self.priority_sampler.sample(now, trace, root_span_idx, priority, 0.0) {
590                return SamplerOutcome::new(true, priority, "", Some(root_span_idx), sampler_name, true);
591            }
592        } else if let TraceIngestInfo::Otlp { receiver_sampling_rate } = trace.ingest_info() {
593            // Rare check mirrors agent behavior: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/agent/agent.go#L1129-L1140
594            if rare {
595                sampler_name = telemetry::SamplerName::Rare;
596                return SamplerOutcome::new(true, PRIORITY_AUTO_KEEP, "", Some(root_span_idx), sampler_name, true);
597            }
598
599            // The OTLP rate decision is probabilistic: its keeps and its drops both record
600            // under the probabilistic sampler, never the no-priority bucket.
601            sampler_name = telemetry::SamplerName::Probabilistic;
602            // some sampling happens upstream in the otlp receiver in the agent: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/api/otlp.go#L572
603            let root_trace_id = trace.trace_id_low;
604            if sample_by_rate(root_trace_id, receiver_sampling_rate) {
605                if let Some(root_span) = trace.spans_mut().get_mut(root_span_idx) {
606                    root_span.attributes.remove(PROB_RATE_KEY);
607                }
608                return SamplerOutcome::new(
609                    true,
610                    PRIORITY_AUTO_KEEP,
611                    DECISION_MAKER_PROBABILISTIC,
612                    Some(root_span_idx),
613                    sampler_name,
614                    true,
615                );
616            }
617        } else {
618            sampler_name = telemetry::SamplerName::NoPriority;
619            if rare {
620                sampler_name = telemetry::SamplerName::Rare;
621                return SamplerOutcome::new(true, PRIORITY_AUTO_KEEP, "", Some(root_span_idx), sampler_name, true);
622            }
623            if self.no_priority_sampler.sample(now, trace, root_span_idx) {
624                return SamplerOutcome::new(true, PRIORITY_AUTO_KEEP, "", Some(root_span_idx), sampler_name, true);
625            }
626        }
627
628        if self.error_sampling_enabled && self.trace_contains_error(trace, false) {
629            sampler_name = telemetry::SamplerName::Error;
630            let keep = self.error_sampler.sample_error(now, trace, root_span_idx);
631            if keep {
632                return SamplerOutcome::new(true, PRIORITY_AUTO_KEEP, "", Some(root_span_idx), sampler_name, true);
633            }
634        }
635
636        // Default: drop the trace
637        SamplerOutcome::new(false, PRIORITY_AUTO_DROP, "", Some(root_span_idx), sampler_name, true)
638    }
639
640    /// Returns whether the trace was already sampled probabilistically upstream.
641    ///
642    /// Tracer head sampling and receiver-side sampling both stamp the decision maker, so the
643    /// first span carrying it identifies the trace.
644    fn trace_chunk_contains_probability_sampling(trace: &Trace) -> bool {
645        trace
646            .spans()
647            .iter()
648            .find_map(|span| {
649                span.attributes
650                    .get(TAG_DECISION_MAKER)
651                    .and_then(AttributeValue::as_string)
652            })
653            .is_some_and(|dm| dm == DECISION_MAKER_PROBABILISTIC)
654    }
655
656    /// Fills in trace-level metadata from the spans.
657    ///
658    /// Origin comes from the root span's `_dd.origin` tag, and the decision maker is the first
659    /// span in chunk order carrying `_dd.p.dm` - both only when not already set. This runs here,
660    /// downstream of span filtering, so the metadata anchors to the final span population rather
661    /// than the one that arrived at decode time.
662    fn backfill_trace_metadata(&self, trace: &mut Trace, root_span_idx: usize) {
663        if trace.origin.is_empty() {
664            if let Some(origin) = trace.spans()[root_span_idx]
665                .attributes
666                .get(TAG_ORIGIN)
667                .and_then(AttributeValue::as_string)
668            {
669                trace.origin = origin.clone();
670            }
671        }
672
673        if trace.decision_maker.is_none() {
674            let first_decision_maker = trace.spans().iter().find_map(|span| {
675                span.attributes
676                    .get(TAG_DECISION_MAKER)
677                    .and_then(AttributeValue::as_string)
678            });
679            if let Some(dm) = first_decision_maker {
680                trace.decision_maker = Some(dm.clone());
681            }
682        }
683
684        if !self.compute_top_level_by_span_kind {
685            compute_top_level(trace.spans_mut());
686        }
687    }
688
689    /// Apply sampling metadata to the trace in-place.
690    ///
691    /// The `root_span_id` parameter identifies which span should receive the sampling metadata.
692    /// This avoids recalculating the root span since it was already found in `run_samplers`.
693    fn apply_sampling_metadata(
694        &self, trace: &mut Trace, keep: bool, priority: i32, decision_maker: &'static str, root_span_idx: usize,
695    ) {
696        let is_otlp = matches!(trace.ingest_info(), TraceIngestInfo::Otlp { .. });
697        // Chunk-level decision maker: the sampler's value when it decided, otherwise the first
698        // carrier promoted during backfill (falling back to the root's own tag).
699        let promoted_decision_maker = if decision_maker.is_empty() {
700            trace.decision_maker.clone()
701        } else {
702            None
703        };
704        let root_span_value = match trace.spans_mut().get_mut(root_span_idx) {
705            Some(span) => span,
706            None => return,
707        };
708
709        let decision_maker_meta = if decision_maker.is_empty() {
710            promoted_decision_maker.or_else(|| {
711                root_span_value
712                    .attributes
713                    .get(TAG_DECISION_MAKER)
714                    .and_then(AttributeValue::as_string)
715                    .cloned()
716            })
717        } else {
718            Some(MetaString::from_static(decision_maker))
719        };
720
721        // The span-level decision maker is stamped only when a sampler made the call: promotion
722        // targets trace chunk metadata, and each span's own tag is left in place because
723        // downstream systems rely on the span keeping its original value.
724        //
725        // With the APM-level probabilistic sampler on OTLP traces, `_dd.p.dm` is written to
726        // trace chunk tags only (not span meta); on the legacy sampling path it is written to
727        // both. The span meta write is skipped only when both conditions hold; the DM value
728        // still flows through trace fields to the encoder.
729        if priority > 0 && !decision_maker.is_empty() && !(is_otlp && self.probabilistic_sampler_enabled) {
730            root_span_value.attributes.insert(
731                MetaString::from_static(TAG_DECISION_MAKER),
732                AttributeValue::String(MetaString::from_static(decision_maker)),
733            );
734        }
735
736        // Now set sampling metadata directly on the trace.
737        trace.dropped_trace = !keep;
738        trace.priority = Some(priority);
739        trace.decision_maker = if priority > 0 { decision_maker_meta } else { None };
740    }
741
742    fn process_trace(&mut self, trace: &mut Trace) -> bool {
743        // keep is a boolean that indicates if the trace should be kept or dropped
744        // priority is the sampling priority
745        // decision_maker is the tag that indicates the decision maker (probabilistic, error, etc.)
746        // root_span_idx is the index of the root span of the trace
747        let SamplerOutcome {
748            keep,
749            priority,
750            decision_maker,
751            root_span_idx,
752            extract_events,
753            ..
754        } = self.run_samplers(trace);
755
756        // Backfill trace-derived metadata before any forwarding path (keep, ETS, or
757        // single-span/analytics sampling), so every forwarded trace carries metadata derived
758        // from its final span population.
759        if let Some(root_idx) = root_span_idx {
760            self.backfill_trace_metadata(trace, root_idx);
761        }
762
763        // Extract events from every trace the samplers did not short-circuit; surviving spans
764        // carry the analyzed marker and their rate metadata whether the trace is kept or dropped,
765        // and are forwarded as standalone events only when the trace is dropped.
766        let events = if extract_events {
767            self.event_processor.process(trace, root_span_idx, priority)
768        } else {
769            event_processor::EventCounts::default()
770        };
771
772        // Apply sampling metadata and forward if kept, or if ETS (dropped non-error traces are
773        // forwarded with DroppedTrace=true, suppressing SSS/analytics).
774        if keep || self.error_tracking_standalone {
775            if let Some(root_idx) = root_span_idx {
776                self.apply_sampling_metadata(trace, keep, priority, decision_maker, root_idx);
777            }
778            return true;
779        }
780
781        // logic taken from here: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/agent/agent.go#L980-L990
782        // try single span sampling (keeps spans marked for sampling when trace would be dropped)
783        let modified = self.single_span_sampling(trace);
784        if !modified {
785            // Fall back to extracted events if no SSS spans
786            if self.forward_analyzed_spans(trace, priority) {
787                return true;
788            }
789        } else if events.sampled > 0 {
790            // Warn about both SSS and analytics events
791            debug!(
792                "Detected both analytics events AND single span sampling in the same trace. Single span sampling wins because App Analytics is deprecated."
793            );
794            return true;
795        }
796
797        // If we modified the trace with SSS, send it
798        if modified {
799            return true;
800        }
801
802        // Neither SSS nor analytics events found, drop the trace
803        debug!("Dropping trace with priority {}", priority);
804        false
805    }
806}
807
808#[async_trait]
809impl Transform for TraceSampler {
810    async fn run(mut self: Box<Self>, mut context: TransformContext) -> Result<(), GenericError> {
811        let mut health = context.take_health_handle();
812        health.mark_ready();
813        debug!("Trace sampler transform started.");
814
815        let mut window = tokio::time::interval_at(tokio::time::Instant::now() + WINDOW, WINDOW);
816
817        loop {
818            select! {
819                _ = health.live() => continue,
820                _ = window.tick() => {
821                    // Report the sampling telemetry through the dedicated metrics output, so the
822                    // metrics flow into the metrics pipeline and on to the backend. The signature
823                    // counts are read here, at report time, so a quiet window cannot republish
824                    // stale gauges.
825                    let mut events = self.telemetry.take_window_events(
826                        self.priority_sampler.tracked_signature_count(),
827                        self.no_priority_sampler.tracked_signature_count(),
828                        self.error_sampler.tracked_signature_count(),
829                    );
830                    events.extend(self.event_processor.take_window_events());
831                    context.dispatcher().buffered_named("metrics")?.send_all(events).await?;
832                }
833                maybe_events = context.events().next() => match maybe_events {
834                    Some(mut events) => {
835                        self.process_buffer(&mut events);
836                        context.dispatcher().buffered()?.send_all(events).await?;
837                    }
838                    None => {
839                        // The input stream has ended, so report the final window before stopping.
840                        let mut events = self.telemetry.take_window_events(
841                            self.priority_sampler.tracked_signature_count(),
842                            self.no_priority_sampler.tracked_signature_count(),
843                            self.error_sampler.tracked_signature_count(),
844                        );
845                        events.extend(self.event_processor.take_window_events());
846                        context.dispatcher().buffered_named("metrics")?.send_all(events).await?;
847                        break;
848                    }
849                }
850            }
851        }
852
853        debug!("Trace sampler transform stopped.");
854        Ok(())
855    }
856}
857
858/// Returns sampler settings carrying the configuration defaults.
859#[cfg(test)]
860pub(crate) fn sampler_configuration(agent_env: AgentEnv) -> TraceSamplerConfiguration {
861    TraceSamplerConfiguration {
862        probabilistic_sampler_enabled: false,
863        probabilistic_hash_seed: 0,
864        probabilistic_full_trace_id: false,
865        sampling_percentage: 0.0,
866        error_sampling_enabled: true,
867        error_tracking_standalone: false,
868        errors_per_second: 0.0,
869        target_traces_per_second: 0.0,
870        extra_sample_rate: 1.0,
871        max_catalog_entries: 0,
872        agent_env,
873        rare_sampler_enabled: false,
874        rare_sampler_tps: 5.0,
875        rare_sampler_cooldown_secs: 300.0,
876        rare_sampler_cardinality: 200,
877        compute_top_level_by_span_kind: true,
878        analyzed_spans_by_service: HashMap::new(),
879        analyzed_rate_by_service: HashMap::new(),
880        max_events_per_second: 0.0,
881        remote_sampling: TraceSamplingSubscription::default(),
882    }
883}
884
885#[cfg(test)]
886mod tests {
887    use std::collections::HashMap;
888
889    use datadog_agent_apm::sampling::test_util::TestSamplingPublisher;
890    use saluki_core::components::test_util::TestComponentDriver;
891    use saluki_core::data_model::event::{
892        trace::{AttributeValue, Span as DdSpan, Trace, TraceIngestInfo},
893        Event,
894    };
895
896    use super::*;
897    use crate::common::datadog::OTEL_TRACE_ID_META_KEY;
898
899    const PRIORITY_USER_DROP: i32 = -1;
900
901    // Deterministic receiver sampling decisions at a rate of 0.5, from the Go trace agent's `TestCreateChunks`:
902    // https://github.com/DataDog/datadog-agent/blob/c6f7e0bc2d5744601a10f231751948ac7a4ee781/pkg/trace/api/otlp_test.go#L740-L810
903    const OTLP_TEST_RECEIVER_SAMPLING_RATE: f64 = 0.5;
904    const OTLP_RECEIVER_KEPT_TRACE_ID: u64 = 123;
905    const OTLP_RECEIVER_DROPPED_TRACE_ID: u64 = 1237892138897;
906
907    fn create_test_sampler() -> TraceSampler {
908        TraceSampler {
909            sampling_rate: 1.0,
910            error_sampling_enabled: true,
911            error_tracking_standalone: false,
912            probabilistic_sampler_enabled: true,
913            probabilistic: probabilistic::ProbabilisticSampler::new(0, false),
914            error_sampler: errors::ErrorsSampler::new(10.0, 1.0),
915            priority_sampler: priority_sampler::PrioritySampler::new(MetaString::from("agent-env"), 1.0, 10.0, 5000),
916            no_priority_sampler: score_sampler::NoPrioritySampler::new(10.0, 1.0),
917            rare_sampler: rare_sampler::RareSampler::new(
918                false,
919                5.0,
920                std::time::Duration::from_secs(300),
921                200,
922                telemetry::SamplerCounters::new(),
923            ),
924            event_processor: EventProcessor::for_tests(&HashMap::new(), &HashMap::new(), f64::INFINITY),
925            telemetry: telemetry::DecisionWindow::new(),
926            compute_top_level_by_span_kind: false,
927            static_settings: SamplerSettings {
928                target_traces_per_second: 10.0,
929                errors_per_second: 10.0,
930                rare_sampler_enabled: false,
931            },
932            agent_env: MetaString::from("agent-env"),
933            remote_sampling: TraceSamplingSubscription::default(),
934            applied_sampling: None,
935        }
936    }
937
938    fn create_test_span(span_id: u64, error: i32) -> DdSpan {
939        DdSpan::new(
940            MetaString::from("test-service"),
941            MetaString::from("test-operation"),
942            MetaString::from("test-resource"),
943            MetaString::from("test-type"),
944            span_id,
945            0,    // parent_id
946            0,    // start
947            1000, // duration
948            error,
949        )
950    }
951
952    fn create_test_span_with_metrics(span_id: u64, metrics: HashMap<String, f64>) -> DdSpan {
953        let attrs: saluki_common::collections::FastHashMap<MetaString, AttributeValue> = metrics
954            .into_iter()
955            .map(|(k, v)| (MetaString::from(k), AttributeValue::Float(v)))
956            .collect();
957        create_test_span(span_id, 0).with_attributes(attrs)
958    }
959
960    #[allow(dead_code)]
961    fn create_test_span_with_meta(span_id: u64, meta: HashMap<String, String>) -> DdSpan {
962        let attrs: saluki_common::collections::FastHashMap<MetaString, AttributeValue> = meta
963            .into_iter()
964            .map(|(k, v)| (MetaString::from(k), AttributeValue::String(MetaString::from(v))))
965            .collect();
966        create_test_span(span_id, 0).with_attributes(attrs)
967    }
968
969    fn create_test_trace(spans: Vec<DdSpan>) -> Trace {
970        Trace::new(spans, TraceIngestInfo::Datadog)
971    }
972
973    fn create_otlp_test_trace(spans: Vec<DdSpan>, receiver_sampling_rate: f64, trace_id_low: u64) -> Trace {
974        let mut trace = Trace::new(spans, TraceIngestInfo::Otlp { receiver_sampling_rate });
975        trace.trace_id_low = trace_id_low;
976        trace
977    }
978
979    fn create_span_with_parent_and_service(
980        span_id: u64, parent_id: u64, service: &str, meta: &[(&str, &str)],
981    ) -> DdSpan {
982        let mut attrs = saluki_common::collections::FastHashMap::default();
983        for (k, v) in meta {
984            attrs.insert(MetaString::from(*k), AttributeValue::String(MetaString::from(*v)));
985        }
986        DdSpan::new(
987            MetaString::from(service),
988            MetaString::from("operation"),
989            MetaString::from("resource"),
990            MetaString::from("type"),
991            span_id,
992            parent_id,
993            0,
994            1000,
995            0,
996        )
997        .with_attributes(attrs)
998    }
999
1000    #[test]
1001    fn apply_sampling_metadata_preserves_backfilled_decision_maker() {
1002        let sampler = create_test_sampler();
1003        let root = create_test_span(1, 0);
1004        let mut trace = create_test_trace(vec![root]);
1005        trace.decision_maker = Some(MetaString::from("-8"));
1006
1007        sampler.apply_sampling_metadata(&mut trace, true, PRIORITY_AUTO_KEEP, "", 0);
1008
1009        assert_eq!(
1010            trace.decision_maker.as_deref(),
1011            Some("-8"),
1012            "the chunk-level decision maker keeps the promoted value"
1013        );
1014        assert!(
1015            !trace.spans()[0].attributes.contains_key(TAG_DECISION_MAKER),
1016            "a promoted decision maker is never stamped onto the root span; span-level _dd.p.dm is written only when a sampler decides"
1017        );
1018    }
1019
1020    #[test]
1021    fn apply_sampling_metadata_keeps_root_decision_maker_without_sampler_decision() {
1022        let sampler = create_test_sampler();
1023        let mut attrs = saluki_common::collections::FastHashMap::default();
1024        attrs.insert(
1025            MetaString::from(TAG_DECISION_MAKER),
1026            AttributeValue::String(MetaString::from("-9")),
1027        );
1028        let root = create_test_span(1, 0).with_attributes(attrs);
1029        let mut trace = create_test_trace(vec![root]);
1030        // Promoted from an earlier child span during backfill.
1031        trace.decision_maker = Some(MetaString::from("-8"));
1032
1033        sampler.apply_sampling_metadata(&mut trace, true, PRIORITY_AUTO_KEEP, "", 0);
1034
1035        assert_eq!(
1036            trace.decision_maker.as_deref(),
1037            Some("-8"),
1038            "the chunk-level decision maker keeps the promoted value"
1039        );
1040        assert_eq!(
1041            trace.spans()[0]
1042                .attributes
1043                .get(TAG_DECISION_MAKER)
1044                .and_then(AttributeValue::as_string)
1045                .map(|s| s.as_ref()),
1046            Some("-9"),
1047            "the root span's own decision maker is never overwritten by a promoted value"
1048        );
1049    }
1050
1051    #[test]
1052    fn backfill_promotes_origin_from_root_span() {
1053        let sampler = create_test_sampler();
1054        // The root is reported last here.
1055        let child = create_span_with_parent_and_service(2, 1, "svc", &[]);
1056        let root = create_span_with_parent_and_service(1, 0, "svc", &[("_dd.origin", "lambda")]);
1057        let mut trace = create_test_trace(vec![child, root]);
1058
1059        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1060        sampler.backfill_trace_metadata(&mut trace, root_idx);
1061
1062        assert_eq!(trace.origin.as_ref(), "lambda");
1063    }
1064
1065    #[test]
1066    fn backfill_ignores_origin_from_non_root_span() {
1067        let sampler = create_test_sampler();
1068        let root = create_span_with_parent_and_service(1, 0, "svc", &[]);
1069        let child = create_span_with_parent_and_service(2, 1, "svc", &[("_dd.origin", "rum")]);
1070        let mut trace = create_test_trace(vec![root, child]);
1071
1072        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1073        sampler.backfill_trace_metadata(&mut trace, root_idx);
1074
1075        assert!(trace.origin.as_ref().is_empty());
1076    }
1077
1078    #[test]
1079    fn backfill_promotes_first_decision_maker() {
1080        let sampler = create_test_sampler();
1081        let root = create_span_with_parent_and_service(1, 0, "svc", &[]);
1082        let early = create_span_with_parent_and_service(2, 1, "svc", &[("_dd.p.dm", "-8")]);
1083        let late = create_span_with_parent_and_service(3, 1, "svc", &[("_dd.p.dm", "-9")]);
1084        let mut trace = create_test_trace(vec![root, early, late]);
1085
1086        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1087        sampler.backfill_trace_metadata(&mut trace, root_idx);
1088
1089        assert_eq!(
1090            trace.decision_maker.as_deref(),
1091            Some("-8"),
1092            "first span carrying the tag wins - not a root-based rule"
1093        );
1094    }
1095
1096    #[test]
1097    fn backfill_marks_top_level_fallback_when_span_kind_computation_disabled() {
1098        let sampler = create_test_sampler();
1099        // Roots, orphans, and service boundaries get marked; interior same-service spans don't.
1100        let root = create_span_with_parent_and_service(1, 0, "svc-a", &[]);
1101        let child = create_span_with_parent_and_service(2, 1, "svc-a", &[]);
1102        let orphan = create_span_with_parent_and_service(3, 0xEE, "svc-a", &[]);
1103        let other_service = create_span_with_parent_and_service(5, 1, "svc-b", &[]);
1104        let local_entry = create_span_with_parent_and_service(6, 5, "svc-a", &[]);
1105        let mut trace = create_test_trace(vec![root, child, orphan, other_service, local_entry]);
1106
1107        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1108        sampler.backfill_trace_metadata(&mut trace, root_idx);
1109
1110        let spans = trace.spans();
1111        let top_level = |sid: u64| {
1112            spans
1113                .iter()
1114                .find(|s| s.span_id() == sid)
1115                .unwrap()
1116                .attributes
1117                .get(crate::common::datadog::TOP_LEVEL_KEY)
1118                .and_then(AttributeValue::as_num)
1119        };
1120        assert_eq!(top_level(1), Some(1.0), "root spans are marked");
1121        assert_eq!(
1122            top_level(3),
1123            Some(1.0),
1124            "orphans whose parent is missing from the chunk are marked"
1125        );
1126        assert_eq!(top_level(5), Some(1.0), "spans entering a different service are marked");
1127        assert_eq!(
1128            top_level(6),
1129            Some(1.0),
1130            "spans crossing back into the resource service are marked (local root)"
1131        );
1132        assert_eq!(
1133            top_level(2),
1134            None,
1135            "same-service children with their parent present are not marked"
1136        );
1137    }
1138
1139    #[test]
1140    fn backfill_skips_top_level_when_span_kind_computation_enabled() {
1141        let sampler = TraceSampler {
1142            compute_top_level_by_span_kind: true,
1143            ..create_test_sampler()
1144        };
1145        let root = create_span_with_parent_and_service(1, 0, "svc", &[]);
1146        let child = create_span_with_parent_and_service(2, 1, "svc", &[]);
1147        let orphan = create_span_with_parent_and_service(3, 0xEE, "svc", &[]);
1148        let mut trace = create_test_trace(vec![root, child, orphan]);
1149
1150        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1151        sampler.backfill_trace_metadata(&mut trace, root_idx);
1152
1153        for span in trace.spans() {
1154            assert!(
1155                !span.attributes.contains_key(crate::common::datadog::TOP_LEVEL_KEY),
1156                "no span should carry a top-level mark with the fallback disabled"
1157            );
1158        }
1159    }
1160
1161    #[test]
1162    fn process_trace_backfills_metadata_for_forwarded_traces() {
1163        let mut sampler = create_test_sampler();
1164        sampler.sampling_rate = 1.0; // keeps the trace, so it is forwarded
1165        sampler.probabilistic_sampler_enabled = true;
1166
1167        let child = create_span_with_parent_and_service(2, 1, "svc", &[]);
1168        let root = create_span_with_parent_and_service(1, 0, "svc", &[("_dd.origin", "lambda")]);
1169        let mut trace = create_test_trace(vec![child, root]);
1170
1171        let forwarded = sampler.process_trace(&mut trace);
1172        assert!(forwarded);
1173        assert_eq!(
1174            trace.origin.as_ref(),
1175            "lambda",
1176            "origin is backfilled for forwarded traces"
1177        );
1178        assert!(
1179            trace
1180                .spans()
1181                .iter()
1182                .any(|s| s.attributes.contains_key(crate::common::datadog::TOP_LEVEL_KEY)),
1183            "top-level marks are set for forwarded traces"
1184        );
1185    }
1186
1187    #[test]
1188    fn apply_sampling_metadata_sampler_decision_overrides_backfill() {
1189        let sampler = create_test_sampler();
1190        let root = create_test_span(1, 0);
1191        let mut trace = create_test_trace(vec![root]);
1192        trace.decision_maker = Some(MetaString::from("-8"));
1193
1194        sampler.apply_sampling_metadata(&mut trace, true, PRIORITY_AUTO_KEEP, DECISION_MAKER_PROBABILISTIC, 0);
1195
1196        assert_eq!(trace.decision_maker.as_deref(), Some(DECISION_MAKER_PROBABILISTIC));
1197        assert_eq!(
1198            trace.spans()[0]
1199                .attributes
1200                .get(TAG_DECISION_MAKER)
1201                .and_then(AttributeValue::as_string)
1202                .map(|s| s.as_ref()),
1203            Some(DECISION_MAKER_PROBABILISTIC)
1204        );
1205    }
1206
1207    #[test]
1208    fn user_priority_detection() {
1209        let sampler = create_test_sampler();
1210
1211        // Test trace with user-set priority = 2 (UserKeep)
1212        let mut metrics = HashMap::new();
1213        metrics.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 2.0);
1214        let span = create_test_span_with_metrics(1, metrics);
1215        let trace = create_test_trace(vec![span]);
1216        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1217
1218        assert_eq!(sampler.get_user_priority(&trace, root_idx), Some(2));
1219
1220        // Test trace with user-set priority = -1 (UserDrop)
1221        let mut metrics = HashMap::new();
1222        metrics.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), -1.0);
1223        let span = create_test_span_with_metrics(1, metrics);
1224        let trace = create_test_trace(vec![span]);
1225        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1226
1227        assert_eq!(sampler.get_user_priority(&trace, root_idx), Some(-1));
1228
1229        // Test trace without user priority
1230        let span = create_test_span(1, 0);
1231        let trace = create_test_trace(vec![span]);
1232        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1233
1234        assert_eq!(sampler.get_user_priority(&trace, root_idx), None);
1235    }
1236
1237    #[test]
1238    fn trace_level_priority_takes_precedence() {
1239        let sampler = create_test_sampler();
1240
1241        // Test trace-level priority overrides span priorities (last-seen priority)
1242        // Create spans with different priorities - root has 0, later span has 2
1243        let mut metrics_root = HashMap::new();
1244        metrics_root.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 0.0);
1245        let root_span = create_test_span_with_metrics(1, metrics_root);
1246
1247        let mut metrics_later = HashMap::new();
1248        metrics_later.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 1.0);
1249        let later_span = create_test_span_with_metrics(2, metrics_later).with_parent_id(1);
1250
1251        let mut trace = create_test_trace(vec![root_span, later_span]);
1252        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1253
1254        // Without trace-level priority, should get priority from root (0)
1255        assert_eq!(sampler.get_user_priority(&trace, root_idx), Some(0));
1256
1257        // Now set trace-level priority to 2 (simulating last-seen priority from OTLP translator)
1258        trace.priority = Some(2);
1259
1260        // Trace-level priority should take precedence
1261        assert_eq!(sampler.get_user_priority(&trace, root_idx), Some(2));
1262
1263        // Test that trace-level priority is used even when no span has priority
1264        let span_no_priority = create_test_span(3, 0);
1265        let mut trace_only_trace_level = create_test_trace(vec![span_no_priority]);
1266        trace_only_trace_level.priority = Some(1);
1267        let root_idx = sampler.get_root_span_index(&trace_only_trace_level).unwrap();
1268
1269        assert_eq!(sampler.get_user_priority(&trace_only_trace_level, root_idx), Some(1));
1270    }
1271
1272    #[test]
1273    fn manual_keep_with_trace_level_priority() {
1274        let mut sampler = create_test_sampler();
1275        sampler.probabilistic_sampler_enabled = false; // Use legacy path that checks user priority
1276
1277        // Test that manual keep (priority = 2) works via trace-level priority
1278        let span = create_test_span(1, 0);
1279        let mut trace = create_test_trace(vec![span]);
1280        trace.priority = Some(PRIORITY_USER_KEEP);
1281
1282        let SamplerOutcome {
1283            keep,
1284            priority,
1285            decision_maker,
1286            ..
1287        } = sampler.run_samplers(&mut trace);
1288        assert!(keep);
1289        assert_eq!(priority, PRIORITY_USER_KEEP);
1290        assert_eq!(decision_maker, "");
1291
1292        // Test manual drop (priority = -1) via trace-level priority
1293        let span = create_test_span(1, 0);
1294        let mut trace = create_test_trace(vec![span]);
1295        trace.priority = Some(PRIORITY_USER_DROP);
1296
1297        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1298        assert!(!keep); // Should not keep when user drops
1299        assert_eq!(priority, PRIORITY_USER_DROP);
1300
1301        // Test that priority = 1 (auto keep) via trace-level is also respected
1302        let span = create_test_span(1, 0);
1303        let mut trace = create_test_trace(vec![span]);
1304        trace.priority = Some(PRIORITY_AUTO_KEEP);
1305
1306        let SamplerOutcome {
1307            keep,
1308            priority,
1309            decision_maker,
1310            ..
1311        } = sampler.run_samplers(&mut trace);
1312        assert!(keep);
1313        assert_eq!(priority, PRIORITY_AUTO_KEEP);
1314        assert_eq!(decision_maker, "");
1315    }
1316
1317    #[test]
1318    fn probabilistic_sampling_known_decisions() {
1319        // The bucketed probabilistic sampler is fully deterministic: it hashes the trace ID into one of 0x4000
1320        // buckets and keeps the trace when `bucket < (rate * 0x4000)`. These cases pin the exact keep/drop decision
1321        // for known trace IDs at known rates, so a regression in the hash, the bucket mask, or the comparison is
1322        // caught (a determinism-only check would not catch any of those).
1323        //
1324        // Expected values were computed directly from the FNV-1a bucket math in `ProbabilisticSampler::sample`.
1325        // For reference, the trace IDs below hash to these buckets (out of 0x4000 = 16384):
1326        // 0x1234567890ABCDEF -> 1764, 0x0 -> 9301, u64::MAX -> 12365.
1327        struct Case {
1328            trace_id: u64,
1329            rate: f64,
1330            expected_keep: bool,
1331        }
1332
1333        let cases = [
1334            // rate 1.0 keeps every trace (the maximum bucket, 16383, is always below 16384).
1335            Case {
1336                trace_id: 0x1234567890ABCDEF,
1337                rate: 1.0,
1338                expected_keep: true,
1339            },
1340            // rate 0.0 drops every trace (no bucket is below 0).
1341            Case {
1342                trace_id: 0x1234567890ABCDEF,
1343                rate: 0.0,
1344                expected_keep: false,
1345            },
1346            // Same trace ID (bucket 1764) flips from drop to keep as the rate crosses its bucket ratio (~0.108).
1347            Case {
1348                trace_id: 0x1234567890ABCDEF,
1349                rate: 0.10,
1350                expected_keep: false,
1351            },
1352            Case {
1353                trace_id: 0x1234567890ABCDEF,
1354                rate: 0.20,
1355                expected_keep: true,
1356            },
1357            // Trace ID 0 (bucket 9301) straddles rate 0.5 (scaled bucket 8192) vs 0.6 (scaled bucket 9830).
1358            Case {
1359                trace_id: 0,
1360                rate: 0.50,
1361                expected_keep: false,
1362            },
1363            Case {
1364                trace_id: 0,
1365                rate: 0.60,
1366                expected_keep: true,
1367            },
1368            // u64::MAX (bucket 12365) straddles rate 0.5 vs 0.8.
1369            Case {
1370                trace_id: u64::MAX,
1371                rate: 0.50,
1372                expected_keep: false,
1373            },
1374            Case {
1375                trace_id: u64::MAX,
1376                rate: 0.80,
1377                expected_keep: true,
1378            },
1379        ];
1380
1381        for case in cases {
1382            let mut sampler = create_test_sampler();
1383            sampler.sampling_rate = case.rate;
1384            assert_eq!(
1385                sampler.sample_probabilistic(0, case.trace_id),
1386                case.expected_keep,
1387                "trace_id={:#018x} rate={}",
1388                case.trace_id,
1389                case.rate
1390            );
1391        }
1392    }
1393
1394    #[test]
1395    fn probabilistic_sampling_is_deterministic() {
1396        // Determinism is a documented property of `ProbabilisticSampler::sample` (same trace ID + rate always yields
1397        // the same decision). This is intentionally a determinism-only check; correctness is covered by
1398        // `test_probabilistic_sampling_known_decisions`.
1399        let sampler = create_test_sampler();
1400        let trace_id = 0x1234567890ABCDEF_u64;
1401        assert_eq!(
1402            sampler.sample_probabilistic(0, trace_id),
1403            sampler.sample_probabilistic(0, trace_id)
1404        );
1405    }
1406
1407    #[test]
1408    fn probabilistic_sampling_hash_seed_changes_decisions() {
1409        // A seed re-buckets every trace ID: 0x1234567890ABCDEF moves from bucket 1764 with seed 0 to
1410        // bucket 7338 with seed 22, so rates that straddle only one of the buckets flip decisions.
1411        let mut seeded = create_test_sampler();
1412        seeded.probabilistic = probabilistic::ProbabilisticSampler::new(22, false);
1413
1414        // Bucket 7338 (7338/16384 = 0.4479): dropped below 0.45, kept above it.
1415        seeded.sampling_rate = 0.40;
1416        assert!(!seeded.sample_probabilistic(0, 0x1234567890ABCDEF));
1417        seeded.sampling_rate = 0.50;
1418        assert!(seeded.sample_probabilistic(0, 0x1234567890ABCDEF));
1419
1420        // At rate 0.20 the zero-seed sampler keeps this trace (bucket 1764, pinned in
1421        // `probabilistic_sampling_known_decisions`) while the seeded sampler drops it.
1422        seeded.sampling_rate = 0.20;
1423        assert!(!seeded.sample_probabilistic(0, 0x1234567890ABCDEF));
1424        let mut unseeded = create_test_sampler();
1425        unseeded.sampling_rate = 0.20;
1426        assert!(unseeded.sample_probabilistic(0, 0x1234567890ABCDEF));
1427    }
1428
1429    #[test]
1430    fn probabilistic_sampling_full_trace_id_mode_hashes_both_halves() {
1431        let high = 0xAABBCCDD00112233_u64;
1432        let low = 0x1234567890ABCDEF_u64;
1433
1434        // Legacy mode buckets on the low half alone, so the high half cannot move the decision.
1435        let mut legacy = create_test_sampler();
1436        legacy.probabilistic = probabilistic::ProbabilisticSampler::new(22, false);
1437        legacy.sampling_rate = 0.45;
1438        assert_eq!(
1439            legacy.sample_probabilistic(0, low),
1440            legacy.sample_probabilistic(high, low)
1441        );
1442
1443        // Full mode hashes the 16-byte big-endian ID, high half first: (high, low) lands in bucket
1444        // 454 (kept at 0.05, dropped at 0.02), moving the decision relative to legacy mode.
1445        let mut full = create_test_sampler();
1446        full.probabilistic = probabilistic::ProbabilisticSampler::new(22, true);
1447        full.sampling_rate = 0.02;
1448        assert!(!full.sample_probabilistic(high, low));
1449        full.sampling_rate = 0.05;
1450        assert!(full.sample_probabilistic(high, low));
1451
1452        // A zero high half is still a different input than legacy mode: the halves swap byte
1453        // ranges, bucket 14666 versus 7338 (kept at 0.90, dropped at 0.89).
1454        full.sampling_rate = 0.89;
1455        assert!(!full.sample_probabilistic(0, low));
1456        full.sampling_rate = 0.90;
1457        assert!(full.sample_probabilistic(0, low));
1458    }
1459
1460    #[test]
1461    fn every_trace_is_counted_under_exactly_one_sampler() {
1462        // With the probabilistic sampler enabled at rate 1.0, every trace is decided (and kept) by
1463        // it: the sum of seen across all decision keys must equal the number of traces, with no
1464        // double counting across samplers.
1465        let mut sampler = create_test_sampler();
1466
1467        for i in 0..10 {
1468            let span = create_test_span(i, 0);
1469            let mut trace = create_test_trace(vec![span]);
1470            sampler.run_samplers(&mut trace);
1471        }
1472
1473        let decisions = sampler.telemetry.snapshot_decisions();
1474        let total_seen: u64 = decisions.values().map(|counts| counts.seen).sum();
1475        let total_kept: u64 = decisions.values().map(|counts| counts.kept).sum();
1476        assert_eq!(total_seen, 10);
1477        assert_eq!(total_kept, 10);
1478        assert!(decisions
1479            .keys()
1480            .all(|key| key.sampler == telemetry::SamplerName::Probabilistic));
1481        assert!(decisions.keys().all(|key| key.service == "test-service"));
1482    }
1483
1484    #[test]
1485    fn priority_decisions_are_counted_under_the_priority_sampler_with_priority_tag() {
1486        // A trace with a user-set sampling priority is decided by the priority sampler, and its
1487        // decision key carries that priority; no other sampler claims it.
1488        let mut sampler = create_test_sampler();
1489        sampler.probabilistic_sampler_enabled = false;
1490
1491        let mut metrics = HashMap::new();
1492        metrics.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 2.0);
1493        let span = create_test_span_with_metrics(1, metrics);
1494        let mut trace = create_test_trace(vec![span]);
1495        sampler.run_samplers(&mut trace);
1496
1497        let decisions = sampler.telemetry.snapshot_decisions();
1498        assert_eq!(decisions.len(), 1);
1499        let (key, counts) = decisions.iter().next().unwrap();
1500        assert_eq!(key.sampler, telemetry::SamplerName::Priority);
1501        assert_eq!(key.priority, Some(telemetry::Priority::ManualKeep));
1502        assert_eq!(counts.seen, 1);
1503        assert_eq!(counts.kept, 1);
1504    }
1505
1506    #[test]
1507    fn upstream_probability_sampling_reattributes_to_the_probabilistic_sampler() {
1508        // A trace already sampled probabilistically upstream carries the probabilistic decision
1509        // maker; its decision counts under the probabilistic sampler, without the priority
1510        // sampler's sampling_priority or target_env tags.
1511        let mut sampler = create_test_sampler();
1512        sampler.probabilistic_sampler_enabled = false;
1513
1514        let mut metrics = HashMap::new();
1515        metrics.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 2.0);
1516        let mut span = create_test_span_with_metrics(1, metrics);
1517        span.attributes.insert(
1518            MetaString::from_static(TAG_DECISION_MAKER),
1519            AttributeValue::String(MetaString::from_static(DECISION_MAKER_PROBABILISTIC)),
1520        );
1521        let mut trace = create_test_trace(vec![span]);
1522        sampler.run_samplers(&mut trace);
1523
1524        let decisions = sampler.telemetry.snapshot_decisions();
1525        assert_eq!(decisions.len(), 1);
1526        let (key, _) = decisions.iter().next().unwrap();
1527        assert_eq!(key.sampler, telemetry::SamplerName::Probabilistic);
1528        assert_eq!(key.priority, None);
1529    }
1530
1531    #[test]
1532    fn empty_traces_record_no_decision() {
1533        // Unclaimed decisions carry no sampler identity, so they never inflate the unknown series;
1534        // a real attribution gap remains the only thing that could produce one.
1535        let mut sampler = create_test_sampler();
1536        sampler.probabilistic_sampler_enabled = false;
1537
1538        let mut trace = create_test_trace(vec![]);
1539        sampler.run_samplers(&mut trace);
1540        assert!(sampler.telemetry.snapshot_decisions().is_empty());
1541    }
1542
1543    #[test]
1544    fn error_detection() {
1545        let sampler = create_test_sampler();
1546
1547        // Test trace with error field set
1548        let span_with_error = create_test_span(1, 1);
1549        let trace = create_test_trace(vec![span_with_error]);
1550        assert!(sampler.trace_contains_error(&trace, false));
1551
1552        // Test trace without error
1553        let span_without_error = create_test_span(1, 0);
1554        let trace = create_test_trace(vec![span_without_error]);
1555        assert!(!sampler.trace_contains_error(&trace, false));
1556    }
1557
1558    #[test]
1559    fn sampling_priority_order() {
1560        // Test modern path: error sampler overrides probabilistic drop
1561        let mut sampler = create_test_sampler();
1562        sampler.sampling_rate = 0.5; // 50% sampling rate
1563        sampler.probabilistic_sampler_enabled = true;
1564
1565        // Create trace with error that would be dropped by probabilistic
1566        // Using a trace ID that we know will be dropped at 50% rate
1567        let span_with_error = create_test_span(1, 1);
1568        let mut trace = create_test_trace(vec![span_with_error]);
1569        trace.trace_id_low = u64::MAX - 1;
1570
1571        let SamplerOutcome {
1572            keep,
1573            priority,
1574            decision_maker,
1575            ..
1576        } = sampler.run_samplers(&mut trace);
1577        assert!(keep);
1578        assert_eq!(priority, PRIORITY_AUTO_KEEP);
1579        assert_eq!(decision_maker, ""); // Error sampler doesn't set decision_maker
1580
1581        // Test legacy path: user priority is respected
1582        let mut sampler = create_test_sampler();
1583        sampler.probabilistic_sampler_enabled = false; // Use legacy path
1584
1585        let mut metrics = HashMap::new();
1586        metrics.insert(SAMPLING_PRIORITY_METRIC_KEY.to_string(), 2.0);
1587        let span = create_test_span_with_metrics(1, metrics);
1588        let mut trace = create_test_trace(vec![span]);
1589
1590        let SamplerOutcome {
1591            keep,
1592            priority,
1593            decision_maker,
1594            ..
1595        } = sampler.run_samplers(&mut trace);
1596        assert!(keep);
1597        assert_eq!(priority, 2); // UserKeep
1598        assert_eq!(decision_maker, "");
1599    }
1600
1601    #[test]
1602    fn empty_trace_handling() {
1603        let mut sampler = create_test_sampler();
1604        let mut trace = create_test_trace(vec![]);
1605
1606        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1607        assert!(!keep);
1608        assert_eq!(priority, PRIORITY_AUTO_DROP);
1609    }
1610
1611    #[test]
1612    fn root_span_detection() {
1613        let sampler = create_test_sampler();
1614
1615        // Test 1: Root span with parent_id = 0 (common case)
1616        let root_span = DdSpan::new(
1617            MetaString::from("service"),
1618            MetaString::from("operation"),
1619            MetaString::from("resource"),
1620            MetaString::from("type"),
1621            1,
1622            0, // parent_id = 0 indicates root
1623            0,
1624            1000,
1625            0,
1626        );
1627        let child_span = DdSpan::new(
1628            MetaString::from("service"),
1629            MetaString::from("child_op"),
1630            MetaString::from("resource"),
1631            MetaString::from("type"),
1632            2,
1633            1, // parent_id = 1 (points to root)
1634            100,
1635            500,
1636            0,
1637        );
1638        // Put root span second to test that we find it even when not first
1639        let trace = create_test_trace(vec![child_span.clone(), root_span.clone()]);
1640        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1641        assert_eq!(trace.spans()[root_idx].span_id(), 1);
1642
1643        // Test 2: Orphaned span (parent not in trace)
1644        let orphan_span = DdSpan::new(
1645            MetaString::from("service"),
1646            MetaString::from("orphan"),
1647            MetaString::from("resource"),
1648            MetaString::from("type"),
1649            3,
1650            999, // parent_id = 999 (doesn't exist in trace)
1651            200,
1652            300,
1653            0,
1654        );
1655        let trace = create_test_trace(vec![orphan_span]);
1656        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1657        assert_eq!(trace.spans()[root_idx].span_id(), 3);
1658
1659        // Test 3: Multiple root candidates: should return the last one found (index 1)
1660        let span1 = create_test_span(1, 0);
1661        let span2 = create_test_span(2, 0);
1662        let trace = create_test_trace(vec![span1, span2]);
1663        // Both have parent_id = 0, should return the last one found (span_id = 2)
1664        let root_idx = sampler.get_root_span_index(&trace).unwrap();
1665        assert_eq!(trace.spans()[root_idx].span_id(), 2);
1666    }
1667
1668    #[test]
1669    fn single_span_sampling() {
1670        let mut sampler = create_test_sampler();
1671
1672        // Test 1: Trace with SSS tags should be kept even when probabilistic would drop it
1673        sampler.sampling_rate = 0.0; // 0% sampling rate - should drop everything
1674        sampler.probabilistic_sampler_enabled = true;
1675
1676        // Create span with SSS metric
1677        let mut attrs_map = saluki_common::collections::FastHashMap::default();
1678        attrs_map.insert(
1679            MetaString::from(KEY_SPAN_SAMPLING_MECHANISM),
1680            AttributeValue::Float(8.0),
1681        );
1682        let sss_span = create_test_span(1, 0).with_attributes(attrs_map.clone());
1683
1684        // Create regular span without SSS
1685        let regular_span = create_test_span(2, 0);
1686
1687        let mut trace = create_test_trace(vec![sss_span.clone(), regular_span]);
1688
1689        // Apply SSS
1690        let modified = sampler.single_span_sampling(&mut trace);
1691        assert!(modified);
1692        assert_eq!(trace.spans().len(), 1); // Only SSS span kept
1693        assert_eq!(trace.spans()[0].span_id(), 1); // It's the SSS span
1694
1695        // Check that trace has been marked as kept with high priority
1696        assert_eq!(trace.priority, Some(PRIORITY_USER_KEEP));
1697
1698        // Test 2: Trace without SSS tags should not be modified
1699        let trace_without_sss = create_test_trace(vec![create_test_span(3, 0)]);
1700        let mut trace_copy = trace_without_sss.clone();
1701        let modified = sampler.single_span_sampling(&mut trace_copy);
1702        assert!(!modified);
1703        assert_eq!(trace_copy.spans().len(), trace_without_sss.spans().len());
1704    }
1705
1706    #[test]
1707    fn probabilistic_sampling_with_prob_rate_key() {
1708        let mut sampler = create_test_sampler();
1709        sampler.sampling_rate = 0.75; // 75% sampling rate
1710        sampler.probabilistic_sampler_enabled = true;
1711
1712        // Use a trace ID that we know will be sampled
1713        let trace_id = 12345_u64;
1714        let root_span = DdSpan::new(
1715            MetaString::from("service"),
1716            MetaString::from("operation"),
1717            MetaString::from("resource"),
1718            MetaString::from("type"),
1719            1,
1720            0, // parent_id = 0 indicates root
1721            0,
1722            1000,
1723            0,
1724        );
1725        let mut trace = create_test_trace(vec![root_span]);
1726        trace.trace_id_low = trace_id;
1727
1728        let SamplerOutcome {
1729            keep,
1730            priority,
1731            decision_maker,
1732            root_span_idx,
1733            ..
1734        } = sampler.run_samplers(&mut trace);
1735
1736        if keep && decision_maker == DECISION_MAKER_PROBABILISTIC {
1737            // If sampled probabilistically, check that probRateKey was already added
1738            assert_eq!(priority, PRIORITY_AUTO_KEEP);
1739            assert_eq!(decision_maker, DECISION_MAKER_PROBABILISTIC); // probabilistic sampling marker
1740
1741            // Check that the root span already has the probRateKey (it should have been added in run_samplers)
1742            let root_idx = root_span_idx.unwrap_or(0);
1743            let root_span = &trace.spans()[root_idx];
1744            assert!(root_span.attributes.contains_key(PROB_RATE_KEY));
1745            assert_eq!(
1746                root_span
1747                    .attributes
1748                    .get(PROB_RATE_KEY)
1749                    .and_then(AttributeValue::as_float),
1750                Some(0.75)
1751            );
1752
1753            // Test that apply_sampling_metadata still works correctly for other metadata
1754            let mut trace_with_metadata = trace.clone();
1755            sampler.apply_sampling_metadata(&mut trace_with_metadata, keep, priority, decision_maker, root_idx);
1756
1757            // Check that decision maker tag was added
1758            let modified_root = &trace_with_metadata.spans()[root_idx];
1759            assert!(modified_root.attributes.contains_key(TAG_DECISION_MAKER));
1760            assert_eq!(
1761                modified_root
1762                    .attributes
1763                    .get(TAG_DECISION_MAKER)
1764                    .and_then(AttributeValue::as_string),
1765                Some(&MetaString::from(DECISION_MAKER_PROBABILISTIC))
1766            );
1767        }
1768    }
1769
1770    // ── Rare-sampler interaction tests ──────────────────────────────────────────
1771    // Adapted from datadog-agent/pkg/trace/agent/agent_test.go TestSampling cases:
1772    // "rare-sampler-catch-unsampled", "rare-sampler-catch-sampled",
1773    // "rare-sampler-disabled", and related probabilistic path interactions.
1774
1775    /// Create a top-level span eligible for rare sampling.
1776    ///
1777    /// The rare sampler only considers spans that have `_top_level=1` or `_dd.measured=1`.
1778    /// This helper sets `_top_level=1` so that the rare sampler can consider the span.
1779    fn create_top_level_span(span_id: u64) -> DdSpan {
1780        let mut attrs = saluki_common::collections::FastHashMap::default();
1781        attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
1782        create_test_span(span_id, 0).with_attributes(attrs)
1783    }
1784
1785    /// Create a `TraceSampler` with the rare sampler enabled and a very high TPS limit so it
1786    /// freely samples first occurrences, plus a long TTL so second occurrences stay within TTL.
1787    fn create_sampler_with_rare_enabled() -> TraceSampler {
1788        TraceSampler {
1789            rare_sampler: rare_sampler::RareSampler::new(
1790                true,
1791                1000.0,
1792                std::time::Duration::from_secs(300),
1793                200,
1794                telemetry::SamplerCounters::new(),
1795            ),
1796            ..create_test_sampler()
1797        }
1798    }
1799
1800    /// Adapted from Go "rare-sampler-catch-unsampled":
1801    ///
1802    /// Rare is enabled + probabilistic would drop → rare catches it (first occurrence).
1803    #[test]
1804    fn rare_sampler_catches_unsampled_trace() {
1805        let mut sampler = create_sampler_with_rare_enabled();
1806        sampler.sampling_rate = 0.0; // probabilistic drops everything
1807        sampler.probabilistic_sampler_enabled = true;
1808
1809        let span = create_top_level_span(1);
1810        let mut trace = create_test_trace(vec![span]);
1811
1812        let SamplerOutcome {
1813            keep,
1814            priority,
1815            decision_maker,
1816            ..
1817        } = sampler.run_samplers(&mut trace);
1818        assert!(keep, "rare sampler should catch first occurrence");
1819        assert_eq!(priority, PRIORITY_AUTO_KEEP);
1820        assert_eq!(decision_maker, "", "rare sampler does not set _dd.p.dm");
1821    }
1822
1823    /// Adapted from Go "rare-sampler-catch-sampled" (first trace):
1824    ///
1825    /// Rare is enabled, first occurrence—trace is kept and `_dd.rare` is set on the span.
1826    #[test]
1827    fn rare_sampler_sets_rare_metric_on_first_occurrence() {
1828        let mut sampler = create_sampler_with_rare_enabled();
1829        sampler.sampling_rate = 0.0;
1830        sampler.probabilistic_sampler_enabled = true;
1831
1832        let span = create_top_level_span(1);
1833        let mut trace = create_test_trace(vec![span]);
1834
1835        let SamplerOutcome {
1836            keep,
1837            root_span_idx: root_idx,
1838            ..
1839        } = sampler.run_samplers(&mut trace);
1840        assert!(keep);
1841        let root = &trace.spans()[root_idx.unwrap()];
1842        assert_eq!(
1843            root.attributes
1844                .get(rare_sampler::RARE_KEY)
1845                .and_then(AttributeValue::as_float),
1846            Some(1.0),
1847            "_dd.rare should be 1 on first occurrence"
1848        );
1849    }
1850
1851    /// Adapted from Go "rare-sampler-catch-sampled" (second trace same signature):
1852    ///
1853    /// Within the TTL, the same signature is no longer "rare" and rare doesn't re-sample it.
1854    /// With probabilistic at 0%, the trace should be dropped.
1855    #[test]
1856    fn rare_sampler_does_not_resample_within_ttl() {
1857        let mut sampler = create_sampler_with_rare_enabled();
1858        sampler.sampling_rate = 0.0;
1859        sampler.probabilistic_sampler_enabled = true;
1860
1861        // First trace: rare catches it.
1862        let span1 = create_top_level_span(1);
1863        let mut trace1 = create_test_trace(vec![span1]);
1864        let SamplerOutcome { keep: keep1, .. } = sampler.run_samplers(&mut trace1);
1865        assert!(keep1, "first occurrence should be kept by rare sampler");
1866
1867        // Second trace: same signature (same service/operation/resource on the top-level span),
1868        // still within TTL → rare won't catch it; probabilistic at 0% drops it.
1869        let span2 = create_top_level_span(2);
1870        let mut trace2 = create_test_trace(vec![span2]);
1871        let SamplerOutcome {
1872            keep: keep2,
1873            priority: priority2,
1874            ..
1875        } = sampler.run_samplers(&mut trace2);
1876        assert!(!keep2, "second occurrence within TTL should be dropped");
1877        assert_eq!(priority2, PRIORITY_AUTO_DROP);
1878    }
1879
1880    /// Adapted from Go "rare-sampler-disabled":
1881    ///
1882    /// Rare is disabled + probabilistic at 0% → trace is dropped.
1883    #[test]
1884    fn rare_sampler_disabled_does_not_catch_unsampled() {
1885        let mut sampler = create_test_sampler(); // rare disabled by default
1886        sampler.sampling_rate = 0.0;
1887        sampler.probabilistic_sampler_enabled = true;
1888
1889        let span = create_top_level_span(1);
1890        let mut trace = create_test_trace(vec![span]);
1891
1892        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1893        assert!(!keep, "rare disabled should not catch the trace");
1894        assert_eq!(priority, PRIORITY_AUTO_DROP);
1895    }
1896
1897    /// Rare + non-probabilistic path (priority path): rare catches `PriorityAutoDrop` on first
1898    /// occurrence, preserving the tracer-set priority rather than upgrading to AutoKeep.
1899    #[test]
1900    fn rare_sampler_catches_priority_auto_drop_in_legacy_path() {
1901        let mut sampler = create_sampler_with_rare_enabled();
1902        sampler.probabilistic_sampler_enabled = false;
1903
1904        let mut attrs = saluki_common::collections::FastHashMap::default();
1905        attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
1906        attrs.insert(
1907            MetaString::from(SAMPLING_PRIORITY_METRIC_KEY),
1908            AttributeValue::Float(PRIORITY_AUTO_DROP as f64),
1909        );
1910        let span = create_test_span(1, 0).with_attributes(attrs);
1911        let mut trace = create_test_trace(vec![span]);
1912
1913        let SamplerOutcome {
1914            keep,
1915            priority,
1916            decision_maker,
1917            ..
1918        } = sampler.run_samplers(&mut trace);
1919        assert!(keep, "rare sampler should catch PriorityAutoDrop on first occurrence");
1920        assert_eq!(priority, PRIORITY_AUTO_DROP, "tracer-set priority should be preserved");
1921        assert_eq!(decision_maker, "");
1922    }
1923
1924    /// Rare + non-probabilistic path (priority path): UserKeep priority is preserved, not
1925    /// downgraded to AutoKeep. Mirrors Go agent behavior at agent.go#L1129-1131.
1926    #[test]
1927    fn rare_sampler_preserves_user_keep_priority_in_legacy_path() {
1928        let mut sampler = create_sampler_with_rare_enabled();
1929        sampler.probabilistic_sampler_enabled = false;
1930
1931        let mut attrs = saluki_common::collections::FastHashMap::default();
1932        attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
1933        attrs.insert(
1934            MetaString::from(SAMPLING_PRIORITY_METRIC_KEY),
1935            AttributeValue::Float(2.0),
1936        ); // UserKeep
1937        let span = create_test_span(1, 0).with_attributes(attrs);
1938        let mut trace = create_test_trace(vec![span]);
1939
1940        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1941        assert!(keep);
1942        assert_eq!(priority, 2, "UserKeep priority must not be downgraded to AutoKeep");
1943    }
1944
1945    /// Probabilistic path with 100% rate and rare disabled: keep with `_dd.p.dm = "-9"`.
1946    #[test]
1947    fn probabilistic_100_percent_keeps_trace_with_decision_maker() {
1948        let mut sampler = create_test_sampler(); // rare disabled
1949        sampler.sampling_rate = 1.0;
1950        sampler.probabilistic_sampler_enabled = true;
1951
1952        let span = create_top_level_span(1);
1953        let mut trace = create_test_trace(vec![span]);
1954
1955        let SamplerOutcome {
1956            keep,
1957            priority,
1958            decision_maker,
1959            ..
1960        } = sampler.run_samplers(&mut trace);
1961        assert!(keep);
1962        assert_eq!(priority, PRIORITY_AUTO_KEEP);
1963        assert_eq!(decision_maker, DECISION_MAKER_PROBABILISTIC);
1964    }
1965
1966    /// Probabilistic path with 0% rate and rare disabled: drop.
1967    #[test]
1968    fn probabilistic_0_percent_drops_trace() {
1969        let mut sampler = create_test_sampler(); // rare disabled
1970        sampler.sampling_rate = 0.0;
1971        sampler.probabilistic_sampler_enabled = true;
1972        sampler.error_sampling_enabled = false;
1973
1974        let span = create_top_level_span(1);
1975        let mut trace = create_test_trace(vec![span]);
1976
1977        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1978        assert!(!keep);
1979        assert_eq!(priority, PRIORITY_AUTO_DROP);
1980    }
1981
1982    /// Rare sampler should catch OTLP traces without a sampling priority on their first occurrence,
1983    /// matching the Go agent behavior: https://github.com/DataDog/datadog-agent/blob/main/pkg/trace/agent/agent.go#L1129-L1140
1984    #[test]
1985    fn otlp_rate_decisions_record_under_the_probabilistic_sampler() {
1986        // Keeps and drops from the OTLP rate decision both belong to the probabilistic sampler;
1987        // the drop must not fall through to the no-priority bucket.
1988        let mut sampler = create_test_sampler();
1989        sampler.probabilistic_sampler_enabled = false;
1990        sampler.error_sampling_enabled = false;
1991
1992        let mut trace = create_otlp_test_trace(
1993            vec![create_top_level_span(1)],
1994            OTLP_TEST_RECEIVER_SAMPLING_RATE,
1995            OTLP_RECEIVER_DROPPED_TRACE_ID,
1996        );
1997
1998        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
1999        assert!(!keep);
2000        assert_eq!(priority, PRIORITY_AUTO_DROP);
2001
2002        let decisions = sampler.telemetry.snapshot_decisions();
2003        let (key, counts) = decisions.iter().next().unwrap();
2004        assert_eq!(key.sampler, telemetry::SamplerName::Probabilistic);
2005        assert_eq!(counts.seen, 1);
2006        assert_eq!(counts.kept, 0);
2007    }
2008
2009    #[test]
2010    fn rare_sampler_catches_otlp_no_priority_trace() {
2011        let mut sampler = create_sampler_with_rare_enabled();
2012        sampler.probabilistic_sampler_enabled = false;
2013        sampler.error_sampling_enabled = false;
2014
2015        let mut trace = create_otlp_test_trace(
2016            vec![create_top_level_span(1)],
2017            OTLP_TEST_RECEIVER_SAMPLING_RATE,
2018            OTLP_RECEIVER_DROPPED_TRACE_ID,
2019        );
2020
2021        let SamplerOutcome {
2022            keep,
2023            priority,
2024            decision_maker,
2025            root_span_idx: root_idx,
2026            ..
2027        } = sampler.run_samplers(&mut trace);
2028        assert!(
2029            keep,
2030            "rare sampler should keep OTLP trace with no priority on first occurrence"
2031        );
2032        assert_eq!(priority, PRIORITY_AUTO_KEEP);
2033        assert_eq!(decision_maker, "");
2034        assert_eq!(
2035            trace.spans()[root_idx.unwrap()]
2036                .attributes
2037                .get(rare_sampler::RARE_KEY)
2038                .and_then(AttributeValue::as_float),
2039            Some(1.0),
2040            "_dd.rare should be set to 1 on first occurrence"
2041        );
2042    }
2043
2044    /// Adapted from Go "probabilistic-rare-100":
2045    ///
2046    /// Rare fires before probabilistic is consulted, so even at 100% sampling rate the decision
2047    /// maker tag isn't set—the trace is attributed to rare, not probabilistic.
2048    #[test]
2049    fn rare_wins_over_probabilistic_no_decision_maker_tag() {
2050        let mut sampler = create_sampler_with_rare_enabled();
2051        sampler.sampling_rate = 1.0;
2052        sampler.probabilistic_sampler_enabled = true;
2053
2054        let span = create_top_level_span(1);
2055        let mut trace = create_test_trace(vec![span]);
2056
2057        let SamplerOutcome {
2058            keep,
2059            priority,
2060            decision_maker,
2061            ..
2062        } = sampler.run_samplers(&mut trace);
2063        assert!(keep);
2064        assert_eq!(priority, PRIORITY_AUTO_KEEP);
2065        assert_eq!(decision_maker, "", "rare takes precedence—_dd.p.dm must not be set");
2066    }
2067
2068    /// Adapted from Go "error-sampled-prio-unsampled":
2069    ///
2070    /// Rare fires before the error sampler is reached. A no-priority error trace on its first
2071    /// occurrence is kept by rare, not by the error sampler.
2072    #[test]
2073    fn rare_catches_error_trace_before_error_sampler() {
2074        let mut sampler = create_sampler_with_rare_enabled();
2075        sampler.probabilistic_sampler_enabled = false;
2076        sampler.error_sampling_enabled = true;
2077
2078        let span = create_top_level_span(1);
2079        let error_span = create_test_span(2, 1); // error=1
2080        let mut trace = create_test_trace(vec![span, error_span]);
2081
2082        let SamplerOutcome {
2083            keep,
2084            priority,
2085            decision_maker,
2086            ..
2087        } = sampler.run_samplers(&mut trace);
2088        assert!(keep, "rare should catch the trace before the error sampler");
2089        assert_eq!(priority, PRIORITY_AUTO_KEEP);
2090        assert_eq!(decision_maker, "");
2091    }
2092
2093    /// Adapted from Go manual-drop short-circuit behavior:
2094    ///
2095    /// UserDrop (-1) priority is checked before rare runs in the priority path. A UserDrop trace
2096    /// must be dropped even when rare is enabled and would otherwise match.
2097    #[test]
2098    fn manual_drop_short_circuits_before_rare() {
2099        let mut sampler = create_sampler_with_rare_enabled();
2100        sampler.probabilistic_sampler_enabled = false;
2101
2102        let mut attrs = saluki_common::collections::FastHashMap::default();
2103        attrs.insert(MetaString::from("_top_level"), AttributeValue::Float(1.0));
2104        attrs.insert(
2105            MetaString::from(SAMPLING_PRIORITY_METRIC_KEY),
2106            AttributeValue::Float(-1.0),
2107        ); // UserDrop
2108        let span = create_test_span(1, 0).with_attributes(attrs);
2109        let mut trace = create_test_trace(vec![span]);
2110
2111        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
2112        assert!(!keep, "UserDrop must be dropped even when rare would match");
2113        assert_eq!(priority, -1);
2114    }
2115
2116    // ── Error Tracking Standalone tests ─────────────────────────────────────────
2117    // Adapted from datadog-agent/pkg/trace/agent/agent.go runSamplers ETS block.
2118
2119    fn create_sampler_with_ets() -> TraceSampler {
2120        TraceSampler {
2121            error_tracking_standalone: true,
2122            ..create_test_sampler()
2123        }
2124    }
2125
2126    /// ETS enabled + trace with error → kept by error sampler.
2127    #[test]
2128    fn ets_keeps_trace_with_error() {
2129        let mut sampler = create_sampler_with_ets();
2130
2131        let span = create_test_span(1, 1); // error=1
2132        let mut trace = create_test_trace(vec![span]);
2133
2134        let SamplerOutcome {
2135            keep,
2136            priority,
2137            decision_maker,
2138            ..
2139        } = sampler.run_samplers(&mut trace);
2140        assert!(keep, "ETS should keep traces with errors");
2141        assert_eq!(priority, PRIORITY_AUTO_KEEP);
2142        assert_eq!(decision_maker, "", "ETS does not set a decision maker");
2143    }
2144
2145    /// ETS enabled + trace without error → dropped; rare/probabilistic/priority not consulted.
2146    #[test]
2147    fn ets_drops_trace_without_error() {
2148        let mut sampler = create_sampler_with_ets();
2149
2150        let span = create_test_span(1, 0); // error=0
2151        let mut trace = create_test_trace(vec![span]);
2152
2153        let SamplerOutcome { keep, priority, .. } = sampler.run_samplers(&mut trace);
2154        assert!(!keep, "ETS should drop traces without errors");
2155        assert_eq!(priority, PRIORITY_AUTO_DROP);
2156    }
2157
2158    /// ETS enabled + non-error trace → forwarded with DroppedTrace=true; SSS/analytics suppressed.
2159    #[test]
2160    fn ets_forwards_dropped_trace_with_dropped_flag() {
2161        let mut sampler = create_sampler_with_ets();
2162
2163        // Span with SSS metric — would trigger single span sampling in non-ETS mode.
2164        let mut attrs = saluki_common::collections::FastHashMap::default();
2165        attrs.insert(
2166            MetaString::from(KEY_SPAN_SAMPLING_MECHANISM),
2167            AttributeValue::Float(8.0),
2168        );
2169        let span = create_test_span(1, 0).with_attributes(attrs);
2170        let mut trace = create_test_trace(vec![span]);
2171
2172        let forwarded = sampler.process_trace(&mut trace);
2173        assert!(forwarded, "ETS should forward non-error traces to intake");
2174        assert!(trace.dropped_trace, "non-error ETS trace should have DroppedTrace=true");
2175    }
2176
2177    /// ETS enabled + trace with exception span event → kept (exception events count as errors in ETS).
2178    #[test]
2179    fn ets_keeps_trace_with_exception_span_event() {
2180        let mut sampler = create_sampler_with_ets();
2181
2182        // Span with error=0 but exception span event metadata.
2183        let mut attrs = saluki_common::collections::FastHashMap::default();
2184        attrs.insert(
2185            MetaString::from("_dd.span_events.has_exception"),
2186            AttributeValue::String(MetaString::from("true")),
2187        );
2188        let span = create_test_span(1, 0).with_attributes(attrs);
2189        let mut trace = create_test_trace(vec![span]);
2190
2191        let SamplerOutcome { keep, .. } = sampler.run_samplers(&mut trace);
2192        assert!(keep, "ETS should treat exception span events as errors");
2193    }
2194
2195    /// ETS disabled → normal sampling path (probabilistic) is used.
2196    #[test]
2197    fn ets_disabled_uses_normal_sampling() {
2198        let mut sampler = create_test_sampler(); // ETS disabled
2199        sampler.sampling_rate = 1.0;
2200        sampler.probabilistic_sampler_enabled = true;
2201
2202        let span = create_test_span(1, 0); // no error
2203        let mut trace = create_test_trace(vec![span]);
2204
2205        let SamplerOutcome {
2206            keep, decision_maker, ..
2207        } = sampler.run_samplers(&mut trace);
2208        assert!(keep, "normal probabilistic sampling should keep the trace");
2209        assert_eq!(decision_maker, DECISION_MAKER_PROBABILISTIC);
2210    }
2211
2212    // ── ETS + OTLP pre-sampling tests ────────────────────────────────────────────
2213    // These mirror DDA's OTLPReceiver.createChunks behavior which pre-assigns
2214    // priority/dm before runSamplersV1, so ETS sees those values even when it
2215    // short-circuits. See: pkg/trace/api/otlp.go#L561-L585.
2216
2217    fn create_receiver_kept_otlp_test_trace(spans: Vec<DdSpan>) -> Trace {
2218        create_otlp_test_trace(spans, OTLP_TEST_RECEIVER_SAMPLING_RATE, OTLP_RECEIVER_KEPT_TRACE_ID)
2219    }
2220
2221    fn create_sampler_with_ets_legacy() -> TraceSampler {
2222        TraceSampler {
2223            error_tracking_standalone: true,
2224            probabilistic_sampler_enabled: false,
2225            ..create_test_sampler()
2226        }
2227    }
2228
2229    /// ETS + OTLP non-error trace (legacy sampler path): pre-sampling sets priority=AutoKeep and dm=-9.
2230    /// Mirrors DDA `OTLPReceiver` assigning priority=1 + dm=-9 before ETS returns early.
2231    #[test]
2232    fn ets_otlp_non_error_gets_presample_priority_and_dm() {
2233        let mut sampler = create_sampler_with_ets_legacy();
2234
2235        let span = create_test_span(1, 0); // no error
2236        let mut trace = create_receiver_kept_otlp_test_trace(vec![span]);
2237
2238        let SamplerOutcome {
2239            keep,
2240            priority,
2241            decision_maker: dm,
2242            ..
2243        } = sampler.run_samplers(&mut trace);
2244        assert!(!keep, "ETS should drop non-error OTLP traces");
2245        assert_eq!(
2246            priority, PRIORITY_AUTO_KEEP,
2247            "OTLP pre-sampling sets priority=AutoKeep even for ETS-dropped traces"
2248        );
2249        assert_eq!(dm, DECISION_MAKER_PROBABILISTIC, "OTLP pre-sampling sets dm=-9");
2250    }
2251
2252    /// ETS + OTLP error trace (legacy sampler path): pre-sampling sets priority=AutoKeep and dm=-9.
2253    #[test]
2254    fn ets_otlp_error_gets_presample_priority_and_dm() {
2255        let mut sampler = create_sampler_with_ets_legacy();
2256
2257        let span = create_test_span(1, 1); // error=1
2258        let mut trace = create_receiver_kept_otlp_test_trace(vec![span]);
2259
2260        let SamplerOutcome {
2261            keep,
2262            priority,
2263            decision_maker: dm,
2264            ..
2265        } = sampler.run_samplers(&mut trace);
2266        assert!(keep, "ETS should keep error OTLP traces");
2267        assert_eq!(priority, PRIORITY_AUTO_KEEP, "OTLP pre-sampling sets priority=AutoKeep");
2268        assert_eq!(dm, DECISION_MAKER_PROBABILISTIC, "OTLP pre-sampling sets dm=-9");
2269    }
2270
2271    /// ETS + OTLP trace dropped by the receiver rate (legacy sampler path): a drop is not stamped with a decision maker.
2272    #[test]
2273    fn ets_otlp_receiver_drop_gets_drop_priority_and_no_dm() {
2274        let mut sampler = create_sampler_with_ets_legacy();
2275
2276        let mut trace = create_otlp_test_trace(
2277            vec![create_test_span(1, 0)],
2278            OTLP_TEST_RECEIVER_SAMPLING_RATE,
2279            OTLP_RECEIVER_DROPPED_TRACE_ID,
2280        );
2281
2282        assert!(sampler.process_trace(&mut trace), "ETS forwards non-error traces");
2283        assert!(trace.dropped_trace);
2284        assert_eq!(trace.priority, Some(PRIORITY_AUTO_DROP));
2285        assert_eq!(trace.decision_maker, None);
2286    }
2287
2288    /// ETS + OTLP + probabilistic_sampler_enabled=true: `OTLPReceiver` defers, no pre-sampling.
2289    /// DDA's `OTLPReceiver` sets PriorityNone and skips when ProbabilisticSamplerEnabled.
2290    #[test]
2291    fn ets_otlp_probabilistic_path_skips_presample() {
2292        let mut sampler = create_sampler_with_ets_legacy();
2293        sampler.probabilistic_sampler_enabled = true; // override to prob path
2294
2295        let span = create_test_span(1, 0); // no error
2296        let mut trace = create_receiver_kept_otlp_test_trace(vec![span]);
2297
2298        let SamplerOutcome {
2299            keep,
2300            priority,
2301            decision_maker: dm,
2302            ..
2303        } = sampler.run_samplers(&mut trace);
2304        assert!(!keep, "ETS should drop non-error traces");
2305        assert_eq!(
2306            priority, PRIORITY_AUTO_DROP,
2307            "no pre-sampling when probabilistic path active"
2308        );
2309        assert_eq!(dm, "", "no dm when probabilistic path active");
2310    }
2311
2312    /// ETS + non-OTLP trace (legacy sampler path): behavior unchanged—no pre-sampling.
2313    #[test]
2314    fn ets_non_otlp_unaffected_by_presample() {
2315        let mut sampler = create_sampler_with_ets_legacy();
2316
2317        let span = create_test_span(1, 0); // no error, no OTLP meta
2318        let mut trace = create_test_trace(vec![span]);
2319
2320        let SamplerOutcome {
2321            keep,
2322            priority,
2323            decision_maker: dm,
2324            ..
2325        } = sampler.run_samplers(&mut trace);
2326        assert!(!keep, "ETS should drop non-error non-OTLP traces");
2327        assert_eq!(priority, PRIORITY_AUTO_DROP, "non-OTLP traces use default ETS priority");
2328        assert_eq!(dm, "", "non-OTLP traces get no dm");
2329    }
2330
2331    /// ETS + OTLP trace with user-set priority: dm="-4" (manual sampling), matching DDA.
2332    #[test]
2333    fn ets_otlp_user_priority_gets_manual_dm() {
2334        let mut sampler = create_sampler_with_ets_legacy();
2335
2336        let mut span = create_test_span(1, 0);
2337        span.attributes.insert(
2338            MetaString::from(SAMPLING_PRIORITY_METRIC_KEY),
2339            AttributeValue::Float(2.0),
2340        ); // UserKeep
2341        let mut trace = create_receiver_kept_otlp_test_trace(vec![span]);
2342
2343        let SamplerOutcome {
2344            keep,
2345            priority,
2346            decision_maker: dm,
2347            ..
2348        } = sampler.run_samplers(&mut trace);
2349        assert!(!keep, "ETS drops non-error traces regardless of user priority");
2350        assert_eq!(priority, PRIORITY_USER_KEEP, "user priority is preserved");
2351        assert_eq!(dm, DECISION_MAKER_MANUAL, "user-set priority gets dm=-4");
2352    }
2353
2354    // ── Ingest information tests ────────────────────────────────────────────────
2355    // Regression tests: the sampler once classified a trace as OTLP by the `otel.trace_id` attribute on its root
2356    // span. Removing that attribute, or filtering out the original root, sent OTLP traces down the native path, and
2357    // a native trace carrying the attribute was sampled at the OTLP receiver rate. Classification now uses the
2358    // ingest information fixed when the trace is constructed.
2359
2360    #[test]
2361    fn otlp_receiver_sampling_does_not_depend_on_span_attributes_or_root() {
2362        let mut sampler = create_test_sampler();
2363        sampler.probabilistic_sampler_enabled = false;
2364
2365        let span_sets = [
2366            ("rooted", vec![create_test_span(1, 0)]),
2367            (
2368                "original root removed",
2369                vec![
2370                    create_test_span(2, 0).with_parent_id(1),
2371                    create_test_span(3, 0).with_parent_id(2),
2372                ],
2373            ),
2374        ];
2375        let cases = [
2376            (
2377                OTLP_RECEIVER_KEPT_TRACE_ID,
2378                true,
2379                PRIORITY_AUTO_KEEP,
2380                DECISION_MAKER_PROBABILISTIC,
2381            ),
2382            (OTLP_RECEIVER_DROPPED_TRACE_ID, false, PRIORITY_AUTO_DROP, ""),
2383        ];
2384        for (name, spans) in &span_sets {
2385            for (trace_id, want_keep, want_priority, want_dm) in cases {
2386                let mut trace = create_otlp_test_trace(spans.clone(), OTLP_TEST_RECEIVER_SAMPLING_RATE, trace_id);
2387
2388                let SamplerOutcome {
2389                    keep,
2390                    priority,
2391                    decision_maker,
2392                    ..
2393                } = sampler.run_samplers(&mut trace);
2394                assert_eq!(keep, want_keep, "{name}, trace ID {trace_id}");
2395                assert_eq!(priority, want_priority, "{name}, trace ID {trace_id}");
2396                assert_eq!(decision_maker, want_dm, "{name}, trace ID {trace_id}");
2397            }
2398        }
2399    }
2400
2401    #[test]
2402    fn native_trace_with_otel_trace_id_attribute_is_not_sampled_as_otlp() {
2403        let spoofed_trace = || {
2404            let mut span = create_top_level_span(1);
2405            span.attributes.insert(
2406                MetaString::from_static(OTEL_TRACE_ID_META_KEY),
2407                AttributeValue::String(MetaString::from("0000000000000000000000000000007b")),
2408            );
2409            let mut trace = create_test_trace(vec![span]);
2410            trace.trace_id_low = OTLP_RECEIVER_KEPT_TRACE_ID;
2411            trace
2412        };
2413
2414        // Legacy path: the no-priority sampler decides, not the OTLP receiver rate.
2415        let mut sampler = create_test_sampler();
2416        sampler.probabilistic_sampler_enabled = false;
2417        let SamplerOutcome { decision_maker, .. } = sampler.run_samplers(&mut spoofed_trace());
2418        assert_eq!(decision_maker, "");
2419        let decisions = sampler.telemetry.snapshot_decisions();
2420        let (key, _) = decisions.iter().next().unwrap();
2421        assert_eq!(key.sampler, telemetry::SamplerName::NoPriority);
2422
2423        // Error tracking standalone: no OTLP pre-sampling priority or decision maker.
2424        let mut sampler = create_sampler_with_ets_legacy();
2425        let SamplerOutcome {
2426            keep,
2427            priority,
2428            decision_maker,
2429            ..
2430        } = sampler.run_samplers(&mut spoofed_trace());
2431        assert!(!keep);
2432        assert_eq!(priority, PRIORITY_AUTO_DROP);
2433        assert_eq!(decision_maker, "");
2434    }
2435
2436    #[test]
2437    fn probabilistic_decision_maker_placement_follows_ingest_info() {
2438        // The APM probabilistic sampler is enabled at a rate of 1.0, so both traces are kept by it. The OTLP trace
2439        // carries no `otel.trace_id` attribute but still gets its decision maker on the chunk only.
2440        let mut sampler = create_test_sampler();
2441
2442        let mut otlp = create_receiver_kept_otlp_test_trace(vec![create_test_span(1, 0)]);
2443        assert!(sampler.process_trace(&mut otlp));
2444        assert_eq!(otlp.decision_maker.as_deref(), Some(DECISION_MAKER_PROBABILISTIC));
2445        assert!(!otlp.spans()[0].attributes.contains_key(TAG_DECISION_MAKER));
2446
2447        let mut native = create_test_trace(vec![create_test_span(1, 0)]);
2448        assert!(sampler.process_trace(&mut native));
2449        assert_eq!(native.decision_maker.as_deref(), Some(DECISION_MAKER_PROBABILISTIC));
2450    }
2451
2452    #[test]
2453    fn analytics_events_forward_dropped_traces_with_only_event_spans() {
2454        let rates = HashMap::from([("test-service".to_string(), 1.0)]);
2455        let mut sampler = create_test_sampler();
2456        sampler.sampling_rate = 0.0; // probabilistic drops everything
2457        sampler.probabilistic_sampler_enabled = true;
2458        sampler.event_processor = EventProcessor::for_tests(&HashMap::new(), &rates, f64::INFINITY);
2459
2460        let root = create_test_span(1, 0);
2461        let child = create_span_with_parent_and_service(2, 1, "other-service", &[]);
2462        let mut trace = create_test_trace(vec![root, child]);
2463
2464        assert!(sampler.process_trace(&mut trace));
2465        // Only the extracted event spans are forwarded; the trace stays marked dropped so the
2466        // backend indexes them as standalone events, carrying the sampling priority.
2467        assert_eq!(trace.spans().len(), 1);
2468        assert!(trace.dropped_trace);
2469        assert_eq!(trace.priority, Some(PRIORITY_AUTO_DROP));
2470        let event_span = &trace.spans()[0];
2471        assert!(event_span.attributes.contains_key(KEY_ANALYZED_SPANS));
2472        // Extraction rates of 1.0 are not written; the backend assumes 1.0.
2473        assert!(!event_span.attributes.contains_key("_dd1.sr.eausr"));
2474    }
2475
2476    #[test]
2477    fn analytics_events_dropped_trace_without_survivors_is_not_forwarded() {
2478        let mut sampler = create_test_sampler();
2479        sampler.sampling_rate = 0.0; // probabilistic drops everything
2480        sampler.probabilistic_sampler_enabled = true;
2481
2482        let mut trace = create_test_trace(vec![create_test_span(1, 0)]);
2483        // No extractor nominates the span, so the trace is dropped without events.
2484        assert!(!sampler.process_trace(&mut trace));
2485    }
2486
2487    #[test]
2488    fn analytics_events_marks_ride_along_on_kept_traces() {
2489        let rates = HashMap::from([("test-service".to_string(), 1.0)]);
2490        let mut sampler = create_test_sampler();
2491        sampler.event_processor = EventProcessor::for_tests(&HashMap::new(), &rates, f64::INFINITY);
2492
2493        let root = create_test_span(1, 0);
2494        let child = create_span_with_parent_and_service(2, 1, "other-service", &[]);
2495        let mut trace = create_test_trace(vec![root, child]);
2496
2497        assert!(sampler.process_trace(&mut trace));
2498        // The full span payload is forwarded, with the analyzed mark riding along on the root.
2499        assert_eq!(trace.spans().len(), 2);
2500        assert!(!trace.dropped_trace);
2501        assert!(trace.spans()[0].attributes.contains_key(KEY_ANALYZED_SPANS));
2502        assert!(!trace.spans()[1].attributes.contains_key(KEY_ANALYZED_SPANS));
2503    }
2504
2505    #[test]
2506    fn single_span_sampling_wins_over_analytics_events() {
2507        let rates = HashMap::from([("test-service".to_string(), 1.0)]);
2508        let mut sampler = create_test_sampler();
2509        sampler.sampling_rate = 0.0; // probabilistic drops everything
2510        sampler.probabilistic_sampler_enabled = true;
2511        sampler.event_processor = EventProcessor::for_tests(&HashMap::new(), &rates, f64::INFINITY);
2512
2513        let mut attrs = saluki_common::collections::FastHashMap::default();
2514        attrs.insert(
2515            MetaString::from(KEY_SPAN_SAMPLING_MECHANISM),
2516            AttributeValue::Float(8.0),
2517        );
2518        let sss_span = create_test_span(1, 0).with_attributes(attrs);
2519        let mut trace = create_test_trace(vec![sss_span]);
2520
2521        assert!(sampler.process_trace(&mut trace));
2522        // The trace is forwarded as kept by single span sampling, not as dropped events.
2523        assert_eq!(trace.spans().len(), 1);
2524        assert!(!trace.dropped_trace);
2525        assert_eq!(trace.priority, Some(PRIORITY_USER_KEEP));
2526    }
2527
2528    #[test]
2529    fn manual_drop_skips_event_extraction() {
2530        let rates = HashMap::from([("test-service".to_string(), 1.0)]);
2531        let mut sampler = create_test_sampler();
2532        // The legacy path is the one that consults user priority.
2533        sampler.probabilistic_sampler_enabled = false;
2534        sampler.event_processor = EventProcessor::for_tests(&HashMap::new(), &rates, f64::INFINITY);
2535
2536        // Manual drop short-circuits the samplers, and the trace is not promoted to events.
2537        let root = create_test_span(1, 0);
2538        let mut trace = create_test_trace(vec![root]);
2539        trace.priority = Some(PRIORITY_USER_DROP);
2540
2541        assert!(!sampler.process_trace(&mut trace));
2542        assert!(!trace.spans()[0].attributes.contains_key(KEY_ANALYZED_SPANS));
2543    }
2544
2545    // Remote sampling tests based on the Datadog Agent's remote configuration tests:
2546    // https://github.com/DataDog/datadog-agent/blob/17ecddf4e3e/pkg/trace/remoteconfighandler/remote_config_handler_test.go
2547
2548    // With probabilistic sampling set to 0, only the rare sampler can keep test traces.
2549    fn create_remote_sampler(errors_per_second: f64) -> (TestSamplingPublisher, TraceSampler) {
2550        let (publisher, remote_sampling) = TestSamplingPublisher::new();
2551        let sampler = TraceSampler {
2552            sampling_rate: 0.0,
2553            error_sampler: errors::ErrorsSampler::new(errors_per_second, 1.0),
2554            rare_sampler: rare_sampler::RareSampler::new(
2555                false,
2556                1000.0,
2557                std::time::Duration::from_secs(300),
2558                200,
2559                telemetry::SamplerCounters::new(),
2560            ),
2561            static_settings: SamplerSettings {
2562                target_traces_per_second: 10.0,
2563                errors_per_second,
2564                rare_sampler_enabled: false,
2565            },
2566            remote_sampling,
2567            ..create_test_sampler()
2568        };
2569        (publisher, sampler)
2570    }
2571
2572    /// The agent environment resolved from `env: Prod`.
2573    fn prod_env() -> AgentEnv {
2574        AgentEnv::resolve(None, Some("Prod"), &[], &[])
2575    }
2576
2577    /// Sampler settings where probabilistic sampling drops every trace, so only the rare sampler keeps one.
2578    fn rare_only_sampler(agent_env: AgentEnv, remote_sampling: TraceSamplingSubscription) -> TraceSamplerConfiguration {
2579        TraceSamplerConfiguration {
2580            target_traces_per_second: 7.0,
2581            errors_per_second: 9.0,
2582            rare_sampler_enabled: true,
2583            probabilistic_sampler_enabled: true,
2584            sampling_percentage: 0.0,
2585            remote_sampling,
2586            ..sampler_configuration(agent_env)
2587        }
2588    }
2589
2590    fn transform_empty_buffer(sampler: &mut TraceSampler) {
2591        sampler.process_buffer(&mut EventsBuffer::default());
2592    }
2593
2594    fn live_tps(sampler: &TraceSampler) -> (f64, f64) {
2595        (
2596            sampler.priority_sampler.get_target_tps(),
2597            sampler.error_sampler.get_target_tps(),
2598        )
2599    }
2600
2601    fn rare_keeps_new_trace(sampler: &mut TraceSampler, span_id: u64) -> bool {
2602        let mut trace = create_test_trace(vec![
2603            create_top_level_span(span_id).with_service(MetaString::from(format!("rare-probe-{span_id}")))
2604        ]);
2605        sampler.run_samplers(&mut trace).keep
2606    }
2607
2608    /// Covers the Datadog Agent's priority, error, and rare sampler update cases.
2609    #[test]
2610    fn remote_configuration_changes_live_sampler_settings() {
2611        let (publisher, mut sampler) = create_remote_sampler(10.0);
2612        publisher.assign([(
2613            "sampling",
2614            r#"{"all_envs":{"priority_sampler_target_TPS":41,"errors_sampler_target_TPS":42,
2615                "rare_sampler_enabled":true}}"#,
2616        )]);
2617        assert_eq!(live_tps(&sampler), (10.0, 10.0), "nothing applies before a buffer");
2618        assert!(!rare_keeps_new_trace(&mut sampler, 1));
2619
2620        transform_empty_buffer(&mut sampler);
2621        assert_eq!(live_tps(&sampler), (41.0, 42.0));
2622        assert!(rare_keeps_new_trace(&mut sampler, 2));
2623        // Remote settings do not change the no-priority sampler.
2624        assert_eq!(sampler.no_priority_sampler.test_target_tps(), 10.0);
2625    }
2626
2627    #[test]
2628    fn more_than_one_remote_configuration_changes_nothing() {
2629        let (publisher, mut sampler) = create_remote_sampler(10.0);
2630        publisher.assign([
2631            (
2632                "a",
2633                r#"{"all_envs":{"priority_sampler_target_TPS":41,"rare_sampler_enabled":true}}"#,
2634            ),
2635            ("b", r#"{"all_envs":{"errors_sampler_target_TPS":42}}"#),
2636        ]);
2637        transform_empty_buffer(&mut sampler);
2638        assert_eq!(live_tps(&sampler), (10.0, 10.0));
2639        assert!(!rare_keeps_new_trace(&mut sampler, 1));
2640    }
2641
2642    #[test]
2643    fn more_than_one_remote_configuration_after_one_keeps_remote_settings() {
2644        let (publisher, mut sampler) = create_remote_sampler(10.0);
2645        publisher.assign([(
2646            "a",
2647            r#"{"all_envs":{"priority_sampler_target_TPS":41,"errors_sampler_target_TPS":42,
2648                "rare_sampler_enabled":true}}"#,
2649        )]);
2650        transform_empty_buffer(&mut sampler);
2651        assert_eq!(live_tps(&sampler), (41.0, 42.0));
2652
2653        publisher.assign([
2654            ("a", r#"{"all_envs":{"priority_sampler_target_TPS":7}}"#),
2655            ("b", r#"{"all_envs":{"errors_sampler_target_TPS":8}}"#),
2656        ]);
2657        transform_empty_buffer(&mut sampler);
2658        assert_eq!(
2659            live_tps(&sampler),
2660            (41.0, 42.0),
2661            "the rejected assignment changes nothing"
2662        );
2663        assert!(rare_keeps_new_trace(&mut sampler, 1));
2664    }
2665
2666    /// Remote sampling uses the resolved agent environment to select a `by_env` entry.
2667    #[test]
2668    fn remote_sampling_subscription_reaches_the_built_sampler() {
2669        let (publisher, subscription) = TestSamplingPublisher::new();
2670        let config = rare_only_sampler(prod_env(), subscription);
2671        let mut sampler = config.build_sampler();
2672        assert_eq!(live_tps(&sampler), (7.0, 9.0));
2673        assert!(rare_keeps_new_trace(&mut sampler, 1));
2674
2675        // The Datadog Agent's tests send unset fields as `null`.
2676        publisher.assign([(
2677            "sampling",
2678            r#"{"all_envs":{"priority_sampler_target_TPS":null,"errors_sampler_target_TPS":null,
2679                "rare_sampler_enabled":null},
2680                "by_env":[{"env":"prod","config":{"priority_sampler_target_TPS":41,"errors_sampler_target_TPS":42,
2681                "rare_sampler_enabled":false}}]}"#,
2682        )]);
2683        transform_empty_buffer(&mut sampler);
2684        assert_eq!(live_tps(&sampler), (41.0, 42.0), "the normalized env selects `prod`");
2685        assert!(!rare_keeps_new_trace(&mut sampler, 2));
2686
2687        publisher.assign([(
2688            "sampling",
2689            r#"{"all_envs":{"priority_sampler_target_TPS":null,"errors_sampler_target_TPS":null,
2690                "rare_sampler_enabled":null},"by_env":null}"#,
2691        )]);
2692        transform_empty_buffer(&mut sampler);
2693        assert_eq!(
2694            live_tps(&sampler),
2695            (7.0, 9.0),
2696            "each setting reverts to its static value"
2697        );
2698        assert!(rare_keeps_new_trace(&mut sampler, 3));
2699    }
2700
2701    /// Remote selection matches the resolved agent environment exactly.
2702    #[test]
2703    fn remote_selection_matches_the_resolved_agent_env() {
2704        let payload = r#"{"all_envs":{"errors_sampler_target_TPS":30},
2705            "by_env":[{"env":"prod","config":{"priority_sampler_target_TPS":42}},
2706                      {"env":"none","config":{"priority_sampler_target_TPS":41}}]}"#;
2707        let cases = [
2708            // Nothing configured resolves to `none`.
2709            (AgentEnv::resolve(None, None, &[], &[]), (41.0, 30.0)),
2710            (prod_env(), (42.0, 30.0)),
2711            // `!!!` normalizes to empty, which matches no entry: `none` is not applied after normalization.
2712            (AgentEnv::resolve(Some("!!!"), None, &[], &[]), (7.0, 30.0)),
2713        ];
2714        for (agent_env, expected) in cases {
2715            let (publisher, subscription) = TestSamplingPublisher::new();
2716            let env = agent_env.as_str().to_owned();
2717            let mut sampler = rare_only_sampler(agent_env, subscription).build_sampler();
2718            publisher.assign([("sampling", payload)]);
2719            transform_empty_buffer(&mut sampler);
2720            assert_eq!(live_tps(&sampler), expected, "agent env {env:?}");
2721        }
2722    }
2723
2724    /// Remote selection and the priority sampler's fallback for traces without an env use the same agent environment.
2725    ///
2726    /// Regression: remote selection followed `env` while the priority sampler used a separate default, so the two
2727    /// could disagree.
2728    #[test]
2729    fn remote_selection_and_priority_sampling_share_agent_env() {
2730        let (publisher, subscription) = TestSamplingPublisher::new();
2731        let agent_env = AgentEnv::resolve(Some("Staging"), Some("prod"), &[], &[]);
2732        let mut sampler = rare_only_sampler(agent_env, subscription).build_sampler();
2733        publisher.assign([(
2734            "sampling",
2735            r#"{"by_env":[{"env":"staging","config":{"priority_sampler_target_TPS":43}},
2736                          {"env":"prod","config":{"priority_sampler_target_TPS":42}}]}"#,
2737        )]);
2738        transform_empty_buffer(&mut sampler);
2739        assert_eq!(live_tps(&sampler).0, 43.0, "remote selection uses the agent env");
2740
2741        // Traces without an env learn their rate under the agent env. Counts in one bucket become rates when the next
2742        // begins.
2743        let start = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
2744        for now in [start, start + std::time::Duration::from_secs(10)] {
2745            for trace_id in 0..100 {
2746                let mut trace = create_test_trace(vec![create_test_span(trace_id, 0)]);
2747                sampler
2748                    .priority_sampler
2749                    .sample(now, &mut trace, 0, PRIORITY_AUTO_KEEP, 0.0);
2750            }
2751        }
2752        let learned: Vec<_> = sampler
2753            .priority_sampler
2754            .test_signature_sample_rates()
2755            .0
2756            .into_keys()
2757            .collect();
2758        assert_eq!(
2759            learned,
2760            vec![signature::ServiceSignature::new("test-service", "staging").hash()],
2761            "priority sampling uses the agent env"
2762        );
2763    }
2764
2765    /// The run loop applies a published update before sampling the next buffer.
2766    #[tokio::test]
2767    async fn run_loop_samples_with_the_published_remote_settings() {
2768        let (publisher, subscription) = TestSamplingPublisher::new();
2769        let config = rare_only_sampler(prod_env(), subscription);
2770        let (control, mut outputs) = TestComponentDriver::transform(config)
2771            .await
2772            .expect("the sampler should start");
2773        let new_service_trace = |span_id: u64| {
2774            Event::Trace(create_test_trace(vec![
2775                create_top_level_span(span_id).with_service(MetaString::from(format!("rare-probe-{span_id}")))
2776            ]))
2777        };
2778
2779        // The rare sampler keeps the first trace. Waiting for it makes sure the update is published after it.
2780        control.send_event(new_service_trace(1)).await;
2781        outputs
2782            .default_output()
2783            .next()
2784            .await
2785            .expect("the rare sampler should keep the first trace");
2786
2787        publisher.assign([("sampling", r#"{"all_envs":{"rare_sampler_enabled":false}}"#)]);
2788        control.send_event(new_service_trace(2)).await;
2789        control.shutdown().await.expect("the sampler should stop cleanly");
2790
2791        let kept = outputs.default_output().collect_events().await;
2792        assert!(
2793            kept.is_empty(),
2794            "the second trace should be dropped now that remote settings disable the rare sampler: {kept:?}"
2795        );
2796    }
2797
2798    #[test]
2799    fn remote_field_removed_later_falls_back_to_static() {
2800        let (publisher, mut sampler) = create_remote_sampler(10.0);
2801        publisher.assign([(
2802            "sampling",
2803            r#"{"all_envs":{"priority_sampler_target_TPS":41,"rare_sampler_enabled":true}}"#,
2804        )]);
2805        transform_empty_buffer(&mut sampler);
2806        assert_eq!(live_tps(&sampler), (41.0, 10.0));
2807
2808        publisher.assign([("sampling", r#"{"all_envs":{"errors_sampler_target_TPS":42}}"#)]);
2809        transform_empty_buffer(&mut sampler);
2810        assert_eq!(
2811            live_tps(&sampler),
2812            (10.0, 42.0),
2813            "the priority target reverts to static, not to 41"
2814        );
2815        assert!(
2816            !rare_keeps_new_trace(&mut sampler, 1),
2817            "the rare sampler reverts to static, not to enabled"
2818        );
2819    }
2820
2821    /// Starting with a zero target disables error sampling; a remote update cannot re-enable it.
2822    #[test]
2823    fn static_zero_errors_tps_stays_disabled_under_remote_configuration() {
2824        let (publisher, mut sampler) = create_remote_sampler(0.0);
2825        publisher.assign([("sampling", r#"{"all_envs":{"errors_sampler_target_TPS":5}}"#)]);
2826        transform_empty_buffer(&mut sampler);
2827        assert_eq!(sampler.error_sampler.get_target_tps(), 5.0);
2828
2829        let mut trace = create_test_trace(vec![create_test_span(1, 1)]);
2830        assert!(!sampler
2831            .error_sampler
2832            .sample_error(std::time::SystemTime::now(), &mut trace, 0));
2833    }
2834
2835    #[test]
2836    fn inert_remote_sampling_changes_nothing() {
2837        let mut sampler = TraceSampler {
2838            remote_sampling: TraceSamplingSubscription::default(),
2839            ..create_remote_sampler(10.0).1
2840        };
2841        // An inert subscription must not reset these overrides.
2842        sampler.priority_sampler.update_target_tps(41.0);
2843        sampler.error_sampler.update_target_tps(42.0);
2844        sampler.rare_sampler.set_enabled(true);
2845
2846        transform_empty_buffer(&mut sampler);
2847        assert_eq!(live_tps(&sampler), (41.0, 42.0));
2848        assert!(rare_keeps_new_trace(&mut sampler, 1));
2849    }
2850
2851    /// Removing the remote assignment does not undo previously applied settings.
2852    #[test]
2853    fn unassigned_after_remote_configuration_keeps_remote_settings() {
2854        let (publisher, mut sampler) = create_remote_sampler(10.0);
2855        publisher.assign([(
2856            "sampling",
2857            r#"{"all_envs":{"priority_sampler_target_TPS":41,"errors_sampler_target_TPS":42,
2858                "rare_sampler_enabled":true}}"#,
2859        )]);
2860        transform_empty_buffer(&mut sampler);
2861        let applied = sampler.remote_sampling.current().expect("a configuration is accepted");
2862
2863        publisher.assign(std::iter::empty::<(&str, &str)>());
2864        assert!(Arc::ptr_eq(
2865            &applied,
2866            &sampler.remote_sampling.current().expect("the configuration is kept")
2867        ));
2868        transform_empty_buffer(&mut sampler);
2869        assert_eq!(live_tps(&sampler), (41.0, 42.0));
2870        assert!(rare_keeps_new_trace(&mut sampler, 1));
2871    }
2872
2873    // The subscription keeps only the latest state, and the sampler reads it once per buffer. Publications the sampler
2874    // has not yet read must not erase the newest accepted configuration, since the Datadog Agent applies each update
2875    // as it arrives, ignores an empty one, and rejects arrays where its JSON decoder expects an object:
2876    // https://github.com/DataDog/datadog-agent/blob/17ecddf4e3e83ccbb0e68aeb99461d1a1d902927/pkg/trace/remoteconfighandler/remote_config_handler.go#L234-L295
2877    #[test]
2878    fn unread_publications_keep_the_newest_accepted_configuration() {
2879        const A: &str = r#"{"all_envs":{"priority_sampler_target_TPS":41,"errors_sampler_target_TPS":42,
2880            "rare_sampler_enabled":true}}"#;
2881        const B: &str = r#"{"all_envs":{"priority_sampler_target_TPS":43,"errors_sampler_target_TPS":44}}"#;
2882        // Each case is a name, the payload applied before the publications under test, those publications (`None`
2883        // for an empty assignment), and the expected targets and rare sampler state.
2884        type Case<'a> = (&'a str, Option<&'a str>, &'a [Option<&'a str>], (f64, f64), bool);
2885        let cases: [Case; 7] = [
2886            ("initial empty assignment", None, &[None], (10.0, 10.0), false),
2887            (
2888                "A then empty before the first buffer",
2889                None,
2890                &[Some(A), None],
2891                (41.0, 42.0),
2892                true,
2893            ),
2894            (
2895                "B then empty after A is applied",
2896                Some(A),
2897                &[Some(B), None],
2898                (43.0, 44.0),
2899                false,
2900            ),
2901            (
2902                "malformed after A is applied",
2903                Some(A),
2904                &[Some("not json")],
2905                (41.0, 42.0),
2906                true,
2907            ),
2908            (
2909                "array payload after A is applied",
2910                Some(A),
2911                &[Some("[]")],
2912                (41.0, 42.0),
2913                true,
2914            ),
2915            (
2916                "array settings after A is applied",
2917                Some(A),
2918                &[Some(r#"{"all_envs":[0,0,false]}"#)],
2919                (41.0, 42.0),
2920                true,
2921            ),
2922            (
2923                "accepted {} after A is applied",
2924                Some(A),
2925                &[Some("{}")],
2926                (10.0, 10.0),
2927                false,
2928            ),
2929        ];
2930
2931        for (name, applied, pending, tps, rare) in cases {
2932            let (publisher, mut sampler) = create_remote_sampler(10.0);
2933            let publish = |payload: &Option<&str>| match payload {
2934                Some(payload) => publisher.assign([("sampling", *payload)]),
2935                None => publisher.assign(std::iter::empty::<(&str, &str)>()),
2936            };
2937            if let Some(applied) = applied {
2938                publish(&Some(applied));
2939                transform_empty_buffer(&mut sampler);
2940            }
2941            pending.iter().for_each(publish);
2942            transform_empty_buffer(&mut sampler);
2943            assert_eq!(live_tps(&sampler), tps, "{name}");
2944            assert_eq!(rare_keeps_new_trace(&mut sampler, 1), rare, "{name}");
2945        }
2946    }
2947
2948    /// The run loop applies a configuration whose withdrawal was published before the sampler's first buffer.
2949    #[tokio::test]
2950    async fn run_loop_applies_a_configuration_withdrawn_before_the_first_buffer() {
2951        let (publisher, subscription) = TestSamplingPublisher::new();
2952        let config = rare_only_sampler(prod_env(), subscription);
2953        publisher.assign([("sampling", r#"{"all_envs":{"rare_sampler_enabled":false}}"#)]);
2954        publisher.assign(std::iter::empty::<(&str, &str)>());
2955
2956        let (control, mut outputs) = TestComponentDriver::transform(config)
2957            .await
2958            .expect("the sampler should start");
2959        control
2960            .send_event(Event::Trace(create_test_trace(vec![
2961                create_top_level_span(1).with_service(MetaString::from("rare-probe-1"))
2962            ])))
2963            .await;
2964        control.shutdown().await.expect("the sampler should stop cleanly");
2965
2966        let kept = outputs.default_output().collect_events().await;
2967        assert!(
2968            kept.is_empty(),
2969            "the remote configuration disables the rare sampler, which would otherwise keep the trace: {kept:?}"
2970        );
2971    }
2972
2973    /// Changing the target scales rates already learned for trace signatures.
2974    #[test]
2975    fn remote_configuration_scales_learned_rates() {
2976        let (publisher, mut sampler) = create_remote_sampler(10.0);
2977
2978        // 100 traces in one 5-second bucket are 20 traces per second, so a target of 10 learns a rate of 0.5 once the
2979        // next bucket begins.
2980        let start = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
2981        for now in [start, start + std::time::Duration::from_secs(10)] {
2982            for trace_id in 0..100 {
2983                let mut trace = create_test_trace(vec![create_test_span(trace_id, 1)]);
2984                sampler
2985                    .priority_sampler
2986                    .sample(now, &mut trace, 0, PRIORITY_AUTO_KEEP, 0.0);
2987                sampler.error_sampler.sample_error(now, &mut trace, 0);
2988            }
2989        }
2990        let learned_rates = |sampler: &TraceSampler| {
2991            let priority: Vec<f64> = sampler
2992                .priority_sampler
2993                .test_signature_sample_rates()
2994                .0
2995                .into_values()
2996                .collect();
2997            let errors: Vec<f64> = sampler
2998                .error_sampler
2999                .test_signature_sample_rates()
3000                .0
3001                .into_values()
3002                .collect();
3003            (priority, errors)
3004        };
3005        assert_eq!(learned_rates(&sampler), (vec![0.5], vec![0.5]));
3006
3007        publisher.assign([(
3008            "sampling",
3009            r#"{"all_envs":{"priority_sampler_target_TPS":5,"errors_sampler_target_TPS":2}}"#,
3010        )]);
3011        transform_empty_buffer(&mut sampler);
3012
3013        assert_eq!(live_tps(&sampler), (5.0, 2.0));
3014        assert_eq!(
3015            learned_rates(&sampler),
3016            (vec![0.5 * (5.0 / 10.0)], vec![0.5 * (2.0 / 10.0)]),
3017            "each learned rate scales by the ratio of the new target to the old one"
3018        );
3019    }
3020
3021    /// Republishing the same settings must not clear learned rates or rare-trace history.
3022    #[test]
3023    fn reapplying_equal_remote_settings_keeps_sampler_state() {
3024        let (publisher, mut sampler) = create_remote_sampler(10.0);
3025        let payload = r#"{"all_envs":{"priority_sampler_target_TPS":5,"errors_sampler_target_TPS":4,
3026            "rare_sampler_enabled":true}}"#;
3027        publisher.assign([("sampling", payload)]);
3028        transform_empty_buffer(&mut sampler);
3029
3030        // Learn a rate for one signature in each sampler: counts in one bucket become rates when the next begins.
3031        let start = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000);
3032        for now in [start, start + std::time::Duration::from_secs(10)] {
3033            for trace_id in 0..100 {
3034                let mut trace = create_test_trace(vec![create_test_span(trace_id, 1)]);
3035                sampler
3036                    .priority_sampler
3037                    .sample(now, &mut trace, 0, PRIORITY_AUTO_KEEP, 0.0);
3038                sampler.error_sampler.sample_error(now, &mut trace, 0);
3039            }
3040        }
3041        assert!(rare_keeps_new_trace(&mut sampler, 1));
3042
3043        #[derive(Debug, PartialEq)]
3044        struct LearnedState {
3045            priority_rates: (saluki_common::collections::FastHashMap<signature::Signature, f64>, f64),
3046            priority_size: i64,
3047            errors_rates: (saluki_common::collections::FastHashMap<signature::Signature, f64>, f64),
3048            errors_size: i64,
3049            tps: (f64, f64),
3050        }
3051        let state = |sampler: &TraceSampler| LearnedState {
3052            priority_rates: sampler.priority_sampler.test_signature_sample_rates(),
3053            priority_size: sampler.priority_sampler.test_size(),
3054            errors_rates: sampler.error_sampler.test_signature_sample_rates(),
3055            errors_size: sampler.error_sampler.test_size(),
3056            tps: live_tps(sampler),
3057        };
3058        let before = state(&sampler);
3059        assert_eq!(
3060            before.priority_rates.0.len(),
3061            1,
3062            "the priority sampler has learned a rate"
3063        );
3064        assert_eq!(before.errors_rates.0.len(), 1, "the errors sampler has learned a rate");
3065
3066        let applied = sampler.remote_sampling.current().expect("a configuration is accepted");
3067        publisher.assign([("sampling", payload)]);
3068        let republished = sampler.remote_sampling.current().expect("a configuration is accepted");
3069        assert!(
3070            !Arc::ptr_eq(&applied, &republished),
3071            "the equal snapshot is a new allocation"
3072        );
3073        transform_empty_buffer(&mut sampler);
3074
3075        assert_eq!(state(&sampler), before);
3076        let mut seen = create_test_trace(vec![
3077            create_top_level_span(1).with_service(MetaString::from("rare-probe-1"))
3078        ]);
3079        let SamplerOutcome { keep, .. } = sampler.run_samplers(&mut seen);
3080        assert!(!keep, "the rare sampler still remembers the signature it kept");
3081    }
3082}