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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub enum AggregateMetricType {
45 Counter,
47
48 Rate,
50
51 Gauge,
53
54 Set,
56
57 Histogram,
59
60 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#[derive(Clone, Debug, Eq, PartialEq)]
81pub struct AggregateContextSnapshotEntry {
82 context: Context,
83 metric_type: AggregateMetricType,
84}
85
86impl AggregateContextSnapshotEntry {
87 pub fn context(&self) -> &Context {
89 &self.context
90 }
91
92 pub fn metric_type(&self) -> AggregateMetricType {
94 self.metric_type
95 }
96
97 #[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#[derive(Clone, Debug)]
113pub struct AggregateContextSnapshotHandle {
114 requests: mpsc::Sender<AggregateContextSnapshotRequest>,
115}
116
117impl AggregateContextSnapshotHandle {
118 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
139pub 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#[cfg(any(test, feature = "test-util"))]
167pub struct AggregateContextSnapshotPendingResponse {
168 response: AggregateContextSnapshotRequest,
169}
170
171#[cfg(any(test, feature = "test-util"))]
172impl AggregateContextSnapshotPendingResponse {
173 pub fn respond(self, snapshot: Vec<AggregateContextSnapshotEntry>) {
177 let _ = self.response.send(snapshot);
178 }
179}
180
181#[cfg(any(test, feature = "test-util"))]
183pub struct AggregateContextSnapshotResponder {
184 receiver: AggregateContextSnapshotRequestReceiver,
185}
186
187#[cfg(any(test, feature = "test-util"))]
188impl AggregateContextSnapshotResponder {
189 pub async fn respond(&mut self, snapshot: Vec<AggregateContextSnapshotEntry>) -> Result<(), GenericError> {
197 self.receive().await?.respond(snapshot);
198 Ok(())
199 }
200
201 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 pub async fn stop_after_receiving(&mut self) -> Result<(), GenericError> {
227 drop(self.receive().await?);
228 Ok(())
229 }
230}
231
232#[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
243pub 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
263pub struct AggregateConfiguration {
283 pub window_duration_seconds: NonZeroU64,
289
290 pub primary_flush_interval: Duration,
295
296 pub context_limit: usize,
305
306 pub flush_open_windows: bool,
316
317 pub counter_expiry_seconds: Option<u64>,
330
331 pub hist_config: HistogramConfiguration,
333
334 pub origin_telemetry_enabled: bool,
343
344 pub context_snapshot_receiver: AggregateContextSnapshotReceiver,
349}
350
351#[cfg(test)]
352impl AggregateConfiguration {
353 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 builder
418 .minimum()
419 .with_single_value::<Aggregate>("component struct");
421 builder
422 .firm()
423 .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 .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 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 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 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 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 loop {
516 select! {
517 biased;
518 _ = health.live() => {},
519 _ = &mut flush => break,
520 }
521 }
522 }
523
524 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 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 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 self.last_seen = timestamp;
596 self.values.merge(values);
597
598 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 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 !self.contexts.contains_key(metric.context()) && self.contexts.len() >= self.context_limit {
658 self.context_limit_breached = true;
659 return false;
660 }
661
662 if self.contexts.is_empty() {
666 self.last_flush = 0;
667 }
668
669 let (context, mut values, metadata) = metric.into_parts();
670
671 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 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 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 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 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 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 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 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 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 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 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 break;
813 }
814 }
815 }
816
817 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 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 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 MetricValues::Histogram(ref mut points) => {
884 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 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 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 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 (bucket_start + bucket_width_secs.get() - 1) < current_time || flush_open_buckets
989}
990
991#[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 const fn bucket_ts(step: u64) -> u64 {
1020 align_to_bucket_start(insert_ts(step), BUCKET_WIDTH_SECS)
1021 }
1022
1023 const fn insert_ts(step: u64) -> u64 {
1025 (BUCKET_WIDTH_SECS.get() * (step + 1)) - 2
1026 }
1027
1028 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 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 state
1080 .flush(timestamp, flush_open_buckets, &mut buffered_dispatcher)
1081 .await
1082 .expect("should not fail to flush aggregation state");
1083
1084 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 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 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 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 let cases = [
1578 (1000, 995, BUCKET_WIDTH_SECS, false, false),
1580 (1000, 995, BUCKET_WIDTH_SECS, true, true),
1581 (1000, 1000, BUCKET_WIDTH_SECS, false, false),
1583 (1000, 1000, BUCKET_WIDTH_SECS, true, true),
1584 (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 let mut state = AggregationState::new(
1613 BUCKET_WIDTH_SECS,
1614 2,
1615 COUNTER_EXPIRE,
1616 HistogramConfiguration::default(),
1617 Telemetry::noop(),
1618 );
1619
1620 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 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 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 let mut state = AggregationState::new(
1663 BUCKET_WIDTH_SECS,
1664 2,
1665 COUNTER_EXPIRE,
1666 HistogramConfiguration::default(),
1667 Telemetry::noop(),
1668 );
1669
1670 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 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 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 assert!(!state.insert(insert_ts(3), input_metrics[2].clone()));
1694
1695 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 let flushed_metrics = get_flushed_metrics(flush_ts(4), &mut state).await;
1704 assert_eq!(flushed_metrics.len(), 0);
1705
1706 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 #[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 #[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 #[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 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 let mut state = AggregationState::new(
1807 BUCKET_WIDTH_SECS,
1808 10,
1809 COUNTER_EXPIRE,
1810 HistogramConfiguration::default(),
1811 Telemetry::noop(),
1812 );
1813
1814 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 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 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 assert!(state.insert(insert_ts(4), input_metrics[0].clone()));
1834 assert!(state.insert(insert_ts(4), input_metrics[1].clone()));
1835
1836 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 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 let mut state = AggregationState::new(
1856 BUCKET_WIDTH_SECS,
1857 10,
1858 COUNTER_EXPIRE,
1859 HistogramConfiguration::default(),
1860 Telemetry::noop(),
1861 );
1862
1863 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 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 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 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 let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
1899 assert_eq!(flushed_metrics.len(), 3);
1900
1901 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 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 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 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 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 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 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 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 let mut state = AggregationState::new(
2049 BUCKET_WIDTH_SECS,
2050 10,
2051 COUNTER_EXPIRE,
2052 HistogramConfiguration::default(),
2053 Telemetry::noop(),
2054 );
2055
2056 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 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 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 let flushed_metrics = get_flushed_metrics(flush_ts(1), &mut state).await;
2093 assert_eq!(flushed_metrics.len(), 4);
2094
2095 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 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 let mut state = AggregationState::new(
2116 BUCKET_WIDTH_SECS,
2117 10,
2118 COUNTER_EXPIRE,
2119 HistogramConfiguration::default(),
2120 Telemetry::noop(),
2121 );
2122
2123 let input_metric = Metric::counter("metric1", counter_value);
2125 assert!(state.insert(insert_ts(1), input_metric.clone()));
2126
2127 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 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 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 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 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 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 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 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}