1use std::any::Any;
30use std::fmt::{self, Formatter};
31use std::pin::Pin;
32use std::sync::Arc;
33use std::task::{Context, Poll};
34
35use common_error::ext::BoxedError;
36use common_query::series_frame::{
37 PendingBatching, frame_schema_with, pack_raw_series_with,
38 raw_series_frame_schema_with_ordering, series_frame_ordering, unpack_raw_series,
39};
40use datafusion::arrow::datatypes::SchemaRef;
41use datafusion::arrow::record_batch::RecordBatch;
42use datafusion::common::tree_node::TreeNodeRecursion;
43use datafusion::common::{DFSchema, DFSchemaRef};
44use datafusion::error::{DataFusionError, Result as DataFusionResult};
45use datafusion::execution::context::TaskContext;
46use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNodeCore};
47use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
48use datafusion::physical_plan::coop::CooperativeExec;
49use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
50use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
51use datafusion::physical_plan::{
52 DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements,
53 Partitioning, PlanProperties, SendableRecordBatchStream,
54};
55use datatypes::series::SeriesOrdering;
56use datatypes::series::frame::{
57 FrameContent, FrameLabelMode, LabelDecodeSpec, SeriesFrameDeclaration,
58};
59use datatypes::series::raw::RawSeriesChunk;
60use datatypes::series::samples::{FieldSpec, SeriesSchema};
61use futures::{Stream, StreamExt};
62use greptime_proto::substrait_extension::RawSeriesSource as RawSeriesSourceProto;
63use prost::Message;
64use store_api::region_engine::{RawLabelSource, RawSeriesStream};
65use table::table::scan::SeriesScanExec;
66
67use crate::extension_plan::series_execution::{
68 HandedSeriesChunk, SendableSeriesStream, SeriesChunk, SeriesExecutionPlan,
69};
70use crate::source::materialize_raw_labels;
71
72const ORDERING: SeriesOrdering = SeriesOrdering::Contiguous;
79const WIRE_VERSION: u32 = 1;
80
81#[derive(Debug, PartialEq, Eq, Hash)]
83pub struct RawSeriesSource {
84 metric_name: Arc<str>,
85 tags: Vec<String>,
87 fields: Vec<String>,
89 input: LogicalPlan,
90 schema: DFSchemaRef,
91}
92
93impl RawSeriesSource {
94 pub const fn name() -> &'static str {
95 "RawSeriesSource"
96 }
97
98 pub fn try_new(
99 metric_name: Arc<str>,
100 tags: Vec<String>,
101 fields: Vec<String>,
102 input: LogicalPlan,
103 ) -> DataFusionResult<Self> {
104 let schema = Arc::new(DFSchema::try_from(frame_schema(&fields)?)?);
105 Ok(Self {
106 metric_name,
107 tags,
108 fields,
109 input,
110 schema,
111 })
112 }
113
114 pub fn metric_name(&self) -> &str {
115 &self.metric_name
116 }
117
118 pub fn tags(&self) -> &[String] {
119 &self.tags
120 }
121
122 pub fn fields(&self) -> &[String] {
123 &self.fields
124 }
125
126 pub fn serialize(&self) -> Vec<u8> {
128 RawSeriesSourceProto {
129 version: WIRE_VERSION,
130 metric_name: self.metric_name.to_string(),
131 tags: self.tags.clone(),
132 fields: self.fields.clone(),
133 }
134 .encode_to_vec()
135 }
136
137 pub fn deserialize(bytes: &[u8]) -> DataFusionResult<Self> {
139 let binding = RawSeriesSourceProto::decode(bytes).map_err(|error| {
140 DataFusionError::Substrait(format!("Failed to deserialize RawSeriesSource: {error}"))
141 })?;
142 if binding.version != WIRE_VERSION {
143 return Err(DataFusionError::Substrait(format!(
144 "Unsupported RawSeriesSource version: {}",
145 binding.version
146 )));
147 }
148 let input = LogicalPlan::EmptyRelation(datafusion::logical_expr::EmptyRelation {
149 produce_one_row: false,
150 schema: Arc::new(DFSchema::empty()),
151 });
152 Self::try_new(
153 Arc::from(binding.metric_name),
154 binding.tags,
155 binding.fields,
156 input,
157 )
158 }
159
160 pub fn to_per_series_execution_plan(
162 &self,
163 series_scan: Arc<dyn ExecutionPlan>,
164 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
165 Ok(Arc::new(RawSeriesSourceExec::try_new_with_provenance(
166 series_scan,
167 Arc::clone(&self.metric_name),
168 self.fields.clone(),
169 true,
170 )?))
171 }
172}
173
174fn series_schema(fields: &[String]) -> Arc<SeriesSchema> {
175 Arc::new(SeriesSchema {
176 fields: fields
177 .iter()
178 .map(|name| FieldSpec {
179 name: Arc::from(name.as_str()),
180 })
181 .collect::<Vec<_>>()
182 .into(),
183 eval_grid: None,
184 })
185}
186
187fn frame_schema(fields: &[String]) -> DataFusionResult<SchemaRef> {
188 raw_series_frame_schema_with_ordering(
189 &series_schema(fields),
190 &RawLabelSource::Explicit,
191 ORDERING,
192 )
193}
194
195impl PartialOrd for RawSeriesSource {
196 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
197 (&self.metric_name, &self.tags, &self.fields)
199 .partial_cmp(&(&other.metric_name, &other.tags, &other.fields))
200 .and_then(|ordering| match ordering {
201 std::cmp::Ordering::Equal => self.input.partial_cmp(&other.input),
202 ordering => Some(ordering),
203 })
204 }
205}
206
207impl UserDefinedLogicalNodeCore for RawSeriesSource {
208 fn name(&self) -> &str {
209 Self::name()
210 }
211
212 fn inputs(&self) -> Vec<&LogicalPlan> {
213 vec![&self.input]
214 }
215
216 fn schema(&self) -> &DFSchemaRef {
217 &self.schema
218 }
219
220 fn expressions(&self) -> Vec<Expr> {
221 Vec::new()
222 }
223
224 fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
225 write!(
226 f,
227 "RawSeriesSource: metric={}, tags=[{}], fields=[{}]",
228 self.metric_name,
229 self.tags.join(", "),
230 self.fields.join(", ")
231 )
232 }
233
234 fn with_exprs_and_inputs(
235 &self,
236 _exprs: Vec<Expr>,
237 mut inputs: Vec<LogicalPlan>,
238 ) -> DataFusionResult<Self> {
239 if inputs.len() != 1 {
240 return Err(DataFusionError::Internal(
241 "RawSeriesSource should have exactly one input".to_string(),
242 ));
243 }
244 Ok(Self {
245 metric_name: Arc::clone(&self.metric_name),
246 tags: self.tags.clone(),
247 fields: self.fields.clone(),
248 input: inputs.swap_remove(0),
249 schema: Arc::clone(&self.schema),
250 })
251 }
252}
253
254struct DeclaredSeries {
264 chunks: SendableSeriesStream,
266 schema: Arc<SeriesSchema>,
268}
269
270impl Stream for DeclaredSeries {
271 type Item = Result<RawSeriesChunk, BoxedError>;
272
273 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
274 match self.chunks.as_mut().poll_next(cx) {
275 Poll::Ready(Some(Ok(handed))) => match handed.into_parts().0 {
278 SeriesChunk::Raw(chunk) => Poll::Ready(Some(Ok(chunk))),
279 other => Poll::Ready(Some(Err(BoxedError::new(
283 common_query::error::Error::from(DataFusionError::Execution(format!(
284 "RawSeriesSourceExec handed over {other:?}"
285 ))),
286 )))),
287 },
288 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
289 Poll::Ready(None) => Poll::Ready(None),
290 Poll::Pending => Poll::Pending,
291 }
292 }
293}
294
295impl RawSeriesStream for DeclaredSeries {
296 fn schema(&self) -> &Arc<SeriesSchema> {
297 &self.schema
298 }
299
300 fn label_source(&self) -> &RawLabelSource {
301 &RawLabelSource::Explicit
302 }
303
304 fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
305 None
306 }
307
308 fn ordering(&self) -> SeriesOrdering {
309 ORDERING
310 }
311}
312
313fn is_series_scan(plan: &dyn ExecutionPlan) -> bool {
318 match plan.downcast_ref::<CooperativeExec>() {
319 Some(cooperative) => is_series_scan(cooperative.input().as_ref()),
320 None => plan.downcast_ref::<SeriesScanExec>().is_some(),
321 }
322}
323
324#[derive(Debug)]
331pub struct RawSeriesSourceExec {
332 input: Arc<dyn ExecutionPlan>,
333 metric_name: Arc<str>,
334 series_schema: Arc<SeriesSchema>,
335 frame_schema: SchemaRef,
337 pass_through: Option<SchemaRef>,
340 properties: Arc<PlanProperties>,
341 per_series_scan: bool,
342}
343
344fn pass_through_frame(
357 child_plan: &Arc<dyn ExecutionPlan>,
358 child: &SchemaRef,
359 series_schema: &Arc<SeriesSchema>,
360) -> Option<SchemaRef> {
361 let mut node = child_plan.as_ref();
365 loop {
366 if node.downcast_ref::<SeriesScanExec>().is_some() {
367 break;
368 }
369 node = node.downcast_ref::<CooperativeExec>()?.input().as_ref();
370 }
371 let declaration = SeriesFrameDeclaration::parse(child.as_ref()).ok()?;
372 if declaration.content() != FrameContent::Raw
373 || declaration.labels() != FrameLabelMode::Explicit
374 || declaration.label_decode().is_some()
375 {
376 return None;
377 }
378 let ordering = series_frame_ordering(child.as_ref()).ok()?;
379 if ordering == SeriesOrdering::Interleaved {
380 return None;
381 }
382 let canonical =
386 frame_schema_with(series_schema, FrameLabelMode::Explicit, None, ordering).ok()?;
387 (*canonical == **child).then(|| Arc::clone(child))
388}
389
390impl RawSeriesSourceExec {
391 fn try_new_with_provenance(
392 input: Arc<dyn ExecutionPlan>,
393 metric_name: Arc<str>,
394 fields: Vec<String>,
395 per_series_scan: bool,
396 ) -> DataFusionResult<Self> {
397 let per_series_scan = per_series_scan && is_series_scan(input.as_ref());
398 let series_schema = series_schema(&fields);
399 let partition_count = input.properties().partitioning.partition_count();
400 if partition_count == 0 {
401 return Err(DataFusionError::Plan(
402 "RawSeriesSourceExec child has zero partitions".to_string(),
403 ));
404 }
405 unpack_raw_series(
408 Box::pin(RecordBatchStreamAdapter::new(
409 input.schema(),
410 futures::stream::empty(),
411 )),
412 Some(Arc::clone(&series_schema)),
413 )?;
414 let published_frame = frame_schema(&fields)?;
415 let pass_through = pass_through_frame(&input, &input.schema(), &series_schema);
418 let properties = Arc::new(PlanProperties::new(
419 EquivalenceProperties::new(Arc::clone(&published_frame)),
420 Partitioning::UnknownPartitioning(partition_count),
421 EmissionType::Incremental,
422 Boundedness::Bounded,
423 ));
424 Ok(Self {
425 input,
426 metric_name,
427 series_schema,
428 frame_schema: published_frame,
429 pass_through,
430 properties,
431 per_series_scan,
432 })
433 }
434
435 pub fn is_per_series_scan(&self) -> bool {
441 self.per_series_scan
442 }
443
444 fn child_frames(
449 &self,
450 partition: usize,
451 context: Arc<TaskContext>,
452 ) -> DataFusionResult<SendableRecordBatchStream> {
453 let partition_count = self.properties.partitioning.partition_count();
454 if partition >= partition_count {
455 return Err(DataFusionError::Execution(format!(
456 "RawSeriesSourceExec partition {partition} is out of bounds for {partition_count} partitions"
457 )));
458 }
459 self.input.execute(partition, context)
460 }
461}
462
463impl DisplayAs for RawSeriesSourceExec {
464 fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
465 write!(
466 f,
467 "RawSeriesSourceExec: metric={}, fields={}",
468 self.metric_name,
469 self.series_schema.fields.len()
470 )
471 }
472}
473
474impl ExecutionPlan for RawSeriesSourceExec {
475 fn name(&self) -> &str {
476 "RawSeriesSourceExec"
477 }
478
479 fn properties(&self) -> &Arc<PlanProperties> {
480 &self.properties
481 }
482
483 fn input_distribution_requirements(&self) -> InputDistributionRequirements {
486 InputDistributionRequirements::new(vec![Distribution::UnspecifiedDistribution])
487 }
488
489 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
490 vec![false]
491 }
492
493 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
494 vec![&self.input]
495 }
496
497 fn apply_expressions(
498 &self,
499 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
500 ) -> DataFusionResult<TreeNodeRecursion> {
501 Ok(TreeNodeRecursion::Continue)
502 }
503
504 fn with_new_children(
505 self: Arc<Self>,
506 mut children: Vec<Arc<dyn ExecutionPlan>>,
507 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
508 if children.len() != 1 {
509 return Err(DataFusionError::Plan(format!(
510 "RawSeriesSourceExec requires one child, got {}",
511 children.len()
512 )));
513 }
514 let fields = self
515 .series_schema
516 .fields
517 .iter()
518 .map(|field| field.name.to_string())
519 .collect();
520 Ok(Arc::new(Self::try_new_with_provenance(
521 children.swap_remove(0),
522 Arc::clone(&self.metric_name),
523 fields,
524 self.per_series_scan,
525 )?))
526 }
527
528 fn execute(
529 &self,
530 partition: usize,
531 context: Arc<TaskContext>,
532 ) -> DataFusionResult<SendableRecordBatchStream> {
533 if let Some(child_schema) = &self.pass_through {
534 let frames = self.child_frames(partition, context)?;
539 let declared = Arc::clone(&self.frame_schema);
540 let child_schema = Arc::clone(child_schema);
541 let batches = frames.map(move |batch| {
542 let batch = batch?;
543 if batch.schema() != child_schema {
544 return Err(DataFusionError::Execution(
545 "raw frame schema mismatch".to_string(),
546 ));
547 }
548 RecordBatch::try_new(Arc::clone(&declared), batch.columns().to_vec())
549 .map_err(DataFusionError::from)
550 });
551 return Ok(Box::pin(RecordBatchStreamAdapter::new(
552 Arc::clone(&self.frame_schema),
553 batches,
554 )));
555 }
556 pack_raw_series_with(
562 Box::pin(DeclaredSeries {
563 chunks: self.execute_series(partition, context)?,
564 schema: Arc::clone(&self.series_schema),
565 }),
566 PendingBatching::Deadline,
567 )
568 }
569}
570
571impl SeriesExecutionPlan for RawSeriesSourceExec {
572 fn as_any(&self) -> &dyn Any {
573 self
574 }
575
576 fn execute_series(
583 &self,
584 partition: usize,
585 context: Arc<TaskContext>,
586 ) -> DataFusionResult<SendableSeriesStream> {
587 let frames = self.child_frames(partition, context)?;
588 let raw = unpack_raw_series(frames, Some(Arc::clone(&self.series_schema)))?;
589 let relabelled = materialize_raw_labels(raw)
590 .map_err(|error| DataFusionError::External(Box::new(error)))?;
591 Ok(relabelled
595 .map(|chunk| chunk.map(|chunk| HandedSeriesChunk::uncharged(SeriesChunk::Raw(chunk))))
596 .boxed())
597 }
598}
599
600#[cfg(test)]
601pub(crate) mod tests {
602 use api::v1::SemanticType;
603 use common_query::series_frame::label_decode_spec;
604 use common_recordbatch::EmptyRecordBatchStream;
605 use datafusion::arrow::array::Float64Array;
606 use datafusion::arrow::buffer::{Buffer, ScalarBuffer};
607 use datafusion::arrow::datatypes::{DataType, Schema as ArrowSchema};
608 use datafusion::datasource::memory::MemorySourceConfig;
609 use datafusion::datasource::source::DataSourceExec;
610 use datafusion::logical_expr::EmptyRelation;
611 use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
612 use datafusion::physical_plan::execution_plan::{
613 ChildrenPropertiesMode, ReplaceChildrenOptions,
614 };
615 use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
616 use datafusion::prelude::SessionContext;
617 use datatypes::data_type::ConcreteDataType;
618 use datatypes::prelude::Value;
619 use datatypes::schema::{ColumnSchema, SchemaRef as DatatypesSchemaRef};
620 use datatypes::series::frame::{
621 LABEL_DECODE_VERSION, LabelDecodeColumn, LabelDecodeEncoding, LabelDecodeTag,
622 pack_raw_series_chunk,
623 };
624 use datatypes::series::raw::RawTimestamps;
625 use datatypes::series::samples::{Samples, SeriesFields};
626 use datatypes::series::time::{EvalGrid, GridSpec};
627 use datatypes::series::{Label, SeriesLabels};
628 use futures::TryStreamExt;
629 use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodec, SortField};
630 use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
631 use store_api::region_engine::{
632 BoundTag, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
633 SendableRawSeriesStream,
634 };
635 use store_api::storage::{RegionId, ScanRequest};
636 use table::table::scan::RegionScanExec;
637
638 use super::*;
639
640 const FIXTURE: &str =
641 include_str!("../../../../tests/compatibility/wire/raw_series_source/v1_payload.hex");
642
643 const FIELD: &str = "value";
645
646 fn declared_fields() -> Vec<String> {
647 vec![FIELD.to_string()]
648 }
649
650 fn fixture_bytes() -> Vec<u8> {
651 let hex = FIXTURE.trim().as_bytes();
652 assert_eq!(hex.len() % 2, 0);
653 hex.as_chunks::<2>()
654 .0
655 .iter()
656 .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
657 .collect()
658 }
659
660 #[test]
661 fn raw_series_source_wire_fixture() {
662 let bytes = fixture_bytes();
663 let source = RawSeriesSource::deserialize(&bytes).unwrap();
664 assert_eq!(source.metric_name(), "http_requests_total");
665 assert_eq!(source.tags(), ["z", "a"]);
666 assert_eq!(source.fields(), ["value_b", "value_a"]);
667 assert_eq!(source.serialize(), bytes);
668 assert!(matches!(
669 source.inputs()[0],
670 LogicalPlan::EmptyRelation(EmptyRelation {
671 produce_one_row: false,
672 ..
673 })
674 ));
675
676 let field = source.schema().field_with_name(None, "fields").unwrap();
677 let DataType::Struct(fields) = field.data_type() else {
678 panic!("expected struct field in frame schema");
679 };
680 assert_eq!(
681 fields
682 .iter()
683 .map(|field| field.name().as_str())
684 .collect::<Vec<_>>(),
685 ["value_b", "value_a"]
686 );
687
688 let child = LogicalPlan::EmptyRelation(EmptyRelation {
689 produce_one_row: true,
690 schema: Arc::new(DFSchema::empty()),
691 });
692 let rebound = source
693 .with_exprs_and_inputs(vec![], vec![child.clone()])
694 .unwrap();
695 assert_eq!(rebound.inputs(), vec![&child]);
696 assert_eq!(rebound.schema(), source.schema());
697 assert_eq!(rebound.serialize(), bytes);
698 assert!(source.with_exprs_and_inputs(vec![], vec![]).is_err());
699 assert!(
700 source
701 .with_exprs_and_inputs(vec![], vec![child.clone(), child])
702 .is_err()
703 );
704 }
705
706 #[test]
707 fn raw_series_source_wire_rejects_unsupported_and_truncated_payloads() {
708 let fixture = fixture_bytes();
709 for version in [0, 2] {
710 let mut bytes = fixture.clone();
711 bytes[1] = version;
712 let error = RawSeriesSource::deserialize(&bytes).unwrap_err();
713 assert!(
714 error
715 .to_string()
716 .contains("Unsupported RawSeriesSource version")
717 );
718 }
719 let error = RawSeriesSource::deserialize(&fixture[..fixture.len() - 1]).unwrap_err();
720 assert!(
721 error
722 .to_string()
723 .contains("Failed to deserialize RawSeriesSource")
724 );
725
726 let mut bytes = fixture;
728 bytes.extend([0x28, 0x01]);
729 assert!(RawSeriesSource::deserialize(&bytes).is_ok());
730 }
731
732 fn region_metadata() -> RegionMetadataRef {
734 let mut builder = RegionMetadataBuilder::new(RegionId::new(1024, 1));
735 builder
736 .push_column_metadata(ColumnMetadata {
737 column_schema: ColumnSchema::new(
738 "host",
739 ConcreteDataType::string_datatype(),
740 false,
741 ),
742 semantic_type: SemanticType::Tag,
743 column_id: 1,
744 })
745 .push_column_metadata(ColumnMetadata {
746 column_schema: ColumnSchema::new(
747 "ts",
748 ConcreteDataType::timestamp_millisecond_datatype(),
749 false,
750 )
751 .with_time_index(true),
752 semantic_type: SemanticType::Timestamp,
753 column_id: 2,
754 })
755 .push_column_metadata(ColumnMetadata {
756 column_schema: ColumnSchema::new(FIELD, ConcreteDataType::float64_datatype(), true),
757 semantic_type: SemanticType::Field,
758 column_id: 3,
759 })
760 .primary_key(vec![1]);
761 Arc::new(builder.build().expect("the fixture metadata is valid"))
762 }
763
764 fn per_series_labels() -> RawLabelSource {
767 RawLabelSource::PrimaryKey {
768 metric_name: Arc::from("cpu"),
769 physical_metadata: region_metadata(),
770 logical_tags: Arc::from([BoundTag {
771 column_id: 1,
772 name: Arc::from("host"),
773 }]),
774 }
775 }
776
777 struct RawSeriesScanner {
783 metadata: RegionMetadataRef,
784 properties: ScannerProperties,
785 chunks: Vec<RawSeriesChunk>,
786 explicit_labels: bool,
787 ordering: SeriesOrdering,
788 }
789
790 struct RawChunks {
792 schema: Arc<SeriesSchema>,
793 label_source: RawLabelSource,
794 label_decode_spec: Option<LabelDecodeSpec>,
795 ordering: SeriesOrdering,
796 chunks: Vec<RawSeriesChunk>,
797 }
798
799 impl Stream for RawChunks {
800 type Item = Result<RawSeriesChunk, BoxedError>;
801
802 fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
803 Poll::Ready((!self.chunks.is_empty()).then(|| Ok(self.chunks.remove(0))))
804 }
805 }
806
807 impl RawSeriesStream for RawChunks {
808 fn schema(&self) -> &Arc<SeriesSchema> {
809 &self.schema
810 }
811
812 fn label_source(&self) -> &RawLabelSource {
813 &self.label_source
814 }
815
816 fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> {
817 self.label_decode_spec.as_ref()
818 }
819
820 fn ordering(&self) -> SeriesOrdering {
821 self.ordering
822 }
823 }
824
825 impl fmt::Debug for RawSeriesScanner {
826 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
827 write!(f, "RawSeriesScanner")
828 }
829 }
830
831 impl DisplayAs for RawSeriesScanner {
832 fn fmt_as(&self, _format: DisplayFormatType, f: &mut Formatter<'_>) -> fmt::Result {
833 write!(f, "RawSeriesScanner")
834 }
835 }
836
837 impl RegionScanner for RawSeriesScanner {
838 fn name(&self) -> &str {
839 "RawSeriesScanner"
840 }
841
842 fn properties(&self) -> &ScannerProperties {
843 &self.properties
844 }
845
846 fn schema(&self) -> DatatypesSchemaRef {
847 Arc::clone(&self.metadata.schema)
848 }
849
850 fn metadata(&self) -> RegionMetadataRef {
851 Arc::clone(&self.metadata)
852 }
853
854 fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
855 self.properties.prepare(request);
856 Ok(())
857 }
858
859 fn scan_partition(
860 &self,
861 _ctx: &QueryScanContext,
862 _metrics: &ExecutionPlanMetricsSet,
863 _partition: usize,
864 ) -> Result<common_recordbatch::SendableRecordBatchStream, BoxedError> {
865 Ok(Box::pin(EmptyRecordBatchStream::new(Arc::clone(
866 &self.metadata.schema,
867 ))))
868 }
869
870 fn raw_series_schema(
871 &self,
872 _label_source: &RawLabelSource,
873 ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
874 Ok(Some(series_schema(&declared_fields())))
875 }
876
877 fn raw_series_has_explicit_labels(
878 &self,
879 _label_source: &RawLabelSource,
880 ) -> Result<bool, BoxedError> {
881 Ok(self.explicit_labels)
882 }
883
884 fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
885 Ok(self.ordering)
886 }
887
888 fn scan_series_partition(
889 &self,
890 _ctx: &QueryScanContext,
891 _metrics: &ExecutionPlanMetricsSet,
892 _partition: usize,
893 label_source: &RawLabelSource,
894 ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
895 Ok(Some(Box::pin(RawChunks {
896 schema: series_schema(&declared_fields()),
897 label_source: label_source.clone(),
898 label_decode_spec: if self.explicit_labels {
901 None
902 } else {
903 label_decode_spec(label_source)
904 },
905 ordering: self.ordering,
906 chunks: self.chunks.clone(),
907 })))
908 }
909
910 fn has_predicate_without_region(&self) -> bool {
911 true
912 }
913
914 fn add_dyn_filter_to_predicate(
915 &mut self,
916 filter_exprs: Vec<Arc<dyn PhysicalExpr>>,
917 ) -> Vec<bool> {
918 vec![false; filter_exprs.len()]
919 }
920
921 fn set_logical_region(&mut self, logical_region: bool) {
922 self.properties.set_logical_region(logical_region);
923 }
924
925 fn set_query_load_region_id(&mut self, region_id: RegionId) {
926 self.properties.set_query_load_region_id(region_id);
927 }
928 }
929
930 pub(crate) fn per_series_scan(partitions: usize) -> Arc<dyn ExecutionPlan> {
932 per_series_scan_with(partitions, Vec::new(), false, SeriesOrdering::Contiguous)
933 }
934
935 fn per_series_scan_with(
938 partitions: usize,
939 chunks: Vec<RawSeriesChunk>,
940 explicit_labels: bool,
941 ordering: SeriesOrdering,
942 ) -> Arc<dyn ExecutionPlan> {
943 let scanner = RawSeriesScanner {
944 metadata: region_metadata(),
945 properties: ScannerProperties::new(vec![vec![]; partitions], false, 0),
946 chunks,
947 explicit_labels,
948 ordering,
949 };
950 let scan = Arc::new(
951 RegionScanExec::new(Box::new(scanner), ScanRequest::default(), None)
952 .expect("the fixture scanner scans"),
953 );
954 scan.try_to_series_scan(per_series_labels())
955 .expect("the fixture binding is legal")
956 .expect("the fixture scanner answers raw series")
957 }
958
959 pub(crate) fn raw_source(child: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {
961 let fields = declared_fields();
962 RawSeriesSource::try_new(
963 Arc::from("cpu"),
964 vec!["host".to_string()],
965 fields.clone(),
966 LogicalPlan::EmptyRelation(EmptyRelation {
967 produce_one_row: false,
968 schema: Arc::new(
969 DFSchema::try_from(frame_schema(&fields).expect("the frame is legal"))
970 .expect("the frame is a legal schema"),
971 ),
972 }),
973 )
974 .expect("the source binds one metric")
975 .to_per_series_execution_plan(child)
976 .expect("the child is a raw frame of these fields")
977 }
978
979 fn provenance(plan: &Arc<dyn ExecutionPlan>) -> bool {
980 plan.downcast_ref::<RawSeriesSourceExec>()
981 .expect("the fixture root is the region's raw source")
982 .is_per_series_scan()
983 }
984
985 fn rebuilt_over(
987 plan: &Arc<dyn ExecutionPlan>,
988 child: Arc<dyn ExecutionPlan>,
989 ) -> Arc<dyn ExecutionPlan> {
990 Arc::clone(plan)
991 .replace_children(
992 vec![child],
993 ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
994 )
995 .expect("the child is still a raw frame of these fields")
996 }
997
998 #[test]
999 fn a_cooperative_child_keeps_the_per_series_provenance() {
1000 let root = raw_source(per_series_scan(2));
1001 assert!(provenance(&root), "the fixture root is the per-series case");
1002
1003 let cooperative: Arc<dyn ExecutionPlan> =
1006 Arc::new(CooperativeExec::new(per_series_scan(2)));
1007 let rebuilt = rebuilt_over(&root, Arc::clone(&cooperative));
1008 assert_eq!(
1009 2,
1010 rebuilt.properties().output_partitioning().partition_count()
1011 );
1012 assert!(
1013 provenance(&rebuilt),
1014 "a cooperative wrapper passes rows through unchanged, so the scan is still per-series"
1015 );
1016
1017 let nested: Arc<dyn ExecutionPlan> = Arc::new(CooperativeExec::new(cooperative));
1019 assert!(
1020 provenance(&rebuilt_over(&root, nested)),
1021 "wrappers nest without moving rows"
1022 );
1023 }
1024
1025 #[test]
1026 fn a_child_that_moves_rows_loses_the_per_series_provenance() {
1027 let root = raw_source(per_series_scan(2));
1028 let coalesced: Arc<dyn ExecutionPlan> =
1031 Arc::new(CoalescePartitionsExec::new(per_series_scan(2)));
1032 assert!(
1033 !provenance(&rebuilt_over(&root, coalesced)),
1034 "the provenance stops at the scan, not at whatever node carries its frames"
1035 );
1036 }
1037
1038 fn labels_of(host: &str) -> SeriesLabels {
1040 SeriesLabels::try_new(
1041 Some(Arc::from("cpu")),
1042 vec![Label {
1043 name: Arc::from("host"),
1044 value: Arc::from(host),
1045 }],
1046 )
1047 .expect("the fixture labels are legal")
1048 }
1049
1050 fn fixture_labels() -> SeriesLabels {
1052 labels_of("a")
1053 }
1054
1055 fn host_decode() -> LabelDecodeSpec {
1057 LabelDecodeSpec {
1058 version: LABEL_DECODE_VERSION,
1059 metric_name: "cpu".to_string(),
1060 encoding: LabelDecodeEncoding::Dense,
1061 primary_key: vec![LabelDecodeColumn {
1062 column_id: 1,
1063 name: "host".to_string(),
1064 physical_type: ConcreteDataType::string_datatype(),
1065 }],
1066 logical_tags: vec![LabelDecodeTag {
1067 column_id: 1,
1068 name: "host".to_string(),
1069 }],
1070 }
1071 }
1072
1073 fn key_of(host: &str) -> Buffer {
1075 let mut bytes = Vec::new();
1076 DensePrimaryKeyCodec::with_fields(vec![(
1077 1,
1078 SortField::new(ConcreteDataType::string_datatype()),
1079 )])
1080 .encode_values(&[(1, Value::String(host.into()))], &mut bytes)
1081 .expect("a dense key of one string");
1082 Buffer::from(bytes)
1083 }
1084
1085 fn host_key() -> Buffer {
1087 key_of("a")
1088 }
1089
1090 fn series_chunk(host: &str, times: &[i64], is_last: bool) -> RawSeriesChunk {
1095 let values = vec![Some(1.0); times.len()];
1096 RawSeriesChunk::try_new(
1097 &series_schema(&declared_fields()),
1098 key_of(host),
1099 Some(labels_of(host)),
1100 RawTimestamps::try_new(ScalarBuffer::from(times.to_vec()))
1101 .expect("ascending timestamps"),
1102 SeriesFields::try_from_vec(vec![Samples::from_float(Float64Array::from(values))])
1103 .expect("one sample per timestamp per field"),
1104 is_last,
1105 )
1106 .expect("a legal raw chunk")
1107 }
1108
1109 fn fixture_chunk(metric: Option<SeriesLabels>) -> RawSeriesChunk {
1111 RawSeriesChunk::try_new(
1112 &series_schema(&declared_fields()),
1113 host_key(),
1114 metric,
1115 RawTimestamps::try_new(ScalarBuffer::from(vec![1000i64, 2000, 3000]))
1116 .expect("ascending timestamps"),
1117 SeriesFields::try_from_vec(vec![Samples::from_float(Float64Array::from(vec![
1118 Some(1.0),
1119 Some(2.5),
1120 None,
1121 ]))])
1122 .expect("one sample per timestamp per field"),
1123 true,
1124 )
1125 .expect("a legal raw chunk")
1126 }
1127
1128 fn root_frame(fields: &[String]) -> SchemaRef {
1130 frame_schema(fields).expect("the fixture frame is legal")
1131 }
1132
1133 fn child_frame(decode: Option<&LabelDecodeSpec>, ordering: SeriesOrdering) -> SchemaRef {
1135 let schema = series_schema(&declared_fields());
1136 let (labels, decode) = match decode {
1137 Some(decode) => (FrameLabelMode::Key, Some(decode)),
1138 None => (FrameLabelMode::Explicit, None),
1139 };
1140 frame_schema_with(&schema, labels, decode, ordering)
1141 .expect("the fixture declares one frame")
1142 }
1143
1144 fn frame_batch(
1146 chunk: &RawSeriesChunk,
1147 decode: Option<&LabelDecodeSpec>,
1148 frame: &SchemaRef,
1149 ) -> RecordBatch {
1150 let labels = match decode {
1151 Some(_) => FrameLabelMode::Key,
1152 None => FrameLabelMode::Explicit,
1153 };
1154 let packed =
1155 pack_raw_series_chunk(&series_schema(&declared_fields()), labels, decode, chunk)
1156 .expect("the fixture chunk packs");
1157 assert_eq!(1, packed.len(), "one chunk is one frame row");
1158 RecordBatch::try_new(Arc::clone(frame), packed[0].columns().to_vec())
1159 .expect("the packed columns match the declared frame")
1160 }
1161
1162 fn framed_child(frame: SchemaRef, batches: Vec<RecordBatch>) -> Arc<dyn ExecutionPlan> {
1164 Arc::new(DataSourceExec::new(Arc::new(
1165 MemorySourceConfig::try_new(&[batches], frame, None)
1166 .expect("the fixture batches match their frame"),
1167 )))
1168 }
1169
1170 async fn publish(root: &Arc<dyn ExecutionPlan>) -> Vec<RecordBatch> {
1172 let published = root
1173 .execute(0, SessionContext::default().task_ctx())
1174 .expect("the fixture root has one partition");
1175 published.try_collect().await.expect("the frame publishes")
1176 }
1177
1178 async fn publish_error(root: &Arc<dyn ExecutionPlan>) -> String {
1180 let mut stream = root
1181 .execute(0, SessionContext::default().task_ctx())
1182 .expect("the fixture root has one partition");
1183 loop {
1184 match stream.try_next().await {
1185 Ok(Some(_)) => continue,
1186 Ok(None) => panic!("the malformed sequence was published instead of rejected"),
1187 Err(error) => return error.to_string(),
1188 }
1189 }
1190 }
1191
1192 fn forwarded_frame_of(plan: &Arc<dyn ExecutionPlan>) -> Option<SchemaRef> {
1194 plan.downcast_ref::<RawSeriesSourceExec>()
1195 .expect("the fixture root is the region's raw source")
1196 .pass_through
1197 .clone()
1198 }
1199
1200 #[test]
1207 fn only_a_scan_chain_is_trusted_to_forward_its_frames() {
1208 let schema = series_schema(&declared_fields());
1209 let canonical = child_frame(None, SeriesOrdering::KeyThenTime);
1210
1211 let memory = framed_child(Arc::clone(&canonical), Vec::new());
1212 assert!(
1213 pass_through_frame(&memory, &canonical, &schema).is_none(),
1214 "an identical frame from an unverified producer still needs decoding"
1215 );
1216
1217 let scan = per_series_scan_with(1, Vec::new(), true, SeriesOrdering::KeyThenTime);
1218 let scan_frame = scan.schema();
1219 assert_eq!(
1220 canonical.as_ref(),
1221 scan_frame.as_ref(),
1222 "the scan writes the very frame the unverified child was refused for"
1223 );
1224 assert!(
1225 pass_through_frame(&scan, &scan_frame, &schema).is_some(),
1226 "the scan validated its own chunks while packing them"
1227 );
1228
1229 let wrapped: Arc<dyn ExecutionPlan> = Arc::new(CooperativeExec::new(scan));
1230 let wrapped_frame = wrapped.schema();
1231 assert!(
1232 pass_through_frame(&wrapped, &wrapped_frame, &schema).is_some(),
1233 "a cooperative wrapper moves rows, not series, so the scan's validation still holds"
1234 );
1235
1236 let coalesced: Arc<dyn ExecutionPlan> =
1237 Arc::new(CoalescePartitionsExec::new(per_series_scan(2)));
1238 let coalesced_frame = coalesced.schema();
1239 assert!(
1240 pass_through_frame(&coalesced, &coalesced_frame, &schema).is_none(),
1241 "a node that merges partitions may hand rows on in any order, so it is not a scan"
1242 );
1243 }
1244
1245 #[tokio::test]
1252 async fn a_per_series_scan_frame_is_published_without_decoding_it() {
1253 let scan = per_series_scan_with(
1254 1,
1255 vec![series_chunk("a", &[1000, 2000], true)],
1256 true,
1257 SeriesOrdering::KeyThenTime,
1258 );
1259 let root = raw_source(Arc::clone(&scan));
1260 assert!(
1261 forwarded_frame_of(&root).is_some(),
1262 "the scan's frame is forwarded"
1263 );
1264
1265 let published = publish(&root).await;
1266 assert_eq!(
1267 SeriesOrdering::KeyThenTime,
1268 series_frame_ordering(scan.schema().as_ref()).expect("a declared ordering"),
1269 "the scan promises key-then-time"
1270 );
1271 assert_eq!(1, published.len(), "one batch in, one batch out");
1272 assert_eq!(
1273 root.schema().as_ref(),
1274 published[0].schema().as_ref(),
1275 "the batch is published under this node's own frame"
1276 );
1277 assert_eq!(
1278 SeriesOrdering::Contiguous,
1279 series_frame_ordering(published[0].schema().as_ref()).expect("a declared ordering"),
1280 "the scan's finer promise is exchanged for this node's own"
1281 );
1282
1283 let scan_batches = publish(&scan).await;
1286 assert_eq!(1, scan_batches.len(), "the scan publishes one batch");
1287 let re_declared = RecordBatch::try_new(
1288 root_frame(&declared_fields()),
1289 scan_batches[0].columns().to_vec(),
1290 )
1291 .expect("the same columns under this node's frame");
1292 assert_eq!(
1293 vec![re_declared],
1294 published,
1295 "forwarding re-declares a batch, it never rewrites one"
1296 );
1297 }
1298
1299 #[tokio::test]
1305 async fn an_unverified_child_keeps_the_pack_path_even_with_this_nodes_frame() {
1306 let frame = child_frame(None, SeriesOrdering::KeyThenTime);
1307 let payload = series_chunk("a", &[1000, 2000, 3000], true);
1308 let batch = frame_batch(&payload, None, &frame);
1309 let root = raw_source(framed_child(Arc::clone(&frame), vec![batch.clone()]));
1310 assert!(
1311 forwarded_frame_of(&root).is_none(),
1312 "a matching frame is not proof that its payload was validated"
1313 );
1314
1315 let published = publish(&root).await;
1316 let expected = frame_batch(&payload, None, &root_frame(&declared_fields()));
1317 assert_eq!(vec![expected], published);
1318 assert!(
1319 !Arc::ptr_eq(batch.column(0), published[0].column(0)),
1320 "the unverified child's columns are re-encoded, not forwarded"
1321 );
1322 }
1323
1324 #[tokio::test]
1331 async fn a_forwarded_frame_carries_what_the_decoded_path_publishes() {
1332 let chunks = vec![series_chunk("a", &[1000, 2000], true)];
1333
1334 let forwarded = publish(&raw_source(per_series_scan_with(
1335 1,
1336 chunks.clone(),
1337 true,
1338 SeriesOrdering::KeyThenTime,
1339 )))
1340 .await;
1341
1342 let decoded_frame = child_frame(None, SeriesOrdering::Interleaved);
1343 let decoded = publish(&raw_source(framed_child(
1344 Arc::clone(&decoded_frame),
1345 chunks
1346 .iter()
1347 .map(|chunk| frame_batch(chunk, None, &decoded_frame))
1348 .collect(),
1349 )))
1350 .await;
1351
1352 assert_eq!(1, forwarded.len(), "the forwarded batch is not split");
1353 assert_eq!(1, decoded.len(), "the decoded path flushes one batch");
1354 assert_eq!(
1355 forwarded, decoded,
1356 "both paths publish the same frame, so the shortcut changes no byte"
1357 );
1358 }
1359
1360 #[tokio::test]
1367 async fn an_unverified_child_malformed_sequences_are_rejected() {
1368 struct Case {
1369 name: &'static str,
1370 chunks: Vec<RawSeriesChunk>,
1371 ordering: SeriesOrdering,
1372 error: &'static str,
1373 }
1374
1375 let cases = vec![
1376 Case {
1377 name: "a chain that never closes",
1378 chunks: vec![series_chunk("a", &[1000], false)],
1379 ordering: SeriesOrdering::Contiguous,
1380 error: "ended before key was final",
1381 },
1382 Case {
1383 name: "a key that recurs after its final chunk",
1384 chunks: vec![
1385 series_chunk("a", &[1000], true),
1386 series_chunk("a", &[2000], true),
1387 ],
1388 ordering: SeriesOrdering::Contiguous,
1389 error: "key recurred after final chunk",
1390 },
1391 Case {
1392 name: "a timestamp that goes back across chunks",
1393 chunks: vec![
1394 series_chunk("a", &[3000], false),
1395 series_chunk("a", &[2000], true),
1396 ],
1397 ordering: SeriesOrdering::Contiguous,
1398 error: "timestamps are not increasing across chunks",
1399 },
1400 Case {
1401 name: "a key that goes back under key-then-time order",
1402 chunks: vec![
1403 series_chunk("b", &[1000], true),
1404 series_chunk("a", &[2000], true),
1405 ],
1406 ordering: SeriesOrdering::KeyThenTime,
1407 error: "keys are not ordered",
1408 },
1409 ];
1410
1411 for case in cases {
1412 let name = case.name;
1413 let frame = child_frame(None, case.ordering);
1414 let batches = case
1415 .chunks
1416 .iter()
1417 .map(|chunk| frame_batch(chunk, None, &frame))
1418 .collect();
1419 let root = raw_source(framed_child(Arc::clone(&frame), batches));
1420 assert!(
1421 forwarded_frame_of(&root).is_none(),
1422 "{name}: an unverified producer is never forwarded"
1423 );
1424 let error = publish_error(&root).await;
1425 assert!(error.contains(case.error), "{name}: {error}");
1426 }
1427 }
1428
1429 #[tokio::test]
1434 async fn a_forwarded_scan_still_reports_a_malformed_sequence() {
1435 let root = raw_source(per_series_scan_with(
1436 1,
1437 vec![series_chunk("a", &[1000], false)],
1438 true,
1439 SeriesOrdering::Contiguous,
1440 ));
1441 assert!(
1442 forwarded_frame_of(&root).is_some(),
1443 "the scan's frame is forwarded"
1444 );
1445
1446 let error = publish_error(&root).await;
1447 assert!(error.contains("ended before key was final"), "{error}");
1448 }
1449
1450 #[tokio::test]
1455 async fn a_key_encoded_child_frame_is_decoded() {
1456 let decode = host_decode();
1457 let keyed_frame = child_frame(Some(&decode), SeriesOrdering::KeyThenTime);
1458 let keyed = frame_batch(&fixture_chunk(None), Some(&decode), &keyed_frame);
1459 let published = publish(&raw_source(framed_child(keyed_frame, vec![keyed]))).await;
1460
1461 let explicit_frame = child_frame(None, SeriesOrdering::Contiguous);
1462 let expected = frame_batch(
1463 &fixture_chunk(Some(fixture_labels())),
1464 None,
1465 &explicit_frame,
1466 );
1467 assert_eq!(
1468 vec![expected],
1469 published,
1470 "the decoded key publishes the explicit frame's own bytes"
1471 );
1472 }
1473
1474 #[tokio::test]
1479 async fn a_foreign_explicit_child_frame_keeps_the_pack_path() {
1480 let canonical = child_frame(None, SeriesOrdering::Contiguous);
1481 let mut metadata = canonical.metadata().clone();
1482 metadata.insert("application.note".to_string(), "foreign".to_string());
1483 let foreign = Arc::new(ArrowSchema::new_with_metadata(
1484 canonical.fields().clone(),
1485 metadata,
1486 ));
1487 let payload = fixture_chunk(Some(fixture_labels()));
1488 let batch = frame_batch(&payload, None, &foreign);
1489 let published = publish(&raw_source(framed_child(foreign, vec![batch.clone()]))).await;
1490
1491 assert_eq!(1, published.len());
1492 assert_eq!(
1493 root_frame(&declared_fields()).as_ref(),
1494 published[0].schema().as_ref(),
1495 "the published frame is this node's, not the child's"
1496 );
1497 assert!(
1498 !Arc::ptr_eq(batch.column(0), published[0].column(0)),
1499 "the child's columns are rewritten, not forwarded"
1500 );
1501 let expected = frame_batch(&payload, None, &root_frame(&declared_fields()));
1502 assert_eq!(vec![expected], published);
1503 }
1504
1505 #[test]
1507 fn a_non_raw_child_is_refused_before_the_plan_runs() {
1508 let evaluated = Arc::new(SeriesSchema {
1509 fields: series_schema(&declared_fields()).fields.clone(),
1510 eval_grid: Some(Arc::new(
1511 EvalGrid::try_new(GridSpec::try_new(0, 1_000, 2).expect("a legal grid"))
1512 .expect("a legal grid"),
1513 )),
1514 });
1515 let frame = frame_schema_with(
1516 &evaluated,
1517 FrameLabelMode::Explicit,
1518 None,
1519 SeriesOrdering::Contiguous,
1520 )
1521 .expect("an evaluated frame declares its grid");
1522 let error = RawSeriesSource::try_new(
1523 Arc::from("cpu"),
1524 vec!["host".to_string()],
1525 declared_fields(),
1526 LogicalPlan::EmptyRelation(EmptyRelation {
1527 produce_one_row: false,
1528 schema: Arc::new(DFSchema::empty()),
1529 }),
1530 )
1531 .expect("the source binds one metric")
1532 .to_per_series_execution_plan(framed_child(frame, vec![]))
1533 .expect_err("an evaluated child is not a raw frame");
1534 assert!(
1535 error.to_string().contains("expected a raw frame"),
1536 "the preflight decides, not the shortcut: {error}"
1537 );
1538 }
1539}