Skip to main content

saluki_components/transforms/aggregate/
mod.rs

1use std::{
2    future::pending,
3    num::NonZeroU64,
4    sync::Mutex,
5    time::{Duration, Instant},
6};
7
8use async_trait::async_trait;
9use ddsketch::DDSketch;
10use hashbrown::{hash_map::Entry, HashMap};
11use saluki_common::time::get_unix_timestamp;
12use saluki_core::{
13    accounting::{MemoryBounds, MemoryBoundsBuilder, UsageExpr},
14    components::{transforms::*, BuildContext},
15    data_model::event::{
16        metric::{context::Context, *},
17        Event, EventType,
18    },
19    observability::ComponentMetricsExt as _,
20    topology::{interconnect::BufferedDispatcher, EventsBuffer, OutputDefinition},
21};
22use saluki_error::{generic_error, GenericError};
23use saluki_metrics::MetricsBuilder;
24use smallvec::SmallVec;
25use stringtheory::MetaString;
26use tokio::{
27    select,
28    sync::{mpsc, oneshot},
29    time::interval_at,
30};
31use tracing::{debug, error, info, trace, warn};
32
33mod telemetry;
34use self::telemetry::{origin_telemetry_bytes, FlushCounts, OriginContextId, Telemetry};
35
36mod config;
37pub use self::config::HistogramConfiguration;
38use self::config::HistogramStatistic;
39
40const CONTEXT_SNAPSHOT_REQUEST_CHANNEL_CAPACITY: usize = 1;
41
42/// The shape of metric values retained by the aggregate transform.
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub enum AggregateMetricType {
45    /// Counter values.
46    Counter,
47
48    /// Rate values.
49    Rate,
50
51    /// Gauge values.
52    Gauge,
53
54    /// Set values.
55    Set,
56
57    /// Histogram values.
58    Histogram,
59
60    /// Distribution values.
61    Distribution,
62}
63
64impl From<&MetricValues> for AggregateMetricType {
65    fn from(values: &MetricValues) -> Self {
66        match values {
67            MetricValues::Counter(_) => Self::Counter,
68            MetricValues::Rate(_, _) => Self::Rate,
69            MetricValues::Gauge(_) => Self::Gauge,
70            MetricValues::Set(_) => Self::Set,
71            MetricValues::Histogram(_) => Self::Histogram,
72            MetricValues::Distribution(_) => Self::Distribution,
73        }
74    }
75}
76
77/// A retained metric context and its small aggregation metadata.
78///
79/// Cloning an entry shares the underlying context name and tags rather than copying their contents.
80#[derive(Clone, Debug, Eq, PartialEq)]
81pub struct AggregateContextSnapshotEntry {
82    context: Context,
83    metric_type: AggregateMetricType,
84}
85
86impl AggregateContextSnapshotEntry {
87    /// Returns the retained metric context.
88    pub fn context(&self) -> &Context {
89        &self.context
90    }
91
92    /// Returns the shape of the retained metric values.
93    pub fn metric_type(&self) -> AggregateMetricType {
94        self.metric_type
95    }
96
97    /// Creates a snapshot entry for downstream test and benchmark fixtures.
98    #[cfg(any(test, feature = "test-util"))]
99    pub fn for_test(context: Context, metric_type: AggregateMetricType) -> Self {
100        Self { context, metric_type }
101    }
102}
103
104type AggregateContextSnapshot = Vec<AggregateContextSnapshotEntry>;
105type AggregateContextSnapshotRequest = oneshot::Sender<AggregateContextSnapshot>;
106type AggregateContextSnapshotRequestReceiver = mpsc::Receiver<AggregateContextSnapshotRequest>;
107
108/// A handle for requesting retained-context snapshots from an aggregate transform.
109///
110/// Snapshot construction runs on the aggregate owner task. The returned entries contain shared context handles and
111/// small metric metadata, allowing callers to perform heavier processing after the owner resumes ingestion.
112#[derive(Clone, Debug)]
113pub struct AggregateContextSnapshotHandle {
114    requests: mpsc::Sender<AggregateContextSnapshotRequest>,
115}
116
117impl AggregateContextSnapshotHandle {
118    /// Requests the aggregate transform's current retained contexts.
119    ///
120    /// The returned snapshot uses O(context count) memory. After delivery, the caller owns this memory, so callers that
121    /// retain snapshots must include their retained size in their own memory accounting.
122    ///
123    /// # Errors
124    ///
125    /// Returns an error if the aggregate owner is unavailable or stops before responding.
126    pub async fn snapshot(&self) -> Result<Vec<AggregateContextSnapshotEntry>, GenericError> {
127        let (response_tx, response_rx) = oneshot::channel();
128        self.requests
129            .send(response_tx)
130            .await
131            .map_err(|_| generic_error!("aggregate context snapshot owner is unavailable"))?;
132
133        response_rx
134            .await
135            .map_err(|_| generic_error!("aggregate context snapshot owner stopped before responding"))
136    }
137}
138
139/// Creates a retained-context snapshot handle and its owner-side receiver.
140///
141/// The receiver belongs to the aggregate transform, and is supplied to it through
142/// [`AggregateConfiguration::context_snapshot_receiver`]. The handle belongs to whoever requests snapshots, and can be
143/// cloned to let several callers request them.
144pub fn aggregate_context_snapshot_channel() -> (AggregateContextSnapshotHandle, AggregateContextSnapshotReceiver) {
145    let (requests, receiver) = mpsc::channel(CONTEXT_SNAPSHOT_REQUEST_CHANNEL_CAPACITY);
146    (
147        AggregateContextSnapshotHandle { requests },
148        AggregateContextSnapshotReceiver {
149            receiver: Mutex::new(Some(receiver)),
150        },
151    )
152}
153
154#[inline]
155fn send_context_snapshot_if_open(
156    response: AggregateContextSnapshotRequest, build_snapshot: impl FnOnce() -> AggregateContextSnapshot,
157) {
158    if response.is_closed() {
159        return;
160    }
161
162    let _ = response.send(build_snapshot());
163}
164
165/// An accepted retained-context snapshot request for test fixtures.
166#[cfg(any(test, feature = "test-util"))]
167pub struct AggregateContextSnapshotPendingResponse {
168    response: AggregateContextSnapshotRequest,
169}
170
171#[cfg(any(test, feature = "test-util"))]
172impl AggregateContextSnapshotPendingResponse {
173    /// Responds to the accepted snapshot request with the supplied entries.
174    ///
175    /// If the requester was canceled after the request was accepted, the response is discarded.
176    pub fn respond(self, snapshot: Vec<AggregateContextSnapshotEntry>) {
177        let _ = self.response.send(snapshot);
178    }
179}
180
181/// A responder for retained-context snapshot test fixtures.
182#[cfg(any(test, feature = "test-util"))]
183pub struct AggregateContextSnapshotResponder {
184    receiver: AggregateContextSnapshotRequestReceiver,
185}
186
187#[cfg(any(test, feature = "test-util"))]
188impl AggregateContextSnapshotResponder {
189    /// Waits for one snapshot request and responds with the supplied entries.
190    ///
191    /// A canceled requester is treated as a successful no-op delivery.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error if the request channel closes before a request arrives.
196    pub async fn respond(&mut self, snapshot: Vec<AggregateContextSnapshotEntry>) -> Result<(), GenericError> {
197        self.receive().await?.respond(snapshot);
198        Ok(())
199    }
200
201    /// Waits for one snapshot request and returns its pending response.
202    ///
203    /// The returned response lets tests deterministically control whether the owner responds, stops, or outlives a
204    /// canceled requester after accepting the request.
205    ///
206    /// # Errors
207    ///
208    /// Returns an error if the request channel closes before a request arrives.
209    pub async fn receive(&mut self) -> Result<AggregateContextSnapshotPendingResponse, GenericError> {
210        let response = self
211            .receiver
212            .recv()
213            .await
214            .ok_or_else(|| generic_error!("aggregate context snapshot request channel is closed"))?;
215        Ok(AggregateContextSnapshotPendingResponse { response })
216    }
217
218    /// Waits for one snapshot request and stops without responding.
219    ///
220    /// This accepts the request from the owner channel before dropping its one-shot response sender, allowing tests to
221    /// distinguish an owner that stops mid-request from an owner whose request channel is unavailable.
222    ///
223    /// # Errors
224    ///
225    /// Returns an error if the request channel closes before a request arrives.
226    pub async fn stop_after_receiving(&mut self) -> Result<(), GenericError> {
227        drop(self.receive().await?);
228        Ok(())
229    }
230}
231
232/// Creates a retained-context snapshot handle and owner-side responder for tests.
233#[cfg(any(test, feature = "test-util"))]
234pub fn aggregate_context_snapshot_channel_for_test(
235) -> (AggregateContextSnapshotHandle, AggregateContextSnapshotResponder) {
236    let (requests, receiver) = mpsc::channel(CONTEXT_SNAPSHOT_REQUEST_CHANNEL_CAPACITY);
237    (
238        AggregateContextSnapshotHandle { requests },
239        AggregateContextSnapshotResponder { receiver },
240    )
241}
242
243/// The owner side of a retained-context snapshot channel.
244///
245/// The aggregate transform takes the receiver out of this holder when it is built. A receiver can only be taken once,
246/// so an [`AggregateConfiguration`] holding one can only build a single transform.
247pub struct AggregateContextSnapshotReceiver {
248    receiver: Mutex<Option<AggregateContextSnapshotRequestReceiver>>,
249}
250
251impl AggregateContextSnapshotReceiver {
252    fn take_receiver(&self) -> Result<AggregateContextSnapshotRequestReceiver, GenericError> {
253        let mut receiver = self
254            .receiver
255            .lock()
256            .map_err(|_| generic_error!("aggregate context snapshot receiver lock is poisoned"))?;
257        receiver
258            .take()
259            .ok_or_else(|| generic_error!("aggregate context snapshot receiver has already been taken"))
260    }
261}
262
263/// Aggregate transform.
264///
265/// Aggregates metrics into fixed-size windows, flushing them at a regular interval.
266///
267/// ## Zero-value counters
268///
269/// When metrics are aggregated and then flushed, they're typically removed entirely from the aggregation state. Unless
270/// they're updated again, they won't be emitted again. However, for counters, a slightly different approach is
271/// taken by tracking "zero-value" counters.
272///
273/// Counters are aggregated and flushed normally. However, when flushed, counters are added to a list of "zero-value"
274/// counters, and if those counters aren't updated again, the transform emits a copy of the counter with a value of
275/// zero. It does this until the counter is updated again, or the zero-value counter expires (no updates), whichever
276/// comes first.
277///
278/// This provides a continuity in the output of a counter, from the perspective of a downstream system, when counters
279/// are otherwise sparse. The expiration period is configurable, and allows a trade-off in how sparse/infrequent the
280/// updates to counters can be versus how long it takes for counters that don't exist anymore to actually cease to be
281/// emitted.
282pub struct AggregateConfiguration {
283    /// Size of the aggregation window, in seconds.
284    ///
285    /// Metrics are aggregated into fixed-size windows, such that all updates to the same metric within a window are
286    /// aggregated into a single metric. The window size controls how efficiently metrics are aggregated, and in turn,
287    /// how many data points are emitted downstream.
288    pub window_duration_seconds: NonZeroU64,
289
290    /// How often to flush buckets.
291    ///
292    /// This represents a trade-off between the savings in network bandwidth (sending fewer requests to downstream
293    /// systems, etc) and the frequency of updates (how often updates to a metric are emitted).
294    pub primary_flush_interval: Duration,
295
296    /// Maximum number of contexts to aggregate per window.
297    ///
298    /// A context is the unique combination of a metric name and its set of tags. For example,
299    /// `metric.name.here{tag1=A,tag2=B}` represents a single context, and would be different than
300    /// `metric.name.here{tag1=A,tag2=C}`.
301    ///
302    /// When the maximum number of contexts is reached in the current aggregation window, additional metrics are dropped
303    /// until the next window starts.
304    pub context_limit: usize,
305
306    /// Whether to flush open buckets when stopping the transform.
307    ///
308    /// Normally, open buckets (a bucket whose end hasn't yet occurred) aren't flushed when the transform is stopped.
309    /// This is done to avoid the chance of flushing a partial window, restarting the process, and then flushing the
310    /// same window again. Downstream systems sometimes can't cope with this gracefully, as there is no way to
311    /// determine that it's an incremental update, and so they treat it as an absolute update, overwriting the
312    /// previously flushed value.
313    ///
314    /// In cases where flushing all outstanding data is paramount, this can be enabled.
315    pub flush_open_windows: bool,
316
317    /// How long to keep idle counters alive after they've been flushed, in seconds.
318    ///
319    /// When metrics are flushed, they're removed from the aggregation state. However, if a counter expiration is set,
320    /// counters will be kept alive in an "idle" state. For as long as a counter is idle, but not yet expired, a zero
321    /// value will be emitted for it during each flush. This allows more gracefully handling sparse counters, where
322    /// updates are infrequent but leaving gaps in the time series would be undesirable from a user experience
323    /// perspective.
324    ///
325    /// After a counter has been idle (no updates) for longer than the expiry period, it will be completely removed and
326    /// no further zero values will be emitted.
327    ///
328    /// A value of `0`, or `None`, disables idle counter keep-alive.
329    pub counter_expiry_seconds: Option<u64>,
330
331    /// Statistics to calculate over histograms, and how to copy them to distributions.
332    pub hist_config: HistogramConfiguration,
333
334    /// Whether to emit active context counts grouped by resolved origin tags.
335    ///
336    /// Defaults to `false` in runtime configuration. Enable this to diagnose origin-specific context usage.
337    /// Contexts without origin tags are skipped. At most 199 origin groups and one `origin_overflow:true`
338    /// series are registered. Groups exceeding 32 tags or 4096 bytes of encoded labels also contribute to overflow.
339    /// A context stays in its original group until expiry; vacant origin slots can admit new contexts. The total
340    /// across all series is exact, but an origin's own series is too low while any of its contexts are counted in
341    /// overflow. An emptied group reports 0 until idle eviction removes its series.
342    pub origin_telemetry_enabled: bool,
343
344    /// Owner side of the channel used to serve retained-context snapshot requests.
345    ///
346    /// This is runtime wiring rather than configuration: it carries no settings, and is created by the caller with
347    /// [`aggregate_context_snapshot_channel`] so that the caller keeps the matching handle.
348    pub context_snapshot_receiver: AggregateContextSnapshotReceiver,
349}
350
351#[cfg(test)]
352impl AggregateConfiguration {
353    /// Creates a fixture configuration, for tests that exercise aggregation behavior rather than configuration.
354    ///
355    /// The snapshot handle paired with the configuration's receiver is dropped. Tests that request snapshots build the
356    /// channel with [`aggregate_context_snapshot_channel`] and override `context_snapshot_receiver`.
357    fn for_test() -> Self {
358        let (_handle, context_snapshot_receiver) = aggregate_context_snapshot_channel();
359
360        Self {
361            window_duration_seconds: NonZeroU64::new(10).expect("not zero"),
362            primary_flush_interval: Duration::from_secs(15),
363            context_limit: 1_000_000,
364            flush_open_windows: false,
365            counter_expiry_seconds: Some(300),
366            hist_config: HistogramConfiguration::default(),
367            origin_telemetry_enabled: false,
368            context_snapshot_receiver,
369        }
370    }
371}
372
373#[async_trait]
374impl TransformBuilder for AggregateConfiguration {
375    async fn build(&self, context: BuildContext) -> Result<Box<dyn Transform + Send>, GenericError> {
376        let context_snapshot_requests = self.context_snapshot_receiver.take_receiver()?;
377        let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
378        let telemetry = Telemetry::new(&metrics_builder, self.origin_telemetry_enabled);
379
380        let state = AggregationState::new(
381            self.window_duration_seconds,
382            self.context_limit,
383            self.counter_expiry_seconds.filter(|s| *s != 0).map(Duration::from_secs),
384            self.hist_config.clone(),
385            telemetry.clone(),
386        );
387
388        Ok(Box::new(Aggregate {
389            state,
390            telemetry,
391            primary_flush_interval: self.primary_flush_interval,
392            flush_open_windows: self.flush_open_windows,
393            context_snapshot_requests: Some(context_snapshot_requests),
394        }))
395    }
396
397    fn input_event_type(&self) -> EventType {
398        EventType::Metric
399    }
400
401    fn outputs(&self) -> &[OutputDefinition<EventType>] {
402        static OUTPUTS: &[OutputDefinition<EventType>] = &[OutputDefinition::default_output(EventType::Metric)];
403        OUTPUTS
404    }
405}
406
407impl MemoryBounds for AggregateConfiguration {
408    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
409        // TODO: While we account for the aggregation state map accurately, what we don't currently account for is the
410        // fact that a metric could have multiple distinct values. For the common pipeline of metrics in via DogStatsD,
411        // this generally shouldn't be a problem because the values don't have a timestamp, so they get aggregated into
412        // the same bucket, leading to two values per `MetricValues` at most, which is already baked into the size of
413        // `MetricValues` due to using `SmallVec`.
414        //
415        // However, there could be many more values in a single metric, and we don't account for that.
416
417        builder
418            .minimum()
419            // Capture the size of the heap allocation when the component is built.
420            .with_single_value::<Aggregate>("component struct");
421        builder
422            .firm()
423            // Account for the aggregation state map, where we map contexts to the merged metric.
424            .with_expr(UsageExpr::product(
425                "aggregation state map",
426                UsageExpr::sum(
427                    "context map entry",
428                    UsageExpr::struct_size::<Context>("context"),
429                    UsageExpr::struct_size::<AggregatedMetric>("aggregated metric"),
430                ),
431                UsageExpr::config("aggregate_context_limit", self.context_limit),
432            ))
433            // A snapshot is constructed while the aggregation state remains live, so its peak allocation is additive.
434            .with_expr(UsageExpr::product(
435                "retained context snapshot",
436                UsageExpr::struct_size::<AggregateContextSnapshotEntry>("snapshot entry"),
437                UsageExpr::config("aggregate_context_limit", self.context_limit),
438            ));
439
440        if self.origin_telemetry_enabled {
441            // Origin telemetry has independent series and byte limits, including owned label storage and
442            // registry/resolver copies rather than assuming strings share the metric context's allocation.
443            builder.firm().with_fixed_amount(
444                "bounded origin context telemetry",
445                origin_telemetry_bytes(self.primary_flush_interval),
446            );
447        }
448    }
449}
450
451pub struct Aggregate {
452    state: AggregationState,
453    telemetry: Telemetry,
454    primary_flush_interval: Duration,
455    flush_open_windows: bool,
456    context_snapshot_requests: Option<AggregateContextSnapshotRequestReceiver>,
457}
458
459#[async_trait]
460impl Transform for Aggregate {
461    async fn run(mut self: Box<Self>, mut context: TransformContext) -> Result<(), GenericError> {
462        let mut health = context.take_health_handle();
463
464        let mut primary_flush = interval_at(
465            tokio::time::Instant::now() + self.primary_flush_interval,
466            self.primary_flush_interval,
467        );
468        let mut final_primary_flush = false;
469
470        health.mark_ready();
471        debug!("Aggregation transform started.");
472
473        loop {
474            select! {
475                _ = health.live() => continue,
476                _ = primary_flush.tick() => {
477                    // We've reached the end of the current window. Flush our aggregation state and forward the metrics
478                    // onwards. Regardless of whether any metrics were aggregated, we always update the aggregation
479                    // state to track the start time of the current aggregation window.
480                    if !self.state.is_empty() {
481                        debug!("Flushing aggregated metrics...");
482
483                        let should_flush_open_windows = final_primary_flush && self.flush_open_windows;
484
485                        // Remember if the context limit had been surpassed before this flush.
486                        let was_breached = self.state.context_limit_breached();
487
488                        let mut dispatcher = context.dispatcher().buffered().expect("default output should always exist");
489                        let flush = async {
490                            let flush_start = Instant::now();
491
492                            if let Err(e) = self.state.flush(get_unix_timestamp(), should_flush_open_windows, &mut dispatcher).await {
493                                error!(error = %e, "Failed to flush aggregation state.");
494                            }
495
496                            self.telemetry.increment_flushes();
497
498                            // If flush recovered us from a breach, log the recovery.
499                            if was_breached && !self.state.context_limit_breached() {
500                                info!("Context limit no longer exceeded, metrics are being accepted again.");
501                            }
502
503                            match dispatcher.flush().await {
504                                Ok(aggregated_events) => debug!(aggregated_events, "Dispatched events."),
505                                Err(e) => error!(error = %e, "Failed to flush aggregated events."),
506                            }
507
508                            self.telemetry.record_last_flush_duration(flush_start.elapsed());
509                        };
510                        tokio::pin!(flush);
511
512                        // A flush can wait a long time for space in a full downstream channel. Keep answering liveness
513                        // probes while it waits. Probes go first so that a waiting probe is seen on every wakeup, even
514                        // when the flush would use up the task's cooperative budget.
515                        loop {
516                            select! {
517                                biased;
518                                _ = health.live() => {},
519                                _ = &mut flush => break,
520                            }
521                        }
522                    }
523
524                    // If this is the final flush, we break out of the loop.
525                    if final_primary_flush {
526                        debug!("All aggregation complete.");
527                        break
528                    }
529                },
530                snapshot_request = receive_context_snapshot_request(&mut self.context_snapshot_requests) => {
531                    match snapshot_request {
532                        Some(response) => {
533                            send_context_snapshot_if_open(response, || self.state.snapshot_contexts());
534                        }
535                        None => self.context_snapshot_requests = None,
536                    }
537                },
538                maybe_events = context.events().next(), if !final_primary_flush => match maybe_events {
539                    Some(events) => {
540                        trace!(events_len = events.len(), "Received events.");
541
542                        let current_time = get_unix_timestamp();
543
544                        for metric in events.into_events::<Metric>() {
545                            let was_breached = self.state.context_limit_breached();
546                            if !self.state.insert(current_time, metric) {
547                                trace!("Dropping metric due to context limit.");
548                                if !was_breached {
549                                    // First drop since the last recovery — emit a single warning.
550                                    warn!(context_limit = self.state.context_limit, "Context limit reached, \
551                                    dropping metrics. Consider increasing `aggregate_context_limit`.");
552                                }
553                                self.telemetry.increment_events_dropped();
554                            }
555                        }
556                    },
557                    None => {
558                        // We've reached the end of our input stream, so mark ourselves for a final flush and reset the
559                        // interval so it ticks immediately on the next loop iteration.
560                        final_primary_flush = true;
561                        primary_flush.reset_immediately();
562
563                        debug!("Aggregation transform stopping...");
564                    }
565                },
566            }
567        }
568
569        debug!("Aggregation transform stopped.");
570
571        Ok(())
572    }
573}
574
575async fn receive_context_snapshot_request(
576    receiver: &mut Option<AggregateContextSnapshotRequestReceiver>,
577) -> Option<AggregateContextSnapshotRequest> {
578    match receiver {
579        Some(receiver) => receiver.recv().await,
580        None => pending().await,
581    }
582}
583
584#[derive(Clone)]
585struct AggregatedMetric {
586    values: MetricValues,
587    metadata: MetricMetadata,
588    last_seen: u64,
589    origin_id: OriginContextId,
590}
591
592impl AggregatedMetric {
593    fn merge(&mut self, timestamp: u64, values: MetricValues, metadata: MetricMetadata) {
594        // Other metadata changes within a flush interval are ignored to keep things simple.
595        self.last_seen = timestamp;
596        self.values.merge(values);
597
598        // The first non-empty unit wins and persists until the entry is removed; non-counters are removed once all
599        // values are flushed, so a stale unit outlives its samples by at most one flush.
600        if self.metadata.unit.is_empty() {
601            self.metadata.unit = metadata.unit;
602        }
603    }
604}
605
606struct AggregationState {
607    contexts: HashMap<Context, AggregatedMetric, foldhash::quality::RandomState>,
608    contexts_remove_buf: Vec<Context>,
609    context_limit: usize,
610    bucket_width_secs: NonZeroU64,
611    counter_expire_secs: Option<NonZeroU64>,
612    last_flush: u64,
613    hist_config: HistogramConfiguration,
614    telemetry: Telemetry,
615    /// Tracks whether the context limit has been breached. Starts out as `false`. Set to `true` on the first dropped
616    /// metric. Reset to `false` when the context count drops below the limit during flush.
617    context_limit_breached: bool,
618}
619
620impl AggregationState {
621    fn new(
622        bucket_width_secs: NonZeroU64, context_limit: usize, counter_expiration: Option<Duration>,
623        hist_config: HistogramConfiguration, telemetry: Telemetry,
624    ) -> Self {
625        let counter_expire_secs = counter_expiration.map(|d| d.as_secs()).and_then(NonZeroU64::new);
626
627        Self {
628            contexts: HashMap::default(),
629            contexts_remove_buf: Vec::new(),
630            context_limit,
631            bucket_width_secs,
632            counter_expire_secs,
633            last_flush: 0,
634            hist_config,
635            telemetry,
636            context_limit_breached: false,
637        }
638    }
639
640    fn is_empty(&self) -> bool {
641        self.contexts.is_empty()
642    }
643
644    fn snapshot_contexts(&self) -> Vec<AggregateContextSnapshotEntry> {
645        let mut snapshot = Vec::with_capacity(self.contexts.len());
646        for (context, aggregated) in &self.contexts {
647            snapshot.push(AggregateContextSnapshotEntry {
648                context: context.clone(),
649                metric_type: AggregateMetricType::from(&aggregated.values),
650            });
651        }
652        snapshot
653    }
654
655    fn insert(&mut self, timestamp: u64, metric: Metric) -> bool {
656        // If we haven't seen this context yet, and it would put us over the limit to insert it, then return early.
657        if !self.contexts.contains_key(metric.context()) && self.contexts.len() >= self.context_limit {
658            self.context_limit_breached = true;
659            return false;
660        }
661
662        // An empty state has no counters to keep alive. The owner skips flushing an empty state, so its last flush can
663        // be arbitrarily old; carrying that timestamp into a newly inserted counter would synthesize zero buckets from
664        // before the counter existed.
665        if self.contexts.is_empty() {
666            self.last_flush = 0;
667        }
668
669        let (context, mut values, metadata) = metric.into_parts();
670
671        // Collapse all non-timestamped values into a single timestamped value.
672        //
673        // We do this pre-aggregation step because unless we're merging into an existing context, we'll end up with
674        // however many values were in the original metric instead of full aggregated values.
675        let bucket_ts = align_to_bucket_start(timestamp, self.bucket_width_secs);
676        values.collapse_non_timestamped(bucket_ts);
677
678        trace!(
679            bucket_ts,
680            kind = values.as_str(),
681            "Inserting metric into aggregation state."
682        );
683
684        // If we're already tracking this context, update the last seen time and merge the new values into the existing
685        // values. Otherwise, create a new entry.
686        match self.contexts.entry(context) {
687            Entry::Occupied(mut entry) => entry.get_mut().merge(timestamp, values, metadata),
688            Entry::Vacant(entry) => {
689                let origin_id = self.telemetry.increment_contexts(entry.key(), &values);
690
691                entry.insert(AggregatedMetric {
692                    values,
693                    metadata,
694                    last_seen: timestamp,
695                    origin_id,
696                });
697
698                saluki_antithesis::always_le!(
699                    self.contexts.len(),
700                    self.context_limit,
701                    "aggregate context map within context_limit",
702                    { "len": self.contexts.len(), "limit": self.context_limit }
703                );
704            }
705        }
706
707        true
708    }
709
710    async fn flush(
711        &mut self, current_time: u64, flush_open_buckets: bool, dispatcher: &mut BufferedDispatcher<'_, EventsBuffer>,
712    ) -> Result<(), GenericError> {
713        // A previous flush may have failed after marking some contexts for removal. Re-evaluate them:
714        // ingestion may have added values since then, and their telemetry admission is still live.
715        self.contexts_remove_buf.clear();
716        let bucket_width_secs = self.bucket_width_secs;
717        let counter_expire_secs = self.counter_expire_secs.map(|d| d.get()).unwrap_or(0);
718
719        // Values with a timestamp less than or equal to `split_timestamp` are flushed. Normally that's just before the
720        // start of the current bucket, so only closed buckets are flushed. When flushing open buckets, it's every value.
721        let split_timestamp = if flush_open_buckets {
722            u64::MAX
723        } else {
724            align_to_bucket_start(current_time, bucket_width_secs).saturating_sub(1)
725        };
726
727        // Calculate the buckets we need to potentially generate zero-value counters for.
728        //
729        // We only need to do this if we've flushed before, since we won't have any knowledge of which counters are idle
730        // or not until that happens.
731        let mut zero_value_buckets = SmallVec::<[(u64, MetricValues); 4]>::new();
732        if self.last_flush != 0 {
733            let start = align_to_bucket_start(self.last_flush, bucket_width_secs);
734
735            // Clock-skew guards. Bucketing reads the wall clock while the flush cadence is monotonic, so a wall-clock
736            // jump is not bounded by the flush interval. A backward jump empties the zero-value range (a silent counter
737            // gap); a forward jump makes the loop below run once per bucket across the whole jumped span — O(jump) work
738            // and allocation. Assert before the loop so a flood fails fast rather than after the damage is done.
739            saluki_antithesis::always_ge!(
740                current_time,
741                self.last_flush,
742                "aggregate flush wall-clock did not move backward",
743                { "current_time": current_time, "last_flush": self.last_flush }
744            );
745            // The 10_000 bound is generous. A default 15s flush over a 10s bucket yields one or two buckets. The bound
746            // trips only on a multi-hour wall-clock jump, never on a slow-but-sane flush.
747            saluki_antithesis::always_le!(
748                current_time.saturating_sub(self.last_flush) / bucket_width_secs.get(),
749                10_000,
750                "aggregate zero-value bucket span bounded across a flush",
751                {
752                    "current_time": current_time,
753                    "last_flush": self.last_flush,
754                    "bucket_width_secs": bucket_width_secs.get()
755                }
756            );
757
758            for bucket_start in (start..current_time).step_by(bucket_width_secs.get() as usize) {
759                if is_bucket_closed(current_time, bucket_start, bucket_width_secs, flush_open_buckets) {
760                    zero_value_buckets.push((bucket_start, MetricValues::counter((bucket_start, 0.0))));
761                }
762            }
763
764            // Anti-vacuity anchor: prove the idle-counter zero-value path actually runs in some timeline.
765            saluki_antithesis::sometimes!(
766                !zero_value_buckets.is_empty(),
767                "aggregate flush generated zero-value counter buckets",
768                { "count": zero_value_buckets.len() }
769            );
770        }
771
772        // Iterate over each context we're tracking, and flush any values that are in buckets which are now closed.
773        debug!(timestamp = current_time, "Flushing buckets.");
774
775        let mut flush_counts = FlushCounts::default();
776
777        for (context, am) in self.contexts.iter_mut() {
778            // Figure out if we should remove this metric or not if it has no values in open buckets.
779            //
780            // We have a special carve-out for counters here, which we have the ability to keep alive after they are
781            // flushed, based on a configured expiration period. This allows us to continue emitting a zero value for
782            // counters when they're idle, which can make them appear "live" in downstream systems, even when they're
783            // not.
784            //
785            // This is useful for sparsely-updated counters.
786            let should_expire_if_empty = match &am.values {
787                MetricValues::Counter(..) => {
788                    saluki_antithesis::always_le!(
789                        am.last_seen,
790                        u64::MAX - counter_expire_secs,
791                        "aggregate counter expiry add does not overflow",
792                        { "last_seen": am.last_seen, "counter_expire_secs": counter_expire_secs }
793                    );
794                    counter_expire_secs == 0 || am.last_seen.saturating_add(counter_expire_secs) < current_time
795                }
796                _ => true,
797            };
798
799            // If we're dealing with a counter, we'll merge in our calculated set of zero values. We only merge in the
800            // values that represent now-closed buckets.
801            //
802            // This is also safe to do even when there are real values in those buckets since adding zero to anything is
803            // a no-op from the perspective of what we end up flushing, and it doesn't mess with the "last seen" time.
804            if let MetricValues::Counter(..) = &mut am.values {
805                let expires_at = am.last_seen.saturating_add(counter_expire_secs);
806                for (zv_bucket_start, zero_value) in &zero_value_buckets {
807                    if expires_at > *zv_bucket_start {
808                        am.values.merge(zero_value.clone());
809                    } else {
810                        // Since zero-value buckets are in order, we can break early if this bucket is past the
811                        // expiration cutoff of the counter. No other bucket will be within the expiration range.
812                        break;
813                    }
814                }
815            }
816
817            // Finally, figure out if the current metric can be removed.
818            //
819            // For any metric with values that are in open buckets, we split off the values that are in closed buckets
820            // and keep the metric alive. When all the values are in closed buckets, or there are no values, we'll
821            // remove the metric if `should_remove_if_empty` is `true`.
822            //
823            // This means we'll always remove all-closed/empty non-counter metrics, and we _may_ remove all-closed/empty
824            // counters.
825            if let Some(closed_bucket_values) = am.values.split_at_timestamp(split_timestamp) {
826                self.telemetry
827                    .increment_flushed(&closed_bucket_values, &mut flush_counts);
828
829                // We got some closed bucket values, so flush those out.
830                transform_and_push_metric(
831                    context.clone(),
832                    closed_bucket_values,
833                    am.metadata.clone(),
834                    bucket_width_secs,
835                    &self.hist_config,
836                    dispatcher,
837                )
838                .await?;
839            }
840
841            if am.values.is_empty() && should_expire_if_empty {
842                self.contexts_remove_buf.push(context.clone());
843            }
844        }
845
846        // Remove any contexts that were marked as needing to be removed.
847        let contexts_len_before = self.contexts.len();
848        for context in self.contexts_remove_buf.drain(..) {
849            if let Some(am) = self.contexts.remove(&context) {
850                self.telemetry.decrement_contexts(&context, &am.values, am.origin_id);
851            }
852        }
853        let contexts_len_after = self.contexts.len();
854
855        let contexts_delta = contexts_len_before.saturating_sub(contexts_len_after);
856        let target_contexts_capacity = contexts_len_after.saturating_add(contexts_delta / 2);
857        self.contexts.shrink_to(target_contexts_capacity);
858
859        if self.context_limit_breached && self.contexts.len() < self.context_limit {
860            self.context_limit_breached = false;
861        }
862
863        self.last_flush = current_time;
864        self.telemetry.record_last_flush_counts(&flush_counts);
865
866        Ok(())
867    }
868
869    fn context_limit_breached(&self) -> bool {
870        self.context_limit_breached
871    }
872}
873
874async fn transform_and_push_metric(
875    context: Context, mut values: MetricValues, metadata: MetricMetadata, bucket_width_secs: NonZeroU64,
876    hist_config: &HistogramConfiguration, dispatcher: &mut BufferedDispatcher<'_, EventsBuffer>,
877) -> Result<(), GenericError> {
878    let bucket_width = Duration::from_secs(bucket_width_secs.get());
879
880    match values {
881        // If we're dealing with a histogram, we calculate a configured set of aggregates/percentiles from it, and emit
882        // them as individual metrics.
883        MetricValues::Histogram(ref mut points) => {
884            // Convert histogram to distribution
885            if hist_config.copy_to_distribution() {
886                let sketch_points = points
887                    .into_iter()
888                    .map(|(ts, hist)| {
889                        let mut sketch = DDSketch::default();
890                        for sample in hist.samples() {
891                            sketch.insert_n(sample.value.into_inner(), sample.weight.0 as u64);
892                        }
893                        (ts, sketch)
894                    })
895                    .collect::<SketchPoints>();
896                let distribution_values = MetricValues::distribution(sketch_points);
897                let metric_context = if !hist_config.copy_to_distribution_prefix().is_empty() {
898                    context.with_name(format!(
899                        "{}{}",
900                        hist_config.copy_to_distribution_prefix(),
901                        context.name()
902                    ))
903                } else {
904                    context.clone()
905                };
906                let new_metric = Metric::from_parts(metric_context, distribution_values, metadata.clone());
907                dispatcher.push(Event::Metric(new_metric)).await?;
908            }
909            // We collect our histogram points in their "summary" view, which sorts the underlying samples allowing
910            // proper quantile queries to be answered, hence our "sorted" points. We do it this way because rather than
911            // sort every time we insert, or cloning the points, we only sort when a summary view is constructed, which
912            // requires mutable access to sort the samples in-place.
913            let mut sorted_points = Vec::new();
914            for (ts, h) in points {
915                sorted_points.push((ts, h.summary_view()));
916            }
917
918            for statistic in hist_config.statistics() {
919                let new_points = sorted_points
920                    .iter()
921                    .map(|(ts, hs)| (*ts, statistic.value_from_histogram(hs)))
922                    .collect::<ScalarPoints>();
923
924                let new_values = if statistic.is_rate_statistic() {
925                    MetricValues::rate(new_points, bucket_width)
926                } else {
927                    MetricValues::gauge(new_points)
928                };
929
930                // Counts are dimensionless, so clear any unit inherited from the input histogram.
931                let new_metadata = if matches!(statistic, HistogramStatistic::Count) {
932                    metadata.clone().with_unit(MetaString::empty())
933                } else {
934                    metadata.clone()
935                };
936
937                let new_context = context.with_name(format!("{}.{}", context.name(), statistic.suffix()));
938                let new_metric = Metric::from_parts(new_context, new_values, new_metadata);
939                dispatcher.push(Event::Metric(new_metric)).await?;
940            }
941
942            Ok(())
943        }
944
945        // If we're not dealing with a histogram, then all we need to worry about is converting counters to rates before
946        // forwarding our single, aggregated metric.
947        values => {
948            let adjusted_values = counter_values_to_rate(values, bucket_width_secs);
949
950            let metric = Metric::from_parts(context, adjusted_values, metadata);
951            dispatcher.push(Event::Metric(metric)).await
952        }
953    }
954}
955
956fn counter_values_to_rate(values: MetricValues, interval_secs: NonZeroU64) -> MetricValues {
957    match values {
958        MetricValues::Counter(points) => MetricValues::rate(points, Duration::from_secs(interval_secs.get())),
959        values => values,
960    }
961}
962
963const fn align_to_bucket_start(timestamp: u64, bucket_width_secs: NonZeroU64) -> u64 {
964    timestamp - (timestamp % bucket_width_secs.get())
965}
966
967const fn is_bucket_closed(
968    current_time: u64, bucket_start: u64, bucket_width_secs: NonZeroU64, flush_open_buckets: bool,
969) -> bool {
970    // A bucket is considered "closed" if the current time is greater than the end of the bucket, or if
971    // `flush_open_buckets` is `true`.
972    //
973    // Buckets represent a half-open interval, where the start is inclusive and the end is exclusive. This means that
974    // for a bucket start of 10, and a width of 10, the bucket is 10 seconds "wide", and its start and end are 10 and
975    // 20, with the 20 excluded, or [10, 20) in interval notation. Simply put, if we have a timestamp of 10, or anything
976    // smaller than 20, we would consider it to fall within the bucket... but 20 or more would be outside of the bucket.
977    //
978    // We can also represent this visually:
979    //
980    // <--------- bucket 1 ----------> <--------- bucket 2 ----------> <--------- bucket 3 ---------->
981    // [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39]
982    //
983    // We can see that each bucket is 10 seconds wide (10 elements, one for each second), and that their ends are
984    // effectively `start + width - 1`. This means that for any of these buckets to be considered "closed", the current
985    // time has to be _greater_ than `start + width - 1`. For example, if the current time is 19, then no buckets are
986    // closed, and if the current time is 29, then bucket 1 is closed but buckets 2 and 3 are still open, and if the
987    // current time is 30, then both buckets 1 and 2 are closed, but bucket 3 is still open.
988    (bucket_start + bucket_width_secs.get() - 1) < current_time || flush_open_buckets
989}
990
991// TODO: One thing we ought to consider is a property test, specifically a state machine property test, where we
992// generate a randomized offset to start time from, a bucket width, flush interval, and operations, and so on... and
993// then we run it to make sure that we are always generating sequential timestamps for data points, etc.
994#[cfg(test)]
995mod tests {
996    use std::{cell::Cell, mem::size_of};
997
998    use float_cmp::ApproxEqRatio as _;
999    use saluki_core::{
1000        accounting::ComponentRegistry,
1001        components::{test_util::TestComponentDriver, ComponentContext},
1002        data_model::tags::{Tag, TagSet},
1003        support::SubsystemIdentifier,
1004        topology::{interconnect::Dispatcher, EventsDispatcher, OutputName},
1005    };
1006    use saluki_metrics::test::TestRecorder;
1007    use stringtheory::MetaString;
1008    use tokio::sync::{mpsc, oneshot};
1009
1010    use super::config::HistogramStatistic;
1011    use super::*;
1012
1013    const BUCKET_WIDTH_SECS: NonZeroU64 = NonZeroU64::new(10).expect("not zero");
1014    const BUCKET_WIDTH: Duration = Duration::from_secs(BUCKET_WIDTH_SECS.get());
1015    const COUNTER_EXPIRE_SECS: u64 = 20;
1016    const COUNTER_EXPIRE: Option<Duration> = Some(Duration::from_secs(COUNTER_EXPIRE_SECS));
1017
1018    /// Gets the bucket start timestamp for the given step.
1019    const fn bucket_ts(step: u64) -> u64 {
1020        align_to_bucket_start(insert_ts(step), BUCKET_WIDTH_SECS)
1021    }
1022
1023    /// Gets the insert timestamp for the given step.
1024    const fn insert_ts(step: u64) -> u64 {
1025        (BUCKET_WIDTH_SECS.get() * (step + 1)) - 2
1026    }
1027
1028    /// Gets the flush timestamp for the given step.
1029    const fn flush_ts(step: u64) -> u64 {
1030        BUCKET_WIDTH_SECS.get() * (step + 1)
1031    }
1032
1033    struct DispatcherReceiver {
1034        receiver: mpsc::Receiver<EventsBuffer>,
1035    }
1036
1037    impl DispatcherReceiver {
1038        fn collect_next(&mut self) -> Vec<Metric> {
1039            match self.receiver.try_recv() {
1040                Ok(event_buffer) => {
1041                    let mut metrics = event_buffer
1042                        .into_iter()
1043                        .filter_map(|event| event.try_into_metric())
1044                        .collect::<Vec<Metric>>();
1045
1046                    metrics.sort_by(|a, b| a.context().name().cmp(b.context().name()));
1047                    metrics
1048                }
1049                Err(_) => Vec::new(),
1050            }
1051        }
1052    }
1053
1054    /// Constructs a basic `Dispatcher` with a fixed-size event buffer.
1055    fn build_basic_dispatcher() -> (EventsDispatcher, DispatcherReceiver) {
1056        let context = ComponentContext::test_transform("test");
1057        let mut dispatcher = Dispatcher::new(context);
1058
1059        let (buffer_tx, buffer_rx) = mpsc::channel(1);
1060        dispatcher.add_output(OutputName::Default).unwrap();
1061        dispatcher
1062            .attach_sender_to_output(&OutputName::Default, buffer_tx)
1063            .unwrap();
1064
1065        (dispatcher, DispatcherReceiver { receiver: buffer_rx })
1066    }
1067
1068    async fn get_flushed_metrics(timestamp: u64, state: &mut AggregationState) -> Vec<Metric> {
1069        get_flushed_metrics_with_open_windows(timestamp, true, state).await
1070    }
1071
1072    async fn get_flushed_metrics_with_open_windows(
1073        timestamp: u64, flush_open_buckets: bool, state: &mut AggregationState,
1074    ) -> Vec<Metric> {
1075        let (dispatcher, mut dispatcher_receiver) = build_basic_dispatcher();
1076        let mut buffered_dispatcher = dispatcher.buffered().expect("default output should always exist");
1077
1078        // Flush the metrics to an event buffer.
1079        state
1080            .flush(timestamp, flush_open_buckets, &mut buffered_dispatcher)
1081            .await
1082            .expect("should not fail to flush aggregation state");
1083
1084        // Flush our buffered dispatcher, which should ensure that the event buffer is sent out, and then read it from the
1085        // receiver:
1086        buffered_dispatcher
1087            .flush()
1088            .await
1089            .expect("should not fail to flush buffered sender");
1090
1091        dispatcher_receiver.collect_next()
1092    }
1093
1094    macro_rules! compare_points {
1095        (scalar, $expected:expr, $actual:expr, $error_ratio:literal) => {
1096            for (idx, (expected_value, actual_value)) in $expected.into_iter().zip($actual.into_iter()).enumerate() {
1097                let (expected_ts, expected_point) = expected_value;
1098                let (actual_ts, actual_point) = actual_value;
1099
1100                assert_eq!(
1101                    expected_ts, actual_ts,
1102                    "timestamp for value #{} does not match: {:?} (expected) vs {:?} (actual)",
1103                    idx, expected_ts, actual_ts
1104                );
1105                assert!(
1106                    expected_point.approx_eq_ratio(&actual_point, $error_ratio),
1107                    "point for value #{} does not match: {} (expected) vs {} (actual)",
1108                    idx,
1109                    expected_point,
1110                    actual_point
1111                );
1112            }
1113        };
1114        (distribution, $expected:expr, $actual:expr) => {
1115            for (idx, (expected_value, actual_value)) in $expected.into_iter().zip($actual.into_iter()).enumerate() {
1116                let (expected_ts, expected_sketch) = expected_value;
1117                let (actual_ts, actual_sketch) = actual_value;
1118
1119                assert_eq!(
1120                    expected_ts, actual_ts,
1121                    "timestamp for value #{} does not match: {:?} (expected) vs {:?} (actual)",
1122                    idx, expected_ts, actual_ts
1123                );
1124                assert_eq!(
1125                    expected_sketch, actual_sketch,
1126                    "sketch for value #{} does not match: {:?} (expected) vs {:?} (actual)",
1127                    idx, expected_sketch, actual_sketch
1128                );
1129            }
1130        };
1131    }
1132
1133    macro_rules! assert_flushed_scalar_metric {
1134        ($original:expr, $actual:expr, [$($ts:expr => $value:expr),+]) => {
1135            assert_flushed_scalar_metric!($original, $actual, [$($ts => $value),+], error_ratio => 0.000001);
1136        };
1137        ($original:expr, $actual:expr, [$($ts:expr => $value:expr),+], error_ratio => $error_ratio:literal) => {
1138            let actual_metric = $actual;
1139
1140            assert_eq!($original.context(), actual_metric.context(), "expected context ({}) and actual context ({}) do not match", $original.context(), actual_metric.context());
1141
1142            let expected_points = ScalarPoints::from([$(($ts, $value)),+]);
1143
1144            match actual_metric.values() {
1145                MetricValues::Counter(ref actual_points) | MetricValues::Gauge(ref actual_points) | MetricValues::Rate(ref actual_points, _) => {
1146                    assert_eq!(expected_points.len(), actual_points.len(), "expected and actual values have different number of points");
1147                    compare_points!(scalar, expected_points, actual_points, $error_ratio);
1148                },
1149                _ => panic!("only counters, rates, and gauges are supported in assert_flushed_scalar_metric"),
1150            }
1151        };
1152    }
1153
1154    macro_rules! assert_flushed_distribution_metric {
1155        ($original:expr, $actual:expr, [$($ts:expr => $value:expr),+]) => {
1156            assert_flushed_distribution_metric!($original, $actual, [$($ts => $value),+], error_ratio => 0.000001);
1157        };
1158        ($original:expr, $actual:expr, [$($ts:expr => $value:expr),+], error_ratio => $error_ratio:literal) => {
1159            let actual_metric = $actual;
1160
1161            assert_eq!($original.context(), actual_metric.context());
1162
1163            match actual_metric.values() {
1164                MetricValues::Distribution(ref actual_points) => {
1165                    let expected_points = SketchPoints::from([$(($ts, $value)),+]);
1166                    assert_eq!(expected_points.len(), actual_points.len(), "expected and actual values have different number of points");
1167
1168                    compare_points!(distribution, &expected_points, actual_points);
1169                },
1170                _ => panic!("only distributions are supported in assert_flushed_distribution_metric"),
1171            }
1172        };
1173    }
1174
1175    #[test]
1176    fn aggregate_metric_type_matches_every_metric_shape() {
1177        let cases = [
1178            (MetricValues::counter(1.0), AggregateMetricType::Counter),
1179            (
1180                MetricValues::rate(1.0, Duration::from_secs(10)),
1181                AggregateMetricType::Rate,
1182            ),
1183            (MetricValues::gauge(1.0), AggregateMetricType::Gauge),
1184            (MetricValues::set("value"), AggregateMetricType::Set),
1185            (MetricValues::histogram([1.0]), AggregateMetricType::Histogram),
1186            (
1187                MetricValues::distribution(&[1.0][..]),
1188                AggregateMetricType::Distribution,
1189            ),
1190        ];
1191
1192        for (values, expected) in cases {
1193            assert_eq!(AggregateMetricType::from(&values), expected);
1194        }
1195    }
1196
1197    #[tokio::test]
1198    async fn flush_records_last_flush_counts() {
1199        let recorder = TestRecorder::default();
1200        let _local = metrics::set_default_local_recorder(&recorder);
1201
1202        let builder = MetricsBuilder::default();
1203        let mut state = AggregationState::new(
1204            BUCKET_WIDTH_SECS,
1205            10,
1206            COUNTER_EXPIRE,
1207            HistogramConfiguration::default(),
1208            Telemetry::new(&builder, false),
1209        );
1210
1211        assert!(state.insert(insert_ts(1), Metric::counter("metric1", 1.0)));
1212        assert!(state.insert(insert_ts(1), Metric::gauge("metric2", 2.0)));
1213        assert!(state.insert(insert_ts(1), Metric::distribution("metric3", 3.0)));
1214
1215        let _ = get_flushed_metrics(flush_ts(1), &mut state).await;
1216
1217        assert_eq!(
1218            recorder.gauge(("aggregate_last_flush_count", &[("data_type", "series")])),
1219            Some(2.0)
1220        );
1221        assert_eq!(
1222            recorder.gauge(("aggregate_last_flush_count", &[("data_type", "sketches")])),
1223            Some(1.0)
1224        );
1225
1226        // The next flush only has the idle counter's zero value, so the gauges reflect just that flush.
1227        let _ = get_flushed_metrics(flush_ts(2), &mut state).await;
1228
1229        assert_eq!(
1230            recorder.gauge(("aggregate_last_flush_count", &[("data_type", "series")])),
1231            Some(1.0)
1232        );
1233        assert_eq!(
1234            recorder.gauge(("aggregate_last_flush_count", &[("data_type", "sketches")])),
1235            Some(0.0)
1236        );
1237    }
1238
1239    #[test]
1240    fn snapshot_contexts_preserves_full_context_shape() {
1241        let mut state = AggregationState::new(
1242            BUCKET_WIDTH_SECS,
1243            10,
1244            COUNTER_EXPIRE,
1245            HistogramConfiguration::default(),
1246            Telemetry::noop(),
1247        );
1248
1249        let histogram_context = Context::from_static_parts("request.duration", &["env:prod"])
1250            .with_host(Some(MetaString::from_static("host-a")))
1251            .with_origin_tags(TagSet::from(Tag::from_static("container:one")));
1252        let gauge_context = Context::from_static_parts("request.duration", &["env:prod"])
1253            .with_host(Some(MetaString::from_static("host-b")))
1254            .with_origin_tags(TagSet::from(Tag::from_static("container:two")));
1255        let histogram = Metric::from_parts(
1256            histogram_context.clone(),
1257            MetricValues::histogram([12.0]),
1258            MetricMetadata::default().with_unit(MetaString::from_static("millisecond")),
1259        );
1260        let gauge = Metric::gauge(gauge_context.clone(), 2.0);
1261
1262        assert!(state.insert(insert_ts(1), histogram));
1263        assert!(state.insert(insert_ts(1), gauge));
1264
1265        let mut snapshot = state.snapshot_contexts();
1266        assert_eq!(snapshot.len(), 2);
1267        assert!(snapshot.capacity() >= state.contexts.len());
1268        snapshot.sort_by(|a, b| a.context().host().cmp(&b.context().host()));
1269
1270        assert_eq!(snapshot[0].context(), &histogram_context);
1271        assert_eq!(snapshot[0].context().tags().len(), 1);
1272        assert_eq!(snapshot[0].context().origin_tags().len(), 1);
1273        assert_eq!(snapshot[0].metric_type(), AggregateMetricType::Histogram);
1274
1275        assert_eq!(snapshot[1].context(), &gauge_context);
1276        assert_eq!(snapshot[1].metric_type(), AggregateMetricType::Gauge);
1277    }
1278
1279    #[tokio::test]
1280    async fn snapshot_contexts_follows_ordinary_context_lifecycle() {
1281        let mut state = AggregationState::new(
1282            BUCKET_WIDTH_SECS,
1283            10,
1284            COUNTER_EXPIRE,
1285            HistogramConfiguration::default(),
1286            Telemetry::noop(),
1287        );
1288        let context = Context::from_static_name("active.gauge");
1289
1290        assert!(state.insert(insert_ts(1), Metric::gauge(context.clone(), 1.0)));
1291        let active_snapshot = state.snapshot_contexts();
1292        assert_eq!(active_snapshot.len(), 1);
1293        assert_eq!(active_snapshot[0].context(), &context);
1294        assert_eq!(active_snapshot[0].metric_type(), AggregateMetricType::Gauge);
1295
1296        let _ = get_flushed_metrics(flush_ts(1), &mut state).await;
1297        assert!(state.snapshot_contexts().is_empty());
1298    }
1299
1300    #[tokio::test]
1301    async fn snapshot_contexts_retains_idle_counter_until_expiry() {
1302        let mut state = AggregationState::new(
1303            BUCKET_WIDTH_SECS,
1304            10,
1305            COUNTER_EXPIRE,
1306            HistogramConfiguration::default(),
1307            Telemetry::noop(),
1308        );
1309        let context = Context::from_static_name("sparse.counter");
1310
1311        assert!(state.insert(insert_ts(1), Metric::counter(context.clone(), 1.0)));
1312        let _ = get_flushed_metrics(flush_ts(1), &mut state).await;
1313        let first_snapshot = state.snapshot_contexts();
1314        assert_eq!(first_snapshot.len(), 1);
1315        assert_eq!(first_snapshot[0].context(), &context);
1316        assert_eq!(first_snapshot[0].metric_type(), AggregateMetricType::Counter);
1317
1318        let _ = get_flushed_metrics(flush_ts(2), &mut state).await;
1319        let second_snapshot = state.snapshot_contexts();
1320        assert_eq!(second_snapshot.len(), 1);
1321        assert_eq!(second_snapshot[0].context(), &context);
1322        assert_eq!(second_snapshot[0].metric_type(), AggregateMetricType::Counter);
1323
1324        let _ = get_flushed_metrics(flush_ts(3), &mut state).await;
1325        assert!(state.snapshot_contexts().is_empty());
1326    }
1327
1328    #[test]
1329    fn canceled_snapshot_response_skips_snapshot_construction() {
1330        let mut state = AggregationState::new(
1331            BUCKET_WIDTH_SECS,
1332            10,
1333            COUNTER_EXPIRE,
1334            HistogramConfiguration::default(),
1335            Telemetry::noop(),
1336        );
1337        assert!(state.insert(
1338            insert_ts(1),
1339            Metric::gauge(Context::from_static_name("canceled.snapshot"), 1.0),
1340        ));
1341        let (response, receiver) = oneshot::channel();
1342        drop(receiver);
1343        let snapshot_calls = Cell::new(0);
1344
1345        send_context_snapshot_if_open(response, || {
1346            snapshot_calls.set(snapshot_calls.get() + 1);
1347            state.snapshot_contexts()
1348        });
1349
1350        assert_eq!(snapshot_calls.get(), 0);
1351    }
1352
1353    #[test]
1354    fn open_snapshot_response_constructs_once_and_returns_exact_entries() {
1355        let mut state = AggregationState::new(
1356            BUCKET_WIDTH_SECS,
1357            10,
1358            COUNTER_EXPIRE,
1359            HistogramConfiguration::default(),
1360            Telemetry::noop(),
1361        );
1362        let context = Context::from_static_name("open.snapshot");
1363        assert!(state.insert(insert_ts(1), Metric::gauge(context.clone(), 1.0)));
1364        let expected = vec![AggregateContextSnapshotEntry {
1365            context,
1366            metric_type: AggregateMetricType::Gauge,
1367        }];
1368        let (response, mut receiver) = oneshot::channel();
1369        let snapshot_calls = Cell::new(0);
1370
1371        send_context_snapshot_if_open(response, || {
1372            snapshot_calls.set(snapshot_calls.get() + 1);
1373            state.snapshot_contexts()
1374        });
1375
1376        assert_eq!(snapshot_calls.get(), 1);
1377        assert_eq!(
1378            receiver.try_recv().expect("open requester should receive a snapshot"),
1379            expected
1380        );
1381    }
1382
1383    #[test]
1384    fn aggregate_memory_bounds_include_peak_context_snapshot() {
1385        let context_limit = 17;
1386        let config = AggregateConfiguration {
1387            context_limit,
1388            ..AggregateConfiguration::for_test()
1389        };
1390        let registry = ComponentRegistry::default();
1391        config.specify_bounds(&mut registry.bounds_builder(&SubsystemIdentifier::from_dotted("test")));
1392        let bounds = registry.as_bounds();
1393
1394        let expected_minimum = size_of::<Aggregate>();
1395        let aggregation_state_bytes = context_limit * (size_of::<Context>() + size_of::<AggregatedMetric>());
1396        let context_snapshot_bytes = context_limit * size_of::<AggregateContextSnapshotEntry>();
1397
1398        assert_eq!(bounds.total_minimum_required_bytes(), expected_minimum);
1399        assert_eq!(
1400            bounds.total_firm_limit_bytes(),
1401            expected_minimum + aggregation_state_bytes + context_snapshot_bytes
1402        );
1403
1404        let origin_config = AggregateConfiguration {
1405            context_limit,
1406            origin_telemetry_enabled: true,
1407            ..AggregateConfiguration::for_test()
1408        };
1409        let origin_registry = ComponentRegistry::default();
1410        origin_config.specify_bounds(&mut origin_registry.bounds_builder(&SubsystemIdentifier::from_dotted("test")));
1411        let origin_bounds = origin_registry.as_bounds();
1412        let origin_tracking_bytes = origin_telemetry_bytes(origin_config.primary_flush_interval);
1413        assert_eq!(
1414            origin_bounds.total_firm_limit_bytes(),
1415            expected_minimum + aggregation_state_bytes + context_snapshot_bytes + origin_tracking_bytes
1416        );
1417        // Faster flushes reuse slots more often while retired series wait for idle eviction.
1418        assert!(origin_telemetry_bytes(Duration::from_secs(1)) > origin_telemetry_bytes(Duration::from_secs(15)));
1419    }
1420
1421    #[tokio::test]
1422    async fn production_owner_loop_serves_snapshots_and_stops_after_cancellation() {
1423        tokio::time::timeout(Duration::from_secs(5), async {
1424            let (snapshot_handle, context_snapshot_receiver) = aggregate_context_snapshot_channel();
1425            let config = AggregateConfiguration {
1426                primary_flush_interval: Duration::from_secs(60),
1427                context_snapshot_receiver,
1428                ..AggregateConfiguration::for_test()
1429            };
1430
1431            let available_request_capacity = snapshot_handle.requests.capacity();
1432            let canceled_request = tokio::spawn({
1433                let snapshot_handle = snapshot_handle.clone();
1434                async move { snapshot_handle.snapshot().await }
1435            });
1436            while snapshot_handle.requests.capacity() == available_request_capacity {
1437                tokio::task::yield_now().await;
1438            }
1439            canceled_request.abort();
1440            assert!(canceled_request
1441                .await
1442                .expect_err("snapshot requester should be canceled")
1443                .is_cancelled());
1444
1445            // The default output has to stay open, since the aggregate dispatches what it doesn't retain.
1446            let (control, _outputs) = TestComponentDriver::transform(config)
1447                .await
1448                .expect("aggregate transform should build");
1449
1450            let retained_context = Context::from_static_name("owner.loop.mixed.counter");
1451            let mixed_values = ScalarPoints::from_iter([(None, 2.0), (NonZeroU64::new(insert_ts(1)), 3.0)]);
1452            control
1453                .send_event(Event::Metric(Metric::counter(retained_context.clone(), mixed_values)))
1454                .await;
1455
1456            let snapshot = loop {
1457                let snapshot = snapshot_handle
1458                    .snapshot()
1459                    .await
1460                    .expect("running aggregate should fulfill snapshots");
1461                if snapshot.iter().any(|entry| entry.context() == &retained_context) {
1462                    break snapshot;
1463                }
1464                tokio::task::yield_now().await;
1465            };
1466            assert_eq!(
1467                snapshot.len(),
1468                1,
1469                "only the mixed metric's retained portion belongs in state"
1470            );
1471            let entry = &snapshot[0];
1472            assert_eq!(entry.context(), &retained_context);
1473            assert_eq!(entry.metric_type(), AggregateMetricType::Counter);
1474
1475            drop(snapshot_handle);
1476            control.shutdown().await.expect("aggregate should stop cleanly");
1477        })
1478        .await
1479        .expect("production aggregate owner loop should complete without spinning or hanging");
1480    }
1481
1482    #[tokio::test]
1483    async fn snapshot_handle_round_trips_through_responder() {
1484        let (handle, mut responder) = aggregate_context_snapshot_channel_for_test();
1485        let expected = vec![AggregateContextSnapshotEntry::for_test(
1486            Context::from_static_name("round.trip"),
1487            AggregateMetricType::Gauge,
1488        )];
1489        let snapshot_task = tokio::spawn(async move { handle.snapshot().await });
1490
1491        responder
1492            .respond(expected.clone())
1493            .await
1494            .expect("responder should receive and fulfill a snapshot request");
1495
1496        let actual = snapshot_task
1497            .await
1498            .expect("snapshot task should complete")
1499            .expect("snapshot request should succeed");
1500        assert_eq!(actual, expected);
1501    }
1502
1503    #[tokio::test]
1504    async fn snapshot_handle_reports_dropped_receiver() {
1505        let (handle, responder) = aggregate_context_snapshot_channel_for_test();
1506        drop(responder);
1507
1508        let error = handle
1509            .snapshot()
1510            .await
1511            .expect_err("snapshot should fail after its owner is dropped");
1512        assert!(error.to_string().contains("unavailable"));
1513    }
1514
1515    #[tokio::test]
1516    async fn snapshot_responder_stops_after_accepting_request_and_cancels_response() {
1517        let (handle, mut responder) = aggregate_context_snapshot_channel_for_test();
1518        let snapshot_task = tokio::spawn(async move { handle.snapshot().await });
1519
1520        responder
1521            .stop_after_receiving()
1522            .await
1523            .expect("responder should accept the snapshot request before stopping");
1524
1525        let error = snapshot_task
1526            .await
1527            .expect("snapshot task should complete")
1528            .expect_err("snapshot should fail when the accepted response is dropped");
1529        assert!(error.to_string().contains("stopped before responding"));
1530    }
1531
1532    #[tokio::test]
1533    async fn aggregate_configuration_receiver_can_only_be_taken_once() {
1534        let config = AggregateConfiguration::for_test();
1535        let first = config.build(BuildContext::test_transform("aggregate_one")).await;
1536        assert!(first.is_ok());
1537
1538        let second = config.build(BuildContext::test_transform("aggregate_two")).await;
1539        let error = match second {
1540            Ok(_) => panic!("second build should not take the snapshot receiver again"),
1541            Err(error) => error,
1542        };
1543        assert!(error.to_string().contains("already been taken"));
1544    }
1545
1546    #[tokio::test]
1547    async fn snapshot_responder_reports_closed_request_channel() {
1548        let (handle, mut responder) = aggregate_context_snapshot_channel_for_test();
1549        drop(handle);
1550
1551        let error = responder
1552            .respond(Vec::new())
1553            .await
1554            .expect_err("responder should fail when every request handle is dropped");
1555        assert!(error.to_string().contains("closed"));
1556    }
1557
1558    #[tokio::test]
1559    async fn snapshot_responder_ignores_canceled_requester() {
1560        let (handle, mut responder) = aggregate_context_snapshot_channel_for_test();
1561        let snapshot_task = tokio::spawn(async move { handle.snapshot().await });
1562        let pending_response = responder
1563            .receive()
1564            .await
1565            .expect("responder should accept the snapshot request");
1566
1567        snapshot_task.abort();
1568        let _ = snapshot_task.await;
1569
1570        pending_response.respond(Vec::new());
1571    }
1572
1573    #[test]
1574    fn bucket_is_closed() {
1575        // Cases are defined as:
1576        // (current time, bucket start, bucket width, flush open buckets, expected result)
1577        let cases = [
1578            // Bucket goes from [995, 1005), current time of 1000, so bucket is open.
1579            (1000, 995, BUCKET_WIDTH_SECS, false, false),
1580            (1000, 995, BUCKET_WIDTH_SECS, true, true),
1581            // Bucket goes from [1000, 1010), current time of 1000, so bucket is open.
1582            (1000, 1000, BUCKET_WIDTH_SECS, false, false),
1583            (1000, 1000, BUCKET_WIDTH_SECS, true, true),
1584            // Bucket goes from [1000, 1010), current time of 1010, so bucket is closed.
1585            (1010, 1000, BUCKET_WIDTH_SECS, false, true),
1586            (1010, 1000, BUCKET_WIDTH_SECS, true, true),
1587        ];
1588
1589        for (current_time, bucket_start, bucket_width_secs, flush_open_buckets, expected) in cases {
1590            let expected_reason = if expected {
1591                "closed, was open"
1592            } else {
1593                "open, was closed"
1594            };
1595
1596            assert_eq!(
1597                is_bucket_closed(current_time, bucket_start, bucket_width_secs, flush_open_buckets),
1598                expected,
1599                "expected bucket to be {} (current_time={}, bucket_start={}, bucket_width={}, flush_open_buckets={})",
1600                expected_reason,
1601                current_time,
1602                bucket_start,
1603                bucket_width_secs,
1604                flush_open_buckets
1605            );
1606        }
1607    }
1608
1609    #[tokio::test]
1610    async fn context_limit() {
1611        // Create our aggregation state with a context limit of 2.
1612        let mut state = AggregationState::new(
1613            BUCKET_WIDTH_SECS,
1614            2,
1615            COUNTER_EXPIRE,
1616            HistogramConfiguration::default(),
1617            Telemetry::noop(),
1618        );
1619
1620        // Create four unique gauges, and insert all of them. The third and fourth should fail because we've reached
1621        // the context limit.
1622        let input_metrics = [
1623            Metric::gauge("metric1", 1.0),
1624            Metric::gauge("metric2", 2.0),
1625            Metric::gauge("metric3", 3.0),
1626            Metric::gauge("metric4", 4.0),
1627        ];
1628
1629        assert!(!state.context_limit_breached());
1630
1631        assert!(state.insert(insert_ts(1), input_metrics[0].clone()));
1632        assert!(state.insert(insert_ts(1), input_metrics[1].clone()));
1633        assert!(!state.context_limit_breached());
1634
1635        assert!(!state.insert(insert_ts(1), input_metrics[2].clone()));
1636        assert!(state.context_limit_breached());
1637        assert!(!state.insert(insert_ts(1), input_metrics[3].clone()));
1638        assert!(state.context_limit_breached());
1639
1640        // We should only see the first two gauges after flushing. The flush should also clear the breached flag since
1641        // contexts drop below the limit.
1642        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1643        assert_eq!(flushed_metrics.len(), 2);
1644        assert_eq!(input_metrics[0].context(), flushed_metrics[0].context());
1645        assert_eq!(input_metrics[1].context(), flushed_metrics[1].context());
1646        assert!(!state.context_limit_breached());
1647
1648        // We should be able to insert the third and fourth gauges now as the first two have been flushed, and along
1649        // with them, their contexts should no longer be tracked in the aggregation state:
1650        assert!(state.insert(insert_ts(2), input_metrics[2].clone()));
1651        assert!(state.insert(insert_ts(2), input_metrics[3].clone()));
1652
1653        let flushed_metrics = get_flushed_metrics(flush_ts(2), &mut state).await;
1654        assert_eq!(flushed_metrics.len(), 2);
1655        assert_eq!(input_metrics[2].context(), flushed_metrics[0].context());
1656        assert_eq!(input_metrics[3].context(), flushed_metrics[1].context());
1657    }
1658
1659    #[tokio::test]
1660    async fn context_limit_with_zero_value_counters() {
1661        // We test here to ensure that zero-value counters contribute to the context limit.
1662        let mut state = AggregationState::new(
1663            BUCKET_WIDTH_SECS,
1664            2,
1665            COUNTER_EXPIRE,
1666            HistogramConfiguration::default(),
1667            Telemetry::noop(),
1668        );
1669
1670        // Create our input metrics.
1671        let input_metrics = [
1672            Metric::counter("metric1", 1.0),
1673            Metric::counter("metric2", 2.0),
1674            Metric::counter("metric3", 3.0),
1675        ];
1676
1677        assert!(state.insert(insert_ts(1), input_metrics[0].clone()));
1678        assert!(state.insert(insert_ts(1), input_metrics[1].clone()));
1679
1680        // Flush the aggregation state, and observe they're both present.
1681        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1682        assert_eq!(flushed_metrics.len(), 2);
1683        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(1) => 1.0]);
1684        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(1) => 2.0]);
1685
1686        // Flush _again_ to ensure that we then emit zero-value variants for both counters.
1687        let flushed_metrics = get_flushed_metrics(flush_ts(2), &mut state).await;
1688        assert_eq!(flushed_metrics.len(), 2);
1689        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(2) => 0.0]);
1690        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(2) => 0.0]);
1691
1692        // Now try to insert a third counter, which should fail because we've reached the context limit.
1693        assert!(!state.insert(insert_ts(3), input_metrics[2].clone()));
1694
1695        // Flush the aggregation state, and observe that we only see the two original counters.
1696        let flushed_metrics = get_flushed_metrics(flush_ts(3), &mut state).await;
1697        assert_eq!(flushed_metrics.len(), 2);
1698        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(3) => 0.0]);
1699        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(3) => 0.0]);
1700
1701        // With a fourth flush interval, the two counters should now have expired, and thus be dropped and no longer
1702        // contributing to the context limit.
1703        let flushed_metrics = get_flushed_metrics(flush_ts(4), &mut state).await;
1704        assert_eq!(flushed_metrics.len(), 0);
1705
1706        // Now we should be able to insert the third counter, and it should be the only one present after flushing.
1707        assert!(state.insert(insert_ts(5), input_metrics[2].clone()));
1708
1709        let flushed_metrics = get_flushed_metrics(flush_ts(5), &mut state).await;
1710        assert_eq!(flushed_metrics.len(), 1);
1711        assert_flushed_scalar_metric!(&input_metrics[2], &flushed_metrics[0], [bucket_ts(5) => 3.0]);
1712    }
1713
1714    /// Regression test: with idle-counter keep-alive disabled (`dogstatsd_expiry_seconds: 0`), a flushed counter used
1715    /// to stay in the aggregation state forever. It emitted no zero values, but still counted toward
1716    /// `aggregate_context_limit`, so enough distinct counters eventually blocked new contexts.
1717    #[tokio::test]
1718    async fn disabled_counter_keep_alive_releases_contexts_after_flush() {
1719        let mut state = AggregationState::new(
1720            BUCKET_WIDTH_SECS,
1721            10,
1722            None,
1723            HistogramConfiguration::default(),
1724            Telemetry::noop(),
1725        );
1726
1727        assert!(state.insert(insert_ts(1), Metric::counter("counter", 1.0)));
1728        let flushed = get_flushed_metrics(flush_ts(1), &mut state).await;
1729
1730        assert_eq!(flushed.len(), 1);
1731        assert!(state.is_empty());
1732    }
1733
1734    /// Regression test: after the state emptied and sat idle, its last flush time stayed behind. The next flush then
1735    /// generated zero-value buckets for the whole idle period and merged them into a counter inserted afterward, so
1736    /// the counter reported points from before it existed (97 extra zeros in this scenario).
1737    #[tokio::test]
1738    async fn counter_after_idle_single_window_does_not_backfill_zeros() {
1739        let mut state = AggregationState::new(
1740            BUCKET_WIDTH_SECS,
1741            10,
1742            Some(Duration::from_secs(300)),
1743            HistogramConfiguration::default(),
1744            Telemetry::noop(),
1745        );
1746
1747        assert!(state.insert(11, Metric::gauge("previous", 1.0)));
1748        let flushed = get_flushed_metrics_with_open_windows(30, false, &mut state).await;
1749        assert_eq!(flushed.len(), 1);
1750        assert!(state.is_empty());
1751
1752        let counter = Metric::counter("counter", 7.0);
1753        assert!(state.insert(1_000, counter.clone()));
1754        let flushed = get_flushed_metrics_with_open_windows(1_010, false, &mut state).await;
1755
1756        assert_eq!(flushed.len(), 1);
1757        assert_flushed_scalar_metric!(&counter, &flushed[0], [1_000 => 7.0]);
1758    }
1759
1760    /// Regression test: flushing open windows (`dogstatsd_flush_incomplete_buckets`) only affected idle-counter zero
1761    /// values. Real values in the still-open window stayed behind the closed-bucket cutoff, so a shutdown flush
1762    /// discarded them. The Core Agent flushes every bucket, open or not, when forced:
1763    /// https://github.com/DataDog/datadog-agent/blob/78c2c984e848055b4aa63c5f6a9e94a534a07a44/pkg/aggregator/time_sampler.go#L184
1764    #[tokio::test]
1765    async fn flushing_open_windows_emits_values_in_the_open_window() {
1766        for flush_open_buckets in [false, true] {
1767            let mut state = AggregationState::new(
1768                BUCKET_WIDTH_SECS,
1769                10,
1770                COUNTER_EXPIRE,
1771                HistogramConfiguration::default(),
1772                Telemetry::noop(),
1773            );
1774            let gauge = Metric::gauge("gauge", 1.0);
1775            let counter = Metric::counter("counter", 2.0);
1776            let distribution = Metric::distribution("distribution", 3.0);
1777            for metric in [&gauge, &counter, &distribution] {
1778                assert!(state.insert(1_001, metric.clone()));
1779            }
1780
1781            // The window [1000, 1010) is still open at 1005.
1782            let mut flushed = get_flushed_metrics_with_open_windows(1_005, flush_open_buckets, &mut state).await;
1783            if !flush_open_buckets {
1784                assert!(
1785                    flushed.is_empty(),
1786                    "open windows must wait unless they're being flushed"
1787                );
1788                continue;
1789            }
1790
1791            flushed.sort_by(|a, b| a.context().name().cmp(b.context().name()));
1792            let names = flushed
1793                .iter()
1794                .map(|metric| metric.context().name().as_ref())
1795                .collect::<Vec<_>>();
1796            assert_eq!(names, ["counter", "distribution", "gauge"]);
1797            assert_flushed_scalar_metric!(&counter, &flushed[0], [1_000 => 2.0]);
1798            assert_flushed_distribution_metric!(&distribution, &flushed[1], [1_000 => &[3.0][..]]);
1799            assert_flushed_scalar_metric!(&gauge, &flushed[2], [1_000 => 1.0]);
1800        }
1801    }
1802
1803    #[tokio::test]
1804    async fn zero_value_counters() {
1805        // We're testing that we properly emit and expire zero-value counters in all relevant scenarios.
1806        let mut state = AggregationState::new(
1807            BUCKET_WIDTH_SECS,
1808            10,
1809            COUNTER_EXPIRE,
1810            HistogramConfiguration::default(),
1811            Telemetry::noop(),
1812        );
1813
1814        // Create two unique counters, and insert both of them.
1815        let input_metrics = [Metric::counter("metric1", 1.0), Metric::counter("metric2", 2.0)];
1816
1817        assert!(state.insert(insert_ts(1), input_metrics[0].clone()));
1818        assert!(state.insert(insert_ts(1), input_metrics[1].clone()));
1819
1820        // Flush the aggregation state, and observe they're both present.
1821        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1822        assert_eq!(flushed_metrics.len(), 2);
1823        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(1) => 1.0]);
1824        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(1) => 2.0]);
1825
1826        // Perform our second flush, which should have them as zero-value counters.
1827        let flushed_metrics = get_flushed_metrics(flush_ts(2), &mut state).await;
1828        assert_eq!(flushed_metrics.len(), 2);
1829        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(2) => 0.0]);
1830        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(2) => 0.0]);
1831
1832        // Now, we'll pretend to skip a flush period and add updates to them again after that.
1833        assert!(state.insert(insert_ts(4), input_metrics[0].clone()));
1834        assert!(state.insert(insert_ts(4), input_metrics[1].clone()));
1835
1836        // Flush the aggregation state, and observe that we have two zero-value counters for the flush period we
1837        // skipped, but that we see them appear again in the fourth flush period.
1838        let flushed_metrics = get_flushed_metrics(flush_ts(4), &mut state).await;
1839        assert_eq!(flushed_metrics.len(), 2);
1840        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(3) => 0.0, bucket_ts(4) => 1.0]);
1841        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(3) => 0.0, bucket_ts(4) => 2.0]);
1842
1843        // Now we'll skip multiple flush periods and ensure that we emit zero-value counters up until the point they
1844        // expire. As our zero-value counter expiration is 20 seconds, this is two flush periods, so we skip by three
1845        // flush periods, and we should only see the counters emitted for the first two.
1846        let flushed_metrics = get_flushed_metrics(flush_ts(7), &mut state).await;
1847        assert_eq!(flushed_metrics.len(), 2);
1848        assert_flushed_scalar_metric!(&input_metrics[0], &flushed_metrics[0], [bucket_ts(5) => 0.0, bucket_ts(6) => 0.0]);
1849        assert_flushed_scalar_metric!(&input_metrics[1], &flushed_metrics[1], [bucket_ts(5) => 0.0, bucket_ts(6) => 0.0]);
1850    }
1851
1852    #[tokio::test]
1853    async fn merge_identical_timestamped_values_on_flush() {
1854        // We're testing that we properly emit and expire zero-value counters in all relevant scenarios.
1855        let mut state = AggregationState::new(
1856            BUCKET_WIDTH_SECS,
1857            10,
1858            COUNTER_EXPIRE,
1859            HistogramConfiguration::default(),
1860            Telemetry::noop(),
1861        );
1862
1863        // Create one multi-value counter, and insert it.
1864        let input_metric = Metric::counter("metric1", [1.0, 2.0, 3.0, 4.0, 5.0]);
1865
1866        assert!(state.insert(insert_ts(1), input_metric.clone()));
1867
1868        // Flush the aggregation state, and observe the metric is present _and_ that we've properly merged all of the
1869        // values within the same timestamp.
1870        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1871        assert_eq!(flushed_metrics.len(), 1);
1872        assert_flushed_scalar_metric!(&input_metric, &flushed_metrics[0], [bucket_ts(1) => 15.0]);
1873    }
1874
1875    #[tokio::test]
1876    async fn histogram_statistics() {
1877        // We're testing that we properly emit individual metrics (min, max, sum, etc) for a histogram.
1878        let hist_config = HistogramConfiguration::from_statistics(
1879            &[
1880                HistogramStatistic::Count,
1881                HistogramStatistic::Sum,
1882                HistogramStatistic::Percentile {
1883                    q: 0.5,
1884                    suffix: "p50".into(),
1885                },
1886            ],
1887            false,
1888            "".into(),
1889        );
1890        let mut state = AggregationState::new(BUCKET_WIDTH_SECS, 10, COUNTER_EXPIRE, hist_config, Telemetry::noop());
1891
1892        // Create one multi-value histogram and insert it.
1893        let input_metric = Metric::histogram("metric1", [1.0, 2.0, 3.0, 4.0, 5.0]);
1894        assert!(state.insert(insert_ts(1), input_metric.clone()));
1895
1896        // Flush the aggregation state, and observe that we've emitted all of the configured distribution statistics in
1897        // the form of three metrics: count, sum, and p50.
1898        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1899        assert_eq!(flushed_metrics.len(), 3);
1900
1901        // Create versions of the metric for each of the statistics we're expecting to emit. The values themselves don't
1902        // matter here, but we do need a `Metric` for it to compare the context to.
1903        let count_metric = Metric::rate("metric1.count", 0.0, Duration::from_secs(BUCKET_WIDTH_SECS.get()));
1904        let sum_metric = Metric::gauge("metric1.sum", 0.0);
1905        let p50_metric = Metric::gauge("metric1.p50", 0.0);
1906
1907        // We use a less strict error ratio (how much the expected vs actual) for the percentile check, as we generally
1908        // expect the value to be somewhat off the exact value due to the lossy nature of `DDSketch`.
1909        assert_flushed_scalar_metric!(count_metric, &flushed_metrics[0], [bucket_ts(1) => 5.0]);
1910        assert_flushed_scalar_metric!(p50_metric, &flushed_metrics[1], [bucket_ts(1) => 3.0], error_ratio => 0.0025);
1911        assert_flushed_scalar_metric!(sum_metric, &flushed_metrics[2], [bucket_ts(1) => 15.0]);
1912    }
1913
1914    #[tokio::test]
1915    async fn histogram_statistics_unit_propagation() {
1916        // We're testing that the unit from the input histogram metadata propagates to all flushed output metrics.
1917        let hist_config = HistogramConfiguration::from_statistics(
1918            &[
1919                HistogramStatistic::Count,
1920                HistogramStatistic::Sum,
1921                HistogramStatistic::Percentile {
1922                    q: 0.5,
1923                    suffix: "p50".into(),
1924                },
1925            ],
1926            false,
1927            "".into(),
1928        );
1929        let mut state = AggregationState::new(BUCKET_WIDTH_SECS, 10, COUNTER_EXPIRE, hist_config, Telemetry::noop());
1930
1931        // Build a histogram with unit = "millisecond", simulating what arrives from a DogStatsD `ms` metric.
1932        let context = Context::from_static_parts("metric1", &[]);
1933        let metadata = MetricMetadata::default().with_unit(MetaString::from_static("millisecond"));
1934        let input_metric = Metric::from_parts(
1935            context,
1936            MetricValues::histogram([1.0_f64, 2.0, 3.0, 4.0, 5.0]),
1937            metadata,
1938        );
1939        assert!(state.insert(insert_ts(1), input_metric));
1940
1941        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1942        assert_eq!(flushed_metrics.len(), 3);
1943
1944        // Counts are dimensionless: the `.count` series must drop the unit while all other
1945        // aggregate series carry the unit from the input histogram.
1946        for metric in &flushed_metrics {
1947            let name = metric.context().name();
1948            if name.ends_with(".count") {
1949                assert_eq!(
1950                    metric.metadata().unit(),
1951                    None,
1952                    "flushed metric '{}' should be dimensionless",
1953                    name
1954                );
1955            } else {
1956                assert_eq!(
1957                    metric.metadata().unit(),
1958                    Some("millisecond"),
1959                    "flushed metric '{}' should carry unit='millisecond'",
1960                    name
1961                );
1962            }
1963        }
1964    }
1965
1966    fn histogram_with_unit(context: &Context, value: f64, unit: &'static str) -> Metric {
1967        Metric::from_parts(
1968            context.clone(),
1969            MetricValues::histogram([value]),
1970            MetricMetadata::default().with_unit(MetaString::from_static(unit)),
1971        )
1972    }
1973
1974    fn max_only_histogram_config() -> HistogramConfiguration {
1975        HistogramConfiguration::from_statistics(&[HistogramStatistic::Maximum], false, "".into())
1976    }
1977
1978    #[tokio::test]
1979    async fn histogram_unit_first_non_empty_wins() {
1980        // DogStatsD `h` and `ms` samples for one context land in one histogram, which carries a unit if any sample did.
1981        for units in [["", "millisecond"], ["millisecond", ""]] {
1982            let mut state = AggregationState::new(
1983                BUCKET_WIDTH_SECS,
1984                10,
1985                COUNTER_EXPIRE,
1986                max_only_histogram_config(),
1987                Telemetry::noop(),
1988            );
1989            let context = Context::from_static_name("mixed.timer");
1990            for (value, unit) in units.into_iter().enumerate() {
1991                assert!(state.insert(insert_ts(1), histogram_with_unit(&context, value as f64, unit)));
1992            }
1993
1994            let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1995            assert_eq!(flushed_metrics.len(), 1);
1996            assert_eq!(
1997                flushed_metrics[0].metadata().unit(),
1998                Some("millisecond"),
1999                "units {units:?}"
2000            );
2001        }
2002    }
2003
2004    #[tokio::test]
2005    async fn histogram_unit_lasts_until_the_context_is_removed() {
2006        // The unit isn't tracked per bucket: every unflushed value of the context shares it until the context is removed.
2007        for (units, expected) in [
2008            (["millisecond", "millisecond"], ["millisecond", "millisecond"]),
2009            (["millisecond", ""], ["millisecond", "millisecond"]),
2010            (["", "millisecond"], ["millisecond", "millisecond"]),
2011            (["", ""], ["", ""]),
2012        ] {
2013            let mut state = AggregationState::new(
2014                BUCKET_WIDTH_SECS,
2015                10,
2016                COUNTER_EXPIRE,
2017                max_only_histogram_config(),
2018                Telemetry::noop(),
2019            );
2020            let context = Context::from_static_name("timer");
2021            assert!(state.insert(insert_ts(1), histogram_with_unit(&context, 1.0, units[0])));
2022            assert!(state.insert(insert_ts(2), histogram_with_unit(&context, 2.0, units[1])));
2023
2024            for (step, unit) in [1, 2].into_iter().zip(expected) {
2025                let flushed_metrics = get_flushed_metrics_with_open_windows(flush_ts(step), false, &mut state).await;
2026                assert_eq!(flushed_metrics.len(), 1, "units {units:?}, step {step}");
2027                let max_metric = Metric::gauge(Context::from_static_name("timer.max"), 0.0);
2028                assert_flushed_scalar_metric!(max_metric, &flushed_metrics[0], [bucket_ts(step) => step as f64]);
2029                assert_eq!(
2030                    flushed_metrics[0].metadata().unit(),
2031                    (!unit.is_empty()).then_some(unit),
2032                    "units {units:?}, step {step}"
2033                );
2034            }
2035            assert!(state.is_empty());
2036
2037            // A context recreated after removal doesn't inherit the old unit.
2038            assert!(state.insert(insert_ts(3), histogram_with_unit(&context, 3.0, "")));
2039            let flushed_metrics = get_flushed_metrics_with_open_windows(flush_ts(3), false, &mut state).await;
2040            assert_eq!(flushed_metrics.len(), 1, "units {units:?}, step 3");
2041            assert_eq!(flushed_metrics[0].metadata().unit(), None, "units {units:?}, step 3");
2042        }
2043    }
2044
2045    #[tokio::test]
2046    async fn distributions() {
2047        // We're testing that we pass through distributions untouched.
2048        let mut state = AggregationState::new(
2049            BUCKET_WIDTH_SECS,
2050            10,
2051            COUNTER_EXPIRE,
2052            HistogramConfiguration::default(),
2053            Telemetry::noop(),
2054        );
2055
2056        // Create one multi-value distribution, with server-side aggregation, and insert it.
2057        let values = [1.0, 2.0, 3.0, 4.0, 5.0];
2058        let input_metric = Metric::distribution("metric1", &values[..]);
2059
2060        assert!(state.insert(insert_ts(1), input_metric.clone()));
2061
2062        // Flush the aggregation state, and observe that we've emitted the original distribution.
2063        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
2064        assert_eq!(flushed_metrics.len(), 1);
2065
2066        assert_flushed_distribution_metric!(&input_metric, &flushed_metrics[0], [bucket_ts(1) => &values[..]]);
2067    }
2068
2069    #[tokio::test]
2070    async fn histogram_copy_to_distribution() {
2071        let hist_config = HistogramConfiguration::from_statistics(
2072            &[
2073                HistogramStatistic::Count,
2074                HistogramStatistic::Sum,
2075                HistogramStatistic::Percentile {
2076                    q: 0.5,
2077                    suffix: "p50".into(),
2078                },
2079            ],
2080            true,
2081            "dist_prefix.".into(),
2082        );
2083        let mut state = AggregationState::new(BUCKET_WIDTH_SECS, 10, COUNTER_EXPIRE, hist_config, Telemetry::noop());
2084
2085        // Create one multi-value histogram and insert it.
2086        let values = [1.0, 2.0, 3.0, 4.0, 5.0];
2087        let input_metric = Metric::histogram("metric1", values);
2088        assert!(state.insert(insert_ts(1), input_metric.clone()));
2089
2090        // Flush the aggregation state, and observe that we've emitted all of the configured distribution statistics in
2091        // the form of three metrics: count, sum, and p50 as well as the additional metric from copying the histogram.
2092        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
2093        assert_eq!(flushed_metrics.len(), 4);
2094
2095        // Create versions of the metric for each of the statistics we're expecting to emit. The values themselves don't
2096        // matter here, but we do need a `Metric` for it to compare the context to.
2097        let count_metric = Metric::rate("metric1.count", 0.0, BUCKET_WIDTH);
2098        let sum_metric = Metric::gauge("metric1.sum", 0.0);
2099        let p50_metric = Metric::gauge("metric1.p50", 0.0);
2100        let expected_distribution = Metric::distribution("dist_prefix.metric1", &values[..]);
2101
2102        // We use a less strict error ratio (how much the expected vs actual) for the percentile check, as we generally
2103        // expect the value to be somewhat off the exact value due to the lossy nature of `DDSketch`.
2104        assert_flushed_distribution_metric!(expected_distribution, &flushed_metrics[0], [bucket_ts(1) => &values[..]]);
2105        assert_flushed_scalar_metric!(count_metric, &flushed_metrics[1], [bucket_ts(1) => 5.0]);
2106        assert_flushed_scalar_metric!(p50_metric, &flushed_metrics[2], [bucket_ts(1) => 3.0], error_ratio => 0.0025);
2107        assert_flushed_scalar_metric!(sum_metric, &flushed_metrics[3], [bucket_ts(1) => 15.0]);
2108    }
2109
2110    #[tokio::test]
2111    async fn nonaggregated_counters_to_rate() {
2112        let counter_value = 42.0;
2113
2114        // Create a basic aggregation state.
2115        let mut state = AggregationState::new(
2116            BUCKET_WIDTH_SECS,
2117            10,
2118            COUNTER_EXPIRE,
2119            HistogramConfiguration::default(),
2120            Telemetry::noop(),
2121        );
2122
2123        // Create a simple non-aggregated counter, and insert it.
2124        let input_metric = Metric::counter("metric1", counter_value);
2125        assert!(state.insert(insert_ts(1), input_metric.clone()));
2126
2127        // Flush the aggregation state, and observe that we've emitted the expected counter and that it has the right
2128        // value, but specifically that it's a rate with an interval that matches our configured bucket width:
2129        let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
2130        assert_eq!(flushed_metrics.len(), 1);
2131        let flushed_metric = &flushed_metrics[0];
2132
2133        assert_flushed_scalar_metric!(&input_metric, flushed_metric, [bucket_ts(1) => counter_value]);
2134        assert_eq!(flushed_metric.values().as_str(), "rate");
2135    }
2136
2137    #[test]
2138    fn origin_context_telemetry_groups_tag_order_and_skips_unresolved_origins() {
2139        let recorder = TestRecorder::default();
2140        let _local = metrics::set_default_local_recorder(&recorder);
2141        let telemetry = Telemetry::new(&MetricsBuilder::default(), true);
2142        let values = MetricValues::counter((insert_ts(1), 1.0));
2143
2144        let mut first_origin = TagSet::default();
2145        first_origin.insert_tag("container:one");
2146        first_origin.insert_tag("namespace:default");
2147        let first_context = Context::from_static_parts("metric.one", &[]).with_origin_tags(first_origin);
2148        let mut same_origin_different_order = TagSet::default();
2149        same_origin_different_order.insert_tag("namespace:default");
2150        same_origin_different_order.insert_tag("container:one");
2151        let second_context =
2152            Context::from_static_parts("metric.two", &[]).with_origin_tags(same_origin_different_order);
2153
2154        let first_id = telemetry.increment_contexts(&first_context, &values);
2155        let second_id = telemetry.increment_contexts(&second_context, &values);
2156        assert_eq!(
2157            recorder.gauge((
2158                "aggregate_active_contexts_by_origin",
2159                &[("container", "one"), ("namespace", "default")]
2160            )),
2161            Some(2.0)
2162        );
2163
2164        telemetry.decrement_contexts(&first_context, &values, first_id);
2165        assert_eq!(
2166            recorder.gauge((
2167                "aggregate_active_contexts_by_origin",
2168                &[("container", "one"), ("namespace", "default")]
2169            )),
2170            Some(1.0)
2171        );
2172        telemetry.decrement_contexts(&second_context, &values, second_id);
2173        assert_eq!(
2174            recorder.gauge((
2175                "aggregate_active_contexts_by_origin",
2176                &[("container", "one"), ("namespace", "default")]
2177            )),
2178            Some(0.0)
2179        );
2180
2181        let unresolved_context = Context::from_static_parts("metric.unresolved", &[]);
2182        telemetry.increment_contexts(&unresolved_context, &values);
2183        assert_eq!(recorder.gauge("aggregate_active_contexts_by_origin"), None);
2184    }
2185
2186    #[tokio::test]
2187    async fn origin_admission_survives_failed_flush_and_new_values_before_retry() {
2188        let recorder = TestRecorder::default();
2189        let _local = metrics::set_default_local_recorder(&recorder);
2190        let telemetry = Telemetry::new(&MetricsBuilder::default(), true);
2191        let mut state = AggregationState::new(
2192            BUCKET_WIDTH_SECS,
2193            2048,
2194            COUNTER_EXPIRE,
2195            HistogramConfiguration::default(),
2196            telemetry,
2197        );
2198        let mut origin = TagSet::default();
2199        origin.insert_tag("container:one");
2200        let count = 1026;
2201        for i in 0..count {
2202            let context =
2203                Context::from_parts(format!("metric.{i}"), TagSet::default()).with_origin_tags(origin.clone());
2204            assert!(state.insert(insert_ts(1), Metric::gauge(context, (insert_ts(1), 1.0))));
2205        }
2206        let (dispatcher, receiver) = build_basic_dispatcher();
2207        drop(receiver);
2208        let mut buffered = dispatcher.buffered().unwrap();
2209        assert!(state.flush(flush_ts(1), false, &mut buffered).await.is_err());
2210        assert!(
2211            !state.contexts_remove_buf.is_empty(),
2212            "failure must follow a pending expiry"
2213        );
2214        assert_eq!(state.contexts.len(), count);
2215        let metric = ("aggregate_active_contexts_by_origin", &[("container", "one")]);
2216        assert_eq!(recorder.gauge(metric), Some(count as f64));
2217
2218        // A context marked for removal before the failure can receive new, still-open values.
2219        let revived = state.contexts_remove_buf[0].clone();
2220        let future_ts = flush_ts(1) + 100;
2221        assert!(state.insert(future_ts, Metric::gauge(revived.clone(), (future_ts, 1.0))));
2222        let _ = get_flushed_metrics_with_open_windows(flush_ts(1), false, &mut state).await;
2223        assert_eq!(state.contexts.len(), 1);
2224        assert!(state.contexts.contains_key(&revived));
2225        assert_eq!(recorder.gauge(metric), Some(1.0));
2226        let _ = get_flushed_metrics_with_open_windows(future_ts + 100, false, &mut state).await;
2227        assert!(state.contexts.is_empty());
2228        assert_eq!(recorder.gauge(metric), Some(0.0));
2229    }
2230
2231    #[tokio::test]
2232    async fn origin_context_telemetry_tracks_aggregation_insertions_and_expirations() {
2233        let recorder = TestRecorder::default();
2234        let _local = metrics::set_default_local_recorder(&recorder);
2235        let telemetry = Telemetry::new(&MetricsBuilder::default(), true);
2236        let mut state = AggregationState::new(
2237            BUCKET_WIDTH_SECS,
2238            10,
2239            COUNTER_EXPIRE,
2240            HistogramConfiguration::default(),
2241            telemetry,
2242        );
2243
2244        let mut origin_tags = TagSet::default();
2245        origin_tags.insert_tag("container_id:container-1");
2246        origin_tags.insert_tag("kube_namespace:default");
2247        let first_context = Context::from_static_parts("metric.one", &[]).with_origin_tags(origin_tags.clone());
2248        let second_context = Context::from_static_parts("metric.two", &[]).with_origin_tags(origin_tags);
2249
2250        assert!(state.insert(insert_ts(1), Metric::gauge(first_context, (insert_ts(1), 1.0))));
2251        assert!(state.insert(insert_ts(1), Metric::gauge(second_context, (insert_ts(1), 1.0))));
2252        let origin_metric = (
2253            "aggregate_active_contexts_by_origin",
2254            &[("container_id", "container-1"), ("kube_namespace", "default")],
2255        );
2256        assert_eq!(recorder.gauge(origin_metric), Some(2.0));
2257
2258        let _ = get_flushed_metrics(flush_ts(1), &mut state).await;
2259        assert!(state.is_empty());
2260        assert_eq!(recorder.gauge(origin_metric), Some(0.0));
2261    }
2262
2263    #[tokio::test]
2264    async fn telemetry() {
2265        // TODO: We don't check that `component_events_dropped_total` increments when a context limit is hit,
2266        // since that increment happens in the aggregate component future rather than `AggregationState`,
2267        // which is harder to drive overall and would have required even more boilerplate.
2268        //
2269        // Leaving that as a future improvement.
2270
2271        let recorder = TestRecorder::default();
2272        let _local = metrics::set_default_local_recorder(&recorder);
2273
2274        let builder = MetricsBuilder::default();
2275        let telemetry = Telemetry::new(&builder, false);
2276
2277        let mut state = AggregationState::new(
2278            BUCKET_WIDTH_SECS,
2279            2,
2280            COUNTER_EXPIRE,
2281            HistogramConfiguration::default(),
2282            telemetry,
2283        );
2284
2285        // Make sure our telemetry is registered at default values.
2286        assert_eq!(recorder.gauge("aggregate_active_contexts"), Some(0.0));
2287        assert_eq!(
2288            recorder.counter(("component_events_dropped_total", &[("intentional", "true")])),
2289            Some(0)
2290        );
2291        for metric_type in &["counter", "gauge", "rate", "set", "histogram", "distribution"] {
2292            assert_eq!(
2293                recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", *metric_type)])),
2294                Some(0.0)
2295            );
2296        }
2297
2298        // Insert a counter with a non-timestamped value.
2299        assert!(state.insert(insert_ts(1), Metric::counter("metric1", 42.0)));
2300        assert_eq!(recorder.gauge("aggregate_active_contexts"), Some(1.0));
2301        assert_eq!(
2302            recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", "counter")])),
2303            Some(1.0)
2304        );
2305
2306        // Insert a gauge with a timestamped value.
2307        assert!(state.insert(insert_ts(1), Metric::gauge("metric2", (insert_ts(1), 42.0))));
2308        assert_eq!(recorder.gauge("aggregate_active_contexts"), Some(2.0));
2309        assert_eq!(
2310            recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", "gauge")])),
2311            Some(1.0)
2312        );
2313
2314        // We've reached our context limit at this point, so the next metric should not be inserted.
2315        assert!(!state.insert(insert_ts(1), Metric::counter("metric3", 42.0)));
2316        assert_eq!(recorder.gauge("aggregate_active_contexts"), Some(2.0));
2317        assert_eq!(
2318            recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", "counter")])),
2319            Some(1.0)
2320        );
2321
2322        // Now let's flush the state which should flush the gauge entirely, reducing the context count, but not flush
2323        // the counter, since it'll be in zero-value mode.
2324        let _ = get_flushed_metrics(flush_ts(1), &mut state).await;
2325        assert_eq!(recorder.gauge("aggregate_active_contexts"), Some(1.0));
2326        assert_eq!(
2327            recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", "counter")])),
2328            Some(1.0)
2329        );
2330        assert_eq!(
2331            recorder.gauge(("aggregate_active_contexts_by_type", &[("metric_type", "gauge")])),
2332            Some(0.0)
2333        );
2334    }
2335}