1use std::collections::HashMap;
36
37use datafusion::physical_plan::metrics::MetricValue;
38use datafusion::physical_plan::metrics::{
39 Count, ExecutionPlanMetricsSet, Gauge, MetricBuilder, Time,
40};
41
42const NATIVE_PREFIX: &str = "native";
44
45pub struct NodeMetric;
51
52impl NodeMetric {
53 pub const INPUT_BATCHES: &'static str = "input_batches";
55 pub const OUTPUT_BATCHES: &'static str = "output_batches";
57 pub const INPUT_SAMPLES: &'static str = "input_samples";
59 pub const EVALUATED_GRID_POINTS: &'static str = "evaluated_grid_points";
61 pub const OUTPUT_VALUES: &'static str = "output_values";
63 pub const COMPLETED_SERIES: &'static str = "completed_series";
65 pub const SELF_COMPUTE_TIME_NS: &'static str = "self_compute_time_ns";
67 pub const CURRENT_RESERVED_BYTES: &'static str = "current_reserved_bytes";
69 pub const PEAK_RESERVED_BYTES: &'static str = "peak_reserved_bytes";
71 pub const GROUPS: &'static str = "groups";
74 pub const STATE_ENTRIES: &'static str = "state_entries";
76
77 pub const ALL: &'static [&'static str] = &[
79 Self::INPUT_BATCHES,
80 Self::OUTPUT_BATCHES,
81 Self::INPUT_SAMPLES,
82 Self::EVALUATED_GRID_POINTS,
83 Self::OUTPUT_VALUES,
84 Self::COMPLETED_SERIES,
85 Self::SELF_COMPUTE_TIME_NS,
86 Self::CURRENT_RESERVED_BYTES,
87 Self::PEAK_RESERVED_BYTES,
88 Self::GROUPS,
89 Self::STATE_ENTRIES,
90 ];
91}
92
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct NodeMetricsSnapshot {
104 nodes: HashMap<String, Vec<(String, usize)>>,
105}
106
107impl NodeMetricsSnapshot {
108 pub fn read(set: &ExecutionPlanMetricsSet) -> Self {
118 let mut nodes: HashMap<String, Vec<(String, usize)>> = HashMap::new();
119 for metric in set.clone_inner().iter() {
120 let Some((path, name)) = split_name(metric.value().name()) else {
121 continue;
122 };
123 let value = metric.value().as_usize();
124 let figures = nodes.entry(path.to_string()).or_default();
125 match figures.iter_mut().find(|(figure, _)| figure == name) {
126 Some((_, accumulated)) if name == NodeMetric::PEAK_RESERVED_BYTES => {
129 *accumulated = (*accumulated).max(value)
130 }
131 Some((_, accumulated)) => *accumulated = accumulated.saturating_add(value),
132 None => figures.push((name.to_string(), value)),
133 }
134 }
135 for figures in nodes.values_mut() {
136 figures.sort_by_key(|(name, _)| node_metric_order(name));
137 }
138 Self { nodes }
139 }
140
141 pub fn described(&self, path: &str) -> Vec<(String, usize)> {
147 self.of(path)
148 .iter()
149 .filter(|(_, value)| *value != 0)
150 .cloned()
151 .collect()
152 }
153
154 pub fn of(&self, path: &str) -> &[(String, usize)] {
157 self.nodes.get(path).map(Vec::as_slice).unwrap_or_default()
158 }
159}
160
161fn split_name(name: &str) -> Option<(&str, &str)> {
168 let rest = name.strip_prefix(NATIVE_PREFIX)?.strip_prefix('.')?;
169 let rest = match rest.strip_prefix('p').and_then(|rest| rest.split_once('.')) {
170 Some((partition, rest))
171 if !partition.is_empty() && partition.bytes().all(|byte| byte.is_ascii_digit()) =>
172 {
173 rest
174 }
175 _ => rest,
176 };
177 let (path, metric) = rest.rsplit_once('.')?;
178 NodeMetric::ALL.contains(&metric).then_some((path, metric))
179}
180
181fn node_metric_order(metric: &str) -> usize {
184 NodeMetric::ALL
185 .iter()
186 .position(|declared| *declared == metric)
187 .unwrap_or(usize::MAX)
188}
189
190#[derive(Clone, Debug)]
195pub struct NodeMetrics {
196 input_batches: Count,
197 output_batches: Count,
198 input_samples: Count,
199 evaluated_grid_points: Count,
200 output_values: Count,
201 completed_series: Count,
202 self_compute_time: Time,
203 current_reserved_bytes: Gauge,
204 peak_reserved_bytes: Gauge,
205 groups: Gauge,
206 state_entries: Gauge,
207}
208
209impl Default for NodeMetrics {
210 fn default() -> Self {
211 Self {
212 input_batches: Count::new(),
213 output_batches: Count::new(),
214 input_samples: Count::new(),
215 evaluated_grid_points: Count::new(),
216 output_values: Count::new(),
217 completed_series: Count::new(),
218 self_compute_time: Time::new(),
219 current_reserved_bytes: Gauge::new(),
220 peak_reserved_bytes: Gauge::new(),
221 groups: Gauge::new(),
222 state_entries: Gauge::new(),
223 }
224 }
225}
226
227pub fn is_node_metric(name: &str) -> bool {
229 name.strip_prefix(NATIVE_PREFIX)
230 .is_some_and(|rest| rest.starts_with('.'))
231}
232
233fn named(name: &str, metric: &str) -> String {
235 format!("{NATIVE_PREFIX}.{name}.{metric}")
236}
237
238fn partitioned(name: &str, metric: &str, partition: usize) -> String {
243 format!("{NATIVE_PREFIX}.p{partition}.{name}.{metric}")
244}
245
246impl NodeMetrics {
247 pub fn register(&self, name: &str, set: &ExecutionPlanMetricsSet, partition: usize) {
254 fn count(set: &ExecutionPlanMetricsSet, partition: usize, name: String, count: &Count) {
255 MetricBuilder::new(set)
256 .with_partition(partition)
257 .build(MetricValue::Count {
258 name: name.into(),
259 count: count.clone(),
260 });
261 }
262 fn gauge(set: &ExecutionPlanMetricsSet, partition: usize, name: String, gauge: &Gauge) {
263 MetricBuilder::new(set)
264 .with_partition(partition)
265 .build(MetricValue::Gauge {
266 name: name.into(),
267 gauge: gauge.clone(),
268 });
269 }
270
271 count(
272 set,
273 partition,
274 named(name, NodeMetric::INPUT_BATCHES),
275 &self.input_batches,
276 );
277 count(
278 set,
279 partition,
280 named(name, NodeMetric::OUTPUT_BATCHES),
281 &self.output_batches,
282 );
283 count(
284 set,
285 partition,
286 named(name, NodeMetric::INPUT_SAMPLES),
287 &self.input_samples,
288 );
289 count(
290 set,
291 partition,
292 named(name, NodeMetric::EVALUATED_GRID_POINTS),
293 &self.evaluated_grid_points,
294 );
295 count(
296 set,
297 partition,
298 named(name, NodeMetric::OUTPUT_VALUES),
299 &self.output_values,
300 );
301 count(
302 set,
303 partition,
304 named(name, NodeMetric::COMPLETED_SERIES),
305 &self.completed_series,
306 );
307 gauge(
308 set,
309 partition,
310 named(name, NodeMetric::CURRENT_RESERVED_BYTES),
311 &self.current_reserved_bytes,
312 );
313 gauge(
320 set,
321 partition,
322 partitioned(name, NodeMetric::PEAK_RESERVED_BYTES, partition),
323 &self.peak_reserved_bytes,
324 );
325 gauge(
326 set,
327 partition,
328 named(name, NodeMetric::GROUPS),
329 &self.groups,
330 );
331 gauge(
332 set,
333 partition,
334 named(name, NodeMetric::STATE_ENTRIES),
335 &self.state_entries,
336 );
337 MetricBuilder::new(set)
338 .with_partition(partition)
339 .build(MetricValue::Time {
340 name: named(name, NodeMetric::SELF_COMPUTE_TIME_NS).into(),
341 time: self.self_compute_time.clone(),
342 });
343 }
344
345 pub fn record_input(&self, batches: usize, samples: usize) {
347 self.input_batches.add(batches);
348 self.input_samples.add(samples);
349 }
350
351 pub fn record_output(&self, batches: usize, values: usize) {
353 self.output_batches.add(batches);
354 self.output_values.add(values);
355 }
356
357 pub fn record_grid_points(&self, points: usize) {
359 self.evaluated_grid_points.add(points);
360 }
361
362 pub fn record_completed_series(&self, series: usize) {
364 self.completed_series.add(series);
365 }
366
367 pub fn record_reserved_bytes(&self, bytes: usize) {
372 self.current_reserved_bytes.set(bytes);
373 self.peak_reserved_bytes.set_max(bytes);
375 }
376
377 pub fn record_state(&self, groups: usize, entries: usize) {
379 self.groups.set(groups);
380 self.state_entries.set(entries);
381 }
382
383 pub fn timer(&self) -> datafusion::physical_plan::metrics::ScopedTimerGuard<'_> {
388 self.self_compute_time.timer()
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use datafusion::physical_plan::metrics::{
395 Count, ExecutionPlanMetricsSet, MetricBuilder, MetricValue,
396 };
397
398 use super::{NodeMetric, NodeMetrics, NodeMetricsSnapshot};
399
400 fn metrics_named(set: &ExecutionPlanMetricsSet) -> Vec<String> {
401 set.clone_inner()
402 .iter()
403 .map(|metric| metric.value().name().to_string())
404 .collect()
405 }
406
407 #[test]
408 fn fresh_exports_register_exactly_the_declared_metrics_without_growth() {
409 assert_eq!(NodeMetric::ALL.len(), 11);
410 let metrics = NodeMetrics::default();
411 for _ in 0..2 {
412 let set = ExecutionPlanMetricsSet::new();
413 metrics.register("root", &set, 0);
414 let names = metrics_named(&set);
415 assert_eq!(names.len(), NodeMetric::ALL.len());
416 let mut names: Vec<_> = names
417 .iter()
418 .map(|name| name.rsplit('.').next().unwrap().to_string())
419 .collect();
420 names.sort();
421 let mut declared: Vec<_> = NodeMetric::ALL
422 .iter()
423 .map(|name| name.to_string())
424 .collect();
425 declared.sort();
426 assert_eq!(names, declared);
427 }
428 }
429
430 #[test]
431 fn exported_counters_have_recorded_values() {
432 let metrics = NodeMetrics::default();
433 metrics.record_input(3, 17);
434 metrics.record_output(2, 11);
435 let set = ExecutionPlanMetricsSet::new();
436 metrics.register("root", &set, 0);
437 let registered = set.clone_inner();
438 let counter = |name: &str| {
439 registered.iter().find_map(|metric| match metric.value() {
440 MetricValue::Count {
441 name: metric_name,
442 count,
443 } if metric_name.as_ref() == name => Some(count.value()),
444 _ => None,
445 })
446 };
447 assert_eq!(counter("native.root.input_batches"), Some(3));
448 assert_eq!(counter("native.root.input_samples"), Some(17));
449 assert_eq!(counter("native.root.output_batches"), Some(2));
450 assert_eq!(counter("native.root.output_values"), Some(11));
451 }
452
453 #[test]
461 fn peak_exports_are_distinct_per_partition() {
462 let first_metrics = NodeMetrics::default();
463 first_metrics.record_reserved_bytes(1024);
464 let first = ExecutionPlanMetricsSet::new();
465 first_metrics.register("root", &first, 0);
466 let second_metrics = NodeMetrics::default();
469 second_metrics.record_reserved_bytes(2048);
470 let second = ExecutionPlanMetricsSet::new();
471 second_metrics.register("root", &second, 1);
472 let peak = |set: &ExecutionPlanMetricsSet, expected: &str| {
473 set.clone_inner()
474 .iter()
475 .find_map(|metric| match metric.value() {
476 MetricValue::Gauge { name, gauge } if name.as_ref() == expected => {
477 Some(gauge.value())
478 }
479 _ => None,
480 })
481 };
482 assert_eq!(
483 peak(&first, "native.p0.root.peak_reserved_bytes"),
484 Some(1024)
485 );
486 assert_eq!(
487 peak(&second, "native.p1.root.peak_reserved_bytes"),
488 Some(2048)
489 );
490 }
491
492 #[test]
496 fn a_node_reports_one_set_of_figures_across_its_partitions() {
497 let set = ExecutionPlanMetricsSet::new();
498 for (partition, batches, samples, peak) in [(0, 2, 10, 1024), (1, 3, 20, 4096)] {
499 let metrics = NodeMetrics::default();
500 metrics.record_input(batches, samples);
501 metrics.record_reserved_bytes(peak);
502 metrics.register("root", &set, partition);
503 }
504
505 let snapshot = NodeMetricsSnapshot::read(&set);
506 let figure = |name: &str| {
507 snapshot
508 .of("root")
509 .iter()
510 .find_map(|(figure, value)| (figure == name).then_some(*value))
511 .unwrap_or_else(|| panic!("{name} is reported"))
512 };
513 assert_eq!(figure(NodeMetric::INPUT_BATCHES), 5);
514 assert_eq!(figure(NodeMetric::INPUT_SAMPLES), 30);
515 assert_eq!(figure(NodeMetric::PEAK_RESERVED_BYTES), 4096);
516 }
517
518 #[test]
521 fn a_partition_belongs_to_the_registration_and_not_to_the_path() {
522 let set = ExecutionPlanMetricsSet::new();
523 NodeMetrics::default().register("root.left", &set, 7);
524
525 let snapshot = NodeMetricsSnapshot::read(&set);
526 assert!(!snapshot.of("root.left").is_empty());
527 assert!(snapshot.of("root").is_empty());
528 assert!(snapshot.of("p7.root.left").is_empty());
529 }
530
531 #[test]
533 fn a_name_outside_the_grammar_is_not_a_node_figure() {
534 let set = ExecutionPlanMetricsSet::new();
535 let metrics = NodeMetrics::default();
536 metrics.register("root", &set, 0);
537 MetricBuilder::new(&set).build(MetricValue::Count {
538 name: "output_rows".into(),
539 count: Count::new(),
540 });
541
542 let snapshot = NodeMetricsSnapshot::read(&set);
543 assert_eq!(snapshot.of("root").len(), NodeMetric::ALL.len());
544 assert!(
545 snapshot
546 .of("root")
547 .iter()
548 .all(|(name, _)| NodeMetric::ALL.contains(&name.as_str()))
549 );
550 }
551
552 #[test]
553 fn a_peak_is_a_high_water_mark() {
554 let metrics = NodeMetrics::default();
555 metrics.record_reserved_bytes(1024);
556 metrics.record_reserved_bytes(64);
557 assert_eq!(metrics.peak_reserved_bytes.value(), 1024);
558 assert_eq!(metrics.current_reserved_bytes.value(), 64);
559 }
560}