1use std::fmt::Display;
20use std::sync::Arc;
21
22use ahash::HashMap;
23use arrow::array::{StringBuilder, UInt32Builder};
24use arrow_schema::{DataType, Field, Schema, SchemaRef};
25use common_recordbatch::adapter::{
26 MetricCollector, NativeTreeMetrics, PlanMetrics, RecordBatchMetrics,
27};
28use common_recordbatch::{DfRecordBatch, DfSendableRecordBatchStream};
29use datafusion::error::Result as DfResult;
30use datafusion::execution::TaskContext;
31use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
32use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
33use datafusion::physical_plan::{
34 ChildrenPropertiesMode, DisplayAs, DisplayFormatType, ExecutionPlan,
35 InputDistributionRequirements, PlanProperties, ReplaceChildrenOptions, accept,
36};
37use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
38use datafusion_common::{DataFusionError, assert_eq_or_internal_err, internal_err};
39use datafusion_physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
40use futures::StreamExt;
41use serde::Serialize;
42use serde_json::{Value, json};
43use sqlparser::ast::AnalyzeFormat;
44
45use crate::dist_plan::MergeScanExec;
46
47const STAGE: &str = "stage";
48const NODE: &str = "node";
49const PLAN: &str = "plan";
50
51pub fn dist_analyze_output_schema() -> SchemaRef {
55 SchemaRef::new(Schema::new(vec![
56 Field::new(STAGE, DataType::UInt32, true),
57 Field::new(NODE, DataType::UInt32, true),
58 Field::new(PLAN, DataType::Utf8, true),
59 ]))
60}
61
62#[derive(Debug)]
63pub struct DistAnalyzeExec {
64 input: Arc<dyn ExecutionPlan>,
65 schema: SchemaRef,
66 properties: Arc<PlanProperties>,
67 verbose: bool,
68 format: AnalyzeFormat,
69}
70
71impl DistAnalyzeExec {
72 pub fn new(input: Arc<dyn ExecutionPlan>, verbose: bool, format: AnalyzeFormat) -> Self {
74 let schema = dist_analyze_output_schema();
75 let properties = Arc::new(Self::compute_properties(&input, schema.clone()));
76 Self {
77 input,
78 schema,
79 properties,
80 verbose,
81 format,
82 }
83 }
84
85 fn compute_properties(input: &Arc<dyn ExecutionPlan>, schema: SchemaRef) -> PlanProperties {
87 let eq_properties = EquivalenceProperties::new(schema);
88 let output_partitioning = Partitioning::UnknownPartitioning(1);
89 let properties = input.properties();
90 PlanProperties::new(
91 eq_properties,
92 output_partitioning,
93 properties.emission_type,
94 properties.boundedness,
95 )
96 }
97
98 pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
99 &self.input
100 }
101}
102
103pub fn analyze_plan_metrics_to_json_value(
111 plan: &Arc<dyn ExecutionPlan>,
112 verbose: bool,
113) -> serde_json::Result<Value> {
114 let input = plan
115 .downcast_ref::<DistAnalyzeExec>()
116 .map(|exec| exec.input().clone())
117 .unwrap_or_else(|| plan.clone());
118
119 let mut stages = Vec::new();
120 let mut collector = MetricCollector::new(verbose);
121 accept(input.as_ref(), &mut collector).unwrap();
122 stages.push(json!({
123 "stage": 0,
124 "node": 0,
125 "plan": JsonMetrics::from_record_batch_metrics(collector.record_batch_metrics),
126 }));
127
128 let _ = input.apply(|plan| {
129 if let Some(merge_scan) = plan.downcast_ref::<MergeScanExec>() {
130 for (node, metric) in merge_scan.sub_stage_metrics().into_iter().enumerate() {
131 stages.push(json!({
132 "stage": 1,
133 "node": node,
134 "plan": JsonMetrics::from_record_batch_metrics(metric),
135 }));
136 }
137 }
138 Ok(TreeNodeRecursion::Continue)
139 });
140
141 Ok(Value::Array(stages))
142}
143
144impl DisplayAs for DistAnalyzeExec {
145 fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result {
146 match t {
147 DisplayFormatType::Default
148 | DisplayFormatType::Verbose
149 | DisplayFormatType::TreeRender => {
150 write!(f, "DistAnalyzeExec",)
151 }
152 }
153 }
154}
155
156impl ExecutionPlan for DistAnalyzeExec {
157 fn name(&self) -> &'static str {
158 "DistAnalyzeExec"
159 }
160
161 fn properties(&self) -> &Arc<PlanProperties> {
162 &self.properties
163 }
164
165 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
166 vec![&self.input]
167 }
168
169 fn apply_expressions(
170 &self,
171 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DfResult<TreeNodeRecursion>,
172 ) -> DfResult<TreeNodeRecursion> {
173 Ok(TreeNodeRecursion::Continue)
174 }
175
176 fn input_distribution_requirements(&self) -> InputDistributionRequirements {
178 InputDistributionRequirements::new(vec![
180 datafusion_physical_expr::Distribution::UnspecifiedDistribution,
181 ])
182 }
183
184 fn replace_children(
185 self: Arc<Self>,
186 mut children: Vec<Arc<dyn ExecutionPlan>>,
187 _options: ReplaceChildrenOptions,
188 ) -> DfResult<Arc<dyn ExecutionPlan>> {
189 assert_eq_or_internal_err!(
190 children.len(),
191 1,
192 "DistAnalyzeExec requires exactly one child"
193 );
194 Ok(Arc::new(Self::new(
195 children.swap_remove(0),
196 self.verbose,
197 self.format,
198 )))
199 }
200
201 #[allow(deprecated)]
202 fn with_new_children(
203 self: Arc<Self>,
204 children: Vec<Arc<dyn ExecutionPlan>>,
205 ) -> DfResult<Arc<dyn ExecutionPlan>> {
206 self.replace_children(
207 children,
208 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
209 )
210 }
211
212 fn execute(
213 &self,
214 partition: usize,
215 context: Arc<TaskContext>,
216 ) -> DfResult<DfSendableRecordBatchStream> {
217 if 0 != partition {
218 return internal_err!("AnalyzeExec invalid partition. Expected 0, got {partition}");
219 }
220
221 let coalesce_partition_plan = CoalescePartitionsExec::new(self.input.clone());
224
225 let captured_input = self.input.clone();
227 let captured_schema = self.schema.clone();
228
229 let format = self.format;
231 let verbose = self.verbose;
232 let mut input_stream = coalesce_partition_plan.execute(0, context)?;
233 let output = async move {
234 let mut total_rows = 0;
235 while let Some(batch) = input_stream.next().await.transpose()? {
236 total_rows += batch.num_rows();
237 }
238
239 create_output_batch(total_rows, captured_input, captured_schema, format, verbose)
240 };
241
242 Ok(Box::pin(RecordBatchStreamAdapter::new(
243 self.schema.clone(),
244 futures::stream::once(output),
245 )))
246 }
247}
248
249struct AnalyzeOutputBuilder {
251 stage_builder: UInt32Builder,
252 node_builder: UInt32Builder,
253 plan_builder: StringBuilder,
254 schema: SchemaRef,
255}
256
257impl AnalyzeOutputBuilder {
258 fn new(schema: SchemaRef) -> Self {
259 Self {
260 stage_builder: UInt32Builder::with_capacity(4),
261 node_builder: UInt32Builder::with_capacity(4),
262 plan_builder: StringBuilder::with_capacity(1, 1024),
263 schema,
264 }
265 }
266
267 fn append_metric(&mut self, stage: u32, node: u32, content: String) {
268 self.stage_builder.append_value(stage);
269 self.node_builder.append_value(node);
270 self.plan_builder.append_value(content);
271 }
272
273 fn append_total_rows(&mut self, total_rows: usize) {
274 self.stage_builder.append_null();
275 self.node_builder.append_null();
276 self.plan_builder
277 .append_value(format!("Total rows: {}", total_rows));
278 }
279
280 fn finish(mut self) -> DfResult<DfRecordBatch> {
281 DfRecordBatch::try_new(
282 self.schema,
283 vec![
284 Arc::new(self.stage_builder.finish()),
285 Arc::new(self.node_builder.finish()),
286 Arc::new(self.plan_builder.finish()),
287 ],
288 )
289 .map_err(DataFusionError::from)
290 }
291}
292
293fn create_output_batch(
295 total_rows: usize,
296 input: Arc<dyn ExecutionPlan>,
297 schema: SchemaRef,
298 format: AnalyzeFormat,
299 verbose: bool,
300) -> DfResult<DfRecordBatch> {
301 let mut builder = AnalyzeOutputBuilder::new(schema);
302
303 let mut collector = MetricCollector::new(verbose);
305 accept(input.as_ref(), &mut collector).unwrap();
307 let stage_0_metrics = collector.record_batch_metrics;
308
309 builder.append_metric(0, 0, metrics_to_string(stage_0_metrics, format)?);
311
312 input.apply(|plan| {
314 if let Some(merge_scan) = plan.downcast_ref::<MergeScanExec>() {
315 let sub_stage_metrics = merge_scan.sub_stage_metrics();
316 for (node, metric) in sub_stage_metrics.into_iter().enumerate() {
317 builder.append_metric(1, node as _, metrics_to_string(metric, format)?);
318 }
319 return Ok(TreeNodeRecursion::Continue);
321 }
322 Ok(TreeNodeRecursion::Continue)
323 })?;
324
325 builder.append_total_rows(total_rows);
327
328 builder.finish()
329}
330
331fn metrics_to_string(metrics: RecordBatchMetrics, format: AnalyzeFormat) -> DfResult<String> {
332 match format {
333 AnalyzeFormat::JSON => Ok(JsonMetrics::from_record_batch_metrics(metrics).to_string()),
334 AnalyzeFormat::TEXT => Ok(metrics.to_string()),
335 format => Err(DataFusionError::NotImplemented(format!(
336 "AnalyzeFormat {format}",
337 ))),
338 }
339}
340
341#[derive(Debug, Default, Serialize)]
342struct JsonMetrics {
343 name: String,
344 param: String,
345
346 output_rows: usize,
348 elapsed_compute: usize,
350
351 metrics: HashMap<String, usize>,
353 #[serde(skip_serializing_if = "Option::is_none")]
354 memory_usage: Option<usize>,
355 children: Vec<JsonMetrics>,
356}
357
358impl JsonMetrics {
359 fn from_record_batch_metrics(record_batch_metrics: RecordBatchMetrics) -> Self {
361 let mut layers: HashMap<usize, Vec<Self>> = HashMap::default();
362
363 let memory_usage = record_batch_metrics.memory_usage;
364 for plan_metrics in record_batch_metrics.plan_metrics.into_iter().rev() {
365 let (level, mut metrics) = Self::from_plan_metrics(plan_metrics);
366 if let Some(next_layer) = layers.remove(&(level + 1)) {
367 metrics.children.extend(next_layer);
370 }
371 if level == 0 {
372 metrics.memory_usage = Some(memory_usage);
373 return metrics;
374 }
375 layers.entry(level).or_default().push(metrics);
376 }
377
378 Self::default()
380 }
381
382 fn from_native_metrics(native: NativeTreeMetrics) -> Self {
387 let NativeTreeMetrics {
388 line,
389 metrics,
390 children,
391 } = native;
392 let (name, param) = line.split_once(": ").unwrap_or((line.as_str(), ""));
393 Self {
394 name: name.to_string(),
395 param: param.to_string(),
396 output_rows: 0,
400 elapsed_compute: 0,
401 metrics: metrics.into_iter().collect(),
402 memory_usage: None,
403 children: children
404 .into_iter()
405 .map(Self::from_native_metrics)
406 .collect(),
407 }
408 }
409
410 fn from_plan_metrics(plan_metrics: PlanMetrics) -> (usize, Self) {
414 let raw_name = plan_metrics.plan.trim_end();
417 let operator_line = raw_name.lines().next().unwrap_or_default();
418 let mut elapsed_compute = 0;
419 let mut output_rows = 0;
420 let mut other_metrics = HashMap::default();
421 let (name, param) = operator_line
422 .split_once(": ")
423 .unwrap_or((operator_line, ""));
424
425 for (name, value) in plan_metrics.metrics.into_iter() {
426 if name == "elapsed_compute" {
427 elapsed_compute = value;
428 } else if name == "output_rows" {
429 output_rows = value;
430 } else {
431 other_metrics.insert(name, value);
432 }
433 }
434
435 let children = plan_metrics
438 .native
439 .map(Self::from_native_metrics)
440 .into_iter()
441 .collect();
442 (
443 plan_metrics.level,
444 Self {
445 name: name.to_string(),
446 param: param.to_string(),
447 output_rows,
448 elapsed_compute,
449 metrics: other_metrics,
450 memory_usage: None,
451 children,
452 },
453 )
454 }
455}
456
457impl Display for JsonMetrics {
458 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459 write!(f, "{}", serde_json::to_string(self).unwrap())
460 }
461}
462
463#[cfg(test)]
464mod tests {
465 use datafusion::physical_plan::empty::EmptyExec;
466 use datatypes::series::SeriesOrdering;
467 use datatypes::series::frame::{FrameLabelMode, raw_series_frame_schema};
468 use datatypes::series::samples::{FieldSpec, SeriesSchema};
469 use datatypes::series::time::{EvalGrid, GridSpec};
470 use promql::extension_plan::{FusedSeries, FusedSeriesBinding};
471 use promql::native::plan::{
472 BoundInput, BoundInstant, InstantValue, NativeExpr, NativeNode, NativeTree, NativeType,
473 };
474 use store_api::region_engine::RawLabelSource;
475
476 use super::*;
477
478 fn empty_plan(name: &str) -> Arc<dyn ExecutionPlan> {
479 Arc::new(EmptyExec::new(Arc::new(Schema::new(vec![Field::new(
480 name,
481 DataType::Utf8,
482 true,
483 )]))))
484 }
485
486 #[test]
487 fn qbs_dist_analyze_rejects_zero_children() {
488 let analyze = Arc::new(DistAnalyzeExec::new(
489 empty_plan("original"),
490 false,
491 AnalyzeFormat::TEXT,
492 ));
493
494 assert!(
495 ExecutionPlan::replace_children(
496 analyze,
497 vec![],
498 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
499 )
500 .is_err()
501 );
502 }
503
504 #[test]
505 fn qbs_dist_analyze_rejects_multiple_children() {
506 let analyze = Arc::new(DistAnalyzeExec::new(
507 empty_plan("original"),
508 false,
509 AnalyzeFormat::TEXT,
510 ));
511
512 let result = ExecutionPlan::replace_children(
513 analyze,
514 vec![empty_plan("first"), empty_plan("second")],
515 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
516 );
517
518 if let Ok(plan) = result {
519 let retained = plan
520 .downcast_ref::<DistAnalyzeExec>()
521 .unwrap()
522 .input()
523 .schema()
524 .field(0)
525 .name()
526 .clone();
527 panic!("expected an arity error for multiple children, but retained `{retained}`");
528 }
529 }
530
531 #[test]
532 fn qbs_dist_analyze_accepts_exactly_one_child() {
533 let analyze = Arc::new(DistAnalyzeExec::new(
534 empty_plan("original"),
535 false,
536 AnalyzeFormat::TEXT,
537 ));
538 let replacement = empty_plan("replacement");
539
540 let rebuilt = ExecutionPlan::replace_children(
541 analyze,
542 vec![replacement],
543 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
544 )
545 .unwrap();
546 let rebuilt = rebuilt.downcast_ref::<DistAnalyzeExec>().unwrap();
547
548 assert_eq!(rebuilt.input().schema().field(0).name(), "replacement");
549 }
550
551 #[test]
552 fn qbs_analyze_json_preserves_plan_name_without_parameters() {
553 let input = empty_plan("input");
554 let mut collector = MetricCollector::new(false);
555 accept(input.as_ref(), &mut collector).unwrap();
556
557 let plan_metrics = &collector.record_batch_metrics.plan_metrics;
558 assert_eq!(plan_metrics.len(), 1);
559 assert_eq!(plan_metrics[0].level, 0);
560 assert_eq!(plan_metrics[0].plan, input.name());
561
562 let analyze: Arc<dyn ExecutionPlan> = Arc::new(DistAnalyzeExec::new(
563 input.clone(),
564 false,
565 AnalyzeFormat::JSON,
566 ));
567 let metrics = analyze_plan_metrics_to_json_value(&analyze, false).unwrap();
568 let plan_name = metrics[0]["plan"]["name"].as_str().unwrap();
569 let plan_param = metrics[0]["plan"]["param"].as_str().unwrap();
570
571 assert!(!plan_name.is_empty());
572 assert_eq!(plan_name, input.name());
573 assert!(plan_param.is_empty());
574 }
575
576 #[test]
584 fn qbs_analyze_json_nests_the_native_tree_below_its_operator() {
585 let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(0, 1_000, 2).unwrap()).unwrap());
586 let schema = Arc::new(SeriesSchema {
587 fields: Arc::from([FieldSpec {
588 name: Arc::from("value"),
589 }]),
590 eval_grid: None,
591 });
592 let raw = NativeType::Samples(Arc::clone(&schema));
593 let evaluated = NativeType::Samples(Arc::new(SeriesSchema {
594 fields: schema.fields.clone(),
595 eval_grid: Some(Arc::clone(&grid)),
596 }));
597 let tree = NativeTree::try_new(NativeNode {
598 expr: NativeExpr::Instant {
599 input: Box::new(NativeNode {
600 expr: NativeExpr::Input(BoundInput {
601 source_index: 0,
602 output: raw.clone(),
603 ordering: SeriesOrdering::Contiguous,
604 }),
605 output: raw,
606 }),
607 op: BoundInstant {
608 lookback_ms: 0,
609 offset_ms: 0,
610 at_ms: None,
611 value: InstantValue::Sample,
612 output_grid: Arc::clone(&grid),
613 },
614 },
615 output: evaluated,
616 })
617 .unwrap();
618 let frame_schema = raw_series_frame_schema(&schema, FrameLabelMode::Explicit).unwrap();
619 let child = datafusion::logical_expr::LogicalPlan::EmptyRelation(
620 datafusion::logical_expr::EmptyRelation {
621 produce_one_row: false,
622 schema: Arc::new(
623 datafusion_common::DFSchema::try_from(frame_schema.clone()).unwrap(),
624 ),
625 },
626 );
627 let binding = FusedSeriesBinding {
628 grid,
629 metric_name: None,
630 time_index: "time".to_string(),
631 tags: vec![],
632 };
633 let rows = Arc::new(Schema::new(vec![
634 Field::new("value", DataType::Float64, true),
635 Field::new(
636 "time",
637 DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, None),
638 false,
639 ),
640 ]));
641 let frame = FusedSeries::series_frame_schema(&tree).unwrap();
642 for (output, format, header, param) in [
643 (
644 rows,
645 promql::extension_plan::FusedOutputFormat::PlainRows,
646 "FusedSeriesExec",
647 "",
648 ),
649 (
650 frame,
651 promql::extension_plan::FusedOutputFormat::SeriesFrame,
652 "FusedSeriesExec: (output: series_frame)",
653 "(output: series_frame)",
654 ),
655 ] {
656 let fused = FusedSeries::try_new_with_format(
657 Arc::from("value"),
658 tree.clone(),
659 binding.clone(),
660 vec![child.clone()],
661 Arc::new(datafusion_common::DFSchema::try_from(output).unwrap()),
662 format,
663 )
664 .unwrap();
665 let exec = fused
666 .to_execution_plan(vec![(
667 Arc::new(EmptyExec::new(frame_schema.clone())),
668 RawLabelSource::Explicit,
669 SeriesOrdering::Contiguous,
670 )])
671 .unwrap();
672 let mut collector = MetricCollector::new(false);
673 accept(exec.as_ref(), &mut collector).unwrap();
674 let collected = collector.record_batch_metrics;
675 let collected_levels = collected
679 .plan_metrics
680 .iter()
681 .map(|plan_metrics| {
682 (
683 plan_metrics.level,
684 plan_metrics.plan.lines().next().unwrap(),
685 )
686 })
687 .collect::<Vec<_>>();
688 assert_eq!(
689 collected_levels,
690 vec![(0, header), (1, "EmptyExec")],
691 "the fused node and its physical child are both collected"
692 );
693 let plan = &collected.plan_metrics[0];
694 assert!(plan.native.is_some(), "the native tree must be collected");
695 let metrics = JsonMetrics::from_record_batch_metrics(collected);
696 let value = serde_json::to_value(metrics).unwrap();
697
698 assert_eq!(value["name"], "FusedSeriesExec");
699 assert_eq!(value["param"], param);
700 assert_eq!(value["children"][0]["name"], "Instant");
702 assert_eq!(
703 value["children"][0]["param"],
704 "lookback 0ms offset 0 on grid 0/1000x2"
705 );
706 assert_eq!(value["children"][0]["children"][0]["name"], "Input");
707 assert_eq!(
708 value["children"][0]["children"][0]["param"],
709 "raw samples source=0, contiguous"
710 );
711 assert_eq!(
714 value["children"].as_array().map(Vec::len),
715 Some(2),
716 "the operator's record carries its tree and its physical child: {value}"
717 );
718 assert_eq!(value["children"][1]["name"], "EmptyExec");
719 assert_eq!(
720 value["children"][1]["param"], "",
721 "a physical child with no parameters names none: {value}"
722 );
723 assert_eq!(
724 value["children"][1]["children"].as_array().map(Vec::len),
725 Some(0),
726 "the fused node's physical child reads nothing below it: {value}"
727 );
728 }
729 }
730
731 #[test]
732 fn qbs_analyze_json_splits_plan_name_and_parameters() {
733 let (_, metrics) = JsonMetrics::from_plan_metrics(PlanMetrics {
734 plan: "FilterExec: predicate".to_string(),
735 plan_name: "FilterExec".to_string(),
736 level: 0,
737 metrics: vec![],
738 native: None,
739 });
740
741 assert_eq!(metrics.name, "FilterExec");
742 assert_eq!(metrics.param, "predicate");
743 }
744
745 #[test]
746 fn qbs_analyze_json_includes_memory_usage_only_at_root() {
747 let metrics = JsonMetrics::from_record_batch_metrics(RecordBatchMetrics {
748 memory_usage: 42,
749 plan_metrics: vec![
750 PlanMetrics {
751 plan: "RootExec".to_string(),
752 plan_name: "RootExec".to_string(),
753 level: 0,
754 metrics: vec![("mem_used".to_string(), 24)],
755 native: None,
756 },
757 PlanMetrics {
758 plan: "ChildExec".to_string(),
759 plan_name: "ChildExec".to_string(),
760 level: 1,
761 metrics: vec![("mem_used".to_string(), 18)],
762 native: None,
763 },
764 ],
765 ..Default::default()
766 });
767 let value = serde_json::to_value(metrics).unwrap();
768
769 assert_eq!(value["memory_usage"], 42);
770 assert!(value["children"][0].get("memory_usage").is_none());
771 assert_eq!(value["metrics"]["mem_used"], 24);
772 assert_eq!(value["children"][0]["metrics"]["mem_used"], 18);
773 }
774}