1use 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#[derive(Debug, Clone)]
27pub struct Count {
28 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 pub fn new() -> Self {
53 Self {
54 value: Arc::new(AtomicUsize::new(0)),
55 }
56 }
57
58 pub fn add(&self, n: usize) {
60 self.value.fetch_add(n, Ordering::Relaxed);
63 }
64
65 pub fn value(&self) -> usize {
67 self.value.load(Ordering::Relaxed)
68 }
69}
70
71#[derive(Debug, Clone)]
76pub struct Gauge {
77 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 pub fn new() -> Self {
102 Self {
103 value: Arc::new(AtomicUsize::new(0)),
104 }
105 }
106
107 pub fn add(&self, n: usize) {
109 self.value.fetch_add(n, Ordering::Relaxed);
112 }
113
114 pub fn sub(&self, n: usize) {
116 self.value.fetch_sub(n, Ordering::Relaxed);
119 }
120
121 pub fn set_max(&self, n: usize) {
123 self.value.fetch_max(n, Ordering::Relaxed);
124 }
125
126 pub fn set(&self, n: usize) -> usize {
128 self.value.swap(n, Ordering::Relaxed)
131 }
132
133 pub fn value(&self) -> usize {
135 self.value.load(Ordering::Relaxed)
136 }
137}
138
139#[derive(Debug, Clone)]
141pub struct Time {
142 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 pub fn new() -> Self {
168 Self {
169 nanos: Arc::new(AtomicUsize::new(0)),
170 }
171 }
172
173 pub fn add_elapsed(&self, start: Instant) {
175 self.add_duration(start.elapsed());
176 }
177
178 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 pub fn add_duration_exact(&self, duration: Duration) {
198 self.nanos
199 .fetch_add(duration.as_nanos() as usize, Ordering::Relaxed);
200 }
201
202 pub fn add(&self, other: &Time) {
204 self.add_duration(Duration::from_nanos(other.value() as u64))
205 }
206
207 pub fn timer(&self) -> ScopedTimerGuard<'_> {
211 ScopedTimerGuard {
212 inner: self,
213 start: Some(Instant::now()),
214 }
215 }
216
217 pub fn value(&self) -> usize {
219 self.nanos.load(Ordering::Relaxed)
220 }
221
222 pub fn timer_with(&self, now: Instant) -> ScopedTimerGuard<'_> {
225 ScopedTimerGuard {
226 inner: self,
227 start: Some(now),
228 }
229 }
230}
231
232#[derive(Debug, Clone)]
235pub struct Timestamp {
236 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 pub fn new() -> Self {
249 Self {
250 timestamp: Arc::new(Mutex::new(None)),
251 }
252 }
253
254 pub fn record(&self) {
256 self.set(Utc::now())
257 }
258
259 pub fn set(&self, now: DateTime<Utc>) {
261 *self.timestamp.lock() = Some(now);
262 }
263
264 pub fn value(&self) -> Option<DateTime<Utc>> {
269 *self.timestamp.lock()
270 }
271
272 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 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
314pub struct ScopedTimerGuard<'a> {
318 inner: &'a Time,
319 start: Option<Instant>,
320}
321
322impl ScopedTimerGuard<'_> {
323 pub fn stop(&mut self) {
325 if let Some(start) = self.start.take() {
326 self.inner.add_elapsed(start)
327 }
328 }
329
330 pub fn restart(&mut self) {
332 self.start = Some(Instant::now())
333 }
334
335 pub fn done(mut self) {
337 self.stop()
338 }
339
340 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 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#[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 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 pub fn add_pruned(&self, n: usize) {
417 self.pruned.fetch_add(n, Ordering::Relaxed);
420 }
421
422 pub fn add_matched(&self, n: usize) {
424 self.matched.fetch_add(n, Ordering::Relaxed);
427 }
428
429 pub fn add_fully_matched(&self, n: usize) {
431 self.fully_matched.fetch_add(n, Ordering::Relaxed);
434 }
435
436 pub fn subtract_matched(&self, n: usize) {
438 self.matched.fetch_sub(n, Ordering::Relaxed);
441 }
442
443 pub fn pruned(&self) -> usize {
445 self.pruned.load(Ordering::Relaxed)
446 }
447
448 pub fn matched(&self) -> usize {
450 self.matched.load(Ordering::Relaxed)
451 }
452
453 pub fn fully_matched(&self) -> usize {
455 self.fully_matched.load(Ordering::Relaxed)
456 }
457}
458
459#[derive(Debug, Clone, Default)]
463pub struct RatioMetrics {
464 part: Arc<AtomicUsize>,
465 total: Arc<AtomicUsize>,
466 merge_strategy: RatioMergeStrategy,
467 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 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 pub fn add_part(&self, n: usize) {
502 self.part.fetch_add(n, Ordering::Relaxed);
503 }
504
505 pub fn add_total(&self, n: usize) {
507 self.total.fetch_add(n, Ordering::Relaxed);
508 }
509
510 pub fn set_part(&self, n: usize) {
512 self.part.store(n, Ordering::Relaxed);
513 }
514
515 pub fn set_total(&self, n: usize) {
517 self.total.store(n, Ordering::Relaxed);
518 }
519
520 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 pub fn part(&self) -> usize {
540 self.part.load(Ordering::Relaxed)
541 }
542
543 pub fn total(&self) -> usize {
545 self.total.load(Ordering::Relaxed)
546 }
547
548 pub fn merge_strategy(&self) -> &RatioMergeStrategy {
550 &self.merge_strategy
551 }
552
553 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 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
571 let part = self.part();
572 let total = self.total();
573
574 if total == 0 {
577 write!(f, "N/A")?;
578 } else {
579 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#[derive(Debug, Clone)]
622pub enum MetricValue {
623 OutputRows(Count),
625 ElapsedCompute(Time),
645 SpillCount(Count),
647 SpilledBytes(Count),
649 OutputBytes(Count),
651 OutputBatches(Count),
653 SpilledRows(Count),
655 CurrentMemoryUsage(Gauge),
657 Count {
659 name: Cow<'static, str>,
661 count: Count,
663 },
664 Gauge {
666 name: Cow<'static, str>,
668 gauge: Gauge,
670 },
671 PeakMemoryUsage {
673 name: Cow<'static, str>,
675 gauge: Gauge,
677 },
678 Time {
680 name: Cow<'static, str>,
682 time: Time,
684 },
685 StartTimestamp(Timestamp),
687 EndTimestamp(Timestamp),
689 PruningMetrics {
691 name: Cow<'static, str>,
692 pruning_metrics: PruningMetrics,
693 },
694 Ratio {
696 name: Cow<'static, str>,
697 ratio_metrics: RatioMetrics,
698 },
699 Custom {
700 name: Cow<'static, str>,
702 value: Arc<dyn CustomMetricValue>,
704 },
705}
706
707impl 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 _ => false,
806 }
807 }
808}
809
810impl MetricValue {
811 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 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 Self::PruningMetrics { .. } => 0,
866 Self::Ratio { .. } => 0,
868 Self::Custom { value, .. } => value.as_usize(),
869 }
870 }
871
872 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 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 (Self::StartTimestamp(timestamp), Self::StartTimestamp(other_timestamp)) => {
970 timestamp.update_to_min(other_timestamp);
971 }
972 (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 pub fn display_sort_key(&self) -> u8 {
1022 match self {
1023 Self::OutputRows(_) => 0,
1025 Self::ElapsedCompute(_) => 1,
1026 Self::OutputBytes(_) => 2,
1027 Self::OutputBatches(_) => 3,
1028 Self::PruningMetrics { name, .. } => match name.as_ref() {
1030 "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 "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, Self::EndTimestamp(_) => 19,
1060 Self::Custom { .. } => 20,
1061 }
1062 }
1063
1064 pub fn is_timestamp(&self) -> bool {
1066 matches!(self, Self::StartTimestamp(_) | Self::EndTimestamp(_))
1067 }
1068}
1069
1070impl Display for MetricValue {
1071 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 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 write!(f, "{}", human_readable_count(gauge.value()))
1097 }
1098 Self::ElapsedCompute(time) | Self::Time { time, .. } => {
1099 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 assert_ne!(other_custom_val, custom_val);
1184
1185 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 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 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 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 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 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 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 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 std::thread::sleep(Duration::from_millis(1));
1414
1415 let mut timer = time.timer_with(start_time);
1417
1418 std::thread::sleep(Duration::from_millis(1));
1420
1421 timer.stop();
1423
1424 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 let end = start + Duration::from_millis(10);
1440
1441 timer.stop_with(end);
1443
1444 let recorded = time.value();
1447 assert!(
1448 (10_000_000..=10_100_000).contains(&recorded),
1449 "Expected ~10ms, got {recorded} ns"
1450 );
1451
1452 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 {
1468 let timer = time.timer_with(start);
1469
1470 let end = start + Duration::from_millis(5);
1472
1473 timer.done_with(end);
1475
1476 }
1478
1479 let recorded = time.value();
1481 assert!(
1482 (5_000_000..=5_100_000).contains(&recorded),
1483 "Expected ~5ms, got {recorded} ns",
1484 );
1485
1486 {
1488 let timer2 = time.timer_with(start);
1489 let end2 = start + Duration::from_millis(5);
1490 timer2.done_with(end2);
1491 }
1493
1494 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 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 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 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 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 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 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 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}