Skip to main content

promql/native/
display.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//! One line per node of a [`NativeTree`].
16//!
17//! The tree is displayed by recursively visiting its bound expressions. The display is an
18//! observation of a compiled tree: it runs nothing, and every line reads as the node it is,
19//! making no claim about whether that node could run.
20//!
21//! A node that recorded figures shows them at the end of its own line, and only its own: the walk
22//! carries the path the runtime registered that node under, so the figures of one node are never
23//! reported as those of another. A tree whose nodes recorded nothing - one that was never run,
24//! which is what `EXPLAIN` shows - prints structure only.
25
26use std::borrow::Cow;
27use std::fmt::{self, Write};
28use std::sync::Arc;
29
30use common_recordbatch::adapter::{NativeTreeMetrics, format_metric};
31use datatypes::series::time::EvalGrid;
32use datatypes::series::{SeriesLabels, SeriesOrdering};
33
34use crate::histogram_eval::HistogramFunction;
35use crate::map::MathOp;
36use crate::native::metrics::NodeMetricsSnapshot;
37use crate::native::plan::{
38    AggregateKind, AggregateStage, BoundAggregate, BoundVectorOp, BoundWindow, Grouping,
39    InstantValue, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, ParameterizedOp,
40};
41use crate::range_eval::RangeFunction;
42use crate::select::{MatchOp, SortOrder};
43use crate::vector_match::{BinaryOp, Cardinality, FillValues, MatchingLabels, SetOp};
44
45/// The path the runtime registers a tree's root node under.
46///
47/// Every other path is this one and the segments of [`child_segments`], so the walk below asks for
48/// a node's figures by the same key its registration used.
49pub const ROOT_PATH: &str = "root";
50
51/// One displayed node: its line, the figures it recorded, and the nodes that consume its output.
52///
53/// The same report feeds the tree's text and, through the operator that owns the tree, the
54/// structure a machine-readable `ANALYZE` publishes, so the two cannot describe different trees.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct NativeNodeReport {
57    /// The node's line without figures, as `<kind>: <what it computes>`.
58    pub line: String,
59    /// The figures this node recorded, in [`crate::native::metrics::NodeMetric::ALL`] order.
60    pub metrics: Vec<(String, usize)>,
61    /// The nodes that consume this one's output, in the order the runtime feeds them.
62    pub children: Vec<NativeNodeReport>,
63}
64
65impl From<NativeNodeReport> for NativeTreeMetrics {
66    /// The same nodes, as the plain data a machine-readable `ANALYZE` publishes.
67    ///
68    /// The text and that record are built from one report, so a reader of either sees the same
69    /// nodes with the same figures.
70    fn from(report: NativeNodeReport) -> Self {
71        Self {
72            line: report.line,
73            metrics: report.metrics,
74            children: report.children.into_iter().map(Self::from).collect(),
75        }
76    }
77}
78
79/// A grid as `<start>/<step>x<len>`.
80fn grid_name(grid: &EvalGrid) -> String {
81    let spec = grid.spec();
82    format!(
83        "{}/{step}x{len}",
84        spec.start_ms,
85        step = spec.step_ms,
86        len = spec.len
87    )
88}
89
90/// A label list in the order it was bound.
91fn label_list(labels: &[Arc<str>]) -> String {
92    labels
93        .iter()
94        .map(|label| label.to_string())
95        .collect::<Vec<_>>()
96        .join(", ")
97}
98
99/// The ordering an input guarantees, when it is weaker than the scan's default.
100fn ordering(ordering: SeriesOrdering) -> &'static str {
101    // `KeyThenTime` is what a scan that orders anything at all provides, so it is the
102    // uninteresting case; a weaker guarantee is what a consumer has to know about.
103    match ordering {
104        SeriesOrdering::KeyThenTime => "",
105        SeriesOrdering::Contiguous => ", contiguous",
106        SeriesOrdering::Interleaved => ", interleaved",
107    }
108}
109
110/// The grid a node's output is evaluated on, or `-` for one that has none.
111fn grid_of(node: &NativeNode) -> String {
112    node.output
113        .grid()
114        .map_or_else(|| "-".to_string(), |grid| grid_name(grid))
115}
116
117/// The operation a node computes, in the words of the query that produced it.
118fn describe(node: &NativeNode) -> String {
119    match &node.expr {
120        NativeExpr::Input(input) => match &input.output {
121            NativeType::Samples(schema) if schema.eval_grid.is_some() => {
122                format!(
123                    "evaluated samples source={}{}",
124                    input.source_index,
125                    ordering(input.ordering)
126                )
127            }
128            NativeType::Samples(_) => format!(
129                "raw samples source={}{}",
130                input.source_index,
131                ordering(input.ordering)
132            ),
133            NativeType::Scalar(grid) => format!("scalar on grid {}", grid_name(grid)),
134            NativeType::AggregateState(_) => "aggregate state".to_string(),
135        },
136        NativeExpr::Scalar(scalar) => scalar.value.to_string(),
137        NativeExpr::EvalTime { date: None } => format!("time() on grid {}", grid_of(node)),
138        NativeExpr::EvalTime { date: Some(date) } => {
139            format!("{}() on grid {}", date.name(), grid_of(node))
140        }
141        NativeExpr::VectorOf { .. } => "vector()".to_string(),
142        NativeExpr::ScalarOf { .. } => "scalar()".to_string(),
143        NativeExpr::ParameterizedTopK { op, .. } => match op {
144            BoundVectorOp::TopK { top: true, .. } => "parameterized topk".to_string(),
145            BoundVectorOp::TopK { top: false, .. } => "parameterized bottomk".to_string(),
146            _ => "parameterized topk".to_string(),
147        },
148        NativeExpr::ParameterizedHistogram { op, parameters, .. } => {
149            format!(
150                "{} ({} parameters)",
151                match op {
152                    BoundVectorOp::Histogram(HistogramFunction::Quantile(_)) =>
153                        "histogram_quantile",
154                    BoundVectorOp::Histogram(HistogramFunction::Fraction { .. }) =>
155                        "histogram_fraction",
156                    _ => "histogram",
157                },
158                parameters.len()
159            )
160        }
161        NativeExpr::ParameterizedMap { op, .. } => match op {
162            ParameterizedOp::Round => "round".to_string(),
163            ParameterizedOp::Clamp => "clamp".to_string(),
164            ParameterizedOp::ClampMin => "clamp_min".to_string(),
165            ParameterizedOp::ClampMax => "clamp_max".to_string(),
166            ParameterizedOp::MaxOf => "max_of".to_string(),
167            ParameterizedOp::MinOf => "min_of".to_string(),
168        },
169        NativeExpr::Instant { op, .. } => {
170            let mut text = format!(
171                "lookback {}ms offset {} on grid {}",
172                op.lookback_ms,
173                op.offset_ms,
174                grid_name(&op.output_grid)
175            );
176            if let Some(at) = op.at_ms {
177                text.push_str(&format!(" @ {at}ms"));
178            }
179            match op.value {
180                InstantValue::Sample => {}
181                InstantValue::Timestamp => text.push_str(" timestamp"),
182                InstantValue::InfoTimestamp => text.push_str(" info timestamp"),
183            }
184            text
185        }
186        NativeExpr::Window { op, .. } => window(op),
187        NativeExpr::Merge { .. } => "canonical label-set merge".to_string(),
188        NativeExpr::Timestamp { .. } => "evaluation time".to_string(),
189        NativeExpr::Map { op, .. } => {
190            let ops: Vec<String> = op.ops.iter().map(map_op).collect();
191            ops.join(", ")
192        }
193        NativeExpr::Vector { op, .. } => match op {
194            BoundVectorOp::TopK { k, top, group } => format!(
195                "{} {k} {}",
196                if *top { "topk" } else { "bottomk" },
197                grouping(group)
198            ),
199            BoundVectorOp::LimitK { k, group } => format!("limitk {k} {}", grouping(group)),
200            BoundVectorOp::LimitRatio { ratio } => format!("limit_ratio {ratio}"),
201            BoundVectorOp::Sort(order) => match order {
202                SortOrder::Asc => "sort".to_string(),
203                SortOrder::Desc => "sort_desc".to_string(),
204                SortOrder::ByLabel(labels) => format!("sort_by_label [{}]", label_list(labels)),
205                SortOrder::ByLabelDesc(labels) => {
206                    format!("sort_by_label_desc [{}]", label_list(labels))
207                }
208            },
209            BoundVectorOp::Absent { labels } => format!("absent {{{}}}", label_pairs(labels)),
210            BoundVectorOp::Histogram(HistogramFunction::Quantile(quantile)) => {
211                format!("histogram_quantile {quantile}")
212            }
213            BoundVectorOp::Histogram(HistogramFunction::Fraction { lower, upper }) => {
214                format!("histogram_fraction {lower} {upper}")
215            }
216            BoundVectorOp::CountValues { label, group } => {
217                format!("count_values {label:?} {}", grouping(group))
218            }
219        },
220        NativeExpr::Aggregate { op, .. } => describe_aggregate(op, &aggregate_kind(op.kind)),
221        // The `φ` this fold reads is not on its binding, so the line leaves the constant out and
222        // says where the value comes from instead.
223        NativeExpr::ParameterizedAggregate { op, .. } => format!(
224            "{}, parameter per point",
225            describe_aggregate(op, aggregate_name(op.kind))
226        ),
227        NativeExpr::Binary { matching, .. } => format!(
228            "{}{} {} {}{}",
229            binary_op(matching.op),
230            if matching.return_bool { " bool" } else { "" },
231            matching_labels(&matching.labels),
232            match &matching.cardinality {
233                Cardinality::OneToOne => "one-to-one".to_string(),
234                Cardinality::ManyToOne(labels) => format!("many-to-one [{}]", label_list(labels)),
235                Cardinality::OneToMany(labels) => format!("one-to-many [{}]", label_list(labels)),
236            },
237            fill(matching.fill)
238        ),
239        NativeExpr::Set { op, .. } => format!(
240            "{} {}",
241            match op.op {
242                SetOp::And => "and",
243                SetOp::Or => "or",
244                SetOp::Unless => "unless",
245            },
246            matching_labels(&op.labels)
247        ),
248        NativeExpr::Info { selector, .. } => format!(
249            "names [{}] data [{}]{}",
250            selector
251                .name_matchers
252                .iter()
253                .map(|(op, value)| format!(
254                    "__name__{}\"{value}\"",
255                    match op {
256                        MatchOp::Equal => "=",
257                        MatchOp::NotEqual => "!=",
258                        MatchOp::Regex => "=~",
259                        MatchOp::NotRegex => "!~",
260                    }
261                ))
262                .collect::<Vec<_>>()
263                .join(", "),
264            label_list(&selector.data_labels),
265            if selector.keep_unmatched {
266                " keep unmatched"
267            } else {
268                ""
269            }
270        ),
271    }
272}
273
274fn matching_labels(labels: &MatchingLabels) -> String {
275    match labels {
276        MatchingLabels::On(labels) => format!("on [{}]", label_list(labels)),
277        MatchingLabels::Ignoring(labels) => format!("ignoring [{}]", label_list(labels)),
278    }
279}
280
281fn fill(values: FillValues) -> String {
282    let side = |name: &str, value: Option<f64>| {
283        value
284            .map(|value| format!(" {name} {value}"))
285            .unwrap_or_default()
286    };
287    format!(
288        "{}{}",
289        side("fill_left", values.lhs),
290        side("fill_right", values.rhs)
291    )
292}
293
294/// An aggregate: what it folds, how its groups are identified and which stage it reports.
295///
296/// `folded` is how the kind is named: with the constant it bound, for a fold that reads one, and
297/// without it for a fold whose argument is read per point.
298fn describe_aggregate(op: &BoundAggregate, folded: &str) -> String {
299    format!(
300        "{} {} [{}] {}",
301        folded,
302        match &op.group {
303            Grouping::By(_) => "by",
304            Grouping::Without(_) => "without",
305        },
306        label_list(match &op.group {
307            Grouping::By(labels) | Grouping::Without(labels) => labels.as_ref(),
308        }),
309        match op.stage {
310            AggregateStage::Complete => "complete",
311            AggregateStage::Partial => "partial",
312            AggregateStage::Final => "final",
313        }
314    )
315}
316
317/// The PromQL name of an aggregate, with the constant argument it was bound to.
318fn aggregate_kind(kind: AggregateKind) -> String {
319    match kind {
320        AggregateKind::Quantile { quantile } => format!("quantile {quantile}"),
321        other => aggregate_name(other).to_string(),
322    }
323}
324
325/// The PromQL name of an aggregate, without the argument it may have bound.
326fn aggregate_name(kind: AggregateKind) -> &'static str {
327    match kind {
328        AggregateKind::Sum => "sum",
329        AggregateKind::Avg => "avg",
330        AggregateKind::Count => "count",
331        AggregateKind::Min => "min",
332        AggregateKind::Max => "max",
333        AggregateKind::Group => "group",
334        AggregateKind::Stddev => "stddev",
335        AggregateKind::Stdvar => "stdvar",
336        AggregateKind::Quantile { .. } => "quantile",
337    }
338}
339
340/// A window: what it runs, over which range, and where it lands.
341fn window(op: &BoundWindow) -> String {
342    format!(
343        "{} [{}ms]{} offset {} anchor {} on grid {}",
344        function(op.function),
345        op.window.range_ms,
346        match op.window.modifier {
347            Some(modifier) => format!(" {} lookback {}ms", modifier.name(), modifier.before_ms()),
348            None => String::new(),
349        },
350        op.window.offset_ms,
351        match op.window.anchor_ms {
352            Some(anchor_ms) => anchor_ms.to_string(),
353            None => "-".to_string(),
354        },
355        grid_name(&op.output_grid)
356    )
357}
358
359/// The PromQL name of a range function, with the constant argument it was bound to.
360fn function(function: RangeFunction) -> String {
361    match function {
362        RangeFunction::Rate => "rate".to_string(),
363        RangeFunction::Increase => "increase".to_string(),
364        RangeFunction::Delta => "delta".to_string(),
365        RangeFunction::Irate => "irate".to_string(),
366        RangeFunction::Idelta => "idelta".to_string(),
367        RangeFunction::AvgOverTime => "avg_over_time".to_string(),
368        RangeFunction::MinOverTime => "min_over_time".to_string(),
369        RangeFunction::MaxOverTime => "max_over_time".to_string(),
370        RangeFunction::SumOverTime => "sum_over_time".to_string(),
371        RangeFunction::CountOverTime => "count_over_time".to_string(),
372        RangeFunction::LastOverTime => "last_over_time".to_string(),
373        RangeFunction::PresentOverTime => "present_over_time".to_string(),
374        RangeFunction::StddevOverTime => "stddev_over_time".to_string(),
375        RangeFunction::StdvarOverTime => "stdvar_over_time".to_string(),
376        RangeFunction::QuantileOverTime(quantile) => format!("quantile_over_time {quantile}"),
377        RangeFunction::Resets => "resets".to_string(),
378        RangeFunction::Changes => "changes".to_string(),
379        RangeFunction::Deriv => "deriv".to_string(),
380        RangeFunction::PredictLinear(seconds) => format!("predict_linear {seconds}"),
381        RangeFunction::DoubleExponentialSmoothing { smoothing, trend } => {
382            format!("double_exponential_smoothing {smoothing} {trend}")
383        }
384        RangeFunction::FirstOverTime => "first_over_time".to_string(),
385        RangeFunction::MadOverTime => "mad_over_time".to_string(),
386        RangeFunction::TsOfFirstOverTime => "ts_of_first_over_time".to_string(),
387        RangeFunction::TsOfLastOverTime => "ts_of_last_over_time".to_string(),
388        RangeFunction::TsOfMinOverTime => "ts_of_min_over_time".to_string(),
389        RangeFunction::TsOfMaxOverTime => "ts_of_max_over_time".to_string(),
390    }
391}
392
393/// The PromQL call a map operation makes, with the constant arguments it was bound to.
394fn map_op(op: &MapOp) -> String {
395    match op {
396        MapOp::Math(op) => math_op(op),
397        MapOp::Histogram(function) => function.name().to_string(),
398        MapOp::Label(rewrite) => rewrite.to_string(),
399    }
400}
401
402/// The PromQL name of a math function, with the constant arguments it was bound to.
403fn math_op(op: &MathOp) -> String {
404    match op {
405        MathOp::Abs => "abs".to_string(),
406        MathOp::Ceil => "ceil".to_string(),
407        MathOp::Floor => "floor".to_string(),
408        MathOp::Sqrt => "sqrt".to_string(),
409        MathOp::Round { nearest } => format!("round {nearest}"),
410        MathOp::Exp => "exp".to_string(),
411        MathOp::Ln => "ln".to_string(),
412        MathOp::Log2 => "log2".to_string(),
413        MathOp::Log10 => "log10".to_string(),
414        MathOp::Sin => "sin".to_string(),
415        MathOp::Cos => "cos".to_string(),
416        MathOp::Tan => "tan".to_string(),
417        MathOp::Asin => "asin".to_string(),
418        MathOp::Acos => "acos".to_string(),
419        MathOp::Atan => "atan".to_string(),
420        MathOp::Sinh => "sinh".to_string(),
421        MathOp::Cosh => "cosh".to_string(),
422        MathOp::Tanh => "tanh".to_string(),
423        MathOp::Asinh => "asinh".to_string(),
424        MathOp::Acosh => "acosh".to_string(),
425        MathOp::Atanh => "atanh".to_string(),
426        MathOp::Deg => "deg".to_string(),
427        MathOp::Rad => "rad".to_string(),
428        MathOp::Sgn => "sgn".to_string(),
429        MathOp::Clamp { min, max } => format!("clamp {min} {max}"),
430        MathOp::ClampMin { min } => format!("clamp_min {min}"),
431        MathOp::ClampMax { max } => format!("clamp_max {max}"),
432        MathOp::Date(function) => function.name().to_string(),
433    }
434}
435
436/// The PromQL symbol of a binary operator.
437fn binary_op(op: BinaryOp) -> &'static str {
438    match op {
439        BinaryOp::Add => "+",
440        BinaryOp::Sub => "-",
441        BinaryOp::Mul => "*",
442        BinaryOp::Div => "/",
443        BinaryOp::Mod => "%",
444        BinaryOp::Pow => "^",
445        BinaryOp::Atan2 => "atan2",
446        BinaryOp::Eq => "==",
447        BinaryOp::Ne => "!=",
448        BinaryOp::Gt => ">",
449        BinaryOp::Lt => "<",
450        BinaryOp::Ge => ">=",
451        BinaryOp::Le => "<=",
452    }
453}
454
455/// The labels of `metric` as `name="value"` pairs, the metric name first.
456fn label_pairs(metric: &SeriesLabels) -> String {
457    metric
458        .name()
459        .map(|name| format!("__name__={name:?}"))
460        .into_iter()
461        .chain(
462            metric
463                .tags()
464                .iter()
465                .map(|tag| format!("{}={:?}", tag.name, tag.value)),
466        )
467        .collect::<Vec<_>>()
468        .join(", ")
469}
470
471/// A grouping as `by [labels]` or `without [labels]`.
472fn grouping(group: &Grouping) -> String {
473    match group {
474        Grouping::By(labels) => format!("by [{}]", label_list(labels)),
475        Grouping::Without(labels) => format!("without [{}]", label_list(labels)),
476    }
477}
478
479/// What kind of node this is, as its line names it.
480fn kind(expr: &NativeExpr) -> &'static str {
481    match expr {
482        NativeExpr::Input(_) => "Input",
483        NativeExpr::Scalar(_) => "Scalar",
484        NativeExpr::Instant { .. } => "Instant",
485        NativeExpr::Window { .. } => "Window",
486        NativeExpr::Merge { .. } => "Merge",
487        NativeExpr::Map { .. } => "Map",
488        NativeExpr::Timestamp { .. } => "Timestamp",
489        NativeExpr::Aggregate { .. } => "Aggregate",
490        NativeExpr::Vector { .. } => "Vector",
491        NativeExpr::Binary { .. } => "Binary",
492        NativeExpr::EvalTime { .. } => "EvalTime",
493        NativeExpr::VectorOf { .. } => "VectorOf",
494        NativeExpr::ScalarOf { .. } => "ScalarOf",
495        NativeExpr::ParameterizedMap { .. } => "ParameterizedMap",
496        NativeExpr::ParameterizedTopK { .. } => "ParameterizedTopK",
497        NativeExpr::ParameterizedAggregate { .. } => "ParameterizedAggregate",
498        NativeExpr::ParameterizedHistogram { .. } => "ParameterizedHistogram",
499        NativeExpr::Set { .. } => "Set",
500        NativeExpr::Info { .. } => "Info",
501    }
502}
503
504/// The child nodes of `node` and the path segment each is registered under, in child order.
505///
506/// The segments are the ones the runtime registers, not the names the bound tree happens to give
507/// the operands: `info` binds its operands as `base` and `info`, while the runtime registers them
508/// as the kernel's `left` and `right`, so the display asks for the figures where they were put.
509fn child_segments(node: &NativeNode) -> Vec<(&NativeNode, Cow<'static, str>)> {
510    let mut children = Vec::new();
511    fn child<'a>(
512        children: &mut Vec<(&'a NativeNode, Cow<'static, str>)>,
513        segment: &'static str,
514        node: &'a NativeNode,
515    ) {
516        children.push((node, Cow::Borrowed(segment)));
517    }
518    match &node.expr {
519        NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => {}
520        NativeExpr::Instant { input, .. }
521        | NativeExpr::Window { input, .. }
522        | NativeExpr::Merge { input }
523        | NativeExpr::Map { input, .. }
524        | NativeExpr::Timestamp { input }
525        | NativeExpr::Aggregate { input, .. }
526        | NativeExpr::Vector { input, .. }
527        | NativeExpr::VectorOf { input }
528        | NativeExpr::ScalarOf { input } => child(&mut children, "input", input),
529        NativeExpr::ParameterizedTopK {
530            input, parameter, ..
531        } => {
532            child(&mut children, "input", input);
533            child(&mut children, "parameter", parameter);
534        }
535        NativeExpr::ParameterizedAggregate {
536            input, parameter, ..
537        } => {
538            child(&mut children, "input", input);
539            child(&mut children, "parameter", parameter);
540        }
541        NativeExpr::ParameterizedHistogram {
542            input, parameters, ..
543        } => {
544            child(&mut children, "input", input);
545            for (index, parameter) in parameters.iter().enumerate() {
546                children.push((parameter, Cow::Owned(format!("parameter{index}"))));
547            }
548        }
549        NativeExpr::ParameterizedMap {
550            input, parameters, ..
551        } => {
552            child(&mut children, "input", input);
553            for (index, parameter) in parameters.iter().enumerate() {
554                children.push((parameter, Cow::Owned(format!("parameter{index}"))));
555            }
556        }
557        NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => {
558            child(&mut children, "left", left);
559            child(&mut children, "right", right);
560        }
561        NativeExpr::Info { base, info, .. } => {
562            child(&mut children, "left", base);
563            child(&mut children, "right", info);
564        }
565    }
566    children
567}
568
569/// The node at `path` and everything below it, with the figures each node recorded.
570fn report_node(node: &NativeNode, path: &str, metrics: &NodeMetricsSnapshot) -> NativeNodeReport {
571    NativeNodeReport {
572        line: format!("{}: {}", kind(&node.expr), describe(node)),
573        metrics: metrics.described(path),
574        children: child_segments(node)
575            .into_iter()
576            .map(|(child, segment)| report_node(child, &format!("{path}.{segment}"), metrics))
577            .collect(),
578    }
579}
580
581impl NativeTree {
582    /// This tree, one report per node, carrying the figures each node recorded.
583    ///
584    /// A snapshot with no entries reports the tree's structure only, which is what a plan that was
585    /// never executed has to show.
586    pub fn report(&self, metrics: &NodeMetricsSnapshot) -> NativeNodeReport {
587        report_node(self.root(), ROOT_PATH, metrics)
588    }
589
590    /// This tree rendered from column zero, with each node's own figures when `metrics` holds them.
591    pub fn display_with<'a>(&'a self, metrics: &'a NodeMetricsSnapshot) -> NativeTreeDisplay<'a> {
592        NativeTreeDisplay {
593            tree: self,
594            metrics,
595        }
596    }
597}
598
599/// A tree as it appears below the operator line: one node per line, two spaces per depth, and each
600/// node's figures on its own line.
601pub struct NativeTreeDisplay<'a> {
602    tree: &'a NativeTree,
603    metrics: &'a NodeMetricsSnapshot,
604}
605
606impl fmt::Display for NativeTreeDisplay<'_> {
607    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608        // The root starts at column zero: the block the caller brackets the tree in carries the
609        // indentation, so each line here is depth-relative to that block rather than to the
610        // caller's own place in the plan.
611        write_report(f, &self.tree.report(self.metrics), 0)
612    }
613}
614
615fn write_report(
616    f: &mut fmt::Formatter<'_>,
617    report: &NativeNodeReport,
618    depth: usize,
619) -> fmt::Result {
620    write!(f, "{:indent$}{}", "", report.line, indent = depth * 2)?;
621    if !report.metrics.is_empty() {
622        let figures = report
623            .metrics
624            .iter()
625            .map(|(name, value)| format_metric(name, *value))
626            .collect::<Vec<_>>()
627            .join(", ");
628        write!(f, ", metrics=[{figures}]")?;
629    }
630    for child in &report.children {
631        f.write_char('\n')?;
632        write_report(f, child, depth + 1)?;
633    }
634    Ok(())
635}
636
637impl fmt::Display for NativeTree {
638    /// One line per node, outermost first, from column zero with two spaces per depth and without
639    /// figures: this is the tree's own shape, which is what a display that holds no metrics
640    /// snapshot can show.
641    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642        write_report(f, &self.report(&NodeMetricsSnapshot::default()), 0)
643    }
644}
645
646#[cfg(test)]
647mod tests;