1use std::any::Any;
48use std::cmp::Ordering;
49use std::collections::VecDeque;
50use std::fmt::{self, Formatter};
51use std::hash::{Hash, Hasher};
52use std::pin::Pin;
53use std::sync::{Arc, Mutex};
54use std::task::{Context, Poll};
55
56use common_error::ext::BoxedError;
57use common_query::native_histogram::{
58 NativeHistogram, Span, build_histogram_array, native_histogram_value_type,
59};
60use common_query::promql_annotations::PromqlAnnotationCollector;
61use common_query::series_frame::{
62 SendableEvaluatedSeriesStream, SendableStateSeriesStream, ensure_frame_matches_label_source,
63 frame_schema_with, pack_aggregate_state, pack_evaluated_series, series_frame_ordering,
64 unpack_aggregate_state, unpack_evaluated_series, unpack_raw_series,
65};
66use common_recordbatch::adapter::{NATIVE_TREE_METRIC, NativeTreeMetric, NativeTreeMetrics};
67use datafusion::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray};
68use datafusion::arrow::buffer::ScalarBuffer;
69use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit};
70use datafusion::arrow::record_batch::RecordBatch;
71use datafusion::common::tree_node::TreeNodeRecursion;
72use datafusion::common::{DFSchema, DFSchemaRef};
73use datafusion::error::{DataFusionError, Result as DataFusionResult};
74use datafusion::execution::context::TaskContext;
75use datafusion::execution::memory_pool::{MemoryPool, MemoryReservation, UnboundedMemoryPool};
76use datafusion::logical_expr::{Expr, LogicalPlan, UserDefinedLogicalNodeCore};
77use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
78use datafusion::physical_plan::coop::CooperativeExec;
79use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
80use datafusion::physical_plan::metrics::{
81 ExecutionPlanMetricsSet, MetricBuilder, MetricValue, MetricsSet,
82};
83use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
84use datafusion::physical_plan::{
85 DisplayAs, DisplayFormatType, Distribution, ExecutionPlan, InputDistributionRequirements,
86 Partitioning, PlanProperties, RecordBatchStream, SendableRecordBatchStream,
87};
88use datatypes::data_type::DataType as _;
89use datatypes::schema::ColumnSchema;
90use datatypes::series::SeriesOrdering;
91use datatypes::series::frame::{
92 FrameContent, FrameLabelMode, SeriesFrameDeclaration, aggregate_state_frame_schema,
93};
94use datatypes::series::histogram::{BucketSideView, HistogramView};
95use datatypes::series::raw::RawSeriesChunk;
96use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, Samples, SeriesSchema};
97use datatypes::series::time::{EvalGrid, GridSpec};
98use futures::stream::SelectAll;
99use futures::{Stream, StreamExt};
100use store_api::region_engine::RawLabelSource;
101use table::table::scan::SeriesScanExec;
102
103use crate::evaluated::EvaluatedChunk;
104use crate::extension_plan::series_execution::{
105 HandedSeriesChunk, SendableSeriesStream, SeriesCharge, SeriesChunk, SeriesExecutionPlan,
106 checked_series_stream, series_execution_plan,
107};
108use crate::extension_plan::series_repartition::SeriesRepartitionExec;
109use crate::extension_plan::{RawSeriesSourceExec, SeriesRouting};
110use crate::grid_series::METADATA_LABELS;
111use crate::histogram_eval::HISTOGRAM_ROUTING_EXCLUDED_LABELS;
112use crate::native::execute::{InputId, NativeExecutionState, NativeExecutor, SourceFacts};
113use crate::native::metrics::NodeMetricsSnapshot;
114use crate::native::plan::{
115 AggregateStage, AggregateStateSchema, BoundInput, BoundMap, Grouping, InstantValue, MapOp,
116 NativeExpr, NativeNode, NativeTree, NativeType, reads_across_series,
117};
118use crate::native::state::{StateChunk, state_row_from_frame_row};
119use crate::source::materialize_raw_labels;
120use crate::vector_match::{BinaryMatching, BinaryOp, DuplicateEvidence, MatchingLabels};
121
122#[cfg(test)]
123mod tests;
124
125const METRIC_NAME: &str = "__name__";
127
128const POLL_BUDGET: usize = 64;
137
138#[derive(Clone, Debug)]
149pub struct FusedSeriesBinding {
150 pub grid: Arc<EvalGrid>,
152 pub metric_name: Option<Arc<str>>,
161 pub time_index: String,
163 pub tags: Vec<String>,
168}
169
170impl PartialEq for FusedSeriesBinding {
171 fn eq(&self, other: &Self) -> bool {
172 self.metric_name == other.metric_name
173 && self.time_index == other.time_index
174 && self.tags == other.tags
175 && self.grid.spec() == other.grid.spec()
176 }
177}
178
179impl Eq for FusedSeriesBinding {}
180
181impl Hash for FusedSeriesBinding {
182 fn hash<H: Hasher>(&self, state: &mut H) {
183 self.metric_name.hash(state);
184 self.time_index.hash(state);
185 self.tags.hash(state);
186 let spec = self.grid.spec();
187 (spec.start_ms, spec.step_ms, spec.len).hash(state);
188 }
189}
190
191impl PartialOrd for FusedSeriesBinding {
192 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
193 Some(
194 (
195 self.metric_name.as_deref(),
196 &self.time_index,
197 &self.tags,
198 self.grid.spec().start_ms,
199 self.grid.spec().step_ms,
200 self.grid.spec().len,
201 )
202 .cmp(&(
203 other.metric_name.as_deref(),
204 &other.time_index,
205 &other.tags,
206 other.grid.spec().start_ms,
207 other.grid.spec().step_ms,
208 other.grid.spec().len,
209 )),
210 )
211 }
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219enum FusedInputKind {
220 Raw,
221 Evaluated,
222 AggregateState,
223}
224
225impl FusedInputKind {
226 fn from_native_type(native_type: &NativeType) -> DataFusionResult<Self> {
227 match native_type {
228 NativeType::Samples(schema) if schema.eval_grid.is_none() => Ok(Self::Raw),
229 NativeType::Samples(_) => Ok(Self::Evaluated),
230 NativeType::AggregateState(_) => Ok(Self::AggregateState),
231 NativeType::Scalar(_) => Err(DataFusionError::Plan(
232 "FusedSeries scalar cannot be a source".into(),
233 )),
234 }
235 }
236}
237
238#[derive(
240 Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
241)]
242pub enum FusedOutputFormat {
243 PlainRows,
245 SeriesFrame,
247}
248
249fn evaluated_output(tree: &NativeTree) -> DataFusionResult<Arc<SeriesSchema>> {
250 match &tree.root().output {
251 NativeType::Samples(schema) if schema.eval_grid.is_some() => Ok(Arc::clone(schema)),
252 NativeType::Samples(_) => Err(DataFusionError::Plan(
253 "FusedSeries frame output requires evaluated samples with a grid".into(),
254 )),
255 NativeType::AggregateState(_) => Err(DataFusionError::Plan(
256 "FusedSeries frame output does not support an aggregate-state root".into(),
257 )),
258 NativeType::Scalar(_) => Err(DataFusionError::Plan(
259 "FusedSeries frame output does not support a scalar root".into(),
260 )),
261 }
262}
263
264fn state_frame_output_schema(tree: &NativeTree) -> DataFusionResult<SchemaRef> {
267 let NativeType::AggregateState(state) = &tree.root().output else {
268 return Err(DataFusionError::Plan(
269 "FusedSeries Partial root does not produce aggregate state".into(),
270 ));
271 };
272 let schema = Arc::new(SeriesSchema {
273 fields: state.accumulators.clone(),
274 eval_grid: Some(Arc::clone(&state.grid)),
275 });
276 let state_schema = datatypes::series::aggregate_state::AggregateStateSchema::try_new(
277 state.kind,
278 state.components.to_vec(),
279 )
280 .map_err(|error| {
281 DataFusionError::Plan(format!(
282 "FusedSeries cannot declare state frame schema: {error}"
283 ))
284 })?;
285 aggregate_state_frame_schema(&state_schema, &schema, FrameLabelMode::Explicit).map_err(
286 |error| {
287 DataFusionError::Plan(format!(
288 "FusedSeries cannot declare state frame schema: {error}"
289 ))
290 },
291 )
292}
293
294fn output_frame_schema(
295 tree: &NativeTree,
296 root_kind: FusedInputKind,
297) -> DataFusionResult<SchemaRef> {
298 match &tree.root().expr {
299 NativeExpr::Aggregate { op, .. }
300 if op.stage == crate::native::plan::AggregateStage::Partial =>
301 {
302 if root_kind != FusedInputKind::AggregateState {
303 return Err(DataFusionError::Plan(
304 "FusedSeries Partial root must produce aggregate state".into(),
305 ));
306 }
307 state_frame_output_schema(tree)
308 }
309 _ => series_frame_output_schema(evaluated_output(tree)?.as_ref()),
310 }
311}
312
313fn series_frame_output_schema(schema: &SeriesSchema) -> DataFusionResult<SchemaRef> {
314 frame_schema_with(
315 schema,
316 FrameLabelMode::Explicit,
317 None,
318 SeriesOrdering::Contiguous,
319 )
320 .map_err(|error| {
321 DataFusionError::Plan(format!("FusedSeries cannot declare frame schema: {error}"))
322 })
323}
324
325#[derive(Debug)]
331pub struct FusedSeries {
332 promql: Arc<str>,
334 tree: NativeTree,
336 binding: FusedSeriesBinding,
338 children: Vec<LogicalPlan>,
340 output_schema: DFSchemaRef,
342 format: FusedOutputFormat,
344 canonical_producer: bool,
354}
355
356fn canonical_evaluated_local_prefix(node: &NativeNode) -> bool {
357 match &node.expr {
358 NativeExpr::Input(input) => input
359 .output
360 .samples()
361 .is_some_and(|schema| schema.eval_grid.is_some()),
362 NativeExpr::Merge { input } => canonical_evaluated_local_prefix(input),
363 NativeExpr::Map { input, .. } | NativeExpr::Timestamp { input } => {
364 canonical_evaluated_local_prefix(input)
365 }
366 NativeExpr::ParameterizedMap {
367 input, parameters, ..
368 } => {
369 canonical_evaluated_local_prefix(input)
370 && parameters.iter().all(canonical_evaluated_local_prefix)
371 }
372 _ => false,
373 }
374}
375
376const FUSED_SERIES_ENVELOPE_VERSION: u32 = 1;
379
380#[derive(serde::Serialize, serde::Deserialize)]
381struct FusedSeriesPayload {
382 tree: NativeTree,
383 grid: GridSpec,
384 metric_name: Option<Arc<str>>,
385 time_index: String,
386 tags: Vec<String>,
387 format: FusedOutputFormat,
388 promql: Arc<str>,
389 output_schema: datafusion::arrow::datatypes::Schema,
390 #[serde(default)]
393 canonical_producer: bool,
394}
395
396impl FusedSeries {
397 pub fn serialize(&self) -> DataFusionResult<Vec<u8>> {
407 let payload = FusedSeriesPayload {
408 tree: self.tree.clone(),
409 grid: self.binding.grid.spec(),
410 metric_name: self.binding.metric_name.clone(),
411 time_index: self.binding.time_index.clone(),
412 tags: self.binding.tags.clone(),
413 format: self.format,
414 promql: Arc::clone(&self.promql),
415 output_schema: self.output_schema.as_arrow().clone(),
416 canonical_producer: self.canonical_producer,
417 };
418 let encoded = postcard::to_stdvec(&payload).map_err(|e| {
419 DataFusionError::Plan(format!("cannot serialize FusedSeries payload: {e}"))
420 })?;
421 let len = u32::try_from(encoded.len())
422 .map_err(|_| DataFusionError::Plan("FusedSeries payload too large".into()))?;
423 let mut out = Vec::with_capacity(8 + encoded.len());
424 out.extend(FUSED_SERIES_ENVELOPE_VERSION.to_le_bytes());
425 out.extend(len.to_le_bytes());
426 out.extend(encoded);
427 Ok(out)
428 }
429
430 pub fn deserialize(bytes: &[u8]) -> DataFusionResult<Self> {
433 if bytes.len() < 8 {
434 return Err(DataFusionError::Plan(
435 "truncated FusedSeries envelope".into(),
436 ));
437 }
438 let version = u32::from_le_bytes(bytes[..4].try_into().unwrap());
439 if version != FUSED_SERIES_ENVELOPE_VERSION {
440 return Err(DataFusionError::Plan(format!(
441 "unsupported FusedSeries envelope version {version}"
442 )));
443 }
444 let len = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize;
445 let end = 8usize
446 .checked_add(len)
447 .ok_or_else(|| DataFusionError::Plan("FusedSeries length overflow".into()))?;
448 if end != bytes.len() {
449 return Err(DataFusionError::Plan(if end > bytes.len() {
450 "truncated FusedSeries payload".into()
451 } else {
452 "trailing bytes in FusedSeries payload".into()
453 }));
454 }
455 let (payload, remainder) = postcard::take_from_bytes::<FusedSeriesPayload>(&bytes[8..])
456 .map_err(|e| {
457 DataFusionError::Plan(format!("cannot deserialize FusedSeries payload: {e}"))
458 })?;
459 if !remainder.is_empty() {
460 return Err(DataFusionError::Plan(
461 "trailing bytes in FusedSeries payload".into(),
462 ));
463 }
464 let FusedSeriesPayload {
465 tree,
466 grid,
467 metric_name,
468 time_index,
469 tags,
470 format,
471 promql,
472 output_schema,
473 canonical_producer: _,
474 } = payload;
475 let grid = Arc::new(
476 EvalGrid::try_deferred(grid)
477 .map_err(|e| DataFusionError::Plan(format!("invalid FusedSeries grid: {e}")))?,
478 );
479 let children = vec![
480 LogicalPlan::EmptyRelation(datafusion::logical_expr::EmptyRelation {
481 produce_one_row: false,
482 schema: Arc::new(datafusion::common::DFSchema::empty()),
483 });
484 collect_source_schemas(&tree)?.len()
485 ];
486 let binding = FusedSeriesBinding {
487 grid,
488 metric_name,
489 time_index,
490 tags,
491 };
492 if binding.tags.iter().any(|tag| tag == &binding.time_index) {
493 return Err(DataFusionError::Plan(
494 "tag column cannot be the time column".into(),
495 ));
496 }
497 let output_schema = Arc::new(datafusion::common::DFSchema::try_from(output_schema)?);
498 let canonical_producer = payload.canonical_producer;
499 let mut node =
500 Self::try_new_with_format(promql, tree, binding, children, output_schema, format)?;
501 if canonical_producer {
502 if !matches!(node.tree.root().expr, NativeExpr::Merge { .. }) {
503 return Err(DataFusionError::Plan(
504 "a canonical merge producer requires a merge at the tree's root".into(),
505 ));
506 }
507 node.canonical_producer = true;
508 }
509 if format == FusedOutputFormat::PlainRows {
512 let schema = Arc::new(node.output_schema.as_arrow().clone());
513 validate_plain_output_schema(
514 &schema,
515 &node.tree,
516 &node.output_tags()?,
517 &node.binding.time_index,
518 &node.promql,
519 )?;
520 }
521 Ok(node)
522 }
523
524 pub const fn name() -> &'static str {
526 "FusedSeries"
527 }
528
529 pub fn try_new(
531 promql: Arc<str>,
532 tree: NativeTree,
533 binding: FusedSeriesBinding,
534 children: Vec<LogicalPlan>,
535 output_schema: DFSchemaRef,
536 ) -> DataFusionResult<Self> {
537 Self::try_new_with_format(
538 promql,
539 tree,
540 binding,
541 children,
542 output_schema,
543 FusedOutputFormat::PlainRows,
544 )
545 }
546
547 pub fn try_new_state_export(
554 promql: Arc<str>,
555 tree: NativeTree,
556 binding: FusedSeriesBinding,
557 children: Vec<LogicalPlan>,
558 ) -> DataFusionResult<Self> {
559 let schema = state_frame_output_schema(&tree)?;
560 let output_schema = DFSchema::try_from(schema).map_err(|error| {
561 DataFusionError::Plan(format!(
562 "FusedSeries cannot declare its state schema: {error}"
563 ))
564 })?;
565 Self::try_new_with_format(
566 promql,
567 tree,
568 binding,
569 children,
570 Arc::new(output_schema),
571 FusedOutputFormat::SeriesFrame,
572 )
573 }
574
575 pub fn split_aggregate(
581 tree: &NativeTree,
582 time_index: &str,
583 ) -> DataFusionResult<Option<(NativeTree, NativeTree)>> {
584 let fields = crate::native::split::prefix_fields(tree)?;
585 let split = match crate::native::split::split(tree.root(), &fields, time_index) {
586 Ok(Some(split)) => split,
587 Ok(None) => return Ok(None),
588 Err(DataFusionError::NotImplemented(_)) => return Ok(None),
591 Err(error) => return Err(error),
592 };
593 Ok(split
594 .into_trees()?
595 .map(|trees| (trees.partial, trees.final_tree)))
596 }
597
598 pub fn series_frame_schema(tree: &NativeTree) -> DataFusionResult<SchemaRef> {
600 series_frame_output_schema(evaluated_output(tree)?.as_ref())
601 }
602
603 pub fn try_new_with_format(
605 promql: Arc<str>,
606 tree: NativeTree,
607 binding: FusedSeriesBinding,
608 children: Vec<LogicalPlan>,
609 output_schema: DFSchemaRef,
610 format: FusedOutputFormat,
611 ) -> DataFusionResult<Self> {
612 validate_binding(&tree, &binding, &children)?;
616 if matches!(
620 &tree.root().expr,
621 NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial
622 ) && format != FusedOutputFormat::SeriesFrame
623 {
624 return Err(DataFusionError::Plan(
625 "FusedSeries Partial stage requires SeriesFrame output".into(),
626 ));
627 }
628 if format == FusedOutputFormat::SeriesFrame {
629 let expected = output_frame_schema(
630 &tree,
631 FusedInputKind::from_native_type(&tree.root().output)?,
632 )?;
633 if output_schema.as_arrow() != expected.as_ref() {
634 return Err(DataFusionError::Plan(format!(
635 "FusedSeries SeriesFrame schema does not match: declared {output_schema:?}, expected {expected:?}"
636 )));
637 }
638 }
639 Ok(Self {
640 promql,
641 tree,
642 binding,
643 children,
644 output_schema,
645 format,
646 canonical_producer: false,
647 })
648 }
649
650 pub fn try_new_canonical_producer(
662 promql: Arc<str>,
663 tree: NativeTree,
664 binding: FusedSeriesBinding,
665 children: Vec<LogicalPlan>,
666 ) -> DataFusionResult<Self> {
667 let NativeExpr::Merge { input: _ } = &tree.root().expr else {
668 return Err(DataFusionError::Plan(
669 "a canonical merge producer requires a merge at the tree's root".into(),
670 ));
671 };
672 validate_binding(&tree, &binding, &children)?;
673 let frame = Self::series_frame_schema(&tree)?;
674 let output_schema = Arc::new(datafusion::common::DFSchema::try_from(
675 frame.as_ref().clone(),
676 )?);
677 Ok(Self {
678 promql,
679 tree,
680 binding,
681 children,
682 output_schema,
683 format: FusedOutputFormat::SeriesFrame,
684 canonical_producer: true,
685 })
686 }
687
688 pub fn canonical_producer_prefix_is_local(&self) -> bool {
690 matches!(&self.tree.root().expr, NativeExpr::Merge { input }
691 if matches!(input_locality(input), InputLocality::PartitionLocal)
692 || canonical_evaluated_local_prefix(input))
693 }
694
695 pub fn is_canonical_producer(&self) -> bool {
697 self.canonical_producer
698 }
699
700 pub fn promql(&self) -> &str {
702 &self.promql
703 }
704
705 pub fn format(&self) -> FusedOutputFormat {
707 self.format
708 }
709
710 pub fn reads_aggregate_state(&self) -> bool {
717 self.tree
718 .root()
719 .inputs()
720 .iter()
721 .any(|input| matches!(input.output, NativeType::AggregateState(_)))
722 }
723
724 pub fn tree(&self) -> &NativeTree {
726 &self.tree
727 }
728
729 pub fn children(&self) -> &[LogicalPlan] {
731 &self.children
732 }
733
734 pub fn binding(&self) -> &FusedSeriesBinding {
736 &self.binding
737 }
738
739 pub fn to_execution_plan(
745 &self,
746 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
747 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
748 self.to_execution_plan_with_parallelism_option(inputs, None)
749 }
750
751 pub fn to_execution_plan_with_parallelism(
753 &self,
754 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
755 target_partitions: usize,
756 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
757 self.to_execution_plan_with_parallelism_option(inputs, Some(target_partitions))
758 }
759
760 fn to_execution_plan_with_parallelism_option(
761 &self,
762 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
763 target_partitions: Option<usize>,
764 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
765 let output_schema: SchemaRef = self.output_schema.inner().clone();
766 if inputs.len() != self.children.len() {
767 return Err(DataFusionError::Plan(format!(
768 "FusedSeries physical input count {} does not match its {} logical children",
769 inputs.len(),
770 self.children.len()
771 )));
772 }
773 let tags = if matches!(self.tree.root().output, NativeType::AggregateState(_)) {
774 self.binding.tags.clone()
775 } else {
776 self.output_tags()?
777 };
778 let evaluated = inputs.iter().any(|(input, _, _)| {
779 SeriesFrameDeclaration::parse(input.schema().as_ref())
780 .is_ok_and(|declaration| declaration.content() == FrameContent::Evaluated)
781 });
782 let locality = self.execution_locality();
783 let state_group = state_routing(self.tree.root());
784 let normalize = matches!(locality, InputLocality::SinglePartition);
785
786 let matching_policy = match &locality {
787 InputLocality::MatchingLocal(policy) => Some(policy.clone()),
788 _ => None,
789 };
790 let matching_partitions = matching_policy.as_ref().map(|_| {
791 target_partitions.map_or_else(
792 || {
793 if let Some(source) = same_source(self.tree.root()) {
794 inputs
795 .get(source)
796 .map(|(input, _, _)| input.properties().partitioning.partition_count())
797 .unwrap_or(1)
798 } else {
799 inputs
800 .iter()
801 .map(|(input, _, _)| input.properties().partitioning.partition_count())
802 .max()
803 .unwrap_or(1)
804 }
805 },
806 |target| target.max(1),
807 )
808 });
809 let window_sources = if evaluated
810 && !normalize
811 && inputs
812 .iter()
813 .any(|(input, _, _)| input.properties().partitioning.partition_count() > 1)
814 {
815 partitioned_window_sources(self.tree.root())?
816 } else {
817 Vec::new()
818 };
819 let inputs = inputs
821 .into_iter()
822 .enumerate()
823 .map(|(index, (input, label_source, ordering))| {
824 let declaration = SeriesFrameDeclaration::parse(input.schema().as_ref())
825 .map_err(|error| DataFusionError::Plan(error.to_string()))?;
826 let actual_ordering = series_frame_ordering(input.schema().as_ref())?;
827 if actual_ordering != ordering {
828 return Err(DataFusionError::Plan(
829 "FusedSeries source supplied ordering does not match its frame declaration"
830 .into(),
831 ));
832 }
833 if declaration.content() == FrameContent::AggregateState {
834 let (group, policy) = state_group.as_ref().ok_or_else(|| {
838 DataFusionError::Plan(
839 "FusedSeries reads aggregate state but holds no Final aggregate".into(),
840 )
841 })?;
842 let count = input.properties().partitioning.partition_count();
843 let required = match group {
846 StateGroup::Single => 1,
847 StateGroup::Grouped => target_partitions.unwrap_or(count).max(1),
848 };
849 let input = if let Some(router) = input.downcast_ref::<SeriesRepartitionExec>()
850 {
851 if router.outputs() == required
852 && (required == 1 || router.routing_policy() == policy)
853 {
854 return Ok((input, label_source, ordering));
855 }
856 Arc::clone(router.children()[0])
859 } else if count == required && required == 1 {
860 return Ok((input, label_source, ordering));
861 } else {
862 input
863 };
864 let routed = Arc::new(SeriesRepartitionExec::try_new_with_routing(
865 input,
866 required,
867 policy.clone(),
868 )?) as Arc<dyn ExecutionPlan>;
869 let ordering = series_frame_ordering(routed.schema().as_ref())?;
870 return Ok((routed, RawLabelSource::Explicit, ordering));
871 }
872 if declaration.content() != FrameContent::Evaluated {
873 let count = input.properties().partitioning.partition_count();
874 if count == 0 {
875 return Err(DataFusionError::Plan(format!(
876 "FusedSeries input {index} has no partitions"
877 )));
878 }
879 let (input, label_source, ordering) = if ordering == SeriesOrdering::Interleaved
882 {
883 let width = if normalize { 1 } else { count };
884 let input = Arc::new(SeriesRepartitionExec::try_new_with_routing(
885 input,
886 width,
887 SeriesRouting::RawPrimaryKey,
888 )?) as Arc<dyn ExecutionPlan>;
889 (input, RawLabelSource::Explicit, SeriesOrdering::Contiguous)
890 } else {
891 (input, label_source, ordering)
892 };
893 let count = input.properties().partitioning.partition_count();
894 if !normalize
898 && count < target_partitions.unwrap_or(count).max(1)
899 && matching_policy.is_none()
900 {
901 let width = target_partitions.unwrap_or(count).max(1);
902 let input = Arc::new(SeriesRepartitionExec::try_new_with_routing(
903 input,
904 width,
905 SeriesRouting::RawPrimaryKey,
906 )?) as Arc<dyn ExecutionPlan>;
907 let ordering = series_frame_ordering(input.schema().as_ref())?;
908 return Ok((input, RawLabelSource::Explicit, ordering));
909 }
910 if normalize && count != 1 {
911 let input = Arc::new(SeriesRepartitionExec::try_new(input, 1)?)
912 as Arc<dyn ExecutionPlan>;
913 let ordering = series_frame_ordering(input.schema().as_ref())?;
914 return Ok((input, RawLabelSource::Explicit, ordering));
915 }
916 if let (Some(policy), Some(required)) =
917 (matching_policy.as_ref(), matching_partitions)
918 {
919 if required == 1 && count != 1 {
920 let input = Arc::new(SeriesRepartitionExec::try_new(input, 1)?)
921 as Arc<dyn ExecutionPlan>;
922 let ordering = series_frame_ordering(input.schema().as_ref())?;
923 return Ok((input, RawLabelSource::Explicit, ordering));
924 }
925 let has_router =
926 input
927 .downcast_ref::<SeriesRepartitionExec>()
928 .is_some_and(|router| {
929 router.outputs() == required
930 && router.routing_policy()
931 == &SeriesRouting::Matching(policy.clone())
932 });
933 if required > 1 && !has_router {
934 let input = Arc::new(SeriesRepartitionExec::try_new_with_routing(
935 input,
936 required,
937 SeriesRouting::Matching(policy.clone()),
938 )?) as Arc<dyn ExecutionPlan>;
939 let ordering = series_frame_ordering(input.schema().as_ref())?;
940 return Ok((input, RawLabelSource::Explicit, ordering));
941 }
942 }
943 return Ok((input, label_source, ordering));
944 }
945 let count = input.properties().partitioning.partition_count();
946 if count == 0 {
947 return Err(DataFusionError::Plan(format!(
948 "FusedSeries input {index} has no partitions"
949 )));
950 }
951 let required = if normalize {
952 1
953 } else {
954 matching_partitions.unwrap_or(count)
955 };
956 let needs_owner = window_sources.contains(&index);
957 let contiguous = actual_ordering == SeriesOrdering::Contiguous;
958 let has_router =
959 input
960 .downcast_ref::<SeriesRepartitionExec>()
961 .is_some_and(|router| {
962 router.outputs() == required
963 && matching_policy.as_ref().is_some_and(|policy| {
964 router.routing_policy()
965 == &SeriesRouting::Matching(policy.clone())
966 })
967 });
968 if normalize && count != required {
969 let input = Arc::new(SeriesRepartitionExec::try_new(input, required)?)
970 as Arc<dyn ExecutionPlan>;
971 Ok((input, label_source, SeriesOrdering::Contiguous))
972 } else if normalize {
973 Ok((input, label_source, ordering))
976 } else if let Some(policy) = matching_policy.as_ref()
977 && required > 1
978 && (count != required || !has_router)
979 {
980 let input = Arc::new(SeriesRepartitionExec::try_new_with_routing(
985 input,
986 required,
987 SeriesRouting::Matching(policy.clone()),
988 )?) as Arc<dyn ExecutionPlan>;
989 Ok((input, label_source, SeriesOrdering::Contiguous))
990 } else if needs_owner
991 && !(count == 1 && contiguous)
992 && input.downcast_ref::<SeriesRepartitionExec>().is_none()
993 {
994 let input = Arc::new(SeriesRepartitionExec::try_new(input, required)?)
995 as Arc<dyn ExecutionPlan>;
996 Ok((input, label_source, SeriesOrdering::Contiguous))
997 } else {
998 Ok((input, label_source, ordering))
999 }
1000 })
1001 .collect::<DataFusionResult<Vec<_>>>()?;
1002 let exec: Arc<dyn ExecutionPlan> = Arc::new(FusedSeriesExec::build(
1003 Arc::clone(&self.promql),
1004 inputs,
1005 Arc::new(self.tree.clone()),
1006 output_schema,
1007 self.binding.time_index.clone(),
1008 tags,
1009 self.binding.metric_name.clone(),
1010 self.format,
1011 target_partitions,
1012 self.canonical_producer,
1013 )?);
1014 self.with_canonical_router(exec)
1015 }
1016
1017 fn with_canonical_router(
1030 &self,
1031 exec: Arc<dyn ExecutionPlan>,
1032 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
1033 if !self.canonical_producer {
1034 return Ok(exec);
1035 }
1036 let outputs = exec.properties().partitioning.partition_count().max(1);
1044 Ok(Arc::new(SeriesRepartitionExec::try_new_with_routing(
1045 exec,
1046 outputs,
1047 SeriesRouting::CanonicalLabels,
1048 )?))
1049 }
1050
1051 fn execution_locality(&self) -> InputLocality {
1061 if self.canonical_producer {
1062 InputLocality::PartitionLocal
1063 } else {
1064 input_locality(self.tree.root())
1065 }
1066 }
1067
1068 fn output_tags(&self) -> DataFusionResult<Vec<String>> {
1074 if matches!(self.tree.root().output, NativeType::Scalar(_)) {
1075 return Ok(Vec::new());
1076 }
1077 if self.format == FusedOutputFormat::PlainRows {
1078 return Ok(self
1081 .output_schema
1082 .fields()
1083 .iter()
1084 .filter(|field| {
1085 field.name() != &self.binding.time_index && field.data_type() == &DataType::Utf8
1086 })
1087 .map(|field| field.name().clone())
1088 .collect());
1089 }
1090 let field_names = self
1091 .tree
1092 .root()
1093 .output
1094 .samples()
1095 .map(|schema| {
1096 schema
1097 .fields
1098 .iter()
1099 .map(|field| field.name.as_ref())
1100 .collect::<std::collections::HashSet<_>>()
1101 })
1102 .unwrap_or_default();
1103 Ok(self
1104 .output_schema
1105 .fields()
1106 .iter()
1107 .filter(|field| {
1108 field.name() != &self.binding.time_index
1109 && !field_names.contains(field.name().as_str())
1110 && !matches!(self.tree.root().output, NativeType::Scalar(_))
1111 })
1112 .map(|field| field.name().clone())
1113 .collect())
1114 }
1115}
1116
1117impl UserDefinedLogicalNodeCore for FusedSeries {
1118 fn name(&self) -> &str {
1119 Self::name()
1120 }
1121
1122 fn inputs(&self) -> Vec<&LogicalPlan> {
1123 self.children.iter().collect()
1124 }
1125
1126 fn schema(&self) -> &DFSchemaRef {
1127 &self.output_schema
1128 }
1129
1130 fn expressions(&self) -> Vec<Expr> {
1131 Vec::new()
1134 }
1135
1136 fn fmt_for_explain(&self, f: &mut Formatter) -> fmt::Result {
1137 write!(f, "FusedSeries")?;
1138 let mut has_params = false;
1139 match self.format {
1140 FusedOutputFormat::SeriesFrame if self.canonical_producer => {
1141 write!(f, ": (output: series_frame, per-partition canonical merge)")?;
1142 has_params = true;
1143 }
1144 FusedOutputFormat::SeriesFrame => {
1145 write!(f, ": (output: series_frame)")?;
1146 has_params = true;
1147 }
1148 FusedOutputFormat::PlainRows => {}
1149 }
1150 if let Some((_, SeriesRouting::CanonicalLabelsExcept(excluded))) =
1151 state_routing(self.tree.root())
1152 {
1153 let separator = if has_params { " " } else { ": " };
1154 write!(
1155 f,
1156 "{separator}(state routing: canonical labels except {excluded:?})"
1157 )?;
1158 }
1159 write!(f, "\nnative_tree=[\n{}\n]", self.tree)
1160 }
1161
1162 fn with_exprs_and_inputs(
1163 &self,
1164 _exprs: Vec<Expr>,
1165 inputs: Vec<LogicalPlan>,
1166 ) -> DataFusionResult<Self> {
1167 validate_binding(&self.tree, &self.binding, &inputs)?;
1168 Ok(Self {
1169 promql: Arc::clone(&self.promql),
1170 tree: self.tree.clone(),
1171 binding: self.binding.clone(),
1172 children: inputs,
1173 output_schema: Arc::clone(&self.output_schema),
1174 format: self.format,
1175 canonical_producer: self.canonical_producer,
1176 })
1177 }
1178}
1179
1180impl PartialEq for FusedSeries {
1181 fn eq(&self, other: &Self) -> bool {
1182 self.tree == other.tree
1183 && self.binding == other.binding
1184 && self.children == other.children
1185 && self.output_schema == other.output_schema
1186 && self.format == other.format
1187 && self.canonical_producer == other.canonical_producer
1188 }
1189}
1190
1191impl Eq for FusedSeries {}
1192
1193impl Hash for FusedSeries {
1194 fn hash<H: Hasher>(&self, state: &mut H) {
1195 self.binding.hash(state);
1196 self.children.hash(state);
1197 self.output_schema.hash(state);
1198 self.tree.hash(state);
1199 self.format.hash(state);
1200 self.canonical_producer.hash(state);
1201 }
1202}
1203
1204impl PartialOrd for FusedSeries {
1205 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1206 match self.binding.partial_cmp(&other.binding) {
1207 Some(Ordering::Equal) => {}
1208 ord => return ord,
1209 }
1210 match self.children.partial_cmp(&other.children) {
1211 Some(Ordering::Equal) => {}
1212 ord => return ord,
1213 }
1214 if self.tree != other.tree {
1215 return None;
1216 }
1217 match self.format.cmp(&other.format) {
1218 Ordering::Equal => {}
1219 ord => return Some(ord),
1220 }
1221 match self.canonical_producer.cmp(&other.canonical_producer) {
1222 Ordering::Equal => {}
1223 ord => return Some(ord),
1224 }
1225 if self.output_schema == other.output_schema {
1226 Some(Ordering::Equal)
1227 } else {
1228 None
1229 }
1230 }
1231}
1232
1233fn collect_source_schemas(tree: &NativeTree) -> DataFusionResult<Vec<Arc<SeriesSchema>>> {
1235 collect_source_schemas_from_inputs(tree.root().inputs())
1236}
1237
1238fn collect_source_schemas_from_inputs(
1239 inputs: Vec<&crate::native::plan::BoundInput>,
1240) -> DataFusionResult<Vec<Arc<SeriesSchema>>> {
1241 let mut schemas: Vec<(usize, Arc<SeriesSchema>, FusedInputKind)> = Vec::new();
1242 for input in inputs {
1243 let kind = FusedInputKind::from_native_type(&input.output)?;
1244 let found = match &input.output {
1245 NativeType::Samples(schema) => Arc::clone(schema),
1246 NativeType::AggregateState(state) => Arc::new(SeriesSchema {
1247 fields: state.accumulators.clone(),
1248 eval_grid: Some(Arc::clone(&state.grid)),
1249 }),
1250 NativeType::Scalar(_) => {
1251 return Err(DataFusionError::Plan(
1252 "FusedSeries scalar cannot be a source".into(),
1253 ));
1254 }
1255 };
1256 if let Some((_, expected, expected_kind)) = schemas
1257 .iter()
1258 .find(|(index, _, _)| *index == input.source_index)
1259 {
1260 if *expected_kind != kind {
1261 return Err(DataFusionError::Plan(
1262 "FusedSeries repeated source disagrees on input kind".into(),
1263 ));
1264 }
1265 let same_grid = match (&expected.eval_grid, &found.eval_grid) {
1266 (None, None) => true,
1267 (Some(left), Some(right)) => left.spec() == right.spec(),
1268 _ => false,
1269 };
1270 if !same_fields(expected, &found) || !same_grid {
1271 return Err(DataFusionError::Plan(
1272 "FusedSeries repeated source has different fields or evaluation grid".into(),
1273 ));
1274 }
1275 } else {
1276 schemas.push((input.source_index, found, kind));
1277 }
1278 }
1279 schemas.sort_unstable_by_key(|(index, _, _)| *index);
1280 if schemas
1281 .iter()
1282 .enumerate()
1283 .any(|(expected, (actual, _, _))| expected != *actual)
1284 {
1285 return Err(DataFusionError::Plan(
1286 "FusedSeries source indexes are not dense".into(),
1287 ));
1288 }
1289 Ok(schemas.into_iter().map(|(_, schema, _)| schema).collect())
1290}
1291
1292#[derive(Clone, Debug)]
1293pub enum InputLocality {
1294 PartitionLocal,
1296 MatchingLocal(MatchingLabels),
1298 SinglePartition,
1300}
1301
1302fn same_source(node: &NativeNode) -> Option<usize> {
1304 match &node.expr {
1305 NativeExpr::Input(input)
1306 if node.output.grid().is_some()
1307 || node
1308 .output
1309 .samples()
1310 .is_some_and(|schema| schema.eval_grid.is_none()) =>
1311 {
1312 Some(input.source_index)
1313 }
1314 NativeExpr::Instant { input, .. }
1315 | NativeExpr::Window { input, .. }
1316 | NativeExpr::Timestamp { input } => same_source(input),
1317 NativeExpr::Map { input, op }
1318 if !op
1319 .ops
1320 .iter()
1321 .any(|op| matches!(op, crate::native::plan::MapOp::Label(_))) =>
1322 {
1323 same_source(input)
1324 }
1325 NativeExpr::ParameterizedMap {
1326 input, parameters, ..
1327 } if parameters.iter().all(|parameter| {
1328 matches!(
1329 parameter.expr,
1330 NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. }
1331 )
1332 }) =>
1333 {
1334 same_source(input)
1335 }
1336 NativeExpr::Binary {
1337 left,
1338 right,
1339 matching,
1340 } if matches!(left.output, NativeType::Scalar(_)) && left.is_data_free() => {
1341 let _ = matching;
1342 same_source(right)
1343 }
1344 NativeExpr::Binary {
1345 left,
1346 right,
1347 matching,
1348 } if matches!(right.output, NativeType::Scalar(_)) && right.is_data_free() => {
1349 let _ = matching;
1350 same_source(left)
1351 }
1352 NativeExpr::Binary {
1353 left,
1354 right,
1355 matching,
1356 } if matching.labels == MatchingLabels::Ignoring(Vec::new())
1357 && matching.cardinality == crate::vector_match::Cardinality::OneToOne =>
1358 {
1359 let source = same_source(left)?;
1360 (same_source(right) == Some(source)).then_some(source)
1361 }
1362 NativeExpr::Aggregate { .. }
1363 | NativeExpr::Vector { .. }
1364 | NativeExpr::VectorOf { .. }
1365 | NativeExpr::Set { .. }
1366 | NativeExpr::Info { .. }
1367 | NativeExpr::Merge { .. }
1368 | NativeExpr::Binary { .. }
1369 | NativeExpr::Input(_)
1370 | NativeExpr::Scalar(_)
1371 | NativeExpr::EvalTime { .. }
1372 | NativeExpr::Map { .. }
1373 | NativeExpr::ParameterizedMap { .. }
1374 | NativeExpr::ScalarOf { .. }
1378 | NativeExpr::ParameterizedTopK { .. }
1379 | NativeExpr::ParameterizedHistogram { .. }
1380 | NativeExpr::ParameterizedAggregate { .. } => None,
1381 }
1382}
1383
1384fn preserves_matching_key(node: &NativeNode, matching: &MatchingLabels) -> bool {
1389 const COMPUTED_LABELS: [&str; 3] = [METRIC_NAME, "__type__", "__unit__"];
1390 let key_contains = |label: &str| match matching {
1391 MatchingLabels::On(labels) => labels.iter().any(|candidate| candidate.as_ref() == label),
1392 MatchingLabels::Ignoring(labels) => {
1393 label != METRIC_NAME && !labels.iter().any(|candidate| candidate.as_ref() == label)
1394 }
1395 };
1396 let labels_removed = |labels: &[&str]| labels.iter().any(|label| key_contains(label));
1397
1398 match &node.expr {
1399 NativeExpr::Input(_) => true,
1400 NativeExpr::Instant { input, op } => {
1401 (op.value != InstantValue::Timestamp || !labels_removed(&COMPUTED_LABELS))
1402 && preserves_matching_key(input, matching)
1403 }
1404 NativeExpr::Map { input, op } => {
1405 op.ops.iter().all(|op| match op {
1406 crate::native::plan::MapOp::Math(_) => !labels_removed(&COMPUTED_LABELS),
1407 crate::native::plan::MapOp::Label(_) | crate::native::plan::MapOp::Histogram(_) => {
1409 false
1410 }
1411 }) && preserves_matching_key(input, matching)
1412 }
1413 NativeExpr::ParameterizedMap {
1414 input, parameters, ..
1415 } => {
1416 !labels_removed(&COMPUTED_LABELS)
1417 && preserves_matching_key(input, matching)
1418 && parameters.iter().all(|parameter| {
1419 matches!(
1420 parameter.expr,
1421 NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. }
1422 )
1423 })
1424 }
1425 NativeExpr::Timestamp { input } => {
1426 !labels_removed(&COMPUTED_LABELS) && preserves_matching_key(input, matching)
1427 }
1428 NativeExpr::Window { input, op } => {
1429 (!op.function.drops_metric_name() || !labels_removed(&COMPUTED_LABELS))
1430 && preserves_matching_key(input, matching)
1431 }
1432 NativeExpr::Binary {
1433 left,
1434 right,
1435 matching: binary,
1436 } if matches!(left.output, NativeType::Scalar(_)) => {
1437 let drops_labels = binary.return_bool || !binary.op.is_comparison();
1438 (!drops_labels || !labels_removed(&COMPUTED_LABELS))
1439 && preserves_matching_key(right, matching)
1440 }
1441 NativeExpr::Binary {
1442 left,
1443 right,
1444 matching: binary,
1445 } if matches!(right.output, NativeType::Scalar(_)) => {
1446 let drops_labels = binary.return_bool || !binary.op.is_comparison();
1447 (!drops_labels || !labels_removed(&COMPUTED_LABELS))
1448 && preserves_matching_key(left, matching)
1449 }
1450 _ => false,
1453 }
1454}
1455
1456pub fn matching_operands_drop_key(root: &NativeNode) -> bool {
1463 matching_site(root).is_some_and(|(left, right, labels)| {
1464 same_source(left).is_some()
1465 && same_source(right).is_some()
1466 && (!preserves_matching_key(left, labels) || !preserves_matching_key(right, labels))
1467 })
1468}
1469
1470fn needs_vector_matching(node: &NativeNode) -> bool {
1477 match &node.expr {
1478 NativeExpr::Binary { left, right, .. } => {
1479 let scalar = |side: &NativeNode| matches!(side.output, NativeType::Scalar(_));
1480 if scalar(left) || scalar(right) {
1481 needs_vector_matching(left) || needs_vector_matching(right)
1482 } else {
1483 true
1484 }
1485 }
1486 NativeExpr::Instant { input, .. }
1487 | NativeExpr::Window { input, .. }
1488 | NativeExpr::Map { input, .. }
1489 | NativeExpr::Timestamp { input }
1490 | NativeExpr::VectorOf { input }
1491 | NativeExpr::Merge { input }
1492 | NativeExpr::Aggregate { input, .. }
1493 | NativeExpr::Vector { input, .. }
1494 | NativeExpr::ScalarOf { input } => needs_vector_matching(input),
1495 NativeExpr::ParameterizedMap {
1496 input, parameters, ..
1497 } => needs_vector_matching(input) || parameters.iter().any(needs_vector_matching),
1498 NativeExpr::ParameterizedTopK {
1499 input, parameter, ..
1500 } => needs_vector_matching(input) || needs_vector_matching(parameter),
1501 NativeExpr::ParameterizedHistogram {
1502 input, parameters, ..
1503 } => needs_vector_matching(input) || parameters.iter().any(needs_vector_matching),
1504 NativeExpr::ParameterizedAggregate {
1508 input, parameter, ..
1509 } => needs_vector_matching(input) || needs_vector_matching(parameter),
1510 NativeExpr::Set { left, right, .. } => {
1511 needs_vector_matching(left) || needs_vector_matching(right)
1512 }
1513 NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => false,
1514 NativeExpr::Info { .. } => true,
1515 }
1516}
1517
1518fn matching_site(node: &NativeNode) -> Option<(&NativeNode, &NativeNode, &MatchingLabels)> {
1527 match &node.expr {
1528 NativeExpr::Binary {
1529 left,
1530 right,
1531 matching,
1532 } => {
1533 let scalar = |side: &NativeNode| {
1534 matches!(side.output, NativeType::Scalar(_)) && side.is_data_free()
1535 };
1536 if scalar(left) {
1537 matching_site(right)
1538 } else if scalar(right) {
1539 matching_site(left)
1540 } else {
1541 Some((left, right, &matching.labels))
1542 }
1543 }
1544 NativeExpr::Instant { input, .. }
1545 | NativeExpr::Map { input, .. }
1546 | NativeExpr::Window { input, .. }
1547 | NativeExpr::Timestamp { input } => matching_site(input),
1548 _ => None,
1549 }
1550}
1551
1552pub fn input_locality(root: &NativeNode) -> InputLocality {
1553 if matches!(
1558 &root.expr,
1559 NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial
1560 ) {
1561 return InputLocality::PartitionLocal;
1562 }
1563 if let Some(index) = same_source(root) {
1564 let raw = root.output.samples().is_some_and(|_| {
1565 root.inputs()
1567 .into_iter()
1568 .find(|input| input.source_index == index)
1569 .is_some_and(|input| {
1570 input
1571 .output
1572 .samples()
1573 .is_some_and(|schema| schema.eval_grid.is_none())
1574 })
1575 });
1576 if !needs_vector_matching(root) {
1580 return InputLocality::PartitionLocal;
1581 }
1582 if raw {
1583 if matching_operands_drop_key(root) {
1584 return InputLocality::SinglePartition;
1585 }
1586 return InputLocality::PartitionLocal;
1587 }
1588 return InputLocality::MatchingLocal(MatchingLabels::Ignoring(Vec::new()));
1589 }
1590 if let Some((left, right, labels)) = matching_site(root)
1593 && let (Some(_left_source), Some(_right_source)) = (same_source(left), same_source(right))
1594 && preserves_matching_key(left, labels)
1595 && preserves_matching_key(right, labels)
1596 {
1597 return InputLocality::MatchingLocal(labels.clone());
1598 }
1599 if reads_across_series(root) {
1600 InputLocality::SinglePartition
1601 } else {
1602 InputLocality::PartitionLocal
1603 }
1604}
1605
1606fn state_routing(root: &NativeNode) -> Option<(StateGroup, SeriesRouting)> {
1619 fn find(node: &NativeNode, histogram: bool, gathered: bool) -> Option<(&Grouping, bool, bool)> {
1621 match &node.expr {
1622 NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Final => {
1623 Some((&op.group, histogram, gathered))
1624 }
1625 NativeExpr::Aggregate { input, .. } => find(input, histogram, true),
1628 NativeExpr::Vector { input, op } => find(
1629 input,
1630 histogram || matches!(op, crate::native::plan::BoundVectorOp::Histogram(_)),
1631 gathered,
1632 ),
1633 NativeExpr::ParameterizedHistogram { input, op, .. } => find(
1636 input,
1637 histogram || matches!(op, crate::native::plan::BoundVectorOp::Histogram(_)),
1638 gathered,
1639 ),
1640 NativeExpr::ScalarOf { input } | NativeExpr::ParameterizedTopK { input, .. } => {
1643 find(input, histogram, true)
1644 }
1645 NativeExpr::ParameterizedAggregate {
1650 input, parameter, ..
1651 } => find(input, histogram, true).or_else(|| find(parameter, histogram, true)),
1652 NativeExpr::Instant { input, .. }
1653 | NativeExpr::Window { input, .. }
1654 | NativeExpr::Merge { input }
1655 | NativeExpr::Map { input, .. }
1656 | NativeExpr::Timestamp { input }
1657 | NativeExpr::VectorOf { input }
1658 | NativeExpr::ParameterizedMap { input, .. } => find(input, histogram, gathered),
1659 NativeExpr::Binary { left, right, .. } | NativeExpr::Set { left, right, .. } => {
1660 find(left, histogram, gathered).or_else(|| find(right, histogram, gathered))
1661 }
1662 NativeExpr::Info { base, info, .. } => {
1663 find(base, histogram, gathered).or_else(|| find(info, histogram, gathered))
1664 }
1665 NativeExpr::Input(_) | NativeExpr::Scalar(_) | NativeExpr::EvalTime { .. } => None,
1666 }
1667 }
1668 let (group, histogram, gathered) = find(root, false, false)?;
1669 if histogram {
1670 let owners = if gathered || crate::native::split::histogram_group_is_single(group) {
1671 StateGroup::Single
1672 } else {
1673 StateGroup::Grouped
1674 };
1675 Some((
1676 owners,
1677 SeriesRouting::CanonicalLabelsExcept(
1678 HISTOGRAM_ROUTING_EXCLUDED_LABELS
1679 .iter()
1680 .copied()
1681 .map(Arc::from)
1682 .collect::<Vec<_>>()
1683 .into(),
1684 ),
1685 ))
1686 } else {
1687 let owners = match group {
1688 _ if gathered => StateGroup::Single,
1689 Grouping::By(labels) if labels.is_empty() => StateGroup::Single,
1690 _ => StateGroup::Grouped,
1691 };
1692 Some((owners, SeriesRouting::CanonicalLabels))
1693 }
1694}
1695
1696#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1698enum StateGroup {
1699 Single,
1701 Grouped,
1703}
1704
1705fn validate_binding(
1706 tree: &NativeTree,
1707 binding: &FusedSeriesBinding,
1708 children: &[LogicalPlan],
1709) -> DataFusionResult<()> {
1710 let schemas = collect_source_schemas(tree)?;
1711 if schemas.is_empty() {
1714 tree.root().validate()?;
1715 }
1716 if schemas.len() != children.len() {
1717 return Err(DataFusionError::Plan(
1718 "FusedSeries source indexes must densely match its children".into(),
1719 ));
1720 }
1721 let root_grid = match &tree.root().output {
1722 NativeType::Samples(schema) => schema.eval_grid.as_ref(),
1723 NativeType::AggregateState(state) => Some(&state.grid),
1724 NativeType::Scalar(grid) => Some(grid),
1725 };
1726 if !root_grid.is_some_and(|grid| grid.spec() == binding.grid.spec()) {
1727 return Err(DataFusionError::Plan(
1728 "FusedSeries output is not on the statement grid".into(),
1729 ));
1730 }
1731 Ok(())
1732}
1733
1734fn partitioned_window_sources(node: &NativeNode) -> DataFusionResult<Vec<usize>> {
1736 fn visit(node: &NativeNode, sources: &mut Vec<usize>) -> DataFusionResult<()> {
1737 if let NativeExpr::Window { input, op } = &node.expr
1741 && op.input_grid.is_none()
1742 {
1743 let NativeExpr::Input(bound) = &input.expr else {
1744 return Err(DataFusionError::Plan(
1745 "partitioned FusedSeries windows require a direct Input under Window".into(),
1746 ));
1747 };
1748 if !sources.contains(&bound.source_index) {
1749 sources.push(bound.source_index);
1750 }
1751 }
1752 for child in node.expr.children() {
1753 visit(child, sources)?;
1754 }
1755 Ok(())
1756 }
1757 let mut sources = Vec::new();
1758 visit(node, &mut sources)?;
1759 Ok(sources)
1760}
1761
1762fn ordering_satisfies(producer: SeriesOrdering, required: SeriesOrdering) -> bool {
1763 match required {
1764 SeriesOrdering::KeyThenTime => producer == SeriesOrdering::KeyThenTime,
1765 SeriesOrdering::Contiguous => producer != SeriesOrdering::Interleaved,
1766 SeriesOrdering::Interleaved => true,
1767 }
1768}
1769
1770fn same_fields(left: &SeriesSchema, right: &SeriesSchema) -> bool {
1771 left.fields.len() == right.fields.len()
1772 && left
1773 .fields
1774 .iter()
1775 .zip(right.fields.iter())
1776 .all(|(a, b)| a.name == b.name)
1777}
1778
1779pub fn tree_source_fields(tree: &NativeTree) -> DataFusionResult<Vec<Vec<String>>> {
1781 Ok(collect_source_schemas(tree)?
1782 .into_iter()
1783 .map(|schema| {
1784 schema
1785 .fields
1786 .iter()
1787 .map(|field| field.name.to_string())
1788 .collect()
1789 })
1790 .collect())
1791}
1792
1793fn validate_plain_output_schema(
1798 schema: &SchemaRef,
1799 tree: &NativeTree,
1800 tags: &[String],
1801 time: &str,
1802 promql: &str,
1803) -> DataFusionResult<()> {
1804 let fields = match &tree.root().output {
1805 NativeType::Samples(s) => s.fields.to_vec(),
1806 NativeType::Scalar(_) => {
1807 let non_time_columns = schema
1808 .fields()
1809 .iter()
1810 .filter(|field| field.name().as_str() != time)
1811 .count();
1812 if non_time_columns != 1 {
1813 return Err(DataFusionError::Plan(format!(
1814 "FusedSeriesExec scalar root cannot produce {} tag columns",
1815 non_time_columns.saturating_sub(1)
1816 )));
1817 }
1818 scalar_root_fields(schema, &[], time)?
1819 }
1820 NativeType::AggregateState(_) => {
1821 return Err(DataFusionError::Plan(
1822 "PlainRows does not support aggregate-state roots".into(),
1823 ));
1824 }
1825 };
1826 classify_output(schema, &fields, tags, time, promql)?;
1827 Ok(())
1828}
1829
1830fn validate_physical_tree(
1835 tree: &NativeTree,
1836) -> DataFusionResult<(Vec<Arc<SeriesSchema>>, Vec<FusedInputKind>, FusedInputKind)> {
1837 let schemas = collect_source_schemas(tree)?;
1838 let mut source_kinds = Vec::new();
1839 for input in tree.root().inputs() {
1840 let kind = FusedInputKind::from_native_type(&input.output)?;
1841 if source_kinds.len() <= input.source_index {
1842 source_kinds.resize(input.source_index + 1, kind);
1843 }
1844 }
1845 let root_kind = match &tree.root().output {
1846 NativeType::Scalar(_) => FusedInputKind::Evaluated,
1847 native_type => FusedInputKind::from_native_type(native_type)?,
1848 };
1849 match root_kind {
1850 FusedInputKind::Evaluated | FusedInputKind::AggregateState => {}
1851 FusedInputKind::Raw => {
1852 return Err(DataFusionError::Plan(
1853 "FusedSeries output is raw samples, not an evaluated or aggregate-state result"
1854 .into(),
1855 ));
1856 }
1857 }
1858 Ok((schemas, source_kinds, root_kind))
1859}
1860
1861#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1866pub enum FieldKind {
1867 Float,
1869 Histogram,
1871}
1872
1873#[derive(Clone, Copy, Debug)]
1875pub(crate) enum OutputColumn {
1876 Time,
1878 Field { index: usize, kind: FieldKind },
1880 Tag(usize),
1882}
1883
1884fn scalar_root_fields(
1886 output_schema: &SchemaRef,
1887 tags: &[String],
1888 time_column: &str,
1889) -> DataFusionResult<Vec<FieldSpec>> {
1890 if !tags.is_empty() {
1891 return Err(DataFusionError::Plan(format!(
1892 "FusedSeriesExec scalar root cannot produce {} tag columns",
1893 tags.len()
1894 )));
1895 }
1896 let mut values = output_schema
1897 .fields()
1898 .iter()
1899 .filter(|field| field.name().as_str() != time_column);
1900 let Some(value) = values.next() else {
1901 return Err(DataFusionError::Plan(
1902 "missing value column in scalar root output schema".to_string(),
1903 ));
1904 };
1905 if values.next().is_some() {
1906 return Err(DataFusionError::Plan(
1907 "scalar root output schema must contain exactly one value column".into(),
1908 ));
1909 }
1910 Ok(vec![FieldSpec {
1911 name: Arc::from(value.name().as_str()),
1912 }])
1913}
1914
1915fn is_value_column(data_type: &DataType) -> bool {
1920 data_type == &DataType::Float64 || data_type == &native_histogram_value_type().as_arrow_type()
1921}
1922
1923fn names_value_columns(value_names: &[&str], names: &[String]) -> bool {
1925 if names.len() != value_names.len() {
1926 return false;
1927 }
1928 let mut declared = names.iter().map(String::as_str).collect::<Vec<_>>();
1929 declared.sort_unstable();
1930 let mut carried = value_names.to_vec();
1931 carried.sort_unstable();
1932 declared == carried
1933}
1934
1935fn output_field_names(
1944 output_schema: &SchemaRef,
1945 series_fields: &[FieldSpec],
1946 promql: &str,
1947) -> Vec<String> {
1948 let value_names = output_schema
1949 .fields()
1950 .iter()
1951 .filter(|field| is_value_column(field.data_type()))
1952 .map(|field| field.name().as_str())
1953 .collect::<Vec<_>>();
1954 let expression_names = series_fields
1955 .iter()
1956 .map(|field| {
1957 if series_fields.len() == 1 {
1958 promql.to_string()
1959 } else {
1960 format!("{promql}.{}", field.name)
1961 }
1962 })
1963 .collect::<Vec<_>>();
1964 if names_value_columns(&value_names, &expression_names) {
1965 return expression_names;
1966 }
1967 series_fields
1968 .iter()
1969 .map(|field| field.name.to_string())
1970 .collect()
1971}
1972
1973pub(crate) fn classify_output(
1975 output_schema: &SchemaRef,
1976 series_fields: &[FieldSpec],
1977 tags: &[String],
1978 time_column: &str,
1979 promql: &str,
1980) -> DataFusionResult<Vec<OutputColumn>> {
1981 let field_names = output_field_names(output_schema, series_fields, promql);
1982 if output_schema
1983 .fields()
1984 .iter()
1985 .filter(|field| field.name().as_str() == time_column)
1986 .count()
1987 > 1
1988 {
1989 return Err(DataFusionError::Plan(format!(
1990 "duplicate time column {time_column:?} in FusedSeriesExec output schema"
1991 )));
1992 }
1993 for (index, tag) in tags.iter().enumerate() {
1994 if tags[..index].contains(tag) {
1995 return Err(DataFusionError::Plan(format!(
1996 "duplicate tag column {tag:?} in FusedSeriesExec output schema"
1997 )));
1998 }
1999 if tag == time_column {
2000 return Err(DataFusionError::Plan(format!(
2001 "tag column {tag:?} of FusedSeriesExec cannot be the time column"
2002 )));
2003 }
2004 }
2005
2006 let mut time_seen = false;
2007 let mut field_seen = vec![false; series_fields.len()];
2008 let mut tag_seen = vec![false; tags.len()];
2009 let mut classification = Vec::with_capacity(output_schema.fields().len());
2010 for field in output_schema.fields() {
2011 let name = field.name();
2012 if name == time_column {
2013 if std::mem::replace(&mut time_seen, true) {
2014 return Err(DataFusionError::Plan(format!(
2015 "duplicate time column {name:?} in FusedSeriesExec output schema"
2016 )));
2017 }
2018 match field.data_type() {
2019 DataType::Timestamp(TimeUnit::Millisecond, None) => {}
2020 other => {
2021 return Err(DataFusionError::Plan(format!(
2022 "time column {name:?} of FusedSeriesExec must be Timestamp(Millisecond, \
2023 None), got {other:?}"
2024 )));
2025 }
2026 }
2027 if field.is_nullable() {
2028 return Err(DataFusionError::Plan(format!(
2029 "time column {name:?} of FusedSeriesExec must not be nullable"
2030 )));
2031 }
2032 classification.push(OutputColumn::Time);
2033 continue;
2034 }
2035 if let Some(index) = field_names.iter().position(|field| field == name) {
2036 if std::mem::replace(&mut field_seen[index], true) {
2037 return Err(DataFusionError::Plan(format!(
2038 "duplicate field column {name:?} in FusedSeriesExec output schema"
2039 )));
2040 }
2041 let kind = if field.data_type() == &DataType::Float64 {
2044 FieldKind::Float
2045 } else if field.data_type() == &native_histogram_value_type().as_arrow_type() {
2046 FieldKind::Histogram
2047 } else {
2048 return Err(DataFusionError::Plan(format!(
2049 "field column {name:?} of FusedSeriesExec must be Float64 or a native \
2050 histogram, got {:?}",
2051 field.data_type()
2052 )));
2053 };
2054 if !field.is_nullable() {
2056 return Err(DataFusionError::Plan(format!(
2057 "field column {name:?} of FusedSeriesExec must be nullable, because a grid \
2058 point can be missing"
2059 )));
2060 }
2061 classification.push(OutputColumn::Field { index, kind });
2062 continue;
2063 }
2064 if let Some(index) = tags.iter().position(|tag| tag == name) {
2065 if std::mem::replace(&mut tag_seen[index], true) {
2066 return Err(DataFusionError::Plan(format!(
2067 "duplicate tag column {name:?} in FusedSeriesExec output schema"
2068 )));
2069 }
2070 if field.data_type() != &DataType::Utf8 {
2071 return Err(DataFusionError::Plan(format!(
2072 "tag column {name:?} of FusedSeriesExec must be Utf8, got {:?}",
2073 field.data_type()
2074 )));
2075 }
2076 if !field.is_nullable() {
2078 return Err(DataFusionError::Plan(format!(
2079 "tag column {name:?} of FusedSeriesExec must be nullable, because range \
2080 functions and map kernels drop the metric name"
2081 )));
2082 }
2083 classification.push(OutputColumn::Tag(index));
2084 continue;
2085 }
2086 return Err(DataFusionError::Plan(format!(
2087 "unknown column {name:?} in FusedSeriesExec output schema"
2088 )));
2089 }
2090
2091 if !time_seen {
2092 return Err(DataFusionError::Plan(format!(
2093 "missing time column {time_column:?} in FusedSeriesExec output schema"
2094 )));
2095 }
2096 for (index, seen) in field_seen.iter().enumerate() {
2097 if !seen {
2098 return Err(DataFusionError::Plan(format!(
2099 "missing field column {:?} in FusedSeriesExec output schema",
2100 field_names[index]
2101 )));
2102 }
2103 }
2104 for (index, seen) in tag_seen.iter().enumerate() {
2105 if !seen {
2106 return Err(DataFusionError::Plan(format!(
2107 "missing tag column {:?} in FusedSeriesExec output schema",
2108 tags[index]
2109 )));
2110 }
2111 }
2112 if output_schema.fields().len() != 1 + series_fields.len() + tags.len() {
2113 return Err(DataFusionError::Plan(
2114 "FusedSeriesExec output schema has an unexpected number of columns".into(),
2115 ));
2116 }
2117 Ok(classification)
2118}
2119
2120fn native_tree_has_vector_binary(node: &NativeNode) -> bool {
2122 node.any(&|node| {
2123 matches!(
2124 &node.expr,
2125 NativeExpr::Binary { left, right, .. }
2126 if !matches!(left.output, NativeType::Scalar(_))
2127 && !matches!(right.output, NativeType::Scalar(_))
2128 )
2129 })
2130}
2131
2132struct EvidenceClaims {
2134 evidence: Option<Arc<DuplicateEvidence>>,
2135 claimed: Vec<bool>,
2136}
2137
2138fn claim_evidence(
2139 claims: &Mutex<EvidenceClaims>,
2140 partition: usize,
2141 partitions: usize,
2142 pool: &Arc<dyn MemoryPool>,
2143) -> DataFusionResult<Arc<DuplicateEvidence>> {
2144 let mut claims = claims.lock().unwrap_or_else(|e| e.into_inner());
2145 if claims.evidence.is_none() {
2146 claims.evidence = Some(Arc::new(DuplicateEvidence::new(pool, partitions)));
2147 claims.claimed = vec![false; partitions];
2148 }
2149 if claims.claimed.get(partition).copied().unwrap_or(false) {
2150 return Err(DataFusionError::Execution(
2151 "FusedSeries plan instance was executed more than once for the same partition".into(),
2152 ));
2153 }
2154 claims.claimed[partition] = true;
2155 Ok(Arc::clone(claims.evidence.as_ref().unwrap()))
2156}
2157
2158pub struct FusedSeriesExec {
2160 promql: Arc<str>,
2162 tree: Arc<NativeTree>,
2164 series_schemas: Vec<Arc<SeriesSchema>>,
2166 source_kinds: Vec<FusedInputKind>,
2167 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
2169 classification: Arc<[OutputColumn]>,
2171 time_column: String,
2174 tags: Arc<[String]>,
2176 metric_name: Option<Arc<str>>,
2183 output_schema: SchemaRef,
2185 duplicate_evidence: Mutex<EvidenceClaims>,
2187 metric: Arc<ExecutionPlanMetricsSet>,
2192 own_metrics: MetricsSet,
2197 format: FusedOutputFormat,
2198 matching_parallelism: Option<usize>,
2199 canonical_producer: bool,
2201 properties: Arc<PlanProperties>,
2203}
2204
2205fn register_tree_metric(tree: &Arc<NativeTree>, metric: &Arc<ExecutionPlanMetricsSet>) {
2211 let tree = Arc::clone(tree);
2212 let figures = Arc::downgrade(metric);
2213 MetricBuilder::new(metric).build(MetricValue::Custom {
2214 name: NATIVE_TREE_METRIC.into(),
2215 value: Arc::new(NativeTreeMetric::new(move || {
2216 let Some(figures) = figures.upgrade() else {
2217 return NativeTreeMetrics::default();
2218 };
2219 NativeTreeMetrics::from(tree.report(&NodeMetricsSnapshot::read(&figures)))
2220 })),
2221 });
2222}
2223
2224#[derive(Clone, Debug)]
2231struct StoredSeriesLabels {
2232 tags: Arc<[Arc<str>]>,
2234 keys_survive_metadata_drop: bool,
2237}
2238
2239pub fn keys_survive_metadata_drop<'a, 'b>(
2264 logical_tags: impl IntoIterator<Item = &'a str>,
2265 key_columns: impl IntoIterator<Item = &'b ColumnSchema>,
2266) -> bool {
2267 let metadata = |name: &str| METADATA_LABELS.contains(&name);
2268 logical_tags.into_iter().all(|tag| !metadata(tag))
2269 && key_columns
2270 .into_iter()
2271 .all(|column| !metadata(&column.name) && !column.is_nullable())
2272}
2273
2274impl StoredSeriesLabels {
2275 fn of(label_source: &RawLabelSource) -> Option<Self> {
2277 let RawLabelSource::PrimaryKey {
2280 physical_metadata,
2281 logical_tags,
2282 ..
2283 } = label_source
2284 else {
2285 return None;
2286 };
2287 Some(Self {
2288 tags: logical_tags
2289 .iter()
2290 .map(|tag| Arc::clone(&tag.name))
2291 .collect(),
2292 keys_survive_metadata_drop: keys_survive_metadata_drop(
2293 logical_tags.iter().map(|tag| tag.name.as_ref()),
2294 physical_metadata
2295 .primary_key_columns()
2296 .map(|column| &column.column_schema),
2297 ),
2298 })
2299 }
2300
2301 fn answers_every_tag(&self, output: &[String]) -> bool {
2306 self.tags
2307 .iter()
2308 .all(|tag| output.iter().any(|column| column.as_str() == tag.as_ref()))
2309 }
2310}
2311
2312fn preserves_partition_identity(node: &NativeNode, labels: Option<&StoredSeriesLabels>) -> bool {
2333 let metadata_drop_keeps_series_apart =
2334 || labels.is_some_and(|labels| labels.keys_survive_metadata_drop);
2335 match &node.expr {
2336 NativeExpr::Input(_) => true,
2337 NativeExpr::Instant { input, op } => {
2338 let drops_metadata = op.value == InstantValue::Timestamp;
2341 (!drops_metadata || metadata_drop_keeps_series_apart())
2342 && preserves_partition_identity(input, labels)
2343 }
2344 NativeExpr::Window { input, op } => {
2345 (!op.function.drops_metric_name() || metadata_drop_keeps_series_apart())
2346 && preserves_partition_identity(input, labels)
2347 }
2348 NativeExpr::Timestamp { input } => {
2349 metadata_drop_keeps_series_apart() && preserves_partition_identity(input, labels)
2350 }
2351 NativeExpr::Map { input, op } => map_preserves_partition_identity(input, op, labels),
2352 NativeExpr::ParameterizedMap {
2353 input, parameters, ..
2354 } => {
2355 metadata_drop_keeps_series_apart()
2358 && parameters.iter().all(|parameter| parameter.is_data_free())
2359 && preserves_partition_identity(input, labels)
2360 }
2361 NativeExpr::Binary {
2362 left,
2363 right,
2364 matching,
2365 } => broadcast_preserves_partition_identity(left, right, matching, labels),
2366 _ => false,
2367 }
2368}
2369
2370fn map_preserves_partition_identity(
2379 input: &NativeNode,
2380 op: &BoundMap,
2381 labels: Option<&StoredSeriesLabels>,
2382) -> bool {
2383 let mut carried = labels.map(|labels| labels.tags.to_vec());
2384 let mut drops_metadata = false;
2385 for operation in op.ops.iter() {
2386 match operation {
2387 MapOp::Label(rewrite) => {
2388 let Some(carried) = carried.as_mut() else {
2389 return false;
2390 };
2391 let destination = rewrite.destination();
2392 if METADATA_LABELS.contains(&destination)
2393 || carried.iter().any(|tag| tag.as_ref() == destination)
2394 {
2395 return false;
2396 }
2397 if rewrite.writes_value() {
2400 carried.push(Arc::from(destination));
2401 }
2402 }
2403 MapOp::Math(_) | MapOp::Histogram(_) => drops_metadata = true,
2404 }
2405 }
2406 (!drops_metadata || labels.is_some_and(|labels| labels.keys_survive_metadata_drop))
2407 && preserves_partition_identity(input, labels)
2408}
2409
2410fn broadcast_preserves_partition_identity(
2418 left: &NativeNode,
2419 right: &NativeNode,
2420 matching: &BinaryMatching,
2421 labels: Option<&StoredSeriesLabels>,
2422) -> bool {
2423 let (vector, scalar) = if matches!(left.output, NativeType::Scalar(_)) {
2424 (right, left)
2425 } else {
2426 (left, right)
2427 };
2428 if !matches!(scalar.output, NativeType::Scalar(_)) || !scalar.is_data_free() {
2431 return false;
2432 }
2433 let keeps_labels = !matching.return_bool
2434 && matches!(
2435 matching.op,
2436 BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Gt | BinaryOp::Lt | BinaryOp::Ge | BinaryOp::Le
2437 );
2438 (keeps_labels || labels.is_some_and(|labels| labels.keys_survive_metadata_drop))
2439 && preserves_partition_identity(vector, labels)
2440}
2441
2442fn bound_tags_cover_primary_key(label_source: &RawLabelSource) -> bool {
2449 let RawLabelSource::PrimaryKey {
2450 physical_metadata,
2451 logical_tags,
2452 ..
2453 } = label_source
2454 else {
2455 return false;
2456 };
2457 let bound_ids = logical_tags
2458 .iter()
2459 .map(|tag| tag.column_id)
2460 .collect::<std::collections::HashSet<_>>();
2461 let table_id = store_api::storage::consts::ReservedColumnId::table_id();
2462 let tsid = store_api::storage::consts::ReservedColumnId::tsid();
2463 physical_metadata.primary_key_columns().all(|column| {
2464 column.column_id == table_id
2465 || column.column_id == tsid
2466 || bound_ids.contains(&column.column_id)
2467 })
2468}
2469
2470enum InputProof {
2472 Scan(Option<StoredSeriesLabels>),
2475 Confined,
2478}
2479
2480fn complete_series_input(plan: &dyn ExecutionPlan) -> Option<InputProof> {
2482 if let Some(scan) = plan.downcast_ref::<SeriesScanExec>() {
2483 let binding = scan.scan_binding();
2484 return bound_tags_cover_primary_key(binding)
2485 .then(|| InputProof::Scan(StoredSeriesLabels::of(binding)));
2486 }
2487 if let Some(source) = plan.downcast_ref::<RawSeriesSourceExec>() {
2488 if !source.is_per_series_scan() {
2492 return None;
2493 }
2494 return complete_series_input(source.children().first()?.as_ref());
2495 }
2496 if let Some(cooperative) = plan.downcast_ref::<CooperativeExec>() {
2497 return complete_series_input(cooperative.children().first()?.as_ref());
2498 }
2499 plan.downcast_ref::<FusedSeriesExec>()
2500 .filter(|fused| fused.has_partition_disjoint_identities())
2501 .map(|_| InputProof::Confined)
2502}
2503
2504impl FusedSeriesExec {
2505 pub fn has_partition_disjoint_identities(&self) -> bool {
2529 if self.inputs.len() != 1 {
2530 return false;
2531 }
2532 let Some(proof) = complete_series_input(self.inputs[0].0.as_ref()) else {
2533 return false;
2534 };
2535 let labels = match proof {
2536 InputProof::Scan(labels) => labels,
2537 InputProof::Confined => None,
2538 };
2539 if self.format == FusedOutputFormat::PlainRows
2542 && let Some(labels) = &labels
2543 && !labels.answers_every_tag(&self.tags)
2544 {
2545 return false;
2546 }
2547 preserves_partition_identity(self.tree.root(), labels.as_ref())
2548 }
2549
2550 #[allow(clippy::too_many_arguments)]
2561 pub fn try_new(
2562 promql: Arc<str>,
2563 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
2564 tree: Arc<NativeTree>,
2565 output_schema: SchemaRef,
2566 time_column: String,
2567 tags: Vec<String>,
2568 ) -> DataFusionResult<Self> {
2569 Self::build(
2570 promql,
2571 inputs,
2572 tree,
2573 output_schema,
2574 time_column,
2575 tags,
2576 None,
2577 FusedOutputFormat::PlainRows,
2578 None,
2579 false,
2580 )
2581 }
2582
2583 #[allow(clippy::too_many_arguments)]
2584 fn build(
2585 promql: Arc<str>,
2586 inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
2587 tree: Arc<NativeTree>,
2588 output_schema: SchemaRef,
2589 time_column: String,
2590 tags: Vec<String>,
2591 metric_name: Option<Arc<str>>,
2592 format: FusedOutputFormat,
2593 matching_parallelism: Option<usize>,
2594 canonical_producer: bool,
2595 ) -> DataFusionResult<Self> {
2596 let locality = if canonical_producer {
2601 InputLocality::PartitionLocal
2602 } else {
2603 input_locality(tree.root())
2604 };
2605 if canonical_producer {
2606 if !matches!(tree.root().expr, NativeExpr::Merge { .. }) {
2607 return Err(DataFusionError::Plan(
2608 "a canonical boundary requires a merge at the tree's root".into(),
2609 ));
2610 }
2611 if matches!(&tree.root().output, NativeType::AggregateState(_)) {
2612 return Err(DataFusionError::Plan(
2613 "a canonical boundary exports series frames, not aggregate state".into(),
2614 ));
2615 }
2616 if format != FusedOutputFormat::SeriesFrame {
2617 return Err(DataFusionError::Plan(
2618 "a canonical merge producer exports a series frame".into(),
2619 ));
2620 }
2621 }
2622 let (raw_schemas, source_kinds, root_kind) = validate_physical_tree(&tree)?;
2623 if inputs.len() != raw_schemas.len() {
2624 return Err(DataFusionError::Plan(format!(
2625 "FusedSeries physical input count {} does not match its {} raw sources",
2626 inputs.len(),
2627 raw_schemas.len()
2628 )));
2629 }
2630 let _ =
2632 NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()), None)?;
2633 let output_series = tree.root().output.samples();
2634 let scalar_root = matches!(tree.root().output, NativeType::Scalar(_));
2635 let partial_root = matches!(&tree.root().expr, NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial);
2636 if partial_root && format != FusedOutputFormat::SeriesFrame {
2637 return Err(DataFusionError::Plan(
2638 "FusedSeries Partial stage requires SeriesFrame output".into(),
2639 ));
2640 }
2641 let frame_schema = if format == FusedOutputFormat::SeriesFrame {
2642 if inputs.iter().any(|(input, _, _)| {
2643 matches!(
2644 input.properties().boundedness,
2645 Boundedness::Unbounded { .. }
2646 )
2647 }) {
2648 return Err(DataFusionError::Plan(
2649 "FusedSeries SeriesFrame output requires finite input to publish final series"
2650 .into(),
2651 ));
2652 }
2653 let declared = output_frame_schema(&tree, root_kind)?;
2654 if declared != output_schema {
2655 return Err(DataFusionError::Plan(format!(
2656 "FusedSeriesExec schema does not match: declared {output_schema:?}, expected {declared:?}"
2657 )));
2658 }
2659 true
2660 } else {
2661 false
2662 };
2663 let classification = if partial_root || frame_schema {
2664 Vec::new()
2665 } else if scalar_root {
2666 let scalar_fields = scalar_root_fields(&output_schema, &tags, &time_column)?;
2667 classify_output(&output_schema, &scalar_fields, &tags, &time_column, &promql)?
2668 } else {
2669 classify_output(
2670 &output_schema,
2671 &output_series
2672 .ok_or_else(|| {
2673 DataFusionError::Plan("FusedSeries output is not samples".into())
2674 })?
2675 .fields,
2676 &tags,
2677 &time_column,
2678 &promql,
2679 )?
2680 };
2681 let partition_count = inputs.first().map_or(1, |(input, _, _)| {
2682 input.properties().partitioning.partition_count()
2683 });
2684 let window_sources = if raw_schemas.iter().any(|schema| schema.eval_grid.is_some())
2685 && inputs
2686 .iter()
2687 .any(|(input, _, _)| input.properties().partitioning.partition_count() > 1)
2688 {
2689 partitioned_window_sources(tree.root())?
2690 .into_iter()
2691 .filter(|&index| raw_schemas[index].eval_grid.is_some())
2692 .collect()
2693 } else {
2694 Vec::new()
2695 };
2696 for (index, (input, label_source, ordering)) in inputs.iter().enumerate() {
2697 let count = input.properties().partitioning.partition_count();
2698 if count == 0 {
2699 return Err(DataFusionError::Plan(format!(
2700 "FusedSeries input {index} has no partitions"
2701 )));
2702 }
2703 if count != partition_count {
2704 return Err(DataFusionError::Plan(format!(
2705 "FusedSeries input {index} has {count} partitions; every source must have the same positive count ({partition_count})"
2706 )));
2707 }
2708 let state = source_kinds[index] == FusedInputKind::AggregateState;
2713 if state && count > 1 {
2714 let (owners, policy) = state_routing(tree.root()).ok_or_else(|| {
2715 DataFusionError::Plan(
2716 "FusedSeries reads aggregate state but holds no Final aggregate".into(),
2717 )
2718 })?;
2719 if owners == StateGroup::Single
2720 || input
2721 .downcast_ref::<SeriesRepartitionExec>()
2722 .is_none_or(|router| {
2723 router.outputs() != count || router.routing_policy() != &policy
2724 })
2725 {
2726 return Err(DataFusionError::Plan(format!(
2727 "FusedSeries state input {index} requires a direct owner router with the Final routing policy"
2728 )));
2729 }
2730 }
2731 if matches!(locality, InputLocality::SinglePartition) && count != 1 && !state {
2732 return Err(DataFusionError::Plan(format!(
2733 "FusedSeries global evaluated input {index} must have one partition"
2734 )));
2735 }
2736 if let InputLocality::MatchingLocal(policy) = &locality
2737 && count > 1
2738 && input
2739 .downcast_ref::<SeriesRepartitionExec>()
2740 .is_none_or(|router| {
2741 router.outputs() != count
2742 || router.routing_policy() != &SeriesRouting::Matching(policy.clone())
2743 })
2744 {
2745 return Err(DataFusionError::Plan(format!(
2746 "FusedSeries matching-local input {index} requires a direct matching-key SeriesRepartitionExec with {count} outputs"
2747 )));
2748 }
2749 if window_sources.contains(&index)
2750 && count > 1
2751 && input.downcast_ref::<SeriesRepartitionExec>().is_none()
2752 {
2753 return Err(DataFusionError::Plan(format!(
2754 "FusedSeries partitioned window input {index} requires a direct SeriesRepartitionExec owner router"
2755 )));
2756 }
2757 let declaration = SeriesFrameDeclaration::parse(input.schema().as_ref())
2758 .map_err(|error| DataFusionError::Plan(error.to_string()))?;
2759 let actual_ordering = series_frame_ordering(input.schema().as_ref())
2760 .map_err(|error| DataFusionError::Plan(error.to_string()))?;
2761 if actual_ordering != *ordering {
2762 return Err(DataFusionError::Plan(format!(
2763 "FusedSeries source {index} supplied ordering does not match its frame declaration"
2764 )));
2765 }
2766 if declaration.content() == FrameContent::Evaluated
2767 && actual_ordering != SeriesOrdering::Contiguous
2768 {
2769 return Err(DataFusionError::Plan(format!(
2770 "FusedSeries evaluated source {index} must declare contiguous ordering"
2771 )));
2772 }
2773 let evaluated_global = raw_schemas[index].eval_grid.is_some()
2774 && matches!(locality, InputLocality::SinglePartition);
2775 let required_ordering = if evaluated_global || (inputs.len() > 1 && count > 1) {
2776 SeriesOrdering::Contiguous
2777 } else {
2778 *ordering
2779 };
2780 if tree
2781 .root()
2782 .inputs()
2783 .iter()
2784 .filter(|node| node.source_index == index)
2785 .any(|node| !ordering_satisfies(required_ordering, node.ordering))
2786 {
2787 return Err(DataFusionError::Plan(format!(
2788 "FusedSeries producer ordering for source {index} does not satisfy every input"
2789 )));
2790 }
2791 ensure_frame_matches_label_source(input.schema().as_ref(), label_source)?;
2792 let expected_content = match source_kinds[index] {
2793 FusedInputKind::Raw => FrameContent::Raw,
2794 FusedInputKind::Evaluated => FrameContent::Evaluated,
2795 FusedInputKind::AggregateState => FrameContent::AggregateState,
2796 };
2797 if declaration.content() != expected_content {
2798 return Err(DataFusionError::Plan(format!(
2799 "FusedSeries source {index} frame content does not match its compiled input"
2800 )));
2801 }
2802 let empty = || {
2803 Box::pin(RecordBatchStreamAdapter::new(
2804 input.schema(),
2805 futures::stream::empty(),
2806 ))
2807 };
2808 match source_kinds[index] {
2809 FusedInputKind::Evaluated => {
2810 let _ = unpack_evaluated_series(empty(), Some(raw_schemas[index].clone()))?;
2811 }
2812 FusedInputKind::Raw => {
2813 unpack_raw_series(empty(), Some(raw_schemas[index].clone()))?;
2814 }
2815 FusedInputKind::AggregateState => {
2816 let bound = tree
2817 .root()
2818 .inputs()
2819 .into_iter()
2820 .find(|bound| bound.source_index == index)
2821 .ok_or_else(|| {
2822 DataFusionError::Plan(format!(
2823 "FusedSeries state source {index} has no bound input"
2824 ))
2825 })?;
2826 let NativeType::AggregateState(state) = &bound.output else {
2827 return Err(DataFusionError::Plan(format!(
2828 "FusedSeries source {index} is declared aggregate state but its binding is not"
2829 )));
2830 };
2831 let _ = unpack_aggregate_state(
2832 empty(),
2833 Some(Arc::new(
2834 datatypes::series::aggregate_state::AggregateStateSchema::try_new(
2835 state.kind,
2836 state.components.to_vec(),
2837 )
2838 .map_err(|error| DataFusionError::Plan(error.to_string()))?,
2839 )),
2840 Some(raw_schemas[index].clone()),
2841 )?;
2842 }
2843 }
2844 }
2845 let properties = Arc::new(PlanProperties::new(
2846 EquivalenceProperties::new(output_schema.clone()),
2847 Partitioning::UnknownPartitioning(partition_count),
2848 if partial_root || frame_schema {
2849 EmissionType::Final
2851 } else {
2852 inputs.first().map_or(EmissionType::Final, |(input, _, _)| {
2855 input.properties().emission_type
2856 })
2857 },
2858 inputs
2859 .first()
2860 .map_or(Boundedness::Bounded, |(input, _, _)| {
2861 input.properties().boundedness
2862 }),
2863 ));
2864 let metric = Arc::new(ExecutionPlanMetricsSet::new());
2865 register_tree_metric(&tree, &metric);
2866 let own_metrics = metric.clone_inner();
2867 Ok(Self {
2868 promql,
2869 tree,
2870 series_schemas: raw_schemas,
2871 source_kinds,
2872 inputs,
2873 classification: classification.into(),
2874 time_column,
2875 tags: tags.into(),
2876 metric_name,
2877 output_schema,
2878 duplicate_evidence: Mutex::new(EvidenceClaims {
2879 evidence: None,
2880 claimed: Vec::new(),
2881 }),
2882 metric,
2883 own_metrics,
2884 properties,
2885 format,
2886 matching_parallelism,
2887 canonical_producer,
2888 })
2889 }
2890
2891 pub const fn name() -> &'static str {
2893 "FusedSeriesExec"
2894 }
2895
2896 fn node_metrics(&self) -> NodeMetricsSnapshot {
2898 NodeMetricsSnapshot::read(&self.metric)
2899 }
2900
2901 pub fn node_metric_set(&self) -> MetricsSet {
2907 self.metric.clone_inner()
2908 }
2909}
2910
2911#[cfg(feature = "test-utils")]
2912pub fn is_canonical_producer_exec(plan: &dyn ExecutionPlan) -> bool {
2913 plan.downcast_ref::<FusedSeriesExec>()
2914 .is_some_and(|fused| fused.canonical_producer)
2915}
2916
2917impl std::fmt::Debug for FusedSeriesExec {
2918 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2919 f.debug_struct("FusedSeriesExec").finish()
2920 }
2921}
2922
2923impl DisplayAs for FusedSeriesExec {
2924 fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
2930 write!(f, "FusedSeriesExec")?;
2931 if self.format == FusedOutputFormat::SeriesFrame {
2934 write!(f, ": (output: series_frame)")?;
2935 }
2936 write!(
2937 f,
2938 "\nnative_tree=[\n{}\n]",
2939 self.tree.display_with(&self.node_metrics())
2940 )
2941 }
2942}
2943
2944impl ExecutionPlan for FusedSeriesExec {
2945 fn name(&self) -> &str {
2946 Self::name()
2947 }
2948
2949 fn metrics(&self) -> Option<MetricsSet> {
2957 Some(self.own_metrics.clone())
2958 }
2959
2960 fn properties(&self) -> &Arc<PlanProperties> {
2961 &self.properties
2962 }
2963
2964 fn input_distribution_requirements(&self) -> InputDistributionRequirements {
2968 InputDistributionRequirements::new(
2969 self.inputs
2970 .iter()
2971 .map(|(_, _, _)| Distribution::UnspecifiedDistribution)
2972 .collect(),
2973 )
2974 }
2975
2976 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
2980 vec![false; self.inputs.len()]
2981 }
2982
2983 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
2984 self.inputs.iter().map(|(input, _, _)| input).collect()
2985 }
2986
2987 fn apply_expressions(
2988 &self,
2989 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> DataFusionResult<TreeNodeRecursion>,
2990 ) -> DataFusionResult<TreeNodeRecursion> {
2991 Ok(TreeNodeRecursion::Continue)
2993 }
2994
2995 fn with_new_children(
2996 self: Arc<Self>,
2997 children: Vec<Arc<dyn ExecutionPlan>>,
2998 ) -> DataFusionResult<Arc<dyn ExecutionPlan>> {
2999 if children.len() != self.inputs.len() {
3000 return Err(DataFusionError::Plan(format!(
3001 "FusedSeriesExec requires {} children, got {}",
3002 self.inputs.len(),
3003 children.len()
3004 )));
3005 }
3006 let children = children
3007 .into_iter()
3008 .zip(&self.inputs)
3009 .map(|(child, (_, label_source, ordering))| (child, label_source.clone(), *ordering))
3010 .collect();
3011 Ok(Arc::new(Self::build(
3014 Arc::clone(&self.promql),
3015 children,
3016 Arc::clone(&self.tree),
3017 self.output_schema.clone(),
3018 self.time_column.clone(),
3019 self.tags.to_vec(),
3020 self.metric_name.clone(),
3021 self.format,
3022 self.matching_parallelism,
3023 self.canonical_producer,
3024 )?))
3025 }
3026
3027 fn execute(
3028 &self,
3029 partition: usize,
3030 context: Arc<TaskContext>,
3031 ) -> DataFusionResult<SendableRecordBatchStream> {
3032 let FusedExecution { stream, state } = self.output_stream(partition, context)?;
3033 match (self.format, state) {
3034 (FusedOutputFormat::SeriesFrame, Some(state)) => {
3035 let source: SendableStateSeriesStream = Box::pin(FusedStateStream {
3036 source: stream,
3037 pending: Vec::new().into_iter(),
3038 reservation: None,
3039 });
3040 Ok(pack_aggregate_state(source, state.declared, state.series)?)
3041 }
3042 (FusedOutputFormat::SeriesFrame, None) => {
3043 let schema = evaluated_output(&self.tree)?;
3044 let source: SendableEvaluatedSeriesStream =
3045 Box::pin(FusedEvaluatedStream { source: stream });
3046 Ok(pack_evaluated_series(source, schema)?)
3047 }
3048 (FusedOutputFormat::PlainRows, _) => Ok(Box::pin(stream)),
3050 }
3051 }
3052}
3053
3054impl SeriesExecutionPlan for FusedSeriesExec {
3055 fn as_any(&self) -> &dyn Any {
3056 self
3057 }
3058
3059 fn execute_series(
3065 &self,
3066 partition: usize,
3067 context: Arc<TaskContext>,
3068 ) -> DataFusionResult<SendableSeriesStream> {
3069 if self.format != FusedOutputFormat::SeriesFrame {
3070 return Err(DataFusionError::Execution(format!(
3071 "FusedSeries partition {partition} answers a row table, which is read as rows"
3072 )));
3073 }
3074 let FusedExecution { stream, state } = self.output_stream(partition, context)?;
3075 match state {
3076 Some(state) => Ok(Box::pin(FusedStateChunks {
3077 source: stream,
3078 declared: state.binding,
3079 pending: Vec::new().into_iter(),
3080 })),
3081 None => {
3082 let source: SendableEvaluatedSeriesStream =
3083 Box::pin(FusedEvaluatedStream { source: stream });
3084 Ok(Box::pin(FusedEvaluatedChunks { source }))
3085 }
3086 }
3087 }
3088}
3089
3090impl FusedSeriesExec {
3091 pub fn hands_over_series(&self) -> bool {
3096 self.format == FusedOutputFormat::SeriesFrame
3097 }
3098
3099 fn output_stream(
3104 &self,
3105 partition: usize,
3106 context: Arc<TaskContext>,
3107 ) -> DataFusionResult<FusedExecution> {
3108 if partition >= self.properties.partitioning.partition_count() {
3109 return Err(DataFusionError::Execution(
3110 "FusedSeries output partition is out of range".into(),
3111 ));
3112 }
3113 let partitions = self.properties.partitioning.partition_count();
3114 let needs_evidence = partitions > 1 && native_tree_has_vector_binary(self.tree.root());
3115 let evidence = if needs_evidence {
3116 Some(claim_evidence(
3117 &self.duplicate_evidence,
3118 partition,
3119 partitions,
3120 &context.runtime_env().memory_pool,
3121 )?)
3122 } else {
3123 None
3124 };
3125 let mut claim = evidence.as_ref().map(|evidence| EvidenceClaim {
3126 evidence: Arc::clone(evidence),
3127 active: true,
3128 });
3129 let sources = SourceFacts::uniform(
3133 self.tags.to_vec(),
3134 self.metric_name.clone(),
3135 self.series_schemas.len(),
3136 );
3137 let mut state = match NativeExecutionState::try_new_with_sources(
3138 &self.tree,
3139 Arc::clone(&context.runtime_env().memory_pool),
3140 evidence.clone(),
3141 &sources,
3142 ) {
3143 Ok(state) => state,
3144 Err(error) => {
3145 if let Some(claim) = &mut claim {
3146 claim.abort();
3147 }
3148 return Err(error);
3149 }
3150 };
3151 if let Some(collector) = context
3157 .session_config()
3158 .options()
3159 .extensions
3160 .get::<PromqlAnnotationCollector>()
3161 {
3162 state.set_annotations(Some(collector.clone()));
3163 }
3164 state.register_metrics(&self.metric, partition);
3165 let mut streams: Vec<futures::stream::BoxStream<'static, Result<FusedFeed, BoxedError>>> =
3166 Vec::new();
3167 let bound_inputs = self.tree.root().inputs();
3168 for (source, (input, _, ordering)) in self.inputs.iter().enumerate() {
3169 let kind = self.source_kinds[source];
3170 if let Some(series_plan) = series_execution_plan(input.as_ref()) {
3176 let chunks = series_plan.execute_series(partition, Arc::clone(&context))?;
3177 let chunks = checked_series_stream(chunks, *ordering);
3178 let state = match kind {
3182 FusedInputKind::AggregateState => {
3183 Some(state_binding_of(&bound_inputs, source)?)
3184 }
3185 FusedInputKind::Raw | FusedInputKind::Evaluated => None,
3186 };
3187 let series = Arc::clone(&self.series_schemas[source]);
3188 streams.push(
3189 chunks
3190 .map(move |item| {
3191 item.and_then(|chunk| {
3192 in_process_feed(source, kind, &series, state.as_ref(), chunk)
3193 })
3194 })
3195 .boxed(),
3196 );
3197 continue;
3198 }
3199 let frames = input.execute(partition, Arc::clone(&context))?;
3200 match kind {
3201 FusedInputKind::Evaluated => {
3202 let decoded = unpack_evaluated_series(
3203 frames,
3204 Some(Arc::clone(&self.series_schemas[source])),
3205 )?;
3206 streams.push(
3207 decoded
3208 .map(move |item| {
3209 item.map(|(series, is_last)| FusedFeed {
3210 source,
3211 charge: None,
3212 chunk: FusedChunk::Evaluated(EvaluatedChunk {
3213 series,
3214 is_last,
3215 }),
3216 })
3217 })
3218 .boxed(),
3219 );
3220 }
3221 FusedInputKind::AggregateState => {
3222 let binding = state_binding_of(&bound_inputs, source)?;
3223 let declared = Arc::new(
3224 datatypes::series::aggregate_state::AggregateStateSchema::try_new(
3225 binding.kind,
3226 binding.components.to_vec(),
3227 )
3228 .map_err(|error| DataFusionError::Plan(error.to_string()))?,
3229 );
3230 let decoded = unpack_aggregate_state(
3231 frames,
3232 Some(declared.clone()),
3233 Some(Arc::clone(&self.series_schemas[source])),
3234 )?;
3235 streams.push(
3236 decoded
3237 .map(move |item| match item {
3238 Ok(row) => state_row_from_frame_row(row, &binding)
3239 .map(|row| FusedFeed {
3240 source,
3241 charge: None,
3242 chunk: FusedChunk::State(StateChunk::Row(row)),
3243 })
3244 .map_err(|error| {
3245 BoxedError::new(common_query::error::Error::from(error))
3246 }),
3247 Err(error) => Err(error),
3248 })
3249 .boxed(),
3250 );
3251 }
3252 FusedInputKind::Raw => {
3253 let raw =
3254 unpack_raw_series(frames, Some(Arc::clone(&self.series_schemas[source])))?;
3255 let raw = materialize_raw_labels(raw)
3256 .map_err(|error| DataFusionError::External(Box::new(error)))?;
3257 streams.push(
3258 raw.map(move |item| {
3259 item.map(|chunk| FusedFeed {
3260 source,
3261 charge: None,
3262 chunk: FusedChunk::Raw(chunk),
3263 })
3264 })
3265 .boxed(),
3266 );
3267 }
3268 }
3269 }
3270 let input_ids = (0..self.series_schemas.len())
3271 .map(|source| state.input_ids(source).collect())
3272 .collect();
3273 let state_binding = match (&self.tree.root().expr, &self.tree.root().output) {
3276 (NativeExpr::Aggregate { op, .. }, NativeType::AggregateState(binding))
3277 if op.stage == AggregateStage::Partial =>
3278 {
3279 Some(Arc::clone(binding))
3280 }
3281 (NativeExpr::Aggregate { op, .. }, _) if op.stage == AggregateStage::Partial => {
3282 return Err(DataFusionError::Plan(
3283 "FusedSeries Partial root must produce aggregate state".into(),
3284 ));
3285 }
3286 _ => None,
3287 };
3288 let state_mode = state_binding.is_some();
3289 let state_schema = state_binding
3290 .as_ref()
3291 .map(|binding| {
3292 datatypes::series::aggregate_state::AggregateStateSchema::try_new(
3293 binding.kind,
3294 binding.components.to_vec(),
3295 )
3296 .map(Arc::new)
3297 .map_err(|error| DataFusionError::Plan(error.to_string()))
3298 })
3299 .transpose()?;
3300 let mut executor = NativeExecutor::new(state);
3301 let inputs = if streams.is_empty() {
3302 executor.end_of_input()?;
3303 None
3304 } else {
3305 Some(futures::stream::select_all(streams))
3306 };
3307 let frame_mode = self.format == FusedOutputFormat::SeriesFrame && !state_mode;
3310 let stream = FusedSeriesStream {
3311 inputs,
3312 executor: Some(executor),
3313 input_ids,
3314 classification: Arc::clone(&self.classification),
3315 tags: Arc::clone(&self.tags),
3316 output_schema: self.output_schema.clone(),
3317 state_mode,
3318 frame_mode,
3319 ready: VecDeque::new(),
3320 done: false,
3321 duplicate_evidence: evidence,
3322 evidence_completed: false,
3323 evidence_claim: claim,
3324 };
3325 Ok(FusedExecution {
3326 state: state_binding.as_ref().map(|binding| FusedStateOutput {
3327 declared: state_schema
3328 .clone()
3329 .expect("a binding declares a frame state layout"),
3330 binding: Arc::clone(binding),
3331 series: Arc::new(SeriesSchema {
3332 fields: binding.accumulators.clone(),
3333 eval_grid: Some(Arc::clone(&binding.grid)),
3334 }),
3335 }),
3336 stream,
3337 })
3338 }
3339}
3340
3341impl Drop for FusedSeriesStream {
3342 fn drop(&mut self) {
3343 if !self.evidence_completed
3344 && let Some(claim) = &mut self.evidence_claim
3345 {
3346 claim.abort();
3347 }
3348 }
3349}
3350
3351pub(crate) fn series_to_record_batch(
3356 classification: &[OutputColumn],
3357 tags: &[String],
3358 output_schema: &SchemaRef,
3359 chunk: &EvaluatedChunk,
3360) -> DataFusionResult<RecordBatch> {
3361 let series = &chunk.series;
3362 let timestamps = match chunk.range() {
3368 Some(range) => range.timestamps(),
3369 None => series
3370 .time
3371 .timestamps()
3372 .map(|timestamps| ScalarBuffer::from(timestamps.into_owned())),
3373 }
3374 .map_err(|error| DataFusionError::Execution(error.to_string()))?;
3375 let rows = timestamps.len();
3376 let mut columns: Vec<ArrayRef> = Vec::with_capacity(classification.len());
3377 for (position, column) in classification.iter().enumerate() {
3378 match column {
3379 OutputColumn::Time => columns.push(Arc::new(TimestampMillisecondArray::new(
3380 timestamps.clone(),
3381 None,
3382 ))),
3383 OutputColumn::Field { index, kind } => {
3384 let samples = series.fields.get(*index).ok_or_else(|| {
3385 DataFusionError::Execution(format!(
3386 "evaluated series has no field at index {index}"
3387 ))
3388 })?;
3389 if samples.len() != rows {
3390 return Err(DataFusionError::Execution(format!(
3391 "evaluated series field {index} has {} rows, time axis has {rows}",
3392 samples.len()
3393 )));
3394 }
3395 columns.push(field_column(samples, *kind)?);
3396 }
3397 OutputColumn::Tag(index) => {
3398 let name = tags.get(*index).ok_or_else(|| {
3400 DataFusionError::Execution(format!(
3401 "output column {position} declares unavailable tag {index}"
3402 ))
3403 })?;
3404 let value = series.metric.get(name);
3405 columns.push(Arc::new(StringArray::from(vec![value; rows])));
3406 }
3407 }
3408 }
3409 Ok(RecordBatch::try_new(output_schema.clone(), columns)?)
3410}
3411
3412fn field_column(samples: &Samples, kind: FieldKind) -> DataFusionResult<ArrayRef> {
3419 match kind {
3420 FieldKind::Float => float_column(samples),
3421 FieldKind::Histogram => histogram_column(samples),
3422 }
3423}
3424
3425fn float_column(samples: &Samples) -> DataFusionResult<ArrayRef> {
3426 match samples.dense() {
3427 Some(DenseSamplesRef::Float(values)) => Ok(Arc::new(values.clone())),
3428 Some(DenseSamplesRef::Histogram(_)) | Some(DenseSamplesRef::Mixed(_)) => {
3429 Err(DataFusionError::Execution(
3430 "a Float64 output column cannot carry histogram samples".into(),
3431 ))
3432 }
3433 None => {
3434 let values = samples
3435 .iter()
3436 .map(|sample| match sample {
3437 SampleRef::Float(value) => Ok(Some(value)),
3438 SampleRef::Missing => Ok(None),
3439 SampleRef::Histogram(_) => Err(DataFusionError::Execution(
3440 "a Float64 output column cannot carry histogram samples".into(),
3441 )),
3442 })
3443 .collect::<DataFusionResult<Vec<_>>>()?;
3444 Ok(Arc::new(Float64Array::from(values)))
3445 }
3446 }
3447}
3448
3449#[derive(Debug)]
3451enum FusedChunk {
3452 Raw(RawSeriesChunk),
3454 Evaluated(EvaluatedChunk),
3456 State(StateChunk),
3458}
3459
3460struct FusedExecution {
3462 stream: FusedSeriesStream,
3464 state: Option<FusedStateOutput>,
3466}
3467
3468struct FusedStateOutput {
3470 declared: Arc<datatypes::series::aggregate_state::AggregateStateSchema>,
3472 binding: Arc<AggregateStateSchema>,
3474 series: Arc<SeriesSchema>,
3476}
3477
3478struct FusedFeed {
3485 source: usize,
3486 chunk: FusedChunk,
3487 charge: Option<SeriesCharge>,
3488}
3489
3490fn in_process_feed(
3496 source: usize,
3497 kind: FusedInputKind,
3498 series: &Arc<SeriesSchema>,
3499 state: Option<&Arc<AggregateStateSchema>>,
3500 handed: HandedSeriesChunk,
3501) -> Result<FusedFeed, BoxedError> {
3502 let (chunk, charge) = handed.into_parts();
3503 let chunk = match (kind, chunk) {
3504 (FusedInputKind::Raw, SeriesChunk::Raw(chunk)) => FusedChunk::Raw(chunk),
3505 (FusedInputKind::Evaluated, SeriesChunk::Evaluated(chunk)) => FusedChunk::Evaluated(chunk),
3506 (FusedInputKind::AggregateState, SeriesChunk::State(chunk)) => {
3507 let Some(binding) = state else {
3508 return Err(failed(format!(
3509 "FusedSeries state source {source} binds no aggregate state"
3510 )));
3511 };
3512 match &chunk {
3518 StateChunk::Row(row) => {
3519 if row.kind != binding.kind
3520 || row.fields.components() != binding.components.as_ref()
3521 {
3522 return Err(failed(format!(
3523 "FusedSeries state source {source} was handed {:?} state, not the {:?} \
3524 state it binds",
3525 row.kind, binding.kind
3526 )));
3527 }
3528 }
3529 StateChunk::Series { state_schema, .. } => {
3530 if state_schema.kind != binding.kind
3531 || state_schema.components.as_ref() != binding.components.as_ref()
3532 {
3533 return Err(failed(format!(
3534 "FusedSeries state source {source} was handed {:?} state, not the {:?} \
3535 state it binds",
3536 state_schema.kind, binding.kind
3537 )));
3538 }
3539 let declared = SeriesSchema {
3540 fields: state_schema.accumulators.clone(),
3541 eval_grid: Some(Arc::clone(&state_schema.grid)),
3542 };
3543 ensure_declared_series(&declared, series, source)?;
3544 }
3545 }
3546 FusedChunk::State(chunk)
3547 }
3548 (kind, chunk) => {
3549 return Err(failed(format!(
3550 "FusedSeries source {source} is bound to {kind:?} but its operator handed over \
3551 {chunk:?}"
3552 )));
3553 }
3554 };
3555 Ok(FusedFeed {
3556 source,
3557 chunk,
3558 charge,
3559 })
3560}
3561
3562fn state_binding_of(
3567 inputs: &[&BoundInput],
3568 source: usize,
3569) -> DataFusionResult<Arc<AggregateStateSchema>> {
3570 let bound = inputs
3571 .iter()
3572 .find(|bound| bound.source_index == source)
3573 .ok_or_else(|| {
3574 DataFusionError::Plan(format!(
3575 "FusedSeries state source {source} has no bound input"
3576 ))
3577 })?;
3578 let NativeType::AggregateState(binding) = bound.output.clone() else {
3579 return Err(DataFusionError::Plan(format!(
3580 "FusedSeries source {source} is declared aggregate state but its binding is not"
3581 )));
3582 };
3583 Ok(binding)
3584}
3585
3586fn ensure_declared_series(
3592 declared: &SeriesSchema,
3593 expected: &SeriesSchema,
3594 source: usize,
3595) -> Result<(), BoxedError> {
3596 let same_fields = expected.fields.len() == declared.fields.len()
3597 && expected
3598 .fields
3599 .iter()
3600 .zip(declared.fields.iter())
3601 .all(|(left, right)| left.name == right.name);
3602 let same_grid = expected.eval_grid.as_ref().map(|grid| grid.spec())
3603 == declared.eval_grid.as_ref().map(|grid| grid.spec());
3604 if same_fields && same_grid {
3605 return Ok(());
3606 }
3607 Err(failed(format!(
3608 "FusedSeries source {source} was handed state of a series layout it does not bind"
3609 )))
3610}
3611
3612fn failed(reason: String) -> BoxedError {
3614 BoxedError::new(common_query::error::Error::from(
3615 DataFusionError::Execution(reason),
3616 ))
3617}
3618
3619fn histogram_column(samples: &Samples) -> DataFusionResult<ArrayRef> {
3625 let mut values: Vec<Option<NativeHistogram>> = Vec::with_capacity(samples.len());
3626 for sample in samples.iter() {
3627 match sample {
3628 SampleRef::Histogram(view) => values.push(Some(canonical_histogram(&view))),
3629 SampleRef::Missing => values.push(None),
3630 SampleRef::Float(_) => {
3631 return Err(DataFusionError::Execution(
3632 "a native histogram output column cannot carry float samples".into(),
3633 ));
3634 }
3635 }
3636 }
3637 Ok(build_histogram_array(&values))
3638}
3639
3640fn canonical_histogram(view: &HistogramView<'_>) -> NativeHistogram {
3645 let span = |side: &BucketSideView<'_>| {
3646 side.span_offsets
3647 .iter()
3648 .copied()
3649 .zip(side.span_lengths.iter().copied())
3650 .map(|(offset, length)| Span { offset, length })
3651 .collect::<Vec<_>>()
3652 };
3653 NativeHistogram {
3654 schema: view.schema,
3655 zero_threshold: view.zero_threshold,
3656 sum: view.sum,
3657 reset_hint: view.reset_hint,
3658 start_timestamp: view.start_timestamp,
3659 custom_values: view.custom_values.to_vec(),
3660 positive_spans: span(&view.positive),
3661 negative_spans: span(&view.negative),
3662 count: view.count,
3663 zero_count: view.zero_count,
3664 positive_buckets: view.positive.buckets.to_vec(),
3665 negative_buckets: view.negative.buckets.to_vec(),
3666 }
3667}
3668
3669pub struct FusedSeriesStream {
3671 inputs: Option<SelectAll<futures::stream::BoxStream<'static, Result<FusedFeed, BoxedError>>>>,
3677 executor: Option<NativeExecutor>,
3679 input_ids: Vec<Vec<InputId>>,
3681 classification: Arc<[OutputColumn]>,
3683 tags: Arc<[String]>,
3685 output_schema: SchemaRef,
3687 state_mode: bool,
3689 frame_mode: bool,
3691 ready: VecDeque<RecordBatch>,
3693 done: bool,
3695 duplicate_evidence: Option<Arc<DuplicateEvidence>>,
3696 evidence_completed: bool,
3697 evidence_claim: Option<EvidenceClaim>,
3698}
3699
3700struct EvidenceClaim {
3701 evidence: Arc<DuplicateEvidence>,
3702 active: bool,
3703}
3704
3705impl EvidenceClaim {
3706 fn abort(&mut self) {
3707 if self.active {
3708 self.evidence.abort();
3709 self.active = false;
3710 }
3711 }
3712 fn complete(&mut self) -> bool {
3713 if self.active {
3714 self.active = false;
3715 self.evidence.complete()
3716 } else {
3717 false
3718 }
3719 }
3720}
3721
3722impl Drop for EvidenceClaim {
3723 fn drop(&mut self) {
3724 self.abort();
3725 }
3726}
3727
3728impl FusedSeriesStream {
3729 fn push(&mut self, feed: FusedFeed) -> DataFusionResult<()> {
3731 let FusedFeed {
3732 source,
3733 chunk,
3734 charge,
3735 } = feed;
3736 let _charge = charge;
3741 let Some(executor) = self.executor.as_mut() else {
3742 return Err(DataFusionError::Execution(
3743 "FusedSeriesExec stream pushed a chunk after its execution closed".to_string(),
3744 ));
3745 };
3746 let input_ids = self.input_ids.get(source).ok_or_else(|| {
3747 DataFusionError::Execution(format!(
3748 "FusedSeries has no runtime input IDs for source {source}"
3749 ))
3750 })?;
3751 if let [input_id] = input_ids.as_slice() {
3756 match chunk {
3757 FusedChunk::Raw(value) => executor.push_raw(*input_id, value)?,
3758 FusedChunk::Evaluated(value) => executor.push_evaluated(*input_id, value)?,
3759 FusedChunk::State(chunk) => executor.push_state(*input_id, chunk)?,
3760 }
3761 } else {
3762 let chunk = Some(chunk);
3763 for input_id in input_ids {
3764 match chunk.as_ref().expect("the feed is read at most twice") {
3765 FusedChunk::Raw(value) => executor.push_raw(*input_id, value.clone())?,
3766 FusedChunk::Evaluated(value) => {
3767 executor.push_evaluated(*input_id, value.clone())?
3768 }
3769 FusedChunk::State(StateChunk::Row(row)) => {
3770 executor.push_state(*input_id, StateChunk::Row(row.clone()))?
3771 }
3772 FusedChunk::State(StateChunk::Series { .. }) => {
3773 return Err(DataFusionError::Execution(
3774 "one producer state batch cannot feed several runtime inputs"
3775 .to_string(),
3776 ));
3777 }
3778 }
3779 }
3780 }
3781 if self.frame_mode || self.state_mode {
3782 Ok(())
3783 } else {
3784 let mut settled = Vec::new();
3785 while let Some(chunk) = executor.next_chunk()? {
3786 settled.push(chunk);
3787 }
3788 for chunk in settled {
3789 self.convert_rows(chunk)?;
3790 }
3791 Ok(())
3792 }
3793 }
3794
3795 fn close_input(&mut self) -> DataFusionResult<()> {
3803 match self.executor.as_mut() {
3804 Some(executor) => executor.end_of_input(),
3805 None => Ok(()),
3807 }
3808 }
3809
3810 fn pull_one(&mut self) -> DataFusionResult<Option<EvaluatedChunk>> {
3817 if self.state_mode {
3818 return Ok(None);
3819 }
3820 let Some(executor) = self.executor.as_mut() else {
3821 return Ok(None);
3822 };
3823 match executor.next_chunk() {
3824 Ok(Some(chunk)) => Ok(Some(chunk)),
3825 Ok(None) => {
3826 self.executor = None;
3827 Ok(None)
3828 }
3829 Err(error) => Err(error),
3830 }
3831 }
3832
3833 fn fail(&mut self) {
3839 self.done = true;
3840 if !self.evidence_completed {
3841 if let Some(claim) = &mut self.evidence_claim {
3842 claim.abort();
3843 }
3844 self.evidence_completed = true;
3845 }
3846 self.executor = None;
3847 self.inputs = None;
3848 self.ready.clear();
3852 }
3853
3854 fn convert_rows(&mut self, chunk: EvaluatedChunk) -> DataFusionResult<()> {
3856 let batch = series_to_record_batch(
3857 &self.classification,
3858 &self.tags,
3859 &self.output_schema,
3860 &chunk,
3861 )?;
3862 self.ready.push_back(batch);
3863 Ok(())
3864 }
3865}
3866
3867enum FusedOutput {
3868 Rows(RecordBatch),
3869 Evaluated(EvaluatedChunk),
3870 State(StateChunk),
3872}
3873
3874impl FusedSeriesStream {
3875 fn poll_output(&mut self, cx: &mut Context<'_>) -> Poll<Option<DataFusionResult<FusedOutput>>> {
3876 for _ in 0..POLL_BUDGET {
3877 if let Some(batch) = self.ready.pop_front() {
3878 return Poll::Ready(Some(Ok(FusedOutput::Rows(batch))));
3879 }
3880 if self.state_mode && !self.done {
3881 match self
3882 .executor
3883 .as_mut()
3884 .map_or(Ok(None), NativeExecutor::next_state)
3885 {
3886 Ok(Some(chunk)) => return Poll::Ready(Some(Ok(FusedOutput::State(chunk)))),
3887 Ok(None) if self.inputs.is_none() => self.executor = None,
3888 Ok(None) => {}
3889 Err(error) => {
3890 self.fail();
3891 return Poll::Ready(Some(Err(error)));
3892 }
3893 }
3894 }
3895 if self.frame_mode && !self.done {
3896 match self
3897 .executor
3898 .as_mut()
3899 .map_or(Ok(None), NativeExecutor::next_chunk)
3900 {
3901 Ok(Some(chunk)) => return Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk)))),
3902 Ok(None) if self.inputs.is_none() => self.executor = None,
3903 Ok(None) => {}
3904 Err(error) => {
3905 self.fail();
3906 return Poll::Ready(Some(Err(error)));
3907 }
3908 }
3909 }
3910 if self.done {
3911 return Poll::Ready(None);
3912 }
3913 let Some(inputs) = self.inputs.as_mut() else {
3914 match self.pull_one() {
3915 Ok(Some(chunk)) if self.frame_mode => {
3916 return Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk))));
3917 }
3918 Ok(Some(chunk)) => {
3919 if let Err(error) = self.convert_rows(chunk) {
3920 self.fail();
3921 return Poll::Ready(Some(Err(error)));
3922 }
3923 }
3924 Ok(None) => {
3925 self.done = true;
3926 if self
3927 .evidence_claim
3928 .as_mut()
3929 .is_some_and(EvidenceClaim::complete)
3930 && let Some(candidate) = self
3931 .duplicate_evidence
3932 .as_ref()
3933 .and_then(|evidence| evidence.take_verdict())
3934 {
3935 self.fail();
3936 return Poll::Ready(Some(Err(DataFusionError::Execution(
3937 candidate.message(),
3938 ))));
3939 }
3940 self.evidence_completed = true;
3941 continue;
3942 }
3943 Err(error) => {
3944 self.fail();
3945 return Poll::Ready(Some(Err(error)));
3946 }
3947 }
3948 continue;
3949 };
3950 match Pin::new(inputs).poll_next(cx) {
3951 Poll::Pending => return Poll::Pending,
3952 Poll::Ready(None) => {
3953 self.inputs = None;
3954 if let Err(error) = self.close_input() {
3955 self.fail();
3956 return Poll::Ready(Some(Err(error)));
3957 }
3958 }
3959 Poll::Ready(Some(Err(error))) => {
3960 self.fail();
3961 return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error)))));
3962 }
3963 Poll::Ready(Some(Ok(feed))) => {
3964 if let Err(error) = self.push(feed) {
3965 self.fail();
3966 return Poll::Ready(Some(Err(error)));
3967 }
3968 }
3969 }
3970 }
3971 cx.waker().wake_by_ref();
3972 Poll::Pending
3973 }
3974}
3975
3976impl RecordBatchStream for FusedSeriesStream {
3977 fn schema(&self) -> SchemaRef {
3978 self.output_schema.clone()
3979 }
3980}
3981
3982impl Stream for FusedSeriesStream {
3983 type Item = DataFusionResult<RecordBatch>;
3984
3985 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
3986 match self.poll_output(cx) {
3987 Poll::Ready(Some(Ok(FusedOutput::Rows(batch)))) => Poll::Ready(Some(Ok(batch))),
3988 Poll::Ready(Some(Ok(FusedOutput::Evaluated(_) | FusedOutput::State(_)))) => {
3989 self.fail();
3990 Poll::Ready(Some(Err(DataFusionError::Internal(
3991 "evaluated chunk reached the row stream adapter".into(),
3992 ))))
3993 }
3994 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
3995 Poll::Ready(None) => Poll::Ready(None),
3996 Poll::Pending => Poll::Pending,
3997 }
3998 }
3999}
4000
4001struct FusedEvaluatedChunks {
4003 source: SendableEvaluatedSeriesStream,
4004}
4005
4006impl Stream for FusedEvaluatedChunks {
4007 type Item = Result<HandedSeriesChunk, BoxedError>;
4008
4009 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
4010 match Pin::new(&mut self.source).poll_next(cx) {
4011 Poll::Ready(Some(Ok((series, is_last)))) => {
4012 Poll::Ready(Some(Ok(HandedSeriesChunk::uncharged(
4013 SeriesChunk::Evaluated(EvaluatedChunk { series, is_last }),
4014 ))))
4015 }
4016 Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
4017 Poll::Ready(None) => Poll::Ready(None),
4018 Poll::Pending => Poll::Pending,
4019 }
4020 }
4021}
4022
4023struct FusedStateChunks {
4029 source: FusedSeriesStream,
4030 declared: Arc<AggregateStateSchema>,
4032 pending: std::vec::IntoIter<(
4039 datatypes::series::aggregate_state::StateSeries,
4040 Option<Arc<MemoryReservation>>,
4041 )>,
4042}
4043
4044impl Stream for FusedStateChunks {
4045 type Item = Result<HandedSeriesChunk, BoxedError>;
4046
4047 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
4048 let this = &mut *self;
4049 loop {
4050 if let Some((series, held)) = this.pending.next() {
4051 let chunk = SeriesChunk::State(StateChunk::Series {
4055 series: vec![series],
4056 state_schema: Arc::clone(&this.declared),
4057 reservation: None,
4058 });
4059 return Poll::Ready(Some(Ok(match held {
4060 Some(held) => {
4061 HandedSeriesChunk::charged(chunk, SeriesCharge::shared(vec![held]))
4062 }
4063 None => HandedSeriesChunk::uncharged(chunk),
4064 })));
4065 }
4066 match Pin::new(&mut this.source).poll_output(cx) {
4067 Poll::Ready(Some(Ok(FusedOutput::State(chunk)))) => {
4068 let StateChunk::Series {
4069 series,
4070 reservation,
4071 ..
4072 } = chunk
4073 else {
4074 Pin::new(&mut this.source).fail();
4075 return Poll::Ready(Some(Err(BoxedError::new(
4076 common_query::error::Error::from(DataFusionError::Internal(
4077 "row state reached the state chunk stream".into(),
4078 )),
4079 ))));
4080 };
4081 this.pending = {
4082 let held = reservation.map(Arc::new);
4084 series
4085 .into_iter()
4086 .map(|group| (group, held.clone()))
4087 .collect::<Vec<_>>()
4088 .into_iter()
4089 };
4090 }
4091 Poll::Ready(Some(Ok(_))) => {
4092 Pin::new(&mut this.source).fail();
4093 return Poll::Ready(Some(Err(BoxedError::new(
4094 common_query::error::Error::from(DataFusionError::Internal(
4095 "non-state output reached the state chunk stream".into(),
4096 )),
4097 ))));
4098 }
4099 Poll::Ready(Some(Err(error))) => {
4100 Pin::new(&mut this.source).fail();
4101 return Poll::Ready(Some(Err(BoxedError::new(
4102 common_query::error::Error::from(error),
4103 ))));
4104 }
4105 Poll::Ready(None) => return Poll::Ready(None),
4106 Poll::Pending => return Poll::Pending,
4107 }
4108 }
4109 }
4110}
4111
4112struct FusedEvaluatedStream {
4113 source: FusedSeriesStream,
4114}
4115
4116impl Stream for FusedEvaluatedStream {
4117 type Item = Result<(datatypes::series::samples::Series, bool), common_error::ext::BoxedError>;
4118
4119 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
4120 match Pin::new(&mut self.source).poll_output(cx) {
4121 Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk)))) => {
4122 Poll::Ready(Some(Ok((chunk.series, chunk.is_last))))
4123 }
4124 Poll::Ready(Some(Ok(FusedOutput::Rows(_) | FusedOutput::State(_)))) => {
4125 Pin::new(&mut self.source).fail();
4126 Poll::Ready(Some(Err(common_error::ext::BoxedError::new(
4127 common_query::error::Error::from(DataFusionError::Internal(
4128 "row batch reached the evaluated stream adapter".into(),
4129 )),
4130 ))))
4131 }
4132 Poll::Ready(Some(Err(error))) => {
4133 Pin::new(&mut self.source).fail();
4134 Poll::Ready(Some(Err(common_error::ext::BoxedError::new(
4135 common_query::error::Error::from(error),
4136 ))))
4137 }
4138 Poll::Ready(None) => Poll::Ready(None),
4139 Poll::Pending => Poll::Pending,
4140 }
4141 }
4142}
4143
4144struct FusedStateStream {
4145 source: FusedSeriesStream,
4146 pending: std::vec::IntoIter<datatypes::series::aggregate_state::StateSeries>,
4148 reservation: Option<MemoryReservation>,
4150}
4151
4152impl FusedStateStream {
4153 fn finish(&mut self) {
4155 self.pending = Vec::new().into_iter();
4156 self.reservation = None;
4157 }
4158}
4159
4160impl Stream for FusedStateStream {
4161 type Item = Result<(datatypes::series::aggregate_state::StateSeries, bool), BoxedError>;
4162
4163 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
4164 loop {
4165 if let Some(series) = self.pending.next() {
4166 return Poll::Ready(Some(Ok((series, true))));
4169 }
4170 self.reservation = None;
4176 self.pending = Vec::new().into_iter();
4177 match Pin::new(&mut self.source).poll_output(cx) {
4178 Poll::Ready(Some(Ok(FusedOutput::State(chunk)))) => {
4179 let StateChunk::Series {
4180 series,
4181 reservation,
4182 ..
4183 } = chunk
4184 else {
4185 Pin::new(&mut self.source).fail();
4186 self.finish();
4187 return Poll::Ready(Some(Err(BoxedError::new(
4188 common_query::error::Error::from(DataFusionError::Internal(
4189 "row state reached state export stream".into(),
4190 )),
4191 ))));
4192 };
4193 self.pending = series.into_iter();
4194 self.reservation = reservation;
4195 }
4196 Poll::Ready(Some(Ok(_))) => {
4197 Pin::new(&mut self.source).fail();
4198 self.finish();
4199 return Poll::Ready(Some(Err(BoxedError::new(
4200 common_query::error::Error::from(DataFusionError::Internal(
4201 "non-state output reached state stream".into(),
4202 )),
4203 ))));
4204 }
4205 Poll::Ready(Some(Err(error))) => {
4206 self.finish();
4207 return Poll::Ready(Some(Err(BoxedError::new(
4208 common_query::error::Error::from(error),
4209 ))));
4210 }
4211 Poll::Ready(None) => {
4212 self.finish();
4213 return Poll::Ready(None);
4214 }
4215 Poll::Pending => return Poll::Pending,
4216 }
4217 }
4218 }
4219}