Skip to main content

promql/native/
metrics.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Per-node metric handles for native PromQL execution and their DataFusion registration.
16//!
17//! Node metrics retain no names or tree topology: [`NodeMetrics::register`] names the handles for
18//! one registration, and the set holds them from there. What outlives an execution is therefore its
19//! counters and gauges, not the nodes that recorded them.
20//!
21//! The name carries the node's position in the runtime tree: the whole native tree registers into
22//! the one [`ExecutionPlanMetricsSet`] the enclosing physical operator (`FusedSeriesExec`) owns, and
23//! the reader aggregates by name, so two nodes of a kind sharing
24//! a name would be summed into a single figure. What a consumer can rely on is the grammar
25//! `native.<path>.<metric>` with the suffixes of [`NodeMetric::ALL`]: splitting off the final
26//! component leaves the metric, and the path before it keys the node within that operator. That key
27//! is promised only inside the topology that produced it:
28//!
29//! - the path names a node of one runtime topology;
30//! - queries, plan rewrites, and versions move it, so it is neither a persisted nor a public
31//!   identifier;
32//! - `peak_reserved_bytes` alone carries `p<partition>`, because the reader sums gauges by name and
33//!   a sum of peaks is not a peak.
34
35use std::collections::HashMap;
36
37use datafusion::physical_plan::metrics::MetricValue;
38use datafusion::physical_plan::metrics::{
39    Count, ExecutionPlanMetricsSet, Gauge, MetricBuilder, Time,
40};
41
42/// The reserved first segment of every native metric name.
43const NATIVE_PREFIX: &str = "native";
44
45/// The metric names one node reports.
46///
47/// [`Self::ALL`] is the list a reader should treat as complete: [`NodeMetrics::register`] names each
48/// handle itself, and `registered_metrics_are_exactly_the_declared_set` fails when the two sides
49/// drift apart.
50pub struct NodeMetric;
51
52impl NodeMetric {
53    /// How many batches this node consumed.
54    pub const INPUT_BATCHES: &'static str = "input_batches";
55    /// How many batches this node produced.
56    pub const OUTPUT_BATCHES: &'static str = "output_batches";
57    /// How many sample positions this node ingested.
58    pub const INPUT_SAMPLES: &'static str = "input_samples";
59    /// How many grid positions this node evaluated, including those with no valid result.
60    pub const EVALUATED_GRID_POINTS: &'static str = "evaluated_grid_points";
61    /// How many valid values this node produced.
62    pub const OUTPUT_VALUES: &'static str = "output_values";
63    /// How many series this node closed.
64    pub const COMPLETED_SERIES: &'static str = "completed_series";
65    /// Time this node spent in its own work, excluding its inputs.
66    pub const SELF_COMPUTE_TIME_NS: &'static str = "self_compute_time_ns";
67    /// Bytes this node currently reserves.
68    pub const CURRENT_RESERVED_BYTES: &'static str = "current_reserved_bytes";
69    /// The highest byte count this node reserved during the execution.
70    pub const PEAK_RESERVED_BYTES: &'static str = "peak_reserved_bytes";
71    /// How many groups this node tracks, counted per partition: a group reached by several
72    /// partitions is one entry in each.
73    pub const GROUPS: &'static str = "groups";
74    /// How many state entries this node tracks.
75    pub const STATE_ENTRIES: &'static str = "state_entries";
76
77    /// Every metric a node may report.
78    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/// The figures every node of one execution left, keyed by the path it was registered under.
94///
95/// A path is the one [`NodeMetrics::register`] was called with (`root`, `root.left`, ...), which is
96/// exactly what the runtime builds while it compiles the tree: a reader that walks the *same* tree
97/// reaches the same path for the same node, so a figure is found rather than guessed.
98///
99/// Partitions are combined here because a node is registered once per partition: counts and times
100/// add up, and `peak_reserved_bytes` — the one figure whose name carries its partition, because a
101/// sum of peaks is not a peak — is the highest of them.
102#[derive(Clone, Debug, Default, PartialEq, Eq)]
103pub struct NodeMetricsSnapshot {
104    nodes: HashMap<String, Vec<(String, usize)>>,
105}
106
107impl NodeMetricsSnapshot {
108    /// Reads every native node figure in `set`.
109    ///
110    /// `set` may hold other metrics, and holds nothing at all before an execution: a snapshot of a
111    /// plan that never ran is empty, which is how a plain `EXPLAIN` shows a tree without figures.
112    ///
113    /// The partitions of one node are combined here rather than by
114    /// [`MetricsSet::aggregate_by_name`](datafusion::physical_plan::metrics::MetricsSet::aggregate_by_name),
115    /// which adds at least one nanosecond to every time it touches: a node whose timer never ran
116    /// would then report time it did not spend.
117    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                // A peak is per partition because partitions peak at different moments: the node's
127                // peak is the highest of theirs, never their sum.
128                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    /// What this node recorded, as `name: value`, dropping the figures that are zero.
142    ///
143    /// A node registers every figure it may record, so a node that did one thing would otherwise
144    /// report ten things it did not: the tree would stop reading as a tree. A node that recorded
145    /// nothing therefore reports nothing, the same way one that never ran does.
146    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    /// What this node recorded, in [`NodeMetric::ALL`] order, or an empty list when it recorded
155    /// nothing.
156    pub fn of(&self, path: &str) -> &[(String, usize)] {
157        self.nodes.get(path).map(Vec::as_slice).unwrap_or_default()
158    }
159}
160
161/// Splits a registered metric name into the node path and the figure it reports.
162///
163/// A name is `native.<path>.<metric>`, and `native.p<partition>.<path>.<metric>` for a figure that
164/// is registered per partition. The partition belongs to that registration rather than to the
165/// node, so it is dropped here and its values are combined by [`NodeMetricsSnapshot::read`]. A name
166/// that is not one of this module's is not a node figure, and is left to whoever else reads `set`.
167fn 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
181/// Where `metric` sits in the declared order, so a node's figures read the same on every node and
182/// on every run.
183fn node_metric_order(metric: &str) -> usize {
184    NodeMetric::ALL
185        .iter()
186        .position(|declared| *declared == metric)
187        .unwrap_or(usize::MAX)
188}
189
190/// The metric handles one node updates as it runs.
191///
192/// The node writes these directly; it never looks a metric up by name, and it never formats a path
193/// on the hot path.
194#[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
227/// Whether `name` is a figure a node of a native tree reports, rather than one of an operator.
228pub fn is_node_metric(name: &str) -> bool {
229    name.strip_prefix(NATIVE_PREFIX)
230        .is_some_and(|rest| rest.starts_with('.'))
231}
232
233/// The full metric name for `metric` reported by the node called `name`.
234fn named(name: &str, metric: &str) -> String {
235    format!("{NATIVE_PREFIX}.{name}.{metric}")
236}
237
238/// The full metric name for `metric` in `partition` of the node called `name`.
239///
240/// A figure that must not be merged across partitions needs the partition in its name: the
241/// collector aggregates by name first, and a sum of peaks is not a peak.
242fn partitioned(name: &str, metric: &str, partition: usize) -> String {
243    format!("{NATIVE_PREFIX}.p{partition}.{name}.{metric}")
244}
245
246impl NodeMetrics {
247    /// Registers this node's handles under `name` into `set`.
248    ///
249    /// A caller registers once per execution, before that execution starts, so what `set` holds
250    /// afterwards follows what this node records as it runs. The name belongs to that registration
251    /// and is not retained here. `partition` is part of the DataFusion registration, and the peak
252    /// name includes it because peaks must not be summed across partitions.
253    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        // The peak is the one figure named per partition. The collector groups by name and sums
314        // gauges, and a sum of two peaks is neither peak: partitions peak at different moments.
315        // Summing the other gauges and counts stays meaningful — the memory held now and the
316        // samples seen add up across partitions. `groups` does not: a `Partial` aggregate sees the
317        // same group in every partition it reaches, so the sum is per-partition entries, not
318        // distinct groups.
319        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    /// Records that this node ingested `batches` batches carrying `samples` sample positions.
346    pub fn record_input(&self, batches: usize, samples: usize) {
347        self.input_batches.add(batches);
348        self.input_samples.add(samples);
349    }
350
351    /// Records that this node produced `batches` batches carrying `values` valid values.
352    pub fn record_output(&self, batches: usize, values: usize) {
353        self.output_batches.add(batches);
354        self.output_values.add(values);
355    }
356
357    /// Records that this node evaluated `points` grid positions.
358    pub fn record_grid_points(&self, points: usize) {
359        self.evaluated_grid_points.add(points);
360    }
361
362    /// Records that this node closed `series` series.
363    pub fn record_completed_series(&self, series: usize) {
364        self.completed_series.add(series);
365    }
366
367    /// Records that this node now reserves `bytes`.
368    ///
369    /// The peak is a high-water mark of this node in this partition, never a sum of the peaks of
370    /// different nodes: those peaks can happen at different times.
371    pub fn record_reserved_bytes(&self, bytes: usize) {
372        self.current_reserved_bytes.set(bytes);
373        // A high-water mark, not a sum: two nodes peak at different moments.
374        self.peak_reserved_bytes.set_max(bytes);
375    }
376
377    /// Records the size of the grouping and state this node holds.
378    pub fn record_state(&self, groups: usize, entries: usize) {
379        self.groups.set(groups);
380        self.state_entries.set(entries);
381    }
382
383    /// Starts timing this node's own work.
384    ///
385    /// The returned timer must be dropped before the node polls its input: a node's self time
386    /// excludes the work its inputs do.
387    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    /// Each partition's peak is exported under a name of its own, from handles of its own.
454    ///
455    /// A [`NodeMetrics`] belongs to one node in one partition, which is the shape one runtime tree
456    /// per partition gives. Two partitions are therefore two sets of handles that grow
457    /// independently: what the second one records never reaches the figure the first one exported,
458    /// and the peak of each is reported under the partition it belongs to rather than summed under
459    /// one shared name.
460    #[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        // The second partition's node is another set of handles, recorded and exported later: the
467        // first export above must not follow it.
468        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    /// A node is registered once per partition, so one node's figures are the sum of its
493    /// partitions' - except the peak, which is the highest one, because partitions peak at
494    /// different moments.
495    #[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    /// The path is what the registration named, and a partition segment is not part of it: the two
519    /// partitions above file under one node rather than under `p0.root` and `p1.root`.
520    #[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    /// A metric this module did not name is not a node figure, so it is not filed under a node.
532    #[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}