datafusion_physical_expr_common/metrics/
baseline.rs1use 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#[derive(Debug, Clone)]
40pub struct BaselineMetrics {
41 end_time: Timestamp,
43
44 elapsed_compute: Time,
46
47 output_rows: Count,
49
50 output_bytes: Count,
57
58 output_batches: Count,
60 }
63
64impl BaselineMetrics {
65 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 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 pub fn elapsed_compute(&self) -> &Time {
106 &self.elapsed_compute
107 }
108
109 pub fn output_rows(&self) -> &Count {
111 &self.output_rows
112 }
113
114 pub fn output_batches(&self) -> &Count {
116 &self.output_batches
117 }
118
119 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 pub fn done(&self) {
182 self.end_time.record()
183 }
184
185 pub fn record_output(&self, num_rows: usize) {
190 self.output_rows.add(num_rows);
191 }
192
193 pub fn try_done(&self) {
195 if self.end_time.value().is_none() {
196 self.end_time.record()
197 }
198 }
199
200 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
227fn 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#[derive(Debug, Clone)]
262pub struct SpillMetrics {
263 pub spill_file_count: Count,
265
266 pub spilled_bytes: Count,
268
269 pub spilled_rows: Count,
271}
272
273impl SpillMetrics {
274 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#[derive(Debug, Clone)]
286pub struct SplitMetrics {
287 pub batches_split: Count,
289}
290
291impl SplitMetrics {
292 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
302pub trait RecordOutput {
304 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}