Skip to main content

datafusion_physical_expr_common/metrics/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Metrics for recording information about execution
6
7mod baseline;
8mod builder;
9mod custom;
10mod elapsed_compute;
11mod expression;
12mod snapshot;
13mod value;
14
15use datafusion_common::HashMap;
16pub use datafusion_common::format::{MetricCategory, MetricType};
17use datafusion_common::human_readable_size;
18use parking_lot::Mutex;
19use snapshot::{Registry, Snapshot};
20use std::{
21    borrow::Cow,
22    fmt::{self, Debug, Display},
23    hash::{Hash, Hasher},
24    sync::Arc,
25    vec::IntoIter,
26};
27
28// public exports
29
30pub use baseline::{BaselineMetrics, RecordOutput, SpillMetrics, SplitMetrics};
31pub use builder::MetricBuilder;
32pub use custom::CustomMetricValue;
33pub use elapsed_compute::{ElapsedComputeFuture, ElapsedComputeFutureExt};
34pub use expression::ExpressionEvaluatorMetrics;
35pub use value::{
36    Count, Gauge, MetricValue, PruningMetrics, RatioMergeStrategy, RatioMetrics,
37    ScopedTimerGuard, Time, Timestamp,
38};
39
40/// Something that tracks a value of interest (metric) during execution.
41///
42/// Typically [`Metric`]s are not created directly, but instead
43/// are created using [`MetricBuilder`] or methods on
44/// [`ExecutionPlanMetricsSet`].
45///
46/// ```
47/// use datafusion_physical_expr_common::metrics::*;
48///
49/// let metrics = ExecutionPlanMetricsSet::new();
50/// assert!(metrics.clone_inner().output_rows().is_none());
51///
52/// // Create a counter to increment using the MetricBuilder
53/// let partition = 1;
54/// let output_rows = MetricBuilder::new(&metrics).output_rows(partition);
55///
56/// // Counter can be incremented
57/// output_rows.add(13);
58///
59/// // The value can be retrieved directly:
60/// assert_eq!(output_rows.value(), 13);
61///
62/// // As well as from the metrics set
63/// assert_eq!(metrics.clone_inner().output_rows(), Some(13));
64/// ```
65
66#[derive(Debug)]
67pub struct Metric {
68    /// The value of the metric
69    value: MetricValue,
70
71    /// arbitrary name=value pairs identifying this metric
72    labels: Vec<Label>,
73
74    /// To which partition of an operators output did this metric
75    /// apply? If `None` then means all partitions.
76    partition: Option<usize>,
77
78    metric_type: MetricType,
79
80    /// Optional semantic category (rows / bytes / timing).
81    ///
82    /// When `None` (the default for custom metrics), the metric is
83    /// **always included** unless the user sets
84    /// `analyze_categories = 'none'`.
85    metric_category: Option<MetricCategory>,
86}
87
88impl Display for Metric {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        write!(f, "{}", self.value.name())?;
91
92        let mut iter = self
93            .partition
94            .iter()
95            .map(|partition| Label::new("partition", partition.to_string()))
96            .chain(self.labels().iter().cloned())
97            .peekable();
98
99        // print out the labels specially
100        if iter.peek().is_some() {
101            write!(f, "{{")?;
102
103            let mut is_first = true;
104            for i in iter {
105                if !is_first {
106                    write!(f, ", ")?;
107                } else {
108                    is_first = false;
109                }
110
111                write!(f, "{i}")?;
112            }
113
114            write!(f, "}}")?;
115        }
116
117        // and now the value
118        write!(f, "=")?;
119
120        if self.metric_category == Some(MetricCategory::Bytes) {
121            match &self.value {
122                MetricValue::Count { count, .. } => {
123                    return write!(f, "{}", human_readable_size(count.value()));
124                }
125                MetricValue::Gauge { gauge, .. } => {
126                    return write!(f, "{}", human_readable_size(gauge.value()));
127                }
128                _ => {}
129            }
130        }
131
132        write!(f, "{}", self.value)
133    }
134}
135
136impl Metric {
137    /// Create a new [`Metric`]. Consider using [`MetricBuilder`]
138    /// rather than this function directly.
139    pub fn new(value: MetricValue, partition: Option<usize>) -> Self {
140        Self {
141            value,
142            labels: vec![],
143            partition,
144            metric_type: MetricType::Dev,
145            metric_category: None,
146        }
147    }
148
149    /// Create a new [`Metric`]. Consider using [`MetricBuilder`]
150    /// rather than this function directly.
151    pub fn new_with_labels(
152        value: MetricValue,
153        partition: Option<usize>,
154        labels: Vec<Label>,
155    ) -> Self {
156        Self {
157            value,
158            labels,
159            partition,
160            metric_type: MetricType::Dev,
161            metric_category: None,
162        }
163    }
164
165    /// Set the type for this metric. Defaults to [`MetricType::Dev`]
166    pub fn with_type(mut self, metric_type: MetricType) -> Self {
167        self.metric_type = metric_type;
168        self
169    }
170
171    /// Set the semantic category for this metric.
172    ///
173    /// See [`MetricCategory`] for details on the determinism properties
174    /// of each category.
175    pub fn with_category(mut self, category: MetricCategory) -> Self {
176        self.metric_category = Some(category);
177        self
178    }
179
180    /// Add a new label to this metric
181    pub fn with_label(mut self, label: Label) -> Self {
182        self.labels.push(label);
183        self
184    }
185
186    /// What labels are present for this metric?
187    pub fn labels(&self) -> &[Label] {
188        &self.labels
189    }
190
191    /// Return a reference to the value of this metric
192    pub fn value(&self) -> &MetricValue {
193        &self.value
194    }
195
196    /// Return a mutable reference to the value of this metric
197    pub fn value_mut(&mut self) -> &mut MetricValue {
198        &mut self.value
199    }
200
201    /// Return a reference to the partition
202    pub fn partition(&self) -> Option<usize> {
203        self.partition
204    }
205
206    /// Return the metric type (verbosity level) associated with this metric
207    pub fn metric_type(&self) -> MetricType {
208        self.metric_type
209    }
210
211    /// Return the metric category, if one was declared.
212    ///
213    /// `None` means the metric is always included (except in `none` mode).
214    pub fn metric_category(&self) -> Option<MetricCategory> {
215        self.metric_category
216    }
217}
218
219/// A snapshot of the metrics for a particular execution plan.
220///
221/// The set's members remain fixed as execution registers more metrics, but their
222/// values continue to reflect execution progress. Use [`Self::for_partition`] to
223/// select the metrics belonging to one partition.
224#[derive(Default, Debug, Clone)]
225pub struct MetricsSet {
226    metrics: Snapshot,
227}
228
229impl MetricsSet {
230    /// Create a new container of metrics
231    pub fn new() -> Self {
232        Default::default()
233    }
234
235    /// Add the specified metric without changing other snapshots.
236    pub fn push(&mut self, metric: Arc<Metric>) {
237        self.metrics.push(metric)
238    }
239
240    /// Returns this set with the derived `output_rows_skew` metric appended,
241    /// or unchanged if no partition reported `output_rows` yet.
242    ///
243    /// This is typically used in `ExecutionPlan::metrics` of operators that
244    /// execute in multiple partitions (e.g. repartitions, partitioned joins and
245    /// aggregations), where it shows how evenly their output rows are spread
246    /// across partitions. With a single partition the skew is always `0%`.
247    ///
248    /// See [`BaselineMetrics::output_rows_skew_metric`] for how skew is computed.
249    pub fn with_output_rows_skew(mut self) -> Self {
250        if let Some(output_rows_skew) = BaselineMetrics::output_rows_skew_metric(&self) {
251            self.push(output_rows_skew);
252        }
253        self
254    }
255
256    /// Return the metrics whose partition ID equals `partition`.
257    ///
258    /// Unpartitioned metrics are excluded; an unknown partition yields an empty
259    /// set. Registration order and duplicates are preserved. Selected metrics
260    /// share their current values with this set, but changes to either set's
261    /// membership do not affect the other.
262    pub fn for_partition(&self, partition: usize) -> Self {
263        Self {
264            metrics: self.metrics.for_partition(partition),
265        }
266    }
267
268    /// Returns an iterator across all metrics
269    pub fn iter(&self) -> impl Iterator<Item = &Arc<Metric>> {
270        self.metrics.iter()
271    }
272
273    /// Convenience: return the number of rows produced, aggregated
274    /// across partitions or `None` if no metric is present
275    pub fn output_rows(&self) -> Option<usize> {
276        self.sum(|metric| matches!(metric.value(), MetricValue::OutputRows(_)))
277            .map(|v| v.as_usize())
278    }
279
280    /// Convenience: return the count of spills, aggregated
281    /// across partitions or `None` if no metric is present
282    pub fn spill_count(&self) -> Option<usize> {
283        self.sum(|metric| matches!(metric.value(), MetricValue::SpillCount(_)))
284            .map(|v| v.as_usize())
285    }
286
287    /// Convenience: return the total byte size of spills, aggregated
288    /// across partitions or `None` if no metric is present
289    pub fn spilled_bytes(&self) -> Option<usize> {
290        self.sum(|metric| matches!(metric.value(), MetricValue::SpilledBytes(_)))
291            .map(|v| v.as_usize())
292    }
293
294    /// Convenience: return the total rows of spills, aggregated
295    /// across partitions or `None` if no metric is present
296    pub fn spilled_rows(&self) -> Option<usize> {
297        self.sum(|metric| matches!(metric.value(), MetricValue::SpilledRows(_)))
298            .map(|v| v.as_usize())
299    }
300
301    /// Convenience: return the amount of elapsed CPU time spent,
302    /// aggregated across partitions or `None` if no metric is present
303    pub fn elapsed_compute(&self) -> Option<usize> {
304        self.sum(|metric| matches!(metric.value(), MetricValue::ElapsedCompute(_)))
305            .map(|v| v.as_usize())
306    }
307
308    /// Sums the values for metrics for which `f(metric)` returns
309    /// `true`, and returns the value. Returns `None` if no metrics match
310    /// the predicate.
311    pub fn sum<F>(&self, mut f: F) -> Option<MetricValue>
312    where
313        F: FnMut(&Metric) -> bool,
314    {
315        let mut iter = self
316            .metrics
317            .iter()
318            .filter(|metric| f(metric.as_ref()))
319            .peekable();
320
321        let mut accum = match iter.peek() {
322            None => {
323                return None;
324            }
325            Some(metric) => metric.value().new_empty(),
326        };
327
328        iter.for_each(|metric| accum.aggregate(metric.value()));
329
330        Some(accum)
331    }
332
333    /// Returns the sum of all the metrics with the specified name
334    /// in the returned set.
335    pub fn sum_by_name(&self, metric_name: &str) -> Option<MetricValue> {
336        self.sum(|m| match m.value() {
337            MetricValue::Count { name, .. } => name == metric_name,
338            MetricValue::Time { name, .. } => name == metric_name,
339            MetricValue::OutputRows(_) => false,
340            MetricValue::ElapsedCompute(_) => false,
341            MetricValue::SpillCount(_) => false,
342            MetricValue::SpilledBytes(_) => false,
343            MetricValue::OutputBytes(_) => false,
344            MetricValue::OutputBatches(_) => false,
345            MetricValue::SpilledRows(_) => false,
346            MetricValue::CurrentMemoryUsage(_) => false,
347            MetricValue::Gauge { name, .. } => name == metric_name,
348            MetricValue::PeakMemoryUsage { name, .. } => name == metric_name,
349            MetricValue::StartTimestamp(_) => false,
350            MetricValue::EndTimestamp(_) => false,
351            MetricValue::PruningMetrics { name, .. } => name == metric_name,
352            MetricValue::Ratio { name, .. } => name == metric_name,
353            MetricValue::Custom { name, .. } => name == metric_name,
354        })
355    }
356
357    /// Returns a new derived `MetricsSet` where all metrics
358    /// that had the same name have been
359    /// aggregated together. The resulting `MetricsSet` has all
360    /// metrics with `Partition=None`
361    pub fn aggregate_by_name(&self) -> Self {
362        let mut map = HashMap::new();
363
364        // There are all sorts of ways to make this more efficient
365        for metric in &self.metrics {
366            let key = metric.value.name();
367            map.entry(key)
368                .and_modify(|accum: &mut Metric| {
369                    accum.value_mut().aggregate(metric.value());
370                })
371                .or_insert_with(|| {
372                    // accumulate with no partition
373                    let partition = None;
374                    let mut accum = Metric::new(metric.value().new_empty(), partition)
375                        .with_type(metric.metric_type());
376                    if let Some(cat) = metric.metric_category() {
377                        accum = accum.with_category(cat);
378                    }
379                    accum.value_mut().aggregate(metric.value());
380                    accum
381                });
382        }
383
384        let new_metrics = map.into_iter().map(|(_k, v)| Arc::new(v)).collect();
385
386        Self {
387            metrics: new_metrics,
388        }
389    }
390
391    /// Sort the order of metrics so the "most useful" show up first
392    pub fn sorted_for_display(self) -> Self {
393        let mut metrics: Vec<_> = self.into_iter().collect();
394        metrics.sort_unstable_by_key(|metric| {
395            (
396                metric.value().display_sort_key(),
397                metric.value().name().to_owned(),
398            )
399        });
400        metrics.into_iter().collect()
401    }
402
403    /// Remove all timestamp metrics (for more compact display)
404    pub fn timestamps_removed(self) -> Self {
405        let Self { metrics } = self;
406
407        let metrics = metrics
408            .into_iter()
409            .filter(|m| !m.value.is_timestamp())
410            .collect();
411
412        Self { metrics }
413    }
414
415    /// Returns a new derived `MetricsSet` containing only metrics whose
416    /// [`MetricType`] appears in `allowed`.
417    pub fn filter_by_metric_types(self, allowed: &[MetricType]) -> Self {
418        if allowed.is_empty() {
419            return Self::new();
420        }
421
422        let metrics = self
423            .metrics
424            .into_iter()
425            .filter(|metric| allowed.contains(&metric.metric_type()))
426            .collect();
427        Self { metrics }
428    }
429
430    /// Returns a new `MetricsSet` filtered by [`MetricCategory`].
431    ///
432    /// - Metrics that declared a category are kept only when that
433    ///   category appears in `allowed`.
434    /// - Metrics with **no** declared category are treated as
435    ///   [`Uncategorized`](MetricCategory::Uncategorized) for filtering.
436    /// - An **empty** `allowed` slice means "plan only": all metrics are
437    ///   removed.
438    pub fn filter_by_categories(self, allowed: &[MetricCategory]) -> Self {
439        if allowed.is_empty() {
440            return Self::new();
441        }
442
443        let metrics = self
444            .metrics
445            .into_iter()
446            .filter(|metric| {
447                let cat = metric
448                    .metric_category()
449                    .unwrap_or(MetricCategory::Uncategorized);
450                allowed.contains(&cat)
451            })
452            .collect();
453        Self { metrics }
454    }
455
456    /// Returns a new `MetricsSet` filtered by metric name.
457    /// Only metrics with the names appearing the list will be kept.
458    pub fn filter_by_names(self, names: &[String]) -> Self {
459        if names.is_empty() {
460            return Self::new();
461        }
462
463        let metrics = self
464            .metrics
465            .into_iter()
466            .filter(|metric| names.iter().any(|name| name == metric.value().name()))
467            .collect();
468        Self { metrics }
469    }
470}
471
472impl Display for MetricsSet {
473    /// Format the [`MetricsSet`] as a single string
474    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
475        let mut is_first = true;
476        for i in self.metrics.iter() {
477            if !is_first {
478                write!(f, ", ")?;
479            } else {
480                is_first = false;
481            }
482
483            write!(f, "{i}")?;
484        }
485        Ok(())
486    }
487}
488
489impl IntoIterator for MetricsSet {
490    type Item = Arc<Metric>;
491    type IntoIter = IntoIter<Self::Item>;
492
493    fn into_iter(self) -> Self::IntoIter {
494        self.metrics.into_iter()
495    }
496}
497
498impl<'a> IntoIterator for &'a MetricsSet {
499    type Item = &'a Arc<Metric>;
500    type IntoIter = std::slice::Iter<'a, Arc<Metric>>;
501
502    fn into_iter(self) -> Self::IntoIter {
503        self.metrics.iter()
504    }
505}
506
507impl Extend<Arc<Metric>> for MetricsSet {
508    fn extend<I: IntoIterator<Item = Arc<Metric>>>(&mut self, iter: I) {
509        self.metrics.extend(iter);
510    }
511}
512
513impl FromIterator<Arc<Metric>> for MetricsSet {
514    fn from_iter<T: IntoIterator<Item = Arc<Metric>>>(iter: T) -> Self {
515        Self {
516            metrics: iter.into_iter().collect(),
517        }
518    }
519}
520
521/// A set of [`Metric`]s for an individual operator.
522///
523/// This structure is intended as a convenience for execution plan
524/// implementations so they can generate different streams for multiple
525/// partitions but easily report them together.
526///
527/// Each `clone()` of this structure will add metrics to the same
528/// underlying metrics set
529#[derive(Default, Debug, Clone)]
530pub struct ExecutionPlanMetricsSet {
531    inner: Arc<Mutex<Registry>>,
532}
533
534impl ExecutionPlanMetricsSet {
535    /// Create a new empty shared metrics set
536    pub fn new() -> Self {
537        Self::default()
538    }
539
540    /// Add the specified metric to the underlying metric set
541    pub fn register(&self, metric: Arc<Metric>) {
542        self.inner.lock().register(metric)
543    }
544
545    /// Return a snapshot of the currently registered metrics.
546    ///
547    /// Later registrations do not appear in this snapshot, but changes to the
548    /// values of existing metrics remain visible.
549    pub fn clone_inner(&self) -> MetricsSet {
550        MetricsSet {
551            metrics: Snapshot::new(Arc::clone(&self.inner)),
552        }
553    }
554}
555
556impl From<MetricsSet> for ExecutionPlanMetricsSet {
557    fn from(metrics: MetricsSet) -> Self {
558        Self {
559            inner: Arc::new(Mutex::new(Registry::new(metrics.into_iter().collect()))),
560        }
561    }
562}
563
564/// `name=value` pairs identifying a metric. This concept is called various things
565/// in various different systems:
566///
567/// "labels" in
568/// [prometheus](https://prometheus.io/docs/concepts/data_model/) and
569/// "tags" in
570/// [InfluxDB](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_tutorial/)
571/// , "attributes" in [open
572/// telemetry]<https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md>,
573/// etc.
574///
575/// As the name and value are expected to often be constant strings, borrowed
576/// static strings avoid allocations in that common case. Dynamic strings are
577/// stored behind [`Arc<str>`] so cloning labels does not copy the underlying
578/// string data.
579#[derive(Debug, Clone, PartialEq, Eq, Hash)]
580pub struct Label {
581    name: LabelValue,
582    value: LabelValue,
583}
584
585impl Label {
586    /// Create a new [`Label`]
587    pub fn new(name: impl Into<LabelValue>, value: impl Into<LabelValue>) -> Self {
588        let name = name.into();
589        let value = value.into();
590        Self { name, value }
591    }
592
593    /// Returns the name of this label
594    pub fn name(&self) -> &str {
595        self.name.as_str()
596    }
597
598    /// Returns the value of this label
599    pub fn value(&self) -> &str {
600        self.value.as_str()
601    }
602}
603
604impl Display for Label {
605    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606        write!(f, "{}={}", self.name, self.value)
607    }
608}
609
610/// A label name or value.
611///
612/// String literals preserve the existing allocation-free path. Dynamic strings
613/// can be stored behind [`Arc<str>`], so cloning a [`Label`] only increments an
614/// atomic reference count and does not allocate or copy the underlying string
615/// data.
616#[derive(Clone)]
617pub struct LabelValue(LabelValueInner);
618
619/// Internal representation for label names and values.
620///
621/// `LabelValue` is public because `Label::new` accepts it, but these storage
622/// variants are implementation details. Keeping them private prevents external
623/// code from constructing or matching on `Static` and `Shared` directly.
624#[derive(Clone)]
625enum LabelValueInner {
626    Static(&'static str),
627    Shared(Arc<str>),
628}
629
630impl LabelValue {
631    /// Return this label value as a string slice.
632    pub fn as_str(&self) -> &str {
633        match &self.0 {
634            LabelValueInner::Static(value) => value,
635            LabelValueInner::Shared(value) => value.as_ref(),
636        }
637    }
638}
639
640impl From<&'static str> for LabelValue {
641    fn from(value: &'static str) -> Self {
642        Self(LabelValueInner::Static(value))
643    }
644}
645
646impl From<String> for LabelValue {
647    fn from(value: String) -> Self {
648        Self(LabelValueInner::Shared(Arc::from(value)))
649    }
650}
651
652impl From<Arc<str>> for LabelValue {
653    fn from(value: Arc<str>) -> Self {
654        Self(LabelValueInner::Shared(value))
655    }
656}
657
658impl From<Cow<'static, str>> for LabelValue {
659    fn from(value: Cow<'static, str>) -> Self {
660        match value {
661            Cow::Borrowed(value) => value.into(),
662            Cow::Owned(value) => value.into(),
663        }
664    }
665}
666
667impl PartialEq for LabelValue {
668    fn eq(&self, other: &Self) -> bool {
669        self.as_str() == other.as_str()
670    }
671}
672
673impl Eq for LabelValue {}
674
675impl Hash for LabelValue {
676    fn hash<H: Hasher>(&self, state: &mut H) {
677        self.as_str().hash(state);
678    }
679}
680
681impl Debug for LabelValue {
682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683        Debug::fmt(self.as_str(), f)
684    }
685}
686
687impl Display for LabelValue {
688    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689        Display::fmt(self.as_str(), f)
690    }
691}
692
693#[cfg(test)]
694mod tests {
695    use std::any::Any;
696    use std::sync::atomic::{AtomicUsize, Ordering};
697    use std::time::Duration;
698
699    use chrono::{TimeZone, Utc};
700
701    use super::*;
702
703    #[test]
704    fn test_display_no_labels_no_partition() {
705        let count = Count::new();
706        count.add(33);
707        let value = MetricValue::OutputRows(count);
708        let partition = None;
709        let metric = Metric::new(value, partition);
710
711        assert_eq!("output_rows=33", metric.to_string())
712    }
713
714    #[test]
715    fn test_display_no_labels_with_partition() {
716        let count = Count::new();
717        count.add(44);
718        let value = MetricValue::OutputRows(count);
719        let partition = Some(1);
720        let metric = Metric::new(value, partition);
721
722        assert_eq!("output_rows{partition=1}=44", metric.to_string())
723    }
724
725    #[test]
726    fn test_display_labels_no_partition() {
727        let count = Count::new();
728        count.add(55);
729        let value = MetricValue::OutputRows(count);
730        let partition = None;
731        let label = Label::new("foo", "bar");
732        let metric = Metric::new_with_labels(value, partition, vec![label]);
733
734        assert_eq!("output_rows{foo=bar}=55", metric.to_string())
735    }
736
737    #[test]
738    fn test_display_labels_and_partition() {
739        let count = Count::new();
740        count.add(66);
741        let value = MetricValue::OutputRows(count);
742        let partition = Some(2);
743        let label = Label::new("foo", "bar");
744        let metric = Metric::new_with_labels(value, partition, vec![label]);
745
746        assert_eq!("output_rows{partition=2, foo=bar}=66", metric.to_string())
747    }
748
749    #[test]
750    fn test_label_owned_and_borrowed_values_are_equal() {
751        let borrowed = Label::new("foo", "bar");
752        let owned = Label::new("foo".to_string(), "bar".to_string());
753        let shared = Label::new("foo", Arc::<str>::from("bar"));
754
755        assert_eq!(borrowed, owned);
756        assert_eq!(borrowed, shared);
757        assert_eq!(borrowed.to_string(), owned.to_string());
758        assert_eq!(borrowed.to_string(), shared.to_string());
759    }
760
761    #[test]
762    fn selected_snapshot_mutations_are_independent() {
763        let registry = ExecutionPlanMetricsSet::new();
764        MetricBuilder::new(&registry).output_rows(0).add(3);
765        MetricBuilder::new(&registry).output_rows(1).add(7);
766        MetricBuilder::new(&registry)
767            .global_counter("global")
768            .add(11);
769        let full = registry.clone_inner();
770        let selected = full.for_partition(0);
771        assert_eq!(selected.for_partition(0).output_rows(), Some(3));
772        assert_eq!(selected.for_partition(1).iter().count(), 0);
773        let mut modified = selected.clone();
774        let count = Count::new();
775        count.add(13);
776        modified.push(Arc::new(Metric::new(
777            MetricValue::OutputRows(count),
778            Some(1),
779        )));
780        assert_eq!(modified.output_rows(), Some(16));
781        assert_eq!(modified.for_partition(1).output_rows(), Some(13));
782        assert_eq!(selected.output_rows(), Some(3));
783        assert_eq!(full.output_rows(), Some(10));
784        assert_eq!(registry.clone_inner().iter().count(), 3);
785        assert_eq!(modified.clone().into_iter().count(), 2);
786        assert_eq!(
787            modified.sorted_for_display().for_partition(0).output_rows(),
788            Some(3)
789        );
790    }
791
792    #[test]
793    fn partition_snapshots_preserve_registration_and_shared_values() {
794        let metrics = ExecutionPlanMetricsSet::new();
795        assert_eq!(metrics.clone_inner().for_partition(0).iter().count(), 0);
796        let first = MetricBuilder::new(&metrics).output_rows(0);
797        first.add(11);
798        MetricBuilder::new(&metrics).global_counter("global").add(7);
799        MetricBuilder::new(&metrics).output_rows(usize::MAX).add(99);
800        // Same name and partition must not overwrite the earlier metric.
801        MetricBuilder::new(&metrics).output_rows(0).add(13);
802        let snapshot = metrics.clone_inner().for_partition(0);
803        assert_eq!(snapshot.output_rows(), Some(24));
804        assert_eq!(snapshot.iter().count(), 2);
805        assert_eq!(snapshot.aggregate_by_name().output_rows(), Some(24));
806        assert_eq!(
807            metrics
808                .clone_inner()
809                .for_partition(usize::MAX)
810                .output_rows(),
811            Some(99)
812        );
813        assert_eq!(metrics.clone_inner().for_partition(1).iter().count(), 0);
814
815        let shared = metrics.clone();
816        first.add(1);
817        MetricBuilder::new(&shared).output_rows(0).add(17);
818        assert_eq!(snapshot.output_rows(), Some(25));
819        assert_eq!(
820            shared.clone_inner().for_partition(0).output_rows(),
821            Some(42)
822        );
823        assert_eq!(
824            metrics.clone_inner().for_partition(0).output_rows(),
825            Some(42)
826        );
827
828        let full = metrics.clone_inner();
829        let imported = ExecutionPlanMetricsSet::from(full.clone());
830        for (original, copied) in full.iter().zip(imported.clone_inner().iter()) {
831            assert!(Arc::ptr_eq(original, copied));
832        }
833        for partition in [0, 1, usize::MAX] {
834            let expected: Vec<_> = full
835                .iter()
836                .filter(|metric| metric.partition() == Some(partition))
837                .collect();
838            let selected = imported.clone_inner().for_partition(partition);
839            assert_eq!(expected.len(), selected.iter().count());
840            for (original, copied) in expected.into_iter().zip(selected.iter()) {
841                assert!(Arc::ptr_eq(original, copied));
842            }
843        }
844        // From shares metric values, but creates an independent registration set.
845        MetricBuilder::new(&imported).output_rows(0).add(3);
846        assert_eq!(
847            imported.clone_inner().for_partition(0).output_rows(),
848            Some(45)
849        );
850        assert_eq!(
851            metrics.clone_inner().for_partition(0).output_rows(),
852            Some(42)
853        );
854        assert_eq!(full.iter().filter(|m| m.partition().is_none()).count(), 1);
855    }
856
857    #[test]
858    fn partition_snapshots_during_registration() {
859        let metrics = ExecutionPlanMetricsSet::new();
860        let barrier = std::sync::Barrier::new(5);
861        std::thread::scope(|scope| {
862            for partition in 0..4 {
863                let metrics = &metrics;
864                let barrier = &barrier;
865                scope.spawn(move || {
866                    barrier.wait();
867                    for _ in 0..1000 {
868                        MetricBuilder::new(metrics).output_rows(partition).add(1);
869                    }
870                });
871            }
872            barrier.wait();
873            for _ in 0..1000 {
874                for partition in 0..4 {
875                    let selected = metrics.clone_inner().for_partition(partition);
876                    assert!(selected.iter().all(|m| m.partition() == Some(partition)));
877                    assert!(selected.iter().count() <= 1000);
878                }
879            }
880        });
881        for partition in 0..4 {
882            let selected = metrics.clone_inner().for_partition(partition);
883            assert_eq!(selected.iter().count(), 1000);
884            assert_eq!(selected.output_rows(), Some(1000));
885        }
886        assert_eq!(metrics.clone_inner().output_rows(), Some(4000));
887    }
888
889    #[test]
890    fn test_output_rows() {
891        let metrics = ExecutionPlanMetricsSet::new();
892        assert!(metrics.clone_inner().output_rows().is_none());
893
894        let partition = 1;
895        let output_rows = MetricBuilder::new(&metrics).output_rows(partition);
896        output_rows.add(13);
897
898        let output_rows = MetricBuilder::new(&metrics).output_rows(partition + 1);
899        output_rows.add(7);
900        assert_eq!(metrics.clone_inner().output_rows().unwrap(), 20);
901    }
902
903    #[test]
904    fn test_elapsed_compute() {
905        let metrics = ExecutionPlanMetricsSet::new();
906        assert!(metrics.clone_inner().elapsed_compute().is_none());
907
908        let partition = 1;
909        let elapsed_compute = MetricBuilder::new(&metrics).elapsed_compute(partition);
910        elapsed_compute.add_duration(Duration::from_nanos(1234));
911
912        let elapsed_compute = MetricBuilder::new(&metrics).elapsed_compute(partition + 1);
913        elapsed_compute.add_duration(Duration::from_nanos(6));
914        assert_eq!(metrics.clone_inner().elapsed_compute().unwrap(), 1240);
915    }
916
917    #[test]
918    fn test_sum() {
919        let metrics = ExecutionPlanMetricsSet::new();
920
921        let count1 = MetricBuilder::new(&metrics)
922            .with_new_label("foo", "bar")
923            .counter("my_counter", 1);
924        count1.add(1);
925
926        let count2 = MetricBuilder::new(&metrics).counter("my_counter", 2);
927        count2.add(2);
928
929        let metrics = metrics.clone_inner();
930        assert!(metrics.sum(|_| false).is_none());
931
932        let expected_count = Count::new();
933        expected_count.add(3);
934        let expected_sum = MetricValue::Count {
935            name: "my_counter".into(),
936            count: expected_count,
937        };
938
939        assert_eq!(metrics.sum(|_| true), Some(expected_sum));
940    }
941
942    #[test]
943    fn test_bytes_counter_and_gauge_use_byte_units() {
944        let metrics = ExecutionPlanMetricsSet::new();
945
946        // A dedicated byte counter/gauge (like `bytes_scanned` or
947        // `stream_memory_usage`) must render with human_readable_size's
948        // 1024-based units (KB/MB/GB), not human_readable_count's 1000-based
949        // units (K/M/B) - see #24203. 3 GiB, chosen to clear
950        // human_readable_size's >= 2x-tier threshold for GB (below that it
951        // falls back to a large MB value).
952        let three_gib = 3 * 1024 * 1024 * 1024;
953        let bytes_scanned =
954            MetricBuilder::new(&metrics).bytes_counter("bytes_scanned", 0);
955        bytes_scanned.add(three_gib);
956
957        let stream_memory_usage =
958            MetricBuilder::new(&metrics).bytes_gauge("stream_memory_usage", 0);
959        stream_memory_usage.add(three_gib);
960
961        // ParquetSink uses the global (non-partitioned) builder for
962        // `bytes_written`, distinct from `bytes_scanned`'s partitioned
963        // `bytes_counter` above - cover that path too.
964        let bytes_written =
965            MetricBuilder::new(&metrics).global_bytes_counter("bytes_written");
966        bytes_written.add(three_gib);
967
968        // A generic Count/Gauge explicitly tagged Bytes must ALSO be
969        // byte-formatted at Display time - see #24203. `MetricValue` is a
970        // public, already-released exhaustive enum, so dedicated
971        // BytesCount/BytesGauge variants would be a SemVer break; instead
972        // `Display for Metric` reinterprets any Bytes-category Count/Gauge.
973        let generic_bytes_gauge = MetricBuilder::new(&metrics)
974            .with_category(MetricCategory::Bytes)
975            .gauge("right_input_bytes", 0);
976        generic_bytes_gauge.add(three_gib);
977
978        // A generic Count/Gauge with NO Bytes category must keep
979        // count-formatting (human_readable_count), not byte-formatting.
980        let generic_rows_gauge =
981            MetricBuilder::new(&metrics).gauge("right_input_rows", 0);
982        generic_rows_gauge.add(three_gib);
983
984        let rendered: Vec<String> = metrics
985            .clone_inner()
986            .iter()
987            .map(|m| m.to_string())
988            .collect();
989
990        assert!(
991            rendered
992                .iter()
993                .any(|s| s == "bytes_scanned{partition=0}=3.0 GB"),
994            "bytes_scanned should be byte-formatted, got: {rendered:?}"
995        );
996        assert!(
997            rendered
998                .iter()
999                .any(|s| s == "stream_memory_usage{partition=0}=3.0 GB"),
1000            "stream_memory_usage should be byte-formatted, got: {rendered:?}"
1001        );
1002        assert!(
1003            rendered.iter().any(|s| s == "bytes_written=3.0 GB"),
1004            "bytes_written (global_bytes_counter, no partition) should be byte-formatted, got: {rendered:?}"
1005        );
1006        assert!(
1007            rendered
1008                .iter()
1009                .any(|s| s == "right_input_bytes{partition=0}=3.0 GB"),
1010            "a generic Gauge tagged Bytes should be byte-formatted, got: {rendered:?}"
1011        );
1012        assert!(
1013            rendered
1014                .iter()
1015                .any(|s| s == "right_input_rows{partition=0}=3.22 B"),
1016            "a generic Gauge with no Bytes category must keep count-formatting, got: {rendered:?}"
1017        );
1018    }
1019
1020    #[test]
1021    fn test_sum_by_name_custom_metric() {
1022        #[derive(Debug)]
1023        struct CustomCount(AtomicUsize);
1024
1025        impl Display for CustomCount {
1026            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027                write!(f, "{}", self.0.load(Ordering::Relaxed))
1028            }
1029        }
1030
1031        impl CustomMetricValue for CustomCount {
1032            fn new_empty(&self) -> Arc<dyn CustomMetricValue> {
1033                Arc::new(Self(AtomicUsize::new(0)))
1034            }
1035
1036            fn aggregate(&self, other: Arc<dyn CustomMetricValue + 'static>) {
1037                let other = other.as_any().downcast_ref::<Self>().unwrap();
1038                self.0
1039                    .fetch_add(other.0.load(Ordering::Relaxed), Ordering::Relaxed);
1040            }
1041
1042            fn as_any(&self) -> &dyn Any {
1043                self
1044            }
1045
1046            fn as_usize(&self) -> usize {
1047                self.0.load(Ordering::Relaxed)
1048            }
1049
1050            fn is_eq(&self, other: &Arc<dyn CustomMetricValue>) -> bool {
1051                other.as_any().downcast_ref::<Self>().is_some_and(|other| {
1052                    self.0.load(Ordering::Relaxed) == other.0.load(Ordering::Relaxed)
1053                })
1054            }
1055        }
1056
1057        let metrics = ExecutionPlanMetricsSet::new();
1058        for (name, value) in [("custom_count", 1), ("custom_count", 2), ("other", 4)] {
1059            MetricBuilder::new(&metrics).build(MetricValue::Custom {
1060                name: name.into(),
1061                value: Arc::new(CustomCount(AtomicUsize::new(value))),
1062            });
1063        }
1064
1065        assert_eq!(
1066            metrics
1067                .clone_inner()
1068                .sum_by_name("custom_count")
1069                .map(|metric| metric.as_usize()),
1070            Some(3)
1071        );
1072    }
1073
1074    #[test]
1075    #[should_panic(expected = "Mismatched metric types. Can not aggregate Count")]
1076    fn test_bad_sum() {
1077        // can not add different kinds of metrics
1078        let metrics = ExecutionPlanMetricsSet::new();
1079
1080        let count = MetricBuilder::new(&metrics).counter("my_metric", 1);
1081        count.add(1);
1082
1083        let time = MetricBuilder::new(&metrics).subset_time("my_metric", 1);
1084        time.add_duration(Duration::from_nanos(10));
1085
1086        // expect that this will error out
1087        metrics.clone_inner().sum(|_| true);
1088    }
1089
1090    #[test]
1091    fn test_aggregate_by_name() {
1092        let metrics = ExecutionPlanMetricsSet::new();
1093
1094        // Note cpu_time1 has labels but it is still aggregated with metrics 2 and 3
1095        let elapsed_compute1 = MetricBuilder::new(&metrics)
1096            .with_new_label("foo", "bar")
1097            .elapsed_compute(1);
1098        elapsed_compute1.add_duration(Duration::from_nanos(12));
1099
1100        let elapsed_compute2 = MetricBuilder::new(&metrics).elapsed_compute(2);
1101        elapsed_compute2.add_duration(Duration::from_nanos(34));
1102
1103        let elapsed_compute3 = MetricBuilder::new(&metrics).elapsed_compute(4);
1104        elapsed_compute3.add_duration(Duration::from_nanos(56));
1105
1106        let output_rows = MetricBuilder::new(&metrics).output_rows(1); // output rows
1107        output_rows.add(56);
1108
1109        let aggregated = metrics.clone_inner().aggregate_by_name();
1110
1111        // cpu time should be aggregated:
1112        let elapsed_computes = aggregated
1113            .iter()
1114            .filter(|metric| matches!(metric.value(), MetricValue::ElapsedCompute(_)))
1115            .collect::<Vec<_>>();
1116        assert_eq!(elapsed_computes.len(), 1);
1117        assert_eq!(elapsed_computes[0].value().as_usize(), 12 + 34 + 56);
1118        assert!(elapsed_computes[0].partition().is_none());
1119
1120        // output rows should
1121        let output_rows = aggregated
1122            .iter()
1123            .filter(|metric| matches!(metric.value(), MetricValue::OutputRows(_)))
1124            .collect::<Vec<_>>();
1125        assert_eq!(output_rows.len(), 1);
1126        assert_eq!(output_rows[0].value().as_usize(), 56);
1127        assert!(output_rows[0].partition.is_none())
1128    }
1129
1130    #[test]
1131    #[should_panic(expected = "Mismatched metric types. Can not aggregate Count")]
1132    fn test_aggregate_partition_bad_sum() {
1133        let metrics = ExecutionPlanMetricsSet::new();
1134
1135        let count = MetricBuilder::new(&metrics).counter("my_metric", 1);
1136        count.add(1);
1137
1138        let time = MetricBuilder::new(&metrics).subset_time("my_metric", 1);
1139        time.add_duration(Duration::from_nanos(10));
1140
1141        // can't aggregate time and count -- expect a panic
1142        metrics.clone_inner().aggregate_by_name();
1143    }
1144
1145    #[test]
1146    fn test_aggregate_partition_timestamps() {
1147        let metrics = ExecutionPlanMetricsSet::new();
1148
1149        // 1431648000000000 == 1970-01-17 13:40:48 UTC
1150        let t1 = Utc.timestamp_nanos(1431648000000000);
1151        // 1531648000000000 == 1970-01-18 17:27:28 UTC
1152        let t2 = Utc.timestamp_nanos(1531648000000000);
1153        // 1631648000000000 == 1970-01-19 21:14:08 UTC
1154        let t3 = Utc.timestamp_nanos(1631648000000000);
1155        // 1731648000000000 == 1970-01-21 01:00:48 UTC
1156        let t4 = Utc.timestamp_nanos(1731648000000000);
1157
1158        let start_timestamp0 = MetricBuilder::new(&metrics).start_timestamp(0);
1159        start_timestamp0.set(t1);
1160        let end_timestamp0 = MetricBuilder::new(&metrics).end_timestamp(0);
1161        end_timestamp0.set(t2);
1162        let start_timestamp1 = MetricBuilder::new(&metrics).start_timestamp(0);
1163        start_timestamp1.set(t3);
1164        let end_timestamp1 = MetricBuilder::new(&metrics).end_timestamp(0);
1165        end_timestamp1.set(t4);
1166
1167        // aggregate
1168        let aggregated = metrics.clone_inner().aggregate_by_name();
1169
1170        let mut ts = aggregated
1171            .iter()
1172            .filter(|metric| {
1173                matches!(metric.value(), MetricValue::StartTimestamp(_))
1174                    && metric.labels().is_empty()
1175            })
1176            .collect::<Vec<_>>();
1177        assert_eq!(ts.len(), 1);
1178        match ts.remove(0).value() {
1179            MetricValue::StartTimestamp(ts) => {
1180                // expect earliest of t1, t2
1181                assert_eq!(ts.value(), Some(t1));
1182            }
1183            _ => {
1184                panic!("Not a timestamp");
1185            }
1186        }
1187
1188        let mut ts = aggregated
1189            .iter()
1190            .filter(|metric| {
1191                matches!(metric.value(), MetricValue::EndTimestamp(_))
1192                    && metric.labels().is_empty()
1193            })
1194            .collect::<Vec<_>>();
1195        assert_eq!(ts.len(), 1);
1196        match ts.remove(0).value() {
1197            MetricValue::EndTimestamp(ts) => {
1198                // expect latest of t3, t4
1199                assert_eq!(ts.value(), Some(t4));
1200            }
1201            _ => {
1202                panic!("Not a timestamp");
1203            }
1204        }
1205    }
1206
1207    #[test]
1208    fn test_extend() {
1209        let mut metrics = MetricsSet::new();
1210        let m1 = Arc::new(Metric::new(MetricValue::OutputRows(Count::new()), None));
1211        let m2 = Arc::new(Metric::new(MetricValue::SpillCount(Count::new()), None));
1212
1213        metrics.extend([Arc::clone(&m1), Arc::clone(&m2)]);
1214        assert_eq!(metrics.iter().count(), 2);
1215
1216        let m3 = Arc::new(Metric::new(MetricValue::SpilledBytes(Count::new()), None));
1217        metrics.extend(std::iter::once(Arc::clone(&m3)));
1218        assert_eq!(metrics.iter().count(), 3);
1219    }
1220
1221    #[test]
1222    fn test_collect() {
1223        let m1 = Arc::new(Metric::new(MetricValue::OutputRows(Count::new()), None));
1224        let m2 = Arc::new(Metric::new(MetricValue::SpillCount(Count::new()), None));
1225
1226        let metrics: MetricsSet =
1227            vec![Arc::clone(&m1), Arc::clone(&m2)].into_iter().collect();
1228        assert_eq!(metrics.iter().count(), 2);
1229
1230        let empty: MetricsSet = std::iter::empty().collect();
1231        assert_eq!(empty.iter().count(), 0);
1232    }
1233
1234    #[test]
1235    fn test_into_iterator_by_ref() {
1236        let mut metrics = MetricsSet::new();
1237        metrics.push(Arc::new(Metric::new(
1238            MetricValue::OutputRows(Count::new()),
1239            None,
1240        )));
1241        metrics.push(Arc::new(Metric::new(
1242            MetricValue::SpillCount(Count::new()),
1243            None,
1244        )));
1245
1246        let mut count = 0;
1247        for _m in &metrics {
1248            count += 1;
1249        }
1250        assert_eq!(count, 2);
1251    }
1252
1253    #[test]
1254    fn test_sorted_for_display() {
1255        let metrics = ExecutionPlanMetricsSet::new();
1256        MetricBuilder::new(&metrics).end_timestamp(0);
1257        MetricBuilder::new(&metrics).start_timestamp(0);
1258        MetricBuilder::new(&metrics).elapsed_compute(0);
1259        MetricBuilder::new(&metrics).counter("the_second_counter", 0);
1260        MetricBuilder::new(&metrics).counter("the_counter", 0);
1261        MetricBuilder::new(&metrics).counter("the_third_counter", 0);
1262        MetricBuilder::new(&metrics).subset_time("the_time", 0);
1263        MetricBuilder::new(&metrics).output_rows(0);
1264        let metrics = metrics.clone_inner();
1265
1266        fn metric_names(metrics: &MetricsSet) -> String {
1267            let n = metrics.iter().map(|m| m.value().name()).collect::<Vec<_>>();
1268            n.join(", ")
1269        }
1270
1271        assert_eq!(
1272            "end_timestamp, start_timestamp, elapsed_compute, the_second_counter, the_counter, the_third_counter, the_time, output_rows",
1273            metric_names(&metrics)
1274        );
1275
1276        let metrics = metrics.sorted_for_display();
1277        assert_eq!(
1278            "output_rows, elapsed_compute, the_counter, the_second_counter, the_third_counter, the_time, start_timestamp, end_timestamp",
1279            metric_names(&metrics)
1280        );
1281    }
1282
1283    #[test]
1284    fn test_filter_by_names() {
1285        let metrics = ExecutionPlanMetricsSet::new();
1286        MetricBuilder::new(&metrics).output_rows(0);
1287        MetricBuilder::new(&metrics).counter("custom_counter", 0);
1288
1289        assert!(
1290            metrics
1291                .clone_inner()
1292                .filter_by_names(&[])
1293                .iter()
1294                .next()
1295                .is_none()
1296        );
1297
1298        let names = vec!["output_rows".to_string()];
1299        let filtered = metrics.clone_inner().filter_by_names(&names);
1300
1301        assert_eq!(filtered.iter().count(), 1);
1302        assert_eq!(
1303            filtered.iter().next().unwrap().value().name(),
1304            "output_rows"
1305        );
1306    }
1307}