Skip to main content

datafusion_physical_expr_common/metrics/
value.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//! Value representation of metrics
6
7use super::CustomMetricValue;
8use chrono::{DateTime, Utc};
9use datafusion_common::{
10    human_readable_count, human_readable_duration, human_readable_size, instant::Instant,
11};
12use parking_lot::Mutex;
13use std::{
14    borrow::{Borrow, Cow},
15    fmt::{Debug, Display},
16    sync::{
17        Arc,
18        atomic::{AtomicUsize, Ordering},
19    },
20    time::Duration,
21};
22
23/// A counter to record things such as number of input or output rows
24///
25/// Note `clone`ing counters update the same underlying metrics
26#[derive(Debug, Clone)]
27pub struct Count {
28    /// value of the metric counter
29    value: Arc<AtomicUsize>,
30}
31
32impl PartialEq for Count {
33    fn eq(&self, other: &Self) -> bool {
34        self.value().eq(&other.value())
35    }
36}
37
38impl Display for Count {
39    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
40        write!(f, "{}", human_readable_count(self.value()))
41    }
42}
43
44impl Default for Count {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl Count {
51    /// create a new counter
52    pub fn new() -> Self {
53        Self {
54            value: Arc::new(AtomicUsize::new(0)),
55        }
56    }
57
58    /// Add `n` to the metric's value
59    pub fn add(&self, n: usize) {
60        // relaxed ordering for operations on `value` poses no issues
61        // we're purely using atomic ops with no associated memory ops
62        self.value.fetch_add(n, Ordering::Relaxed);
63    }
64
65    /// Get the current value
66    pub fn value(&self) -> usize {
67        self.value.load(Ordering::Relaxed)
68    }
69}
70
71/// A gauge is the simplest metrics type. It just returns a value.
72/// For example, you can easily expose current memory consumption with a gauge.
73///
74/// Note `clone`ing gauge update the same underlying metrics
75#[derive(Debug, Clone)]
76pub struct Gauge {
77    /// value of the metric gauge
78    value: Arc<AtomicUsize>,
79}
80
81impl PartialEq for Gauge {
82    fn eq(&self, other: &Self) -> bool {
83        self.value().eq(&other.value())
84    }
85}
86
87impl Display for Gauge {
88    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
89        write!(f, "{}", self.value())
90    }
91}
92
93impl Default for Gauge {
94    fn default() -> Self {
95        Self::new()
96    }
97}
98
99impl Gauge {
100    /// create a new gauge
101    pub fn new() -> Self {
102        Self {
103            value: Arc::new(AtomicUsize::new(0)),
104        }
105    }
106
107    /// Add `n` to the metric's value
108    pub fn add(&self, n: usize) {
109        // relaxed ordering for operations on `value` poses no issues
110        // we're purely using atomic ops with no associated memory ops
111        self.value.fetch_add(n, Ordering::Relaxed);
112    }
113
114    /// Sub `n` from the metric's value
115    pub fn sub(&self, n: usize) {
116        // relaxed ordering for operations on `value` poses no issues
117        // we're purely using atomic ops with no associated memory ops
118        self.value.fetch_sub(n, Ordering::Relaxed);
119    }
120
121    /// Set metric's value to maximum of `n` and current value
122    pub fn set_max(&self, n: usize) {
123        self.value.fetch_max(n, Ordering::Relaxed);
124    }
125
126    /// Set the metric's value to `n` and return the previous value
127    pub fn set(&self, n: usize) -> usize {
128        // relaxed ordering for operations on `value` poses no issues
129        // we're purely using atomic ops with no associated memory ops
130        self.value.swap(n, Ordering::Relaxed)
131    }
132
133    /// Get the current value
134    pub fn value(&self) -> usize {
135        self.value.load(Ordering::Relaxed)
136    }
137}
138
139/// Measure a potentially non contiguous duration of time
140#[derive(Debug, Clone)]
141pub struct Time {
142    /// elapsed time, in nanoseconds
143    nanos: Arc<AtomicUsize>,
144}
145
146impl Default for Time {
147    fn default() -> Self {
148        Self::new()
149    }
150}
151
152impl PartialEq for Time {
153    fn eq(&self, other: &Self) -> bool {
154        self.value().eq(&other.value())
155    }
156}
157
158impl Display for Time {
159    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
160        write!(f, "{}", human_readable_duration(self.value() as u64))
161    }
162}
163
164impl Time {
165    /// Create a new [`Time`] wrapper suitable for recording elapsed
166    /// times for operations.
167    pub fn new() -> Self {
168        Self {
169            nanos: Arc::new(AtomicUsize::new(0)),
170        }
171    }
172
173    /// Add elapsed nanoseconds since `start`to self
174    pub fn add_elapsed(&self, start: Instant) {
175        self.add_duration(start.elapsed());
176    }
177
178    /// Add duration of time to self
179    ///
180    /// Note: this will always increment the recorded time by at least 1 nanosecond
181    /// to distinguish between the scenario of no values recorded, in which
182    /// case the value will be 0, and no measurable amount of time having passed,
183    /// in which case the value will be small but not 0.
184    ///
185    /// This is based on the assumption that the timing logic in most cases is likely
186    /// to take at least a nanosecond, and so this is reasonable mechanism to avoid
187    /// ambiguity, especially on systems with low-resolution monotonic clocks
188    pub fn add_duration(&self, duration: Duration) {
189        let more_nanos = duration.as_nanos() as usize;
190        self.nanos.fetch_add(more_nanos.max(1), Ordering::Relaxed);
191    }
192
193    /// Adds a duration without rounding it up to one nanosecond.
194    ///
195    /// Use only for metrics that record many independent operations, where a
196    /// minimum per recording would materially inflate the total.
197    pub fn add_duration_exact(&self, duration: Duration) {
198        self.nanos
199            .fetch_add(duration.as_nanos() as usize, Ordering::Relaxed);
200    }
201
202    /// Add the number of nanoseconds of other `Time` to self
203    pub fn add(&self, other: &Time) {
204        self.add_duration(Duration::from_nanos(other.value() as u64))
205    }
206
207    /// return a scoped guard that adds the amount of time elapsed
208    /// between its creation and its drop or call to `stop` to the
209    /// underlying metric.
210    pub fn timer(&self) -> ScopedTimerGuard<'_> {
211        ScopedTimerGuard {
212            inner: self,
213            start: Some(Instant::now()),
214        }
215    }
216
217    /// Get the number of nanoseconds record by this Time metric
218    pub fn value(&self) -> usize {
219        self.nanos.load(Ordering::Relaxed)
220    }
221
222    /// Return a scoped guard that adds the amount of time elapsed between the
223    /// given instant and its drop (or the call to `stop`) to the underlying metric
224    pub fn timer_with(&self, now: Instant) -> ScopedTimerGuard<'_> {
225        ScopedTimerGuard {
226            inner: self,
227            start: Some(now),
228        }
229    }
230}
231
232/// Stores a single timestamp, stored as the number of nanoseconds
233/// elapsed from Jan 1, 1970 UTC
234#[derive(Debug, Clone)]
235pub struct Timestamp {
236    /// Time thing started
237    timestamp: Arc<Mutex<Option<DateTime<Utc>>>>,
238}
239
240impl Default for Timestamp {
241    fn default() -> Self {
242        Self::new()
243    }
244}
245
246impl Timestamp {
247    /// Create a new timestamp and sets its value to 0
248    pub fn new() -> Self {
249        Self {
250            timestamp: Arc::new(Mutex::new(None)),
251        }
252    }
253
254    /// Sets the timestamps value to the current time
255    pub fn record(&self) {
256        self.set(Utc::now())
257    }
258
259    /// Sets the timestamps value to a specified time
260    pub fn set(&self, now: DateTime<Utc>) {
261        *self.timestamp.lock() = Some(now);
262    }
263
264    /// return the timestamps value at the last time `record()` was
265    /// called.
266    ///
267    /// Returns `None` if `record()` has not been called
268    pub fn value(&self) -> Option<DateTime<Utc>> {
269        *self.timestamp.lock()
270    }
271
272    /// sets the value of this timestamp to the minimum of this and other
273    pub fn update_to_min(&self, other: &Timestamp) {
274        let min = match (self.value(), other.value()) {
275            (None, None) => None,
276            (Some(v), None) => Some(v),
277            (None, Some(v)) => Some(v),
278            (Some(v1), Some(v2)) => Some(if v1 < v2 { v1 } else { v2 }),
279        };
280
281        *self.timestamp.lock() = min;
282    }
283
284    /// sets the value of this timestamp to the maximum of this and other
285    pub fn update_to_max(&self, other: &Timestamp) {
286        let max = match (self.value(), other.value()) {
287            (None, None) => None,
288            (Some(v), None) => Some(v),
289            (None, Some(v)) => Some(v),
290            (Some(v1), Some(v2)) => Some(if v1 < v2 { v2 } else { v1 }),
291        };
292
293        *self.timestamp.lock() = max;
294    }
295}
296
297impl PartialEq for Timestamp {
298    fn eq(&self, other: &Self) -> bool {
299        self.value().eq(&other.value())
300    }
301}
302
303impl Display for Timestamp {
304    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
305        match self.value() {
306            None => write!(f, "NONE"),
307            Some(v) => {
308                write!(f, "{v}")
309            }
310        }
311    }
312}
313
314/// RAAI structure that adds all time between its construction and
315/// destruction to the CPU time or the first call to `stop` whichever
316/// comes first
317pub struct ScopedTimerGuard<'a> {
318    inner: &'a Time,
319    start: Option<Instant>,
320}
321
322impl ScopedTimerGuard<'_> {
323    /// Stop the timer timing and record the time taken
324    pub fn stop(&mut self) {
325        if let Some(start) = self.start.take() {
326            self.inner.add_elapsed(start)
327        }
328    }
329
330    /// Restarts the timer recording from the current time
331    pub fn restart(&mut self) {
332        self.start = Some(Instant::now())
333    }
334
335    /// Stop the timer, record the time taken and consume self
336    pub fn done(mut self) {
337        self.stop()
338    }
339
340    /// Stop the timer timing and record the time taken since the given endpoint.
341    pub fn stop_with(&mut self, end_time: Instant) {
342        if let Some(start) = self.start.take() {
343            let elapsed = end_time - start;
344            self.inner.add_duration(elapsed)
345        }
346    }
347
348    /// Stop the timer, record the time taken since `end_time` endpoint, and
349    /// consume self.
350    pub fn done_with(mut self, end_time: Instant) {
351        self.stop_with(end_time)
352    }
353}
354
355impl Drop for ScopedTimerGuard<'_> {
356    fn drop(&mut self) {
357        self.stop()
358    }
359}
360
361/// Counters tracking pruning metrics
362///
363/// For example, a file scanner initially is planned to scan 10 files, but skipped
364/// 8 of them using statistics, the pruning metrics would look like: 10 total -> 2 matched
365///
366/// Note `clone`ing update the same underlying metrics
367#[derive(Debug, Clone)]
368pub struct PruningMetrics {
369    pruned: Arc<AtomicUsize>,
370    matched: Arc<AtomicUsize>,
371    fully_matched: Arc<AtomicUsize>,
372}
373
374impl Display for PruningMetrics {
375    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
376        let matched = self.matched.load(Ordering::Relaxed);
377        let total = self.pruned.load(Ordering::Relaxed) + matched;
378        let fully_matched = self.fully_matched.load(Ordering::Relaxed);
379
380        if fully_matched != 0 {
381            write!(
382                f,
383                "{} total → {} matched -> {} fully matched",
384                human_readable_count(total),
385                human_readable_count(matched),
386                human_readable_count(fully_matched)
387            )
388        } else {
389            write!(
390                f,
391                "{} total → {} matched",
392                human_readable_count(total),
393                human_readable_count(matched)
394            )
395        }
396    }
397}
398
399impl Default for PruningMetrics {
400    fn default() -> Self {
401        Self::new()
402    }
403}
404
405impl PruningMetrics {
406    /// create a new PruningMetrics
407    pub fn new() -> Self {
408        Self {
409            pruned: Arc::new(AtomicUsize::new(0)),
410            matched: Arc::new(AtomicUsize::new(0)),
411            fully_matched: Arc::new(AtomicUsize::new(0)),
412        }
413    }
414
415    /// Add `n` to the metric's pruned value
416    pub fn add_pruned(&self, n: usize) {
417        // relaxed ordering for operations on `value` poses no issues
418        // we're purely using atomic ops with no associated memory ops
419        self.pruned.fetch_add(n, Ordering::Relaxed);
420    }
421
422    /// Add `n` to the metric's matched value
423    pub fn add_matched(&self, n: usize) {
424        // relaxed ordering for operations on `value` poses no issues
425        // we're purely using atomic ops with no associated memory ops
426        self.matched.fetch_add(n, Ordering::Relaxed);
427    }
428
429    /// Add `n` to the metric's fully matched value
430    pub fn add_fully_matched(&self, n: usize) {
431        // relaxed ordering for operations on `value` poses no issues
432        // we're purely using atomic ops with no associated memory ops
433        self.fully_matched.fetch_add(n, Ordering::Relaxed);
434    }
435
436    /// Subtract `n` to the metric's matched value.
437    pub fn subtract_matched(&self, n: usize) {
438        // relaxed ordering for operations on `value` poses no issues
439        // we're purely using atomic ops with no associated memory ops
440        self.matched.fetch_sub(n, Ordering::Relaxed);
441    }
442
443    /// Number of items pruned
444    pub fn pruned(&self) -> usize {
445        self.pruned.load(Ordering::Relaxed)
446    }
447
448    /// Number of items matched (not pruned)
449    pub fn matched(&self) -> usize {
450        self.matched.load(Ordering::Relaxed)
451    }
452
453    /// Number of items fully matched
454    pub fn fully_matched(&self) -> usize {
455        self.fully_matched.load(Ordering::Relaxed)
456    }
457}
458
459/// Counters tracking ratio metrics (e.g. matched vs total)
460///
461/// The counters are thread-safe and shared across clones.
462#[derive(Debug, Clone, Default)]
463pub struct RatioMetrics {
464    part: Arc<AtomicUsize>,
465    total: Arc<AtomicUsize>,
466    merge_strategy: RatioMergeStrategy,
467    /// Ratios are displayed as `1% (1/100)`; this controls the latter part.
468    display_raw_values: bool,
469}
470
471#[derive(Debug, Clone, Default)]
472pub enum RatioMergeStrategy {
473    #[default]
474    AddPartAddTotal,
475    AddPartSetTotal,
476    SetPartAddTotal,
477}
478
479impl RatioMetrics {
480    /// Create a new [`RatioMetrics`]
481    pub fn new() -> Self {
482        Self {
483            part: Arc::new(AtomicUsize::new(0)),
484            total: Arc::new(AtomicUsize::new(0)),
485            merge_strategy: RatioMergeStrategy::AddPartAddTotal,
486            display_raw_values: true,
487        }
488    }
489
490    pub fn with_merge_strategy(mut self, merge_strategy: RatioMergeStrategy) -> Self {
491        self.merge_strategy = merge_strategy;
492        self
493    }
494
495    pub fn with_display_raw_values(mut self, display_raw_values: bool) -> Self {
496        self.display_raw_values = display_raw_values;
497        self
498    }
499
500    /// Add `n` to the numerator (`part`) value
501    pub fn add_part(&self, n: usize) {
502        self.part.fetch_add(n, Ordering::Relaxed);
503    }
504
505    /// Add `n` to the denominator (`total`) value
506    pub fn add_total(&self, n: usize) {
507        self.total.fetch_add(n, Ordering::Relaxed);
508    }
509
510    /// Set the numerator (`part`) value to `n`, overwriting any existing value
511    pub fn set_part(&self, n: usize) {
512        self.part.store(n, Ordering::Relaxed);
513    }
514
515    /// Set the denominator (`total`) value to `n`, overwriting any existing value
516    pub fn set_total(&self, n: usize) {
517        self.total.store(n, Ordering::Relaxed);
518    }
519
520    /// Merge the value from `other` into `self`
521    pub fn merge(&self, other: &Self) {
522        match self.merge_strategy {
523            RatioMergeStrategy::AddPartAddTotal => {
524                self.add_part(other.part());
525                self.add_total(other.total());
526            }
527            RatioMergeStrategy::AddPartSetTotal => {
528                self.add_part(other.part());
529                self.set_total(other.total());
530            }
531            RatioMergeStrategy::SetPartAddTotal => {
532                self.set_part(other.part());
533                self.add_total(other.total());
534            }
535        }
536    }
537
538    /// Return the numerator (`part`) value
539    pub fn part(&self) -> usize {
540        self.part.load(Ordering::Relaxed)
541    }
542
543    /// Return the denominator (`total`) value
544    pub fn total(&self) -> usize {
545        self.total.load(Ordering::Relaxed)
546    }
547
548    /// Return the strategy used to merge two [`RatioMetrics`] values
549    pub fn merge_strategy(&self) -> &RatioMergeStrategy {
550        &self.merge_strategy
551    }
552
553    /// Whether `Display` for this metric appends the raw `(part/total)` numbers
554    /// alongside the percentage
555    pub fn display_raw_values(&self) -> bool {
556        self.display_raw_values
557    }
558}
559
560impl PartialEq for RatioMetrics {
561    fn eq(&self, other: &Self) -> bool {
562        self.part() == other.part()
563            && self.total() == other.total()
564            && self.display_raw_values == other.display_raw_values
565    }
566}
567
568impl Display for RatioMetrics {
569    /// Format the ratio to a format like '18.26% (220/1150)'
570    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
571        let part = self.part();
572        let total = self.total();
573
574        // Format the ratio first (for example, `6667/10000` -> `66.67%`),
575        // then optionally append the raw values as ` (6.67 K/10.00 K)`.
576        if total == 0 {
577            write!(f, "N/A")?;
578        } else {
579            // Use basis points so we can round with integer math:
580            // e.g. 18.26% has basis point 1826
581            let basis_points = (((part as u128 * 10_000) + (total as u128 / 2))
582                / total as u128) as usize;
583            let whole = basis_points / 100;
584            let fractional = basis_points % 100;
585
586            if fractional == 0 {
587                write!(f, "{whole}%")?;
588            } else if fractional.is_multiple_of(10) {
589                write!(f, "{whole}.{}%", fractional / 10)?;
590            } else {
591                write!(f, "{whole}.{fractional:02}%")?;
592            }
593        }
594
595        if !self.display_raw_values {
596            return Ok(());
597        }
598
599        if total == 0 {
600            if part == 0 {
601                write!(f, " (0/0)")
602            } else {
603                write!(f, " ({}/0)", human_readable_count(part))
604            }
605        } else {
606            write!(
607                f,
608                " ({}/{})",
609                human_readable_count(part),
610                human_readable_count(total)
611            )
612        }
613    }
614}
615
616/// Possible values for a [super::Metric].
617///
618/// Among other differences, the metric types have different ways to
619/// logically interpret their underlying values and some metrics are
620/// so common they are given special treatment.
621#[derive(Debug, Clone)]
622pub enum MetricValue {
623    /// Number of output rows produced: "output_rows" metric
624    OutputRows(Count),
625    /// Elapsed Compute Time: the wall clock time spent in "cpu
626    /// intensive" work.
627    ///
628    /// This measurement represents, roughly:
629    /// ```
630    /// use std::time::Instant;
631    /// let start = Instant::now();
632    /// // ...CPU intensive work here...
633    /// let elapsed_compute = (Instant::now() - start).as_nanos();
634    /// ```
635    ///
636    /// Note 1: Does *not* include time other operators spend
637    /// computing input.
638    ///
639    /// Note 2: *Does* includes time when the thread could have made
640    /// progress but the OS did not schedule it (e.g. due to CPU
641    /// contention), thus making this value different than the
642    /// classical definition of "cpu_time", which is the time reported
643    /// from `clock_gettime(CLOCK_THREAD_CPUTIME_ID, ..)`.
644    ElapsedCompute(Time),
645    /// Number of spills produced: "spill_count" metric
646    SpillCount(Count),
647    /// Total size of spilled bytes produced: "spilled_bytes" metric
648    SpilledBytes(Count),
649    /// Total size of output bytes produced: "output_bytes" metric
650    OutputBytes(Count),
651    /// Total number of output batches produced: "output_batches" metric
652    OutputBatches(Count),
653    /// Total size of spilled rows produced: "spilled_rows" metric
654    SpilledRows(Count),
655    /// Current memory used
656    CurrentMemoryUsage(Gauge),
657    /// Operator defined count.
658    Count {
659        /// The provided name of this metric
660        name: Cow<'static, str>,
661        /// The value of the metric
662        count: Count,
663    },
664    /// Operator defined gauge.
665    Gauge {
666        /// The provided name of this metric
667        name: Cow<'static, str>,
668        /// The value of the metric
669        gauge: Gauge,
670    },
671    /// Operator defined peak memory usage in bytes.
672    PeakMemoryUsage {
673        /// The provided name of this metric
674        name: Cow<'static, str>,
675        /// The value of the metric
676        gauge: Gauge,
677    },
678    /// Operator defined time
679    Time {
680        /// The provided name of this metric
681        name: Cow<'static, str>,
682        /// The value of the metric
683        time: Time,
684    },
685    /// The time at which execution started
686    StartTimestamp(Timestamp),
687    /// The time at which execution ended
688    EndTimestamp(Timestamp),
689    /// Metrics related to scan pruning
690    PruningMetrics {
691        name: Cow<'static, str>,
692        pruning_metrics: PruningMetrics,
693    },
694    /// Metrics that should be displayed as ratio like (42%)
695    Ratio {
696        name: Cow<'static, str>,
697        ratio_metrics: RatioMetrics,
698    },
699    Custom {
700        /// The provided name of this metric
701        name: Cow<'static, str>,
702        /// A custom implementation of the metric value.
703        value: Arc<dyn CustomMetricValue>,
704    },
705}
706
707// Manually implement PartialEq for `MetricValue` because it contains CustomMetricValue in its
708// definition which is a dyn trait. This wouldn't allow us to just derive PartialEq.
709impl PartialEq for MetricValue {
710    fn eq(&self, other: &Self) -> bool {
711        match (self, other) {
712            (MetricValue::OutputRows(count), MetricValue::OutputRows(other)) => {
713                count == other
714            }
715            (MetricValue::ElapsedCompute(time), MetricValue::ElapsedCompute(other)) => {
716                time == other
717            }
718            (MetricValue::SpillCount(count), MetricValue::SpillCount(other)) => {
719                count == other
720            }
721            (MetricValue::SpilledBytes(count), MetricValue::SpilledBytes(other)) => {
722                count == other
723            }
724            (MetricValue::OutputBytes(count), MetricValue::OutputBytes(other)) => {
725                count == other
726            }
727            (MetricValue::OutputBatches(count), MetricValue::OutputBatches(other)) => {
728                count == other
729            }
730            (MetricValue::SpilledRows(count), MetricValue::SpilledRows(other)) => {
731                count == other
732            }
733            (
734                MetricValue::CurrentMemoryUsage(gauge),
735                MetricValue::CurrentMemoryUsage(other),
736            ) => gauge == other,
737            (
738                MetricValue::Count { name, count },
739                MetricValue::Count {
740                    name: other_name,
741                    count: other_count,
742                },
743            ) => name == other_name && count == other_count,
744            (
745                MetricValue::Gauge { name, gauge },
746                MetricValue::Gauge {
747                    name: other_name,
748                    gauge: other_gauge,
749                },
750            )
751            | (
752                MetricValue::PeakMemoryUsage { name, gauge },
753                MetricValue::PeakMemoryUsage {
754                    name: other_name,
755                    gauge: other_gauge,
756                },
757            ) => name == other_name && gauge == other_gauge,
758            (
759                MetricValue::Time { name, time },
760                MetricValue::Time {
761                    name: other_name,
762                    time: other_time,
763                },
764            ) => name == other_name && time == other_time,
765
766            (
767                MetricValue::StartTimestamp(timestamp),
768                MetricValue::StartTimestamp(other),
769            ) => timestamp == other,
770            (MetricValue::EndTimestamp(timestamp), MetricValue::EndTimestamp(other)) => {
771                timestamp == other
772            }
773            (
774                MetricValue::PruningMetrics {
775                    name,
776                    pruning_metrics,
777                },
778                MetricValue::PruningMetrics {
779                    name: other_name,
780                    pruning_metrics: other_pruning_metrics,
781                },
782            ) => {
783                name == other_name
784                    && pruning_metrics.pruned() == other_pruning_metrics.pruned()
785                    && pruning_metrics.matched() == other_pruning_metrics.matched()
786            }
787            (
788                MetricValue::Ratio {
789                    name,
790                    ratio_metrics,
791                },
792                MetricValue::Ratio {
793                    name: other_name,
794                    ratio_metrics: other_ratio_metrics,
795                },
796            ) => name == other_name && ratio_metrics == other_ratio_metrics,
797            (
798                MetricValue::Custom { name, value },
799                MetricValue::Custom {
800                    name: other_name,
801                    value: other_value,
802                },
803            ) => name == other_name && value.is_eq(other_value),
804            // Default case when the two sides do not have the same type.
805            _ => false,
806        }
807    }
808}
809
810impl MetricValue {
811    /// Return the name of this SQL metric
812    pub fn name(&self) -> &str {
813        match self {
814            Self::OutputRows(_) => "output_rows",
815            Self::SpillCount(_) => "spill_count",
816            Self::SpilledBytes(_) => "spilled_bytes",
817            Self::OutputBytes(_) => "output_bytes",
818            Self::OutputBatches(_) => "output_batches",
819            Self::SpilledRows(_) => "spilled_rows",
820            Self::CurrentMemoryUsage(_) => "mem_used",
821            Self::ElapsedCompute(_) => "elapsed_compute",
822            Self::Count { name, .. } => name.borrow(),
823            Self::Gauge { name, .. } | Self::PeakMemoryUsage { name, .. } => {
824                name.borrow()
825            }
826            Self::Time { name, .. } => name.borrow(),
827            Self::StartTimestamp(_) => "start_timestamp",
828            Self::EndTimestamp(_) => "end_timestamp",
829            Self::PruningMetrics { name, .. } => name.borrow(),
830            Self::Ratio { name, .. } => name.borrow(),
831            Self::Custom { name, .. } => name.borrow(),
832        }
833    }
834
835    /// Return the value of the metric as a usize value, used to aggregate metric
836    /// value across partitions.
837    pub fn as_usize(&self) -> usize {
838        match self {
839            Self::OutputRows(count) => count.value(),
840            Self::SpillCount(count) => count.value(),
841            Self::SpilledBytes(bytes) => bytes.value(),
842            Self::OutputBytes(bytes) => bytes.value(),
843            Self::OutputBatches(count) => count.value(),
844            Self::SpilledRows(count) => count.value(),
845            Self::CurrentMemoryUsage(used) => used.value(),
846            Self::ElapsedCompute(time) => time.value(),
847            Self::Count { count, .. } => count.value(),
848            Self::Gauge { gauge, .. } | Self::PeakMemoryUsage { gauge, .. } => {
849                gauge.value()
850            }
851            Self::Time { time, .. } => time.value(),
852            Self::StartTimestamp(timestamp) => timestamp
853                .value()
854                .and_then(|ts| ts.timestamp_nanos_opt())
855                .map(|nanos| nanos as usize)
856                .unwrap_or(0),
857            Self::EndTimestamp(timestamp) => timestamp
858                .value()
859                .and_then(|ts| ts.timestamp_nanos_opt())
860                .map(|nanos| nanos as usize)
861                .unwrap_or(0),
862            // This function is a utility for aggregating metrics, for complex metric
863            // like `PruningMetrics`, this function is not supposed to get called.
864            // Metrics aggregation for them are implemented inside `MetricsSet` directly.
865            Self::PruningMetrics { .. } => 0,
866            // Should not be used. See comments in `PruningMetrics` for details.
867            Self::Ratio { .. } => 0,
868            Self::Custom { value, .. } => value.as_usize(),
869        }
870    }
871
872    /// create a new MetricValue with the same type as `self` suitable
873    /// for accumulating
874    pub fn new_empty(&self) -> Self {
875        match self {
876            Self::OutputRows(_) => Self::OutputRows(Count::new()),
877            Self::SpillCount(_) => Self::SpillCount(Count::new()),
878            Self::SpilledBytes(_) => Self::SpilledBytes(Count::new()),
879            Self::OutputBytes(_) => Self::OutputBytes(Count::new()),
880            Self::OutputBatches(_) => Self::OutputBatches(Count::new()),
881            Self::SpilledRows(_) => Self::SpilledRows(Count::new()),
882            Self::CurrentMemoryUsage(_) => Self::CurrentMemoryUsage(Gauge::new()),
883            Self::ElapsedCompute(_) => Self::ElapsedCompute(Time::new()),
884            Self::Count { name, .. } => Self::Count {
885                name: name.clone(),
886                count: Count::new(),
887            },
888            Self::Gauge { name, .. } => Self::Gauge {
889                name: name.clone(),
890                gauge: Gauge::new(),
891            },
892            Self::PeakMemoryUsage { name, .. } => Self::PeakMemoryUsage {
893                name: name.clone(),
894                gauge: Gauge::new(),
895            },
896            Self::Time { name, .. } => Self::Time {
897                name: name.clone(),
898                time: Time::new(),
899            },
900            Self::StartTimestamp(_) => Self::StartTimestamp(Timestamp::new()),
901            Self::EndTimestamp(_) => Self::EndTimestamp(Timestamp::new()),
902            Self::PruningMetrics { name, .. } => Self::PruningMetrics {
903                name: name.clone(),
904                pruning_metrics: PruningMetrics::new(),
905            },
906            Self::Ratio {
907                name,
908                ratio_metrics,
909            } => {
910                let merge_strategy = ratio_metrics.merge_strategy.clone();
911                Self::Ratio {
912                    name: name.clone(),
913                    ratio_metrics: RatioMetrics::new()
914                        .with_merge_strategy(merge_strategy)
915                        .with_display_raw_values(ratio_metrics.display_raw_values),
916                }
917            }
918            Self::Custom { name, value } => Self::Custom {
919                name: name.clone(),
920                value: value.new_empty(),
921            },
922        }
923    }
924
925    /// Aggregates the value of other to `self`. panic's if the types
926    /// are mismatched or aggregating does not make sense for this
927    /// value
928    ///
929    /// Note this is purposely marked `mut` (even though atomics are
930    /// used) so Rust's type system can be used to ensure the
931    /// appropriate API access. `MetricValues` should be modified
932    /// using the original [`Count`] or [`Time`] they were created
933    /// from.
934    pub fn aggregate(&mut self, other: &Self) {
935        match (self, other) {
936            (Self::OutputRows(count), Self::OutputRows(other_count))
937            | (Self::SpillCount(count), Self::SpillCount(other_count))
938            | (Self::SpilledBytes(count), Self::SpilledBytes(other_count))
939            | (Self::OutputBytes(count), Self::OutputBytes(other_count))
940            | (Self::OutputBatches(count), Self::OutputBatches(other_count))
941            | (Self::SpilledRows(count), Self::SpilledRows(other_count))
942            | (
943                Self::Count { count, .. },
944                Self::Count {
945                    count: other_count, ..
946                },
947            ) => count.add(other_count.value()),
948            (Self::CurrentMemoryUsage(gauge), Self::CurrentMemoryUsage(other_gauge))
949            | (
950                Self::Gauge { gauge, .. },
951                Self::Gauge {
952                    gauge: other_gauge, ..
953                },
954            )
955            | (
956                Self::PeakMemoryUsage { gauge, .. },
957                Self::PeakMemoryUsage {
958                    gauge: other_gauge, ..
959                },
960            ) => gauge.add(other_gauge.value()),
961            (Self::ElapsedCompute(time), Self::ElapsedCompute(other_time))
962            | (
963                Self::Time { time, .. },
964                Self::Time {
965                    time: other_time, ..
966                },
967            ) => time.add(other_time),
968            // timestamps are aggregated by min/max
969            (Self::StartTimestamp(timestamp), Self::StartTimestamp(other_timestamp)) => {
970                timestamp.update_to_min(other_timestamp);
971            }
972            // timestamps are aggregated by min/max
973            (Self::EndTimestamp(timestamp), Self::EndTimestamp(other_timestamp)) => {
974                timestamp.update_to_max(other_timestamp);
975            }
976            (
977                Self::PruningMetrics {
978                    pruning_metrics, ..
979                },
980                Self::PruningMetrics {
981                    pruning_metrics: other_pruning_metrics,
982                    ..
983                },
984            ) => {
985                let pruned = other_pruning_metrics.pruned.load(Ordering::Relaxed);
986                let matched = other_pruning_metrics.matched.load(Ordering::Relaxed);
987                let fully_matched =
988                    other_pruning_metrics.fully_matched.load(Ordering::Relaxed);
989                pruning_metrics.add_pruned(pruned);
990                pruning_metrics.add_matched(matched);
991                pruning_metrics.add_fully_matched(fully_matched);
992            }
993            (
994                Self::Ratio { ratio_metrics, .. },
995                Self::Ratio {
996                    ratio_metrics: other_ratio_metrics,
997                    ..
998                },
999            ) => {
1000                ratio_metrics.merge(other_ratio_metrics);
1001            }
1002            (
1003                Self::Custom { value, .. },
1004                Self::Custom {
1005                    value: other_value, ..
1006                },
1007            ) => {
1008                value.aggregate(Arc::clone(other_value));
1009            }
1010            m @ (_, _) => {
1011                panic!(
1012                    "Mismatched metric types. Can not aggregate {:?} with value {:?}",
1013                    m.0, m.1
1014                )
1015            }
1016        }
1017    }
1018
1019    /// Returns a number by which to sort metrics by display. Lower
1020    /// numbers are "more useful" (and displayed first)
1021    pub fn display_sort_key(&self) -> u8 {
1022        match self {
1023            // `BaselineMetrics` that is common for most operators
1024            Self::OutputRows(_) => 0,
1025            Self::ElapsedCompute(_) => 1,
1026            Self::OutputBytes(_) => 2,
1027            Self::OutputBatches(_) => 3,
1028            // Other metrics
1029            Self::PruningMetrics { name, .. } => match name.as_ref() {
1030                // The following metrics belong to `DataSourceExec` with a Parquet data source.
1031                // They are displayed in a specific order that reflects the actual pruning process,
1032                // from coarse-grained to fine-grained pruning levels.
1033                //
1034                // You may update these metrics as long as their relative order remains unchanged.
1035                //
1036                // Reference PR: <https://github.com/apache/datafusion/pull/18379>
1037                "files_ranges_pruned_statistics" => 4,
1038                "row_groups_pruned_statistics" => 5,
1039                "row_groups_pruned_bloom_filter" => 6,
1040                "page_index_pages_pruned" => 7,
1041                "page_index_rows_pruned" => 8,
1042                _ => 9,
1043            },
1044            Self::SpillCount(_) => 10,
1045            Self::SpilledBytes(_) => 11,
1046            Self::SpilledRows(_) => 12,
1047            Self::CurrentMemoryUsage(_) => 13,
1048            Self::Count { name, .. } => match name.as_ref() {
1049                // Keep lazy Parquet pruning counters grouped with the other
1050                // page-index pruning metrics in EXPLAIN output.
1051                "page_index_pages_skipped_by_fully_matched" | "limit_pruned_rows" => 8,
1052                _ => 14,
1053            },
1054            Self::PeakMemoryUsage { .. } => 13,
1055            Self::Gauge { .. } => 15,
1056            Self::Time { .. } => 16,
1057            Self::Ratio { .. } => 17,
1058            Self::StartTimestamp(_) => 18, // show timestamps last
1059            Self::EndTimestamp(_) => 19,
1060            Self::Custom { .. } => 20,
1061        }
1062    }
1063
1064    /// returns true if this metric has a timestamp value
1065    pub fn is_timestamp(&self) -> bool {
1066        matches!(self, Self::StartTimestamp(_) | Self::EndTimestamp(_))
1067    }
1068}
1069
1070impl Display for MetricValue {
1071    /// Prints the value of this metric
1072    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1073        match self {
1074            Self::OutputRows(count)
1075            | Self::OutputBatches(count)
1076            | Self::SpillCount(count)
1077            | Self::SpilledRows(count)
1078            | Self::Count { count, .. } => {
1079                write!(f, "{count}")
1080            }
1081            Self::SpilledBytes(count) | Self::OutputBytes(count) => {
1082                let readable_count = human_readable_size(count.value());
1083                write!(f, "{readable_count}")
1084            }
1085            Self::CurrentMemoryUsage(gauge) => {
1086                // CurrentMemoryUsage is in bytes, format like SpilledBytes
1087                let readable_size = human_readable_size(gauge.value());
1088                write!(f, "{readable_size}")
1089            }
1090            Self::PeakMemoryUsage { gauge, .. } => {
1091                let readable_size = human_readable_size(gauge.value());
1092                write!(f, "{readable_size}")
1093            }
1094            Self::Gauge { gauge, .. } => {
1095                // Generic gauge metrics - format with human-readable count
1096                write!(f, "{}", human_readable_count(gauge.value()))
1097            }
1098            Self::ElapsedCompute(time) | Self::Time { time, .. } => {
1099                // distinguish between no time recorded and very small
1100                // amount of time recorded
1101                if time.value() > 0 {
1102                    write!(f, "{time}")
1103                } else {
1104                    write!(f, "NOT RECORDED")
1105                }
1106            }
1107            Self::StartTimestamp(timestamp) | Self::EndTimestamp(timestamp) => {
1108                write!(f, "{timestamp}")
1109            }
1110            Self::PruningMetrics {
1111                pruning_metrics, ..
1112            } => {
1113                write!(f, "{pruning_metrics}")
1114            }
1115            Self::Ratio { ratio_metrics, .. } => write!(f, "{ratio_metrics}"),
1116            Self::Custom { value, .. } => {
1117                write!(f, "{value}")
1118            }
1119        }
1120    }
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use std::any::Any;
1126
1127    use chrono::TimeZone;
1128    use datafusion_common::units::MB;
1129
1130    use super::*;
1131
1132    #[derive(Debug, Default)]
1133    pub struct CustomCounter {
1134        count: AtomicUsize,
1135    }
1136
1137    impl Display for CustomCounter {
1138        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1139            write!(f, "count: {}", self.count.load(Ordering::Relaxed))
1140        }
1141    }
1142
1143    impl CustomMetricValue for CustomCounter {
1144        fn new_empty(&self) -> Arc<dyn CustomMetricValue> {
1145            Arc::new(CustomCounter::default())
1146        }
1147
1148        fn aggregate(&self, other: Arc<dyn CustomMetricValue + 'static>) {
1149            let other = other.as_any().downcast_ref::<Self>().unwrap();
1150            self.count
1151                .fetch_add(other.count.load(Ordering::Relaxed), Ordering::Relaxed);
1152        }
1153
1154        fn as_any(&self) -> &dyn Any {
1155            self
1156        }
1157
1158        fn is_eq(&self, other: &Arc<dyn CustomMetricValue>) -> bool {
1159            let Some(other) = other.as_any().downcast_ref::<Self>() else {
1160                return false;
1161            };
1162
1163            self.count.load(Ordering::Relaxed) == other.count.load(Ordering::Relaxed)
1164        }
1165    }
1166
1167    fn new_custom_counter(name: &'static str, value: usize) -> MetricValue {
1168        let custom_counter = CustomCounter::default();
1169        custom_counter.count.fetch_add(value, Ordering::Relaxed);
1170
1171        MetricValue::Custom {
1172            name: Cow::Borrowed(name),
1173            value: Arc::new(custom_counter),
1174        }
1175    }
1176
1177    #[test]
1178    fn test_custom_metric_with_mismatching_names() {
1179        let mut custom_val = new_custom_counter("Hi", 1);
1180        let other_custom_val = new_custom_counter("Hello", 1);
1181
1182        // Not equal since the name differs.
1183        assert_ne!(other_custom_val, custom_val);
1184
1185        // Should work even though the name differs
1186        custom_val.aggregate(&other_custom_val);
1187
1188        let expected_val = new_custom_counter("Hi", 2);
1189        assert_eq!(expected_val, custom_val);
1190    }
1191
1192    #[test]
1193    fn test_custom_metric() {
1194        let mut custom_val = new_custom_counter("hi", 11);
1195        let other_custom_val = new_custom_counter("hi", 20);
1196
1197        custom_val.aggregate(&other_custom_val);
1198
1199        assert_ne!(custom_val, other_custom_val);
1200
1201        if let MetricValue::Custom { value, .. } = custom_val {
1202            let counter = value
1203                .as_any()
1204                .downcast_ref::<CustomCounter>()
1205                .expect("Expected CustomCounter");
1206            assert_eq!(counter.count.load(Ordering::Relaxed), 31);
1207        } else {
1208            panic!("Unexpected value");
1209        }
1210    }
1211
1212    #[test]
1213    fn test_display_custom_metric() {
1214        let custom_val = new_custom_counter("hi", 11);
1215        assert_eq!(custom_val.to_string(), "count: 11");
1216    }
1217
1218    #[test]
1219    fn test_display_output_rows() {
1220        let count = Count::new();
1221        let values = vec![
1222            MetricValue::OutputRows(count.clone()),
1223            MetricValue::Count {
1224                name: "my_counter".into(),
1225                count: count.clone(),
1226            },
1227        ];
1228
1229        for value in &values {
1230            assert_eq!("0", value.to_string(), "value {value:?}");
1231        }
1232
1233        count.add(42);
1234        for value in &values {
1235            assert_eq!("42", value.to_string(), "value {value:?}");
1236        }
1237    }
1238
1239    #[test]
1240    fn test_display_spilled_bytes() {
1241        let count = Count::new();
1242        let spilled_byte = MetricValue::SpilledBytes(count.clone());
1243
1244        assert_eq!("0.0 B", spilled_byte.to_string());
1245
1246        count.add((100 * MB) as usize);
1247        assert_eq!("100.0 MB", spilled_byte.to_string());
1248
1249        count.add((0.5 * MB as f64) as usize);
1250        assert_eq!("100.5 MB", spilled_byte.to_string());
1251    }
1252
1253    #[test]
1254    fn test_display_time() {
1255        let time = Time::new();
1256        let values = vec![
1257            MetricValue::ElapsedCompute(time.clone()),
1258            MetricValue::Time {
1259                name: "my_time".into(),
1260                time: time.clone(),
1261            },
1262        ];
1263
1264        // if time is not set, it should not be reported as zero
1265        for value in &values {
1266            assert_eq!("NOT RECORDED", value.to_string(), "value {value:?}");
1267        }
1268
1269        time.add_duration(Duration::from_nanos(1042));
1270        for value in &values {
1271            assert_eq!("1.04µs", value.to_string(), "value {value:?}");
1272        }
1273    }
1274
1275    #[test]
1276    fn test_time_merge_marks_a_zero_duration_measurement_as_recorded() {
1277        let merged = Time::new();
1278        merged.add(&Time::new());
1279
1280        assert_eq!(merged.value(), 1);
1281    }
1282
1283    #[test]
1284    fn test_display_ratio() {
1285        let ratio_metrics = RatioMetrics::new();
1286        let ratio = MetricValue::Ratio {
1287            name: Cow::Borrowed("ratio_metric"),
1288            ratio_metrics: ratio_metrics.clone(),
1289        };
1290
1291        assert_eq!("N/A (0/0)", ratio.to_string());
1292
1293        ratio_metrics.add_part(10);
1294        assert_eq!("N/A (10/0)", ratio.to_string());
1295
1296        ratio_metrics.add_total(40);
1297        assert_eq!("25% (10/40)", ratio.to_string());
1298
1299        let tiny_ratio_metrics = RatioMetrics::new();
1300        let tiny_ratio = MetricValue::Ratio {
1301            name: Cow::Borrowed("tiny_ratio_metric"),
1302            ratio_metrics: tiny_ratio_metrics.clone(),
1303        };
1304        tiny_ratio_metrics.add_part(1);
1305        tiny_ratio_metrics.add_total(3000);
1306        assert_eq!("0.03% (1/3.00 K)", tiny_ratio.to_string());
1307
1308        ratio_metrics.set_part(6667);
1309        ratio_metrics.set_total(10_000);
1310        assert_eq!("66.67% (6.67 K/10.00 K)", ratio.to_string());
1311
1312        let percentage_only = RatioMetrics::new().with_display_raw_values(false);
1313        let ratio = MetricValue::Ratio {
1314            name: Cow::Borrowed("percentage_only"),
1315            ratio_metrics: percentage_only.clone(),
1316        };
1317        assert_eq!("N/A", ratio.to_string());
1318        percentage_only.set_part(6667);
1319        percentage_only.set_total(10_000);
1320        assert_eq!("66.67%", ratio.to_string());
1321    }
1322
1323    #[test]
1324    fn test_ratio_set_methods() {
1325        let ratio_metrics = RatioMetrics::new();
1326
1327        // Ensure set methods don't increment
1328        ratio_metrics.set_part(10);
1329        ratio_metrics.set_part(10);
1330        ratio_metrics.set_total(40);
1331        ratio_metrics.set_total(40);
1332        assert_eq!("25% (10/40)", ratio_metrics.to_string());
1333
1334        let ratio_metrics = RatioMetrics::new();
1335
1336        // Calling set should change the value
1337        ratio_metrics.set_part(10);
1338        ratio_metrics.set_part(30);
1339        ratio_metrics.set_total(40);
1340        ratio_metrics.set_total(50);
1341        assert_eq!("60% (30/50)", ratio_metrics.to_string());
1342    }
1343
1344    #[test]
1345    fn test_ratio_merge_strategy() {
1346        // Test AddPartSetTotal strategy
1347        let ratio_metrics1 =
1348            RatioMetrics::new().with_merge_strategy(RatioMergeStrategy::AddPartSetTotal);
1349
1350        ratio_metrics1.set_part(10);
1351        ratio_metrics1.set_total(40);
1352        assert_eq!("25% (10/40)", ratio_metrics1.to_string());
1353        let ratio_metrics2 =
1354            RatioMetrics::new().with_merge_strategy(RatioMergeStrategy::AddPartSetTotal);
1355        ratio_metrics2.set_part(20);
1356        ratio_metrics2.set_total(40);
1357        assert_eq!("50% (20/40)", ratio_metrics2.to_string());
1358
1359        ratio_metrics1.merge(&ratio_metrics2);
1360        assert_eq!("75% (30/40)", ratio_metrics1.to_string());
1361
1362        // Test SetPartAddTotal strategy
1363        let ratio_metrics1 =
1364            RatioMetrics::new().with_merge_strategy(RatioMergeStrategy::SetPartAddTotal);
1365        ratio_metrics1.set_part(20);
1366        ratio_metrics1.set_total(50);
1367        let ratio_metrics2 = RatioMetrics::new();
1368        ratio_metrics2.set_part(20);
1369        ratio_metrics2.set_total(50);
1370        ratio_metrics1.merge(&ratio_metrics2);
1371        assert_eq!("20% (20/100)", ratio_metrics1.to_string());
1372
1373        // Test AddPartAddTotal strategy (default)
1374        let ratio_metrics1 = RatioMetrics::new();
1375        ratio_metrics1.set_part(20);
1376        ratio_metrics1.set_total(50);
1377        let ratio_metrics2 = RatioMetrics::new();
1378        ratio_metrics2.set_part(20);
1379        ratio_metrics2.set_total(50);
1380        ratio_metrics1.merge(&ratio_metrics2);
1381        assert_eq!("40% (40/100)", ratio_metrics1.to_string());
1382    }
1383
1384    #[test]
1385    fn test_display_timestamp() {
1386        let timestamp = Timestamp::new();
1387        let values = vec![
1388            MetricValue::StartTimestamp(timestamp.clone()),
1389            MetricValue::EndTimestamp(timestamp.clone()),
1390        ];
1391
1392        // if time is not set, it should not be reported as zero
1393        for value in &values {
1394            assert_eq!("NONE", value.to_string(), "value {value:?}");
1395        }
1396
1397        timestamp.set(Utc.timestamp_nanos(1431648000000000));
1398        for value in &values {
1399            assert_eq!(
1400                "1970-01-17 13:40:48 UTC",
1401                value.to_string(),
1402                "value {value:?}"
1403            );
1404        }
1405    }
1406
1407    #[test]
1408    fn test_timer_with_custom_instant() {
1409        let time = Time::new();
1410        let start_time = Instant::now();
1411
1412        // Sleep a bit to ensure some time passes
1413        std::thread::sleep(Duration::from_millis(1));
1414
1415        // Create timer with the earlier start time
1416        let mut timer = time.timer_with(start_time);
1417
1418        // Sleep a bit more
1419        std::thread::sleep(Duration::from_millis(1));
1420
1421        // Stop the timer
1422        timer.stop();
1423
1424        // The recorded time should be at least 20ms (both sleeps)
1425        assert!(
1426            time.value() >= 2_000_000,
1427            "Expected at least 2ms, got {} ns",
1428            time.value()
1429        );
1430    }
1431
1432    #[test]
1433    fn test_stop_with_custom_endpoint() {
1434        let time = Time::new();
1435        let start = Instant::now();
1436        let mut timer = time.timer_with(start);
1437
1438        // Simulate exactly 10ms passing
1439        let end = start + Duration::from_millis(10);
1440
1441        // Stop with custom endpoint
1442        timer.stop_with(end);
1443
1444        // Should record exactly 10ms (10_000_000 nanoseconds)
1445        // Allow for small variations due to timer resolution
1446        let recorded = time.value();
1447        assert!(
1448            (10_000_000..=10_100_000).contains(&recorded),
1449            "Expected ~10ms, got {recorded} ns"
1450        );
1451
1452        // Calling stop_with again should not add more time
1453        timer.stop_with(end);
1454        assert_eq!(
1455            recorded,
1456            time.value(),
1457            "Time should not change after second stop"
1458        );
1459    }
1460
1461    #[test]
1462    fn test_done_with_custom_endpoint() {
1463        let time = Time::new();
1464        let start = Instant::now();
1465
1466        // Create a new scope for the timer
1467        {
1468            let timer = time.timer_with(start);
1469
1470            // Simulate 50ms passing
1471            let end = start + Duration::from_millis(5);
1472
1473            // Call done_with to stop and consume the timer
1474            timer.done_with(end);
1475
1476            // Timer is consumed, can't use it anymore
1477        }
1478
1479        // Should record exactly 5ms
1480        let recorded = time.value();
1481        assert!(
1482            (5_000_000..=5_100_000).contains(&recorded),
1483            "Expected ~5ms, got {recorded} ns",
1484        );
1485
1486        // Test that done_with prevents drop from recording time again
1487        {
1488            let timer2 = time.timer_with(start);
1489            let end2 = start + Duration::from_millis(5);
1490            timer2.done_with(end2);
1491            // drop happens here but should not record additional time
1492        }
1493
1494        // Should have added only 5ms more
1495        let new_recorded = time.value();
1496        assert!(
1497            (10_000_000..=10_100_000).contains(&new_recorded),
1498            "Expected ~10ms total, got {new_recorded} ns",
1499        );
1500    }
1501
1502    #[test]
1503    fn test_human_readable_metric_formatting() {
1504        // Test Count formatting with various sizes
1505        let small_count = Count::new();
1506        small_count.add(42);
1507        assert_eq!(
1508            MetricValue::OutputRows(small_count.clone()).to_string(),
1509            "42"
1510        );
1511
1512        let thousand_count = Count::new();
1513        thousand_count.add(10_100);
1514        assert_eq!(
1515            MetricValue::OutputRows(thousand_count.clone()).to_string(),
1516            "10.10 K"
1517        );
1518
1519        let million_count = Count::new();
1520        million_count.add(1_532_000);
1521        assert_eq!(
1522            MetricValue::SpilledRows(million_count.clone()).to_string(),
1523            "1.53 M"
1524        );
1525
1526        let billion_count = Count::new();
1527        billion_count.add(2_500_000_000);
1528        assert_eq!(
1529            MetricValue::OutputBatches(billion_count.clone()).to_string(),
1530            "2.50 B"
1531        );
1532
1533        // Test Time formatting with various durations
1534        let micros_time = Time::new();
1535        micros_time.add_duration(Duration::from_nanos(1_234));
1536        assert_eq!(
1537            MetricValue::ElapsedCompute(micros_time.clone()).to_string(),
1538            "1.23µs"
1539        );
1540
1541        let millis_time = Time::new();
1542        millis_time.add_duration(Duration::from_nanos(11_295_377));
1543        assert_eq!(
1544            MetricValue::ElapsedCompute(millis_time.clone()).to_string(),
1545            "11.30ms"
1546        );
1547
1548        let seconds_time = Time::new();
1549        seconds_time.add_duration(Duration::from_nanos(1_234_567_890));
1550        assert_eq!(
1551            MetricValue::ElapsedCompute(seconds_time.clone()).to_string(),
1552            "1.23s"
1553        );
1554
1555        // Test CurrentMemoryUsage formatting (should use size, not count)
1556        let mem_gauge = Gauge::new();
1557        mem_gauge.add(100 * MB as usize);
1558        assert_eq!(
1559            MetricValue::CurrentMemoryUsage(mem_gauge.clone()).to_string(),
1560            "100.0 MB"
1561        );
1562
1563        // Test PeakMemoryUsage formatting (should use size, not count)
1564        let peak_mem_gauge = Gauge::new();
1565        peak_mem_gauge.add(100 * MB as usize);
1566        assert_eq!(
1567            MetricValue::PeakMemoryUsage {
1568                name: "peak_mem_used".into(),
1569                gauge: peak_mem_gauge.clone()
1570            }
1571            .to_string(),
1572            "100.0 MB"
1573        );
1574
1575        // Test custom Gauge formatting (should use count)
1576        let custom_gauge = Gauge::new();
1577        custom_gauge.add(50_000);
1578        assert_eq!(
1579            MetricValue::Gauge {
1580                name: "custom".into(),
1581                gauge: custom_gauge.clone()
1582            }
1583            .to_string(),
1584            "50.00 K"
1585        );
1586
1587        // Test PruningMetrics formatting
1588        let pruning = PruningMetrics::new();
1589        pruning.add_matched(500_000);
1590        pruning.add_pruned(500_000);
1591        assert_eq!(
1592            MetricValue::PruningMetrics {
1593                name: "test_pruning".into(),
1594                pruning_metrics: pruning.clone()
1595            }
1596            .to_string(),
1597            "1.00 M total → 500.0 K matched"
1598        );
1599
1600        // Test RatioMetrics formatting
1601        let ratio = RatioMetrics::new();
1602        ratio.add_part(250_000);
1603        ratio.add_total(1_000_000);
1604        assert_eq!(
1605            MetricValue::Ratio {
1606                name: "test_ratio".into(),
1607                ratio_metrics: ratio.clone()
1608            }
1609            .to_string(),
1610            "25% (250.0 K/1.00 M)"
1611        );
1612    }
1613}