Skip to main content

query/
analyze.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//! Customized `ANALYZE` plan that aware of [MergeScanExec].
16//!
17//! The code skeleton is taken from `datafusion/physical-plan/src/analyze.rs`
18
19use std::any::Any;
20use std::fmt::Display;
21use std::sync::Arc;
22
23use ahash::HashMap;
24use arrow::array::{StringBuilder, UInt32Builder};
25use arrow_schema::{DataType, Field, Schema, SchemaRef};
26use common_recordbatch::adapter::{MetricCollector, PlanMetrics, RecordBatchMetrics};
27use common_recordbatch::{DfRecordBatch, DfSendableRecordBatchStream};
28use datafusion::error::Result as DfResult;
29use datafusion::execution::TaskContext;
30use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
31use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
32use datafusion::physical_plan::{
33    DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, accept,
34};
35use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
36use datafusion_common::{DataFusionError, internal_err};
37use datafusion_physical_expr::{Distribution, EquivalenceProperties, Partitioning};
38use futures::StreamExt;
39use serde::Serialize;
40use serde_json::{Value, json};
41use sqlparser::ast::AnalyzeFormat;
42
43use crate::dist_plan::MergeScanExec;
44
45const STAGE: &str = "stage";
46const NODE: &str = "node";
47const PLAN: &str = "plan";
48
49#[derive(Debug)]
50pub struct DistAnalyzeExec {
51    input: Arc<dyn ExecutionPlan>,
52    schema: SchemaRef,
53    properties: Arc<PlanProperties>,
54    verbose: bool,
55    format: AnalyzeFormat,
56}
57
58impl DistAnalyzeExec {
59    /// Create a new DistAnalyzeExec
60    pub fn new(input: Arc<dyn ExecutionPlan>, verbose: bool, format: AnalyzeFormat) -> Self {
61        let schema = SchemaRef::new(Schema::new(vec![
62            Field::new(STAGE, DataType::UInt32, true),
63            Field::new(NODE, DataType::UInt32, true),
64            Field::new(PLAN, DataType::Utf8, true),
65        ]));
66        let properties = Arc::new(Self::compute_properties(&input, schema.clone()));
67        Self {
68            input,
69            schema,
70            properties,
71            verbose,
72            format,
73        }
74    }
75
76    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
77    fn compute_properties(input: &Arc<dyn ExecutionPlan>, schema: SchemaRef) -> PlanProperties {
78        let eq_properties = EquivalenceProperties::new(schema);
79        let output_partitioning = Partitioning::UnknownPartitioning(1);
80        let properties = input.properties();
81        PlanProperties::new(
82            eq_properties,
83            output_partitioning,
84            properties.emission_type,
85            properties.boundedness,
86        )
87    }
88
89    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
90        &self.input
91    }
92}
93
94/// Returns verbose analyze metrics as JSON values using the same `JsonMetrics` shape
95/// as `EXPLAIN ANALYZE VERBOSE FORMAT JSON`.
96///
97/// This reads metrics directly from a running physical plan for the experimental
98/// HTTP analyze stream. It is a best-effort diagnostic live snapshot, not a
99/// transactionally consistent snapshot; metric values may change while this
100/// function traverses the plan.
101pub fn analyze_plan_metrics_to_json_value(
102    plan: &Arc<dyn ExecutionPlan>,
103    verbose: bool,
104) -> serde_json::Result<Value> {
105    let input = plan
106        .as_any()
107        .downcast_ref::<DistAnalyzeExec>()
108        .map(|exec| exec.input().clone())
109        .unwrap_or_else(|| plan.clone());
110
111    let mut stages = Vec::new();
112    let mut collector = MetricCollector::new(verbose);
113    accept(input.as_ref(), &mut collector).unwrap();
114    stages.push(json!({
115        "stage": 0,
116        "node": 0,
117        "plan": JsonMetrics::from_record_batch_metrics(collector.record_batch_metrics),
118    }));
119
120    let _ = input.apply(|plan| {
121        if let Some(merge_scan) = plan.as_any().downcast_ref::<MergeScanExec>() {
122            for (node, metric) in merge_scan.sub_stage_metrics().into_iter().enumerate() {
123                stages.push(json!({
124                    "stage": 1,
125                    "node": node,
126                    "plan": JsonMetrics::from_record_batch_metrics(metric),
127                }));
128            }
129        }
130        Ok(TreeNodeRecursion::Continue)
131    });
132
133    Ok(Value::Array(stages))
134}
135
136impl DisplayAs for DistAnalyzeExec {
137    fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
138        match t {
139            DisplayFormatType::Default
140            | DisplayFormatType::Verbose
141            | DisplayFormatType::TreeRender => {
142                write!(f, "DistAnalyzeExec",)
143            }
144        }
145    }
146}
147
148impl ExecutionPlan for DistAnalyzeExec {
149    fn name(&self) -> &'static str {
150        "DistAnalyzeExec"
151    }
152
153    /// Return a reference to Any that can be used for downcasting
154    fn as_any(&self) -> &dyn Any {
155        self
156    }
157
158    fn properties(&self) -> &Arc<PlanProperties> {
159        &self.properties
160    }
161
162    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
163        vec![&self.input]
164    }
165
166    /// AnalyzeExec is handled specially so this value is ignored
167    fn required_input_distribution(&self) -> Vec<Distribution> {
168        vec![]
169    }
170
171    fn with_new_children(
172        self: Arc<Self>,
173        mut children: Vec<Arc<dyn ExecutionPlan>>,
174    ) -> DfResult<Arc<dyn ExecutionPlan>> {
175        Ok(Arc::new(Self::new(
176            children.pop().unwrap(),
177            self.verbose,
178            self.format,
179        )))
180    }
181
182    fn execute(
183        &self,
184        partition: usize,
185        context: Arc<TaskContext>,
186    ) -> DfResult<DfSendableRecordBatchStream> {
187        if 0 != partition {
188            return internal_err!("AnalyzeExec invalid partition. Expected 0, got {partition}");
189        }
190
191        // Wrap the input plan using `CoalescePartitionsExec` to poll multiple
192        // partitions in parallel
193        let coalesce_partition_plan = CoalescePartitionsExec::new(self.input.clone());
194
195        // Create future that computes thefinal output
196        let captured_input = self.input.clone();
197        let captured_schema = self.schema.clone();
198
199        // Finish the input stream and create the output
200        let format = self.format;
201        let verbose = self.verbose;
202        let mut input_stream = coalesce_partition_plan.execute(0, context)?;
203        let output = async move {
204            let mut total_rows = 0;
205            while let Some(batch) = input_stream.next().await.transpose()? {
206                total_rows += batch.num_rows();
207            }
208
209            create_output_batch(total_rows, captured_input, captured_schema, format, verbose)
210        };
211
212        Ok(Box::pin(RecordBatchStreamAdapter::new(
213            self.schema.clone(),
214            futures::stream::once(output),
215        )))
216    }
217}
218
219/// Build the result [`DfRecordBatch`] of `ANALYZE`
220struct AnalyzeOutputBuilder {
221    stage_builder: UInt32Builder,
222    node_builder: UInt32Builder,
223    plan_builder: StringBuilder,
224    schema: SchemaRef,
225}
226
227impl AnalyzeOutputBuilder {
228    fn new(schema: SchemaRef) -> Self {
229        Self {
230            stage_builder: UInt32Builder::with_capacity(4),
231            node_builder: UInt32Builder::with_capacity(4),
232            plan_builder: StringBuilder::with_capacity(1, 1024),
233            schema,
234        }
235    }
236
237    fn append_metric(&mut self, stage: u32, node: u32, content: String) {
238        self.stage_builder.append_value(stage);
239        self.node_builder.append_value(node);
240        self.plan_builder.append_value(content);
241    }
242
243    fn append_total_rows(&mut self, total_rows: usize) {
244        self.stage_builder.append_null();
245        self.node_builder.append_null();
246        self.plan_builder
247            .append_value(format!("Total rows: {}", total_rows));
248    }
249
250    fn finish(mut self) -> DfResult<DfRecordBatch> {
251        DfRecordBatch::try_new(
252            self.schema,
253            vec![
254                Arc::new(self.stage_builder.finish()),
255                Arc::new(self.node_builder.finish()),
256                Arc::new(self.plan_builder.finish()),
257            ],
258        )
259        .map_err(DataFusionError::from)
260    }
261}
262
263/// Creates the output of AnalyzeExec as a RecordBatch
264fn create_output_batch(
265    total_rows: usize,
266    input: Arc<dyn ExecutionPlan>,
267    schema: SchemaRef,
268    format: AnalyzeFormat,
269    verbose: bool,
270) -> DfResult<DfRecordBatch> {
271    let mut builder = AnalyzeOutputBuilder::new(schema);
272
273    // Treat the current stage as stage 0. Fetch its metrics
274    let mut collector = MetricCollector::new(verbose);
275    // Safety: metric collector won't return error
276    accept(input.as_ref(), &mut collector).unwrap();
277    let stage_0_metrics = collector.record_batch_metrics;
278
279    // Append the metrics of the current stage
280    builder.append_metric(0, 0, metrics_to_string(stage_0_metrics, format)?);
281
282    // Find merge scan and append its sub_stage_metrics
283    input.apply(|plan| {
284        if let Some(merge_scan) = plan.as_any().downcast_ref::<MergeScanExec>() {
285            let sub_stage_metrics = merge_scan.sub_stage_metrics();
286            for (node, metric) in sub_stage_metrics.into_iter().enumerate() {
287                builder.append_metric(1, node as _, metrics_to_string(metric, format)?);
288            }
289            // might have multiple merge scans, so continue
290            return Ok(TreeNodeRecursion::Continue);
291        }
292        Ok(TreeNodeRecursion::Continue)
293    })?;
294
295    // Write total rows
296    builder.append_total_rows(total_rows);
297
298    builder.finish()
299}
300
301fn metrics_to_string(metrics: RecordBatchMetrics, format: AnalyzeFormat) -> DfResult<String> {
302    match format {
303        AnalyzeFormat::JSON => Ok(JsonMetrics::from_record_batch_metrics(metrics).to_string()),
304        AnalyzeFormat::TEXT => Ok(metrics.to_string()),
305        format => Err(DataFusionError::NotImplemented(format!(
306            "AnalyzeFormat {format}",
307        ))),
308    }
309}
310
311#[derive(Debug, Default, Serialize)]
312struct JsonMetrics {
313    name: String,
314    param: String,
315
316    // well-known metrics
317    output_rows: usize,
318    // busy time in nanoseconds
319    elapsed_compute: usize,
320
321    // other metrics
322    metrics: HashMap<String, usize>,
323    children: Vec<JsonMetrics>,
324}
325
326impl JsonMetrics {
327    fn from_record_batch_metrics(record_batch_metrics: RecordBatchMetrics) -> Self {
328        let mut layers: HashMap<usize, Vec<Self>> = HashMap::default();
329
330        for plan_metrics in record_batch_metrics.plan_metrics.into_iter().rev() {
331            let (level, mut metrics) = Self::from_plan_metrics(plan_metrics);
332            if let Some(next_layer) = layers.remove(&(level + 1)) {
333                metrics.children = next_layer;
334            }
335            if level == 0 {
336                return metrics;
337            }
338            layers.entry(level).or_default().push(metrics);
339        }
340
341        // Unreachable path. Each metrics should contains at least one level 0.
342        Self::default()
343    }
344
345    /// Convert a [`PlanMetrics`] to a [`JsonMetrics`] without children.
346    ///
347    /// Returns the level of the plan and the [`JsonMetrics`].
348    fn from_plan_metrics(plan_metrics: PlanMetrics) -> (usize, Self) {
349        let raw_name = plan_metrics.plan.trim_end();
350        let mut elapsed_compute = 0;
351        let mut output_rows = 0;
352        let mut other_metrics = HashMap::default();
353        let (name, param) = raw_name.split_once(": ").unwrap_or_default();
354
355        for (name, value) in plan_metrics.metrics.into_iter() {
356            if name == "elapsed_compute" {
357                elapsed_compute = value;
358            } else if name == "output_rows" {
359                output_rows = value;
360            } else {
361                other_metrics.insert(name, value);
362            }
363        }
364
365        (
366            plan_metrics.level,
367            Self {
368                name: name.to_string(),
369                param: param.to_string(),
370                output_rows,
371                elapsed_compute,
372                metrics: other_metrics,
373                children: vec![],
374            },
375        )
376    }
377}
378
379impl Display for JsonMetrics {
380    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
381        write!(f, "{}", serde_json::to_string(self).unwrap())
382    }
383}