Skip to main content

datafusion_physical_expr_common/metrics/
baseline.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Metrics common for almost all operators
6
7use std::{borrow::Cow, collections::BTreeMap, sync::Arc, task::Poll};
8
9use arrow::record_batch::RecordBatch;
10use datafusion_common::{Result, utils::memory::get_record_batch_memory_size};
11
12use super::{
13    Count, ExecutionPlanMetricsSet, Metric, MetricBuilder, MetricsSet, Time, Timestamp,
14};
15
16const OUTPUT_ROWS_SKEW_METRIC_NAME: &str = "output_rows_skew";
17
18/// Helper for creating and tracking common "baseline" metrics for
19/// each operator
20///
21/// Example:
22/// ```
23/// use datafusion_physical_expr_common::metrics::{
24///     BaselineMetrics, ExecutionPlanMetricsSet,
25/// };
26/// let metrics = ExecutionPlanMetricsSet::new();
27///
28/// let partition = 2;
29/// let baseline_metrics = BaselineMetrics::new(&metrics, partition);
30///
31/// // during execution, in CPU intensive operation:
32/// let timer = baseline_metrics.elapsed_compute().timer();
33/// // .. do CPU intensive work
34/// timer.done();
35///
36/// // when operator is finished:
37/// baseline_metrics.done();
38/// ```
39#[derive(Debug, Clone)]
40pub struct BaselineMetrics {
41    /// end_time is set when `BaselineMetrics::done()` is called
42    end_time: Timestamp,
43
44    /// amount of time the operator was actively trying to use the CPU
45    elapsed_compute: Time,
46
47    /// output rows: the total output rows
48    output_rows: Count,
49
50    /// Memory usage of all output batches.
51    ///
52    /// Note: This value may be overestimated. If multiple output `RecordBatch`
53    /// instances share underlying memory buffers, their sizes will be counted
54    /// multiple times.
55    /// Issue: <https://github.com/apache/datafusion/issues/16841>
56    output_bytes: Count,
57
58    /// output batches: the total output batch count
59    output_batches: Count,
60    // Remember to update `docs/source/user-guide/metrics.md` when updating comments
61    // or adding new metrics
62}
63
64impl BaselineMetrics {
65    /// Create a new BaselineMetric structure, and set `start_time` to now
66    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
67        let start_time = MetricBuilder::new(metrics).start_timestamp(partition);
68        start_time.record();
69
70        Self {
71            end_time: MetricBuilder::new(metrics)
72                .with_type(super::MetricType::Summary)
73                .end_timestamp(partition),
74            elapsed_compute: MetricBuilder::new(metrics)
75                .with_type(super::MetricType::Summary)
76                .elapsed_compute(partition),
77            output_rows: MetricBuilder::new(metrics)
78                .with_type(super::MetricType::Summary)
79                .output_rows(partition),
80            output_bytes: MetricBuilder::new(metrics)
81                .with_type(super::MetricType::Summary)
82                .output_bytes(partition),
83            output_batches: MetricBuilder::new(metrics)
84                .with_type(super::MetricType::Dev)
85                .output_batches(partition),
86        }
87    }
88
89    /// Returns a [`BaselineMetrics`] that updates the same `elapsed_compute` ignoring
90    /// all other metrics
91    ///
92    /// This is useful when an operator offloads some of its intermediate work to separate tasks
93    /// that as a result won't be recorded by [`Self::record_poll`]
94    pub fn intermediate(&self) -> BaselineMetrics {
95        Self {
96            end_time: Default::default(),
97            elapsed_compute: self.elapsed_compute.clone(),
98            output_rows: Default::default(),
99            output_bytes: Default::default(),
100            output_batches: Default::default(),
101        }
102    }
103
104    /// return the metric for cpu time spend in this operator
105    pub fn elapsed_compute(&self) -> &Time {
106        &self.elapsed_compute
107    }
108
109    /// return the metric for the total number of output rows produced
110    pub fn output_rows(&self) -> &Count {
111        &self.output_rows
112    }
113
114    /// return the metric for the total number of output batches produced
115    pub fn output_batches(&self) -> &Count {
116        &self.output_batches
117    }
118
119    /// Returns a derived metric that summarizes how unevenly `output_rows`
120    /// are distributed across partitions.
121    ///
122    /// The score is normalized to the range `[0%, 100%]`, where `0%`
123    /// indicates a perfectly balanced distribution and `100%` indicates the
124    /// most skewed distribution.
125    ///
126    /// The calculation is:
127    /// `effective_parallelism = square(sum(r_i)) / sum(square(r_i))`
128    /// `output_rows_skew = (1 - ((effective_parallelism - 1) / (partition_count - 1))) * 100%`
129    ///
130    /// Example: for 4 partitions with output rows `[10, 10, 10, 10]`,
131    /// `effective_parallelism = 40^2 / (10^2 + 10^2 + 10^2 + 10^2) = 4`,
132    /// so `output_rows_skew = 0%`. For `[40, 0, 0, 0]`, the score is `100%`.
133    pub fn output_rows_skew_metric(metrics: &MetricsSet) -> Option<Arc<Metric>> {
134        let output_rows = metrics
135            .iter()
136            .filter_map(|metric| match (metric.partition(), metric.value()) {
137                (Some(partition), super::MetricValue::OutputRows(count)) => {
138                    Some((partition, count.value() as u128))
139                }
140                _ => None,
141            })
142            .fold(
143                BTreeMap::<usize, u128>::new(),
144                |mut output_rows, (partition, rows)| {
145                    *output_rows.entry(partition).or_default() += rows;
146                    output_rows
147                },
148            )
149            .into_values()
150            .collect::<Vec<_>>();
151
152        if output_rows.is_empty() {
153            return None;
154        }
155
156        let ratio_metrics = super::RatioMetrics::new().with_display_raw_values(false);
157        if let Some(score) = output_rows_skew_score(&output_rows) {
158            ratio_metrics.set_part((score * 10_000.0).round() as usize);
159            ratio_metrics.set_total(10_000);
160        }
161
162        Some(Arc::new(
163            Metric::new(
164                super::MetricValue::Ratio {
165                    name: Cow::Borrowed(OUTPUT_ROWS_SKEW_METRIC_NAME),
166                    ratio_metrics,
167                },
168                None,
169            )
170            .with_type(super::MetricType::Dev),
171        ))
172    }
173
174    /// Records the fact that this operator's execution is complete
175    /// (recording the `end_time` metric).
176    ///
177    /// Note care should be taken to call `done()` manually if
178    /// `BaselineMetrics` is not `drop`ped immediately upon operator
179    /// completion, as async streams may not be dropped immediately
180    /// depending on the consumer.
181    pub fn done(&self) {
182        self.end_time.record()
183    }
184
185    /// Record that some number of rows have been produced as output
186    ///
187    /// See the [`RecordOutput`] for conveniently recording record
188    /// batch output for other thing
189    pub fn record_output(&self, num_rows: usize) {
190        self.output_rows.add(num_rows);
191    }
192
193    /// If not previously recorded `done()`, record
194    pub fn try_done(&self) {
195        if self.end_time.value().is_none() {
196            self.end_time.record()
197        }
198    }
199
200    /// Process a poll result of a stream producing output for an operator.
201    ///
202    /// Note: this method only updates `output_rows` and `end_time` metrics.
203    /// Remember to update `elapsed_compute` and other metrics manually.
204    pub fn record_poll(
205        &self,
206        poll: Poll<Option<Result<RecordBatch>>>,
207    ) -> Poll<Option<Result<RecordBatch>>> {
208        if let Poll::Ready(maybe_batch) = &poll {
209            match maybe_batch {
210                Some(Ok(batch)) => {
211                    batch.record_output(self);
212                }
213                Some(Err(_)) => self.done(),
214                None => self.done(),
215            }
216        }
217        poll
218    }
219}
220
221impl Drop for BaselineMetrics {
222    fn drop(&mut self) {
223        self.try_done()
224    }
225}
226
227/// See [`BaselineMetrics::output_rows_skew_metric`] for the algorithm.
228fn output_rows_skew_score(output_rows: &[u128]) -> Option<f64> {
229    if output_rows.is_empty() {
230        return None;
231    }
232
233    let partition_count = output_rows.len();
234    if partition_count == 1 {
235        return Some(0.0);
236    }
237
238    let (total_rows, sum_of_squares) =
239        output_rows
240            .iter()
241            .fold((0.0, 0.0), |(total_rows, sum_of_squares), rows| {
242                let rows = *rows as f64;
243                (total_rows + rows, sum_of_squares + rows.powi(2))
244            });
245    if total_rows == 0.0 {
246        return None;
247    }
248
249    if sum_of_squares == 0.0 {
250        return None;
251    }
252
253    let effective_parallelism = total_rows.powi(2) / sum_of_squares;
254    let balanced_score = (effective_parallelism - 1.0) / (partition_count as f64 - 1.0);
255
256    Some((1.0 - balanced_score).clamp(0.0, 1.0))
257}
258
259/// Helper for creating and tracking spill-related metrics for
260/// each operator
261#[derive(Debug, Clone)]
262pub struct SpillMetrics {
263    /// count of spills during the execution of the operator
264    pub spill_file_count: Count,
265
266    /// total bytes actually written to disk during the execution of the operator
267    pub spilled_bytes: Count,
268
269    /// total spilled rows during the execution of the operator
270    pub spilled_rows: Count,
271}
272
273impl SpillMetrics {
274    /// Create a new SpillMetrics structure
275    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
276        Self {
277            spill_file_count: MetricBuilder::new(metrics).spill_count(partition),
278            spilled_bytes: MetricBuilder::new(metrics).spilled_bytes(partition),
279            spilled_rows: MetricBuilder::new(metrics).spilled_rows(partition),
280        }
281    }
282}
283
284/// Metrics for tracking batch splitting activity
285#[derive(Debug, Clone)]
286pub struct SplitMetrics {
287    /// Number of times an input [`RecordBatch`] was split
288    pub batches_split: Count,
289}
290
291impl SplitMetrics {
292    /// Create a new [`SplitMetrics`]
293    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
294        Self {
295            batches_split: MetricBuilder::new(metrics)
296                .with_category(super::MetricCategory::Rows)
297                .counter("batches_split", partition),
298        }
299    }
300}
301
302/// Trait for things that produce output rows as a result of execution.
303pub trait RecordOutput {
304    /// Record that some number of output rows have been produced
305    ///
306    /// Meant to be composable so that instead of returning `batch`
307    /// the operator can return `batch.record_output(baseline_metrics)`
308    fn record_output(self, bm: &BaselineMetrics) -> Self;
309}
310
311impl RecordOutput for usize {
312    fn record_output(self, bm: &BaselineMetrics) -> Self {
313        bm.record_output(self);
314        self
315    }
316}
317
318impl RecordOutput for RecordBatch {
319    fn record_output(self, bm: &BaselineMetrics) -> Self {
320        bm.record_output(self.num_rows());
321        let n_bytes = get_record_batch_memory_size(&self);
322        bm.output_bytes.add(n_bytes);
323        bm.output_batches.add(1);
324        self
325    }
326}
327
328impl RecordOutput for &RecordBatch {
329    fn record_output(self, bm: &BaselineMetrics) -> Self {
330        bm.record_output(self.num_rows());
331        let n_bytes = get_record_batch_memory_size(self);
332        bm.output_bytes.add(n_bytes);
333        bm.output_batches.add(1);
334        self
335    }
336}
337
338impl RecordOutput for Option<&RecordBatch> {
339    fn record_output(self, bm: &BaselineMetrics) -> Self {
340        if let Some(record_batch) = &self {
341            record_batch.record_output(bm);
342        }
343        self
344    }
345}
346
347impl RecordOutput for Option<RecordBatch> {
348    fn record_output(self, bm: &BaselineMetrics) -> Self {
349        if let Some(record_batch) = &self {
350            record_batch.record_output(bm);
351        }
352        self
353    }
354}
355
356impl RecordOutput for Result<RecordBatch> {
357    fn record_output(self, bm: &BaselineMetrics) -> Self {
358        if let Ok(record_batch) = &self {
359            record_batch.record_output(bm);
360        }
361        self
362    }
363}