1use std::sync::Arc;
16
17use async_trait::async_trait;
18use common_query::series_frame::series_frame_ordering;
19use datafusion::arrow::datatypes::Schema;
20use datafusion::catalog::Session;
21use datafusion::error::{DataFusionError, Result as DfResult};
22use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
23use datafusion::logical_expr::{LogicalPlan, UserDefinedLogicalNode};
24use datafusion::physical_plan::ExecutionPlan;
25use datafusion::physical_plan::PhysicalExpr;
26use datafusion::physical_plan::expressions::Column;
27use datafusion::physical_plan::projection::ProjectionExec;
28use datafusion::physical_plan::union::UnionExec;
29use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner};
30use datatypes::series::SeriesOrdering;
31use datatypes::series::frame::{FrameLabelMode, SeriesFrameDeclaration};
32use store_api::region_engine::RawLabelSource;
33use table::table::scan::{RegionScanExec, SeriesScanExec};
34
35use crate::extension_plan::{
36 Absent, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate, RangeManipulate,
37 RawSeriesSource, ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn,
38};
39
40pub struct PromExtensionPlanner;
41
42#[async_trait]
43impl ExtensionPlanner for PromExtensionPlanner {
44 async fn plan_extension(
45 &self,
46 planner: &dyn PhysicalPlanner,
47 node: &dyn UserDefinedLogicalNode,
48 _logical_inputs: &[&LogicalPlan],
49 physical_inputs: &[Arc<dyn ExecutionPlan>],
50 session: &dyn Session,
51 planning_ctx: &PhysicalPlanningContext,
52 ) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
53 if let Some(node) = node.as_any().downcast_ref::<SeriesNormalize>() {
54 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
55 } else if let Some(node) = node.as_any().downcast_ref::<InstantManipulate>() {
56 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
57 } else if let Some(node) = node.as_any().downcast_ref::<RangeManipulate>() {
58 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
59 } else if let Some(node) = node.as_any().downcast_ref::<SeriesDivide>() {
60 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
61 } else if let Some(node) = node.as_any().downcast_ref::<EmptyMetric>() {
62 Ok(Some(node.to_execution_plan(
63 session,
64 planner,
65 planning_ctx,
66 )?))
67 } else if let Some(node) = node.as_any().downcast_ref::<ScalarCalculate>() {
68 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())?))
69 } else if let Some(node) = node.as_any().downcast_ref::<HistogramFold>() {
70 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
71 } else if let Some(node) = node.as_any().downcast_ref::<UnionDistinctOn>() {
72 Ok(Some(node.to_execution_plan(
73 physical_inputs[0].clone(),
74 physical_inputs[1].clone(),
75 )))
76 } else if let Some(node) = node.as_any().downcast_ref::<Absent>() {
77 Ok(Some(node.to_execution_plan(physical_inputs[0].clone())))
78 } else if let Some(node) = node.as_any().downcast_ref::<FusedSeries>() {
79 plan_fused_series(
80 node,
81 physical_inputs,
82 session.config_options().execution.target_partitions,
83 )
84 } else if let Some(node) = node.as_any().downcast_ref::<RawSeriesSource>() {
85 plan_raw_series_source(
86 node,
87 physical_inputs,
88 session.config_options().execution.target_partitions,
89 )
90 .map(Some)
91 } else {
92 Ok(None)
93 }
94 }
95}
96
97const METRIC_NAME: &str = "__name__";
100
101fn plan_fused_series(
115 fused: &FusedSeries,
116 physical_inputs: &[Arc<dyn ExecutionPlan>],
117 target_partitions: usize,
118) -> DfResult<Option<Arc<dyn ExecutionPlan>>> {
119 if physical_inputs.len() != fused.children().len() {
120 return Err(DataFusionError::Plan(
121 "FusedSeries physical child count mismatch".into(),
122 ));
123 }
124 if physical_inputs.is_empty() {
125 return fused
126 .to_execution_plan_with_parallelism(Vec::new(), target_partitions)
127 .map(Some);
128 }
129 let explicit_inputs = physical_inputs
130 .iter()
131 .map(normalize_raw_union)
132 .collect::<DfResult<Vec<_>>>()?;
133 if let Some(inputs) = explicit_inputs
134 .iter()
135 .map(|input| {
136 explicit_label_frame_ordering(input.schema().as_ref())
137 .map(|ordering| (Arc::clone(input), RawLabelSource::Explicit, ordering))
138 })
139 .collect::<Option<Vec<_>>>()
140 {
141 return fused
142 .to_execution_plan_with_parallelism(inputs, target_partitions)
143 .map(Some);
144 }
145 if physical_inputs
146 .iter()
147 .any(|input| input.downcast_ref::<RegionScanExec>().is_none())
148 {
149 return Ok(None);
150 }
151
152 let binding = fused.binding();
153 let Some(metric_name) = binding.metric_name.as_deref() else {
154 return Err(DataFusionError::Plan(
155 "the FusedSeries node binds no metric name, so the region scan below it cannot be \
156 asked for the series of one metric"
157 .to_string(),
158 ));
159 };
160 let source_fields = super::fused_series::tree_source_fields(fused.tree())?;
161 if source_fields.len() != physical_inputs.len() {
162 return Err(DataFusionError::Plan(
163 "FusedSeries physical plan source count mismatch".into(),
164 ));
165 }
166 let mut series_inputs = Vec::with_capacity(physical_inputs.len());
167 for (physical, field_names) in physical_inputs.iter().zip(source_fields) {
168 let Some(scan) = physical.downcast_ref::<RegionScanExec>() else {
169 return Ok(None);
170 };
171 let series_scan = series_scan(
172 scan,
173 metric_name,
174 &binding.tags,
175 &field_names,
176 target_partitions,
177 )?;
178 series_inputs.push((
179 series_scan.clone() as Arc<dyn ExecutionPlan>,
180 series_scan.label_source().clone(),
181 series_scan.raw_series_ordering(),
182 ));
183 }
184 fused
185 .to_execution_plan_with_parallelism(series_inputs, target_partitions)
186 .map(Some)
187}
188
189fn plan_raw_series_source(
194 source: &RawSeriesSource,
195 physical_inputs: &[Arc<dyn ExecutionPlan>],
196 target_partitions: usize,
197) -> DfResult<Arc<dyn ExecutionPlan>> {
198 let [input] = physical_inputs else {
199 return Err(DataFusionError::Plan(
200 "RawSeriesSource requires exactly one physical input".into(),
201 ));
202 };
203 let Some(scan) = input.downcast_ref::<RegionScanExec>() else {
204 return Err(DataFusionError::Plan(format!(
205 "RawSeriesSource for metric {:?} must be planned over a region scan, got {}",
206 source.metric_name(),
207 input.name()
208 )));
209 };
210 let series_scan = series_scan(
211 scan,
212 source.metric_name(),
213 source.tags(),
214 source.fields(),
215 target_partitions,
216 )?;
217 source.to_per_series_execution_plan(series_scan)
218}
219
220fn series_scan(
226 scan: &RegionScanExec,
227 metric_name: &str,
228 tags: &[String],
229 fields: &[String],
230 target_partitions: usize,
231) -> DfResult<Arc<SeriesScanExec>> {
232 let scan = if scan.is_partition_set() {
233 Arc::new(scan.clone())
234 } else {
235 let partitions = table::table::scan::assign_partition_ranges(
236 scan.get_partition_ranges(),
237 target_partitions.max(1),
238 );
239 Arc::new(
240 scan.with_new_partitions(partitions, target_partitions.max(1))
241 .map_err(|error| DataFusionError::External(error.into_inner()))?,
242 )
243 };
244 let logical_tags = tags
247 .iter()
248 .filter(|tag| tag.as_str() != METRIC_NAME)
249 .cloned()
250 .collect::<Vec<_>>();
251 scan.try_to_named_series_scan(metric_name, &logical_tags, fields)?
252 .ok_or_else(|| {
253 DataFusionError::Plan(format!(
254 "the region scan could not serve a raw series frame for metric {metric_name:?}: \
255 the scanner refused the raw series path for this scan"
256 ))
257 })
258}
259
260fn normalize_raw_union(input: &Arc<dyn ExecutionPlan>) -> DfResult<Arc<dyn ExecutionPlan>> {
268 let Some(union) = input.downcast_ref::<UnionExec>() else {
269 return Ok(Arc::clone(input));
270 };
271 if explicit_label_frame_ordering(input.schema().as_ref()) != Some(SeriesOrdering::Contiguous)
272 || weakest_union_ordering(union) != SeriesOrdering::Interleaved
273 {
274 return Ok(Arc::clone(input));
275 }
276 let mut metadata = input.schema().metadata().clone();
277 metadata.insert(RAW_SERIES_ORDERING_KEY.into(), "interleaved".into());
278 let schema = Arc::new(Schema::new_with_metadata(
279 input.schema().fields().clone(),
280 metadata,
281 ));
282 let exprs = input
283 .schema()
284 .fields()
285 .iter()
286 .enumerate()
287 .map(|(index, field)| {
288 (
289 Arc::new(Column::new(field.name(), index)) as Arc<dyn PhysicalExpr>,
290 field.name().clone(),
291 )
292 })
293 .collect::<Vec<_>>();
294 Ok(Arc::new(ProjectionExec::try_new_with_schema_metadata(
295 exprs,
296 Arc::clone(input),
297 schema.as_ref(),
298 )?))
299}
300
301const RAW_SERIES_ORDERING_KEY: &str = "greptime.series.ordering";
304
305fn weakest_union_ordering(union: &UnionExec) -> SeriesOrdering {
308 union
309 .children()
310 .iter()
311 .map(|child| match child.downcast_ref::<UnionExec>() {
312 Some(nested) => weakest_union_ordering(nested),
313 None => explicit_label_frame_ordering(child.schema().as_ref())
314 .unwrap_or(SeriesOrdering::Contiguous),
315 })
316 .find(|ordering| *ordering == SeriesOrdering::Interleaved)
317 .unwrap_or(SeriesOrdering::Contiguous)
318}
319
320fn explicit_label_frame_ordering(schema: &Schema) -> Option<SeriesOrdering> {
321 let declaration = SeriesFrameDeclaration::parse(schema).ok()?;
322 if declaration.labels() != FrameLabelMode::Explicit {
323 return None;
324 }
325 series_frame_ordering(schema).ok()
326}
327
328#[cfg(test)]
329mod tests {
330 use std::fmt::{self, Formatter};
331 use std::sync::Arc;
332
333 use common_error::ext::BoxedError;
334 use common_query::series_frame::{
335 raw_series_frame_schema_with_ordering, series_frame_ordering,
336 };
337 use common_recordbatch::{EmptyRecordBatchStream, SendableRecordBatchStream};
338 use datafusion::common::DFSchema;
339 use datafusion::logical_expr::{EmptyRelation, LogicalPlan};
340 use datafusion::physical_plan::ExecutionPlan;
341 use datafusion::physical_plan::empty::EmptyExec;
342 use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
343 use datafusion::physical_plan::union::UnionExec;
344 use datafusion::physical_plan::{DisplayAs, DisplayFormatType};
345 use datatypes::prelude::ConcreteDataType;
346 use datatypes::schema::{ColumnSchema, SchemaRef as DatatypesSchemaRef};
347 use datatypes::series::SeriesOrdering;
348 use datatypes::series::samples::{FieldSpec, SeriesSchema};
349 use datatypes::series::time::{EvalGrid, GridSpec};
350 use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
351 use store_api::region_engine::{
352 PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
353 };
354 use store_api::storage::{RegionId, ScanRequest};
355 use table::table::scan::RegionScanExec;
356
357 use super::{METRIC_NAME, normalize_raw_union, plan_fused_series};
358 use crate::extension_plan::{FusedSeries, FusedSeriesBinding};
359 use crate::native::plan::{BoundInput, NativeExpr, NativeNode, NativeTree, NativeType};
360
361 fn raw_frame(ordering: SeriesOrdering) -> Arc<datafusion::arrow::datatypes::Schema> {
362 let series = SeriesSchema {
363 fields: vec![FieldSpec {
364 name: Arc::from("val"),
365 }]
366 .into(),
367 eval_grid: None,
368 };
369 raw_series_frame_schema_with_ordering(
370 &series,
371 &store_api::region_engine::RawLabelSource::Explicit,
372 ordering,
373 )
374 .expect("a raw schema declares an explicit-label frame")
375 }
376
377 fn union(children: &[SeriesOrdering]) -> Arc<dyn ExecutionPlan> {
378 let children = children
379 .iter()
380 .map(|ordering| {
381 Arc::new(EmptyExec::new(raw_frame(*ordering))) as Arc<dyn ExecutionPlan>
382 })
383 .collect::<Vec<_>>();
384 UnionExec::try_new(children).expect("two framed children")
385 }
386
387 #[test]
391 fn raw_union_declaration_lowers_to_the_weakest_member() {
392 for members in [
393 vec![SeriesOrdering::Interleaved, SeriesOrdering::Contiguous],
394 vec![SeriesOrdering::Contiguous, SeriesOrdering::Interleaved],
395 ] {
396 let union = union(&members);
397 assert_eq!(
398 series_frame_ordering(union.schema().as_ref()).unwrap(),
399 *members.last().unwrap(),
400 "the union itself keeps its last child's declaration"
401 );
402 let normalized =
403 normalize_raw_union(&Arc::clone(&union)).expect("a raw union normalizes");
404 assert_eq!(
405 series_frame_ordering(normalized.schema().as_ref()).unwrap(),
406 SeriesOrdering::Interleaved,
407 "the fused edge sees the weakest member"
408 );
409 }
410
411 let union = union(&[SeriesOrdering::Contiguous, SeriesOrdering::Contiguous]);
412 let normalized = normalize_raw_union(&(Arc::clone(&union) as Arc<dyn ExecutionPlan>))
413 .expect("a raw union normalizes");
414 assert_eq!(
415 series_frame_ordering(normalized.schema().as_ref()).unwrap(),
416 SeriesOrdering::Contiguous,
417 "nothing is lowered when every member is complete"
418 );
419 }
420
421 fn region_metadata() -> RegionMetadataRef {
424 let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
425 builder
426 .push_column_metadata(ColumnMetadata {
427 column_schema: ColumnSchema::new(
428 "ts",
429 ConcreteDataType::timestamp_millisecond_datatype(),
430 false,
431 )
432 .with_time_index(true),
433 semantic_type: api::v1::SemanticType::Timestamp,
434 column_id: 1,
435 })
436 .primary_key(vec![]);
437 Arc::new(builder.build().expect("the fixture metadata is valid"))
438 }
439
440 #[derive(Debug)]
442 struct BareScanner {
443 metadata: RegionMetadataRef,
444 properties: ScannerProperties,
445 }
446
447 impl DisplayAs for BareScanner {
448 fn fmt_as(&self, _format: DisplayFormatType, f: &mut Formatter<'_>) -> fmt::Result {
449 write!(f, "BareScanner")
450 }
451 }
452
453 impl RegionScanner for BareScanner {
454 fn name(&self) -> &str {
455 "BareScanner"
456 }
457
458 fn properties(&self) -> &ScannerProperties {
459 &self.properties
460 }
461
462 fn schema(&self) -> DatatypesSchemaRef {
463 Arc::clone(&self.metadata.schema)
464 }
465
466 fn metadata(&self) -> RegionMetadataRef {
467 Arc::clone(&self.metadata)
468 }
469
470 fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
471 self.properties.prepare(request);
472 Ok(())
473 }
474
475 fn scan_partition(
476 &self,
477 _ctx: &QueryScanContext,
478 _metrics: &ExecutionPlanMetricsSet,
479 _partition: usize,
480 ) -> Result<SendableRecordBatchStream, BoxedError> {
481 Ok(Box::pin(EmptyRecordBatchStream::new(Arc::clone(
482 &self.metadata.schema,
483 ))))
484 }
485
486 fn set_logical_region(&mut self, logical_region: bool) {
487 self.properties.set_logical_region(logical_region);
488 }
489
490 fn set_query_load_region_id(&mut self, region_id: RegionId) {
491 self.properties.set_query_load_region_id(region_id);
492 }
493
494 fn has_predicate_without_region(&self) -> bool {
495 true
496 }
497
498 fn add_dyn_filter_to_predicate(
499 &mut self,
500 filter_exprs: Vec<Arc<dyn datafusion::physical_expr::PhysicalExpr>>,
501 ) -> Vec<bool> {
502 vec![false; filter_exprs.len()]
503 }
504 }
505
506 fn bare_region_scan() -> Arc<dyn ExecutionPlan> {
508 let scanner = BareScanner {
509 metadata: region_metadata(),
510 properties: ScannerProperties::default(),
511 };
512 Arc::new(
513 RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None)
514 .expect("the fixture scanner scans"),
515 )
516 }
517
518 fn one_source_tree() -> (NativeTree, Arc<EvalGrid>) {
520 let grid = Arc::new(
521 EvalGrid::try_new(GridSpec::try_new(0, 60_000, 2).expect("the grid spec is legal"))
522 .expect("the grid is legal"),
523 );
524 let samples = NativeType::Samples(Arc::new(SeriesSchema {
525 fields: vec![FieldSpec {
526 name: Arc::from("val"),
527 }]
528 .into(),
529 eval_grid: Some(Arc::clone(&grid)),
530 }));
531 let tree = NativeTree::try_new(NativeNode {
532 expr: NativeExpr::Input(BoundInput {
533 output: samples.clone(),
534 source_index: 0,
535 ordering: SeriesOrdering::Contiguous,
536 }),
537 output: samples,
538 })
539 .expect("the fixture tree is legal");
540 (tree, grid)
541 }
542
543 #[test]
549 fn a_bare_region_scan_without_a_bound_metric_name_is_refused() {
550 let (tree, grid) = one_source_tree();
551 let node = FusedSeries::try_new(
552 Arc::from(r#"absent_over_time({job="api"}[5m])"#),
553 tree,
554 FusedSeriesBinding {
555 grid,
556 metric_name: None,
557 time_index: "time".to_string(),
558 tags: vec![METRIC_NAME.to_string()],
559 },
560 vec![LogicalPlan::EmptyRelation(EmptyRelation {
561 produce_one_row: false,
562 schema: Arc::new(
563 DFSchema::try_from(raw_frame(SeriesOrdering::Contiguous).as_ref().clone())
564 .expect("the frame is a legal schema"),
565 ),
566 })],
567 Arc::new(
568 DFSchema::try_from(datafusion::arrow::datatypes::Schema::new(vec![
569 datafusion::arrow::datatypes::Field::new(
570 "val",
571 datafusion::arrow::datatypes::DataType::Float64,
572 true,
573 ),
574 ]))
575 .expect("the output is a legal schema"),
576 ),
577 )
578 .expect("one source binds one child");
579 assert_eq!(1, node.children().len(), "the node has its one input");
580 let error = plan_fused_series(&node, &[bare_region_scan()], 4)
581 .expect_err("a region scan has no series to answer without the bound name");
582 assert!(
583 error.to_string().contains("binds no metric name"),
584 "the refusal names what is missing: {error}"
585 );
586 }
587}