From b59b1c0a235cd7c078378f3fa017ea2753a8f0a3 Mon Sep 17 00:00:00 2001 From: dennis zhuang Date: Wed, 2 Dec 2026 10:37:55 +0000 Subject: [PATCH] refactor(promql): type FusedSeries output modes and drop redundant checks (#10785) - FusedSeriesExec picks its output kind (rows, evaluated, state) once; each stream pulls its own output from one shared driver, removing the mode bools, FusedOutput and the "cannot happen" adapter arms. - The evidence claim alone tracks completion; drop the duplicated flag, the extra Drop impl and the second Arc. - Remove the unused FusedSeriesExec::try_new, write-only matching_parallelism, and exec checks the logical node already makes (canonical producer format is now checked on decode). - Share router helpers in to_execution_plan, the plain-row classification, and the aggregate-state schema conversions. - split: compute the state binding at the cut so into_trees cannot return None or a missing-grid error. - Trim restating comments. Signed-off-by: Dennis Zhuang --- src/promql/src/extension_plan/fused_series.rs | 1321 +++++------------ src/promql/src/native/split.rs | 56 +- 2 files changed, 438 insertions(+), 939 deletions(-) diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs index 079eebdc237..8fa2726a7aa 100644 --- a/src/promql/src/extension_plan/fused_series.rs +++ b/src/promql/src/extension_plan/fused_series.rs @@ -46,7 +46,6 @@ use std::any::Any; use std::cmp::Ordering; -use std::collections::VecDeque; use std::fmt::{self, Formatter}; use std::hash::{Hash, Hasher}; use std::pin::Pin; @@ -88,6 +87,7 @@ use datafusion::physical_plan::{ use datatypes::data_type::DataType as _; use datatypes::schema::ColumnSchema; use datatypes::series::SeriesOrdering; +use datatypes::series::aggregate_state::{AggregateStateSchema as FrameStateSchema, StateSeries}; use datatypes::series::frame::{ FrameContent, FrameLabelMode, SeriesFrameDeclaration, aggregate_state_frame_schema, }; @@ -96,7 +96,7 @@ use datatypes::series::raw::RawSeriesChunk; use datatypes::series::samples::{DenseSamplesRef, FieldSpec, SampleRef, Samples, SeriesSchema}; use datatypes::series::time::{EvalGrid, GridSpec}; use futures::stream::SelectAll; -use futures::{Stream, StreamExt}; +use futures::{Stream, StreamExt, TryStreamExt}; use store_api::region_engine::RawLabelSource; use table::table::scan::SeriesScanExec; @@ -118,7 +118,9 @@ use crate::native::plan::{ use crate::native::state::{StateChunk, state_row_from_frame_row}; use crate::raw_time::RawTimeUnit; use crate::source::materialize_raw_labels; -use crate::vector_match::{BinaryMatching, BinaryOp, DuplicateEvidence, MatchingLabels}; +use crate::vector_match::{ + BinaryMatching, BinaryOp, DuplicateCandidate, DuplicateEvidence, MatchingLabels, +}; #[cfg(test)] mod tests; @@ -126,7 +128,7 @@ mod tests; /// The label a metric name is stored under, which is not a tag column of the input. const METRIC_NAME: &str = "__name__"; -/// How many input steps one poll of [`FusedSeriesStream`] runs before it wakes itself. +/// How many input steps one poll of a [`FusedExecution`] runs before it wakes itself. /// /// A step polls the input once and hands what it settled to the executor. Settling is not /// guaranteed: raw samples before the first evaluation point settle nothing, so an input of many @@ -270,26 +272,31 @@ fn state_frame_output_schema(tree: &NativeTree) -> DataFusionResult { "FusedSeries Partial root does not produce aggregate state".into(), )); }; - let schema = Arc::new(SeriesSchema { - fields: state.accumulators.clone(), - eval_grid: Some(Arc::clone(&state.grid)), - }); - let state_schema = datatypes::series::aggregate_state::AggregateStateSchema::try_new( - state.kind, - state.components.to_vec(), + aggregate_state_frame_schema( + frame_state_schema(state)?.as_ref(), + &state_series_schema(state), + FrameLabelMode::Explicit, ) .map_err(|error| { DataFusionError::Plan(format!( "FusedSeries cannot declare state frame schema: {error}" )) - })?; - aggregate_state_frame_schema(&state_schema, &schema, FrameLabelMode::Explicit).map_err( - |error| { - DataFusionError::Plan(format!( - "FusedSeries cannot declare state frame schema: {error}" - )) - }, - ) + }) +} + +/// The series layout aggregate state is indexed by: one accumulator column per field, on its grid. +fn state_series_schema(state: &AggregateStateSchema) -> SeriesSchema { + SeriesSchema { + fields: state.accumulators.clone(), + eval_grid: Some(Arc::clone(&state.grid)), + } +} + +/// The state layout a frame declares for a tree's aggregate-state binding. +fn frame_state_schema(state: &AggregateStateSchema) -> DataFusionResult> { + FrameStateSchema::try_new(state.kind, state.components.to_vec()) + .map(Arc::new) + .map_err(|error| DataFusionError::Plan(error.to_string())) } fn output_frame_schema( @@ -512,9 +519,13 @@ impl FusedSeries { let mut node = Self::try_new_with_format(promql, tree, binding, children, output_schema, format)?; if canonical_producer { - if !matches!(node.tree.root().expr, NativeExpr::Merge { .. }) { + if !matches!(node.tree.root().expr, NativeExpr::Merge { .. }) + || format != FusedOutputFormat::SeriesFrame + { return Err(DataFusionError::Plan( - "a canonical merge producer requires a merge at the tree's root".into(), + "a canonical merge producer requires a merge at the tree's root and a \ + series frame output" + .into(), )); } node.canonical_producer = true; @@ -522,9 +533,8 @@ impl FusedSeries { // Placement is not part of the encoding: the envelope keeps the bytes it has always had, and // a node read back from one is placed by its shape, which keeps a producer above the regions. if format == FusedOutputFormat::PlainRows { - let schema = Arc::new(node.output_schema.as_arrow().clone()); - validate_plain_output_schema( - &schema, + classify_plain_output( + node.output_schema.inner(), &node.tree, &node.output_tags()?, &node.binding.time_index, @@ -603,9 +613,8 @@ impl FusedSeries { Err(DataFusionError::NotImplemented(_)) => return Ok(None), Err(error) => return Err(error), }; - Ok(split - .into_trees()? - .map(|trees| (trees.partial, trees.final_tree))) + let trees = split.into_trees()?; + Ok(Some((trees.partial, trees.final_tree))) } /// The evaluated series-frame schema declared by a native tree's root. @@ -785,7 +794,7 @@ impl FusedSeries { SeriesFrameDeclaration::parse(input.schema().as_ref()) .is_ok_and(|declaration| declaration.content() == FrameContent::Evaluated) }); - let locality = self.execution_locality(); + let locality = execution_locality(self.tree.root(), self.canonical_producer); let state_group = state_routing(self.tree.root()); let normalize = matches!(locality, InputLocality::SinglePartition); @@ -867,86 +876,7 @@ impl FusedSeries { } else { input }; - let routed = Arc::new(SeriesRepartitionExec::try_new_with_routing( - input, - required, - policy.clone(), - )?) as Arc; - let ordering = series_frame_ordering(routed.schema().as_ref())?; - return Ok((routed, RawLabelSource::Explicit, ordering)); - } - if declaration.content() != FrameContent::Evaluated { - let count = input.properties().partitioning.partition_count(); - if count == 0 { - return Err(DataFusionError::Plan(format!( - "FusedSeries input {index} has no partitions" - ))); - } - // Region streams may each close the same storage key. Reconcile those - // fragments even when the merged stream has only one output partition. - let (input, label_source, ordering) = if ordering == SeriesOrdering::Interleaved - { - let width = if normalize { 1 } else { count }; - let input = Arc::new(SeriesRepartitionExec::try_new_with_routing( - input, - width, - SeriesRouting::RawPrimaryKey, - )?) as Arc; - (input, RawLabelSource::Explicit, SeriesOrdering::Contiguous) - } else { - (input, label_source, ordering) - }; - let count = input.properties().partitioning.partition_count(); - // A per-series tree reads each raw series on its own, so its width is a choice: - // route the raw frames by their stored key up to the width this execution was - // asked for, and each series still lands on exactly one owner. - if !normalize - && count < target_partitions.unwrap_or(count).max(1) - && matching_policy.is_none() - { - let width = target_partitions.unwrap_or(count).max(1); - let input = Arc::new(SeriesRepartitionExec::try_new_with_routing( - input, - width, - SeriesRouting::RawPrimaryKey, - )?) as Arc; - let ordering = series_frame_ordering(input.schema().as_ref())?; - return Ok((input, RawLabelSource::Explicit, ordering)); - } - if normalize && count != 1 { - let input = Arc::new(SeriesRepartitionExec::try_new(input, 1)?) - as Arc; - let ordering = series_frame_ordering(input.schema().as_ref())?; - return Ok((input, RawLabelSource::Explicit, ordering)); - } - if let (Some(policy), Some(required)) = - (matching_policy.as_ref(), matching_partitions) - { - if required == 1 && count != 1 { - let input = Arc::new(SeriesRepartitionExec::try_new(input, 1)?) - as Arc; - let ordering = series_frame_ordering(input.schema().as_ref())?; - return Ok((input, RawLabelSource::Explicit, ordering)); - } - let has_router = - input - .downcast_ref::() - .is_some_and(|router| { - router.outputs() == required - && router.routing_policy() - == &SeriesRouting::Matching(policy.clone()) - }); - if required > 1 && !has_router { - let input = Arc::new(SeriesRepartitionExec::try_new_with_routing( - input, - required, - SeriesRouting::Matching(policy.clone()), - )?) as Arc; - let ordering = series_frame_ordering(input.schema().as_ref())?; - return Ok((input, RawLabelSource::Explicit, ordering)); - } - } - return Ok((input, label_source, ordering)); + return routed_frames(input, required, policy.clone()); } let count = input.properties().partitioning.partition_count(); if count == 0 { @@ -954,55 +884,77 @@ impl FusedSeries { "FusedSeries input {index} has no partitions" ))); } + if declaration.content() != FrameContent::Evaluated { + // Region streams may each close the same storage key. Reconcile those + // fragments even when the merged stream has only one output partition. + let (input, label_source, ordering) = if ordering == SeriesOrdering::Interleaved + { + let width = if normalize { 1 } else { count }; + routed_frames(input, width, SeriesRouting::RawPrimaryKey)? + } else { + (input, label_source, ordering) + }; + let count = input.properties().partitioning.partition_count(); + // A per-series tree reads each raw series on its own, so its width is a choice: + // route the raw frames by their stored key up to the width this execution was + // asked for, and each series still lands on exactly one owner. + let width = target_partitions.unwrap_or(count).max(1); + if !normalize && count < width && matching_policy.is_none() { + return routed_frames(input, width, SeriesRouting::RawPrimaryKey); + } + if normalize && count != 1 { + return routed_frames(input, 1, SeriesRouting::RawPrimaryKey); + } + if let (Some(policy), Some(required)) = + (matching_policy.as_ref(), matching_partitions) + { + if required == 1 && count != 1 { + return routed_frames(input, 1, SeriesRouting::RawPrimaryKey); + } + let routing = SeriesRouting::Matching(policy.clone()); + if required > 1 && !routes_as(input.as_ref(), required, &routing) { + return routed_frames(input, required, routing); + } + } + return Ok((input, label_source, ordering)); + } let required = if normalize { 1 } else { matching_partitions.unwrap_or(count) }; - let needs_owner = window_sources.contains(&index); - let contiguous = actual_ordering == SeriesOrdering::Contiguous; - let has_router = - input - .downcast_ref::() - .is_some_and(|router| { - router.outputs() == required - && matching_policy.as_ref().is_some_and(|policy| { - router.routing_policy() - == &SeriesRouting::Matching(policy.clone()) - }) - }); - if normalize && count != required { - let input = Arc::new(SeriesRepartitionExec::try_new(input, required)?) - as Arc; - Ok((input, label_source, SeriesOrdering::Contiguous)) - } else if normalize { - // Already the one partition a global tree needs; wrapping it would add a node - // that changes nothing. - Ok((input, label_source, ordering)) - } else if let Some(policy) = matching_policy.as_ref() - && required > 1 - && (count != required || !has_router) + let routing = if normalize { + // One partition is what a global tree needs; a router over one already there + // would change nothing. + (count != required).then_some(SeriesRouting::CanonicalLabels) + } else if let Some(routing) = matching_policy + .as_ref() + .map(|policy| SeriesRouting::Matching(policy.clone())) + .filter(|routing| required > 1 && !routes_as(input.as_ref(), required, routing)) { // Either there is no router yet or the one there routes by another key. The // second case re-routes what the first produced: a router's output is plain // partitions, so another one above it is a legitimate shuffle rather than a // no-op, and refusing the query would be worse than paying for the move. - let input = Arc::new(SeriesRepartitionExec::try_new_with_routing( - input, - required, - SeriesRouting::Matching(policy.clone()), - )?) as Arc; - Ok((input, label_source, SeriesOrdering::Contiguous)) - } else if needs_owner - && !(count == 1 && contiguous) + Some(routing) + } else if window_sources.contains(&index) + && !(count == 1 && actual_ordering == SeriesOrdering::Contiguous) && input.downcast_ref::().is_none() { - let input = Arc::new(SeriesRepartitionExec::try_new(input, required)?) - as Arc; - Ok((input, label_source, SeriesOrdering::Contiguous)) + Some(SeriesRouting::CanonicalLabels) } else { - Ok((input, label_source, ordering)) - } + None + }; + Ok(match routing { + Some(routing) => ( + Arc::new(SeriesRepartitionExec::try_new_with_routing( + input, required, routing, + )?) as Arc, + label_source, + SeriesOrdering::Contiguous, + ), + None => (input, label_source, ordering), + }) }) .collect::>>()?; let exec: Arc = Arc::new(FusedSeriesExec::build( @@ -1014,24 +966,16 @@ impl FusedSeries { tags, self.binding.metric_name.clone(), self.format, - target_partitions, self.canonical_producer, )?); self.with_canonical_router(exec) } - /// Routes a canonical producer's frames by label set: the canonical collection step above it. + /// Routes a canonical producer's frames by canonical label set. /// - /// The producer cannot do this itself. - /// - /// The producer answers one series per label set *per partition*: it merged what it found there. - /// The pieces of one set that landed in other partitions are still apart, and every consumer - /// above this boundary reads whole label sets, so they are collected here - by canonical label - /// set, not by matching key, and by the conservative completion contract, because a producer can - /// only promise one series per set per partition and not that each set lives in one partition. - /// - /// This router is the boundary's middle stage and nothing else: a query whose tree holds no - /// canonical merge never reaches this code, and a merge that is not a boundary stays where it is. + /// The producer answers one series per label set *per partition*, so the pieces of one set in + /// other partitions are still apart; the router collects them with the merging completion + /// contract, since a set may span partitions. fn with_canonical_router( &self, exec: Arc, @@ -1039,13 +983,9 @@ impl FusedSeries { if !self.canonical_producer { return Ok(exec); } - // The producer's own partitions are where the pieces are, so the router runs at exactly that - // width: it neither invents more owners than there is work for nor collects every piece into - // one. The session's `target_partitions` is not consulted, because it describes the session - // that plans this node and not the work below it: this boundary is planned where its producer - // runs - in the region for a regional producer - and the producer's width is already the - // scan's, which the frontend assigned. Asking the region's own default instead would gather - // every piece into a single owner, which is the shape this boundary exists to avoid. + // The router keeps the producer's width, not the session's `target_partitions`: this is + // planned where the producer runs (in the region for a regional producer), whose width the + // frontend already assigned, and the region's default would gather every piece into one. let outputs = exec.properties().partitioning.partition_count().max(1); Ok(Arc::new(SeriesRepartitionExec::try_new_with_routing( exec, @@ -1054,23 +994,6 @@ impl FusedSeries { )?)) } - /// The locality this node's physical execution runs at. - /// - /// Normally that is the tree's own classification: a tree that reads across series answers one - /// partition and gathers what it reads. A partition-local canonical merge is the one deliberate - /// exception, and it is a fact about *this* node's contract rather than about the tree, so it is - /// read here and not inferred from the root: the caller that built the node knows its inputs are - /// whole per partition, and the merge it ends with collects only that partition's fragments. - /// Treating every merge as partition-local would instead let a merge that needs every piece run - /// where it cannot see them. - fn execution_locality(&self) -> InputLocality { - if self.canonical_producer { - InputLocality::PartitionLocal - } else { - input_locality(self.tree.root()) - } - } - /// The label columns of the output, independent of the raw-input binding. /// /// A scalar root has no labels; its one other column is the value. The planner decides them @@ -1249,10 +1172,7 @@ fn collect_source_schemas_from_inputs( let kind = FusedInputKind::from_native_type(&input.output)?; let found = match &input.output { NativeType::Samples(schema) => Arc::clone(schema), - NativeType::AggregateState(state) => Arc::new(SeriesSchema { - fields: state.accumulators.clone(), - eval_grid: Some(Arc::clone(&state.grid)), - }), + NativeType::AggregateState(state) => Arc::new(state_series_schema(state)), NativeType::Scalar(_) => { return Err(DataFusionError::Plan( "FusedSeries scalar cannot be a source".into(), @@ -1339,20 +1259,14 @@ fn same_source(node: &NativeNode) -> Option { { same_source(input) } - NativeExpr::Binary { - left, - right, - matching, - } if matches!(left.output, NativeType::Scalar(_)) && left.is_data_free() => { - let _ = matching; + NativeExpr::Binary { left, right, .. } + if matches!(left.output, NativeType::Scalar(_)) && left.is_data_free() => + { same_source(right) } - NativeExpr::Binary { - left, - right, - matching, - } if matches!(right.output, NativeType::Scalar(_)) && right.is_data_free() => { - let _ = matching; + NativeExpr::Binary { left, right, .. } + if matches!(right.output, NativeType::Scalar(_)) && right.is_data_free() => + { same_source(left) } NativeExpr::Binary { @@ -1473,7 +1387,6 @@ pub fn matching_operands_drop_key(root: &NativeNode) -> bool { }) } -/// Derives the partition contract from the bound root, not from a physical property registry. /// Whether `node` contains a vector-vector binary, which matches series of the whole vector. /// /// A tree of unary nodes evaluates each series on its own, so its partitions need nothing from @@ -1555,6 +1468,21 @@ fn matching_site(node: &NativeNode) -> Option<(&NativeNode, &NativeNode, &Matchi } } +/// The locality a node over `root` runs at. +/// +/// A canonical producer's root merge reads across series in general; only the caller that built +/// the producer knows each partition holds whole label sets, so the merge collects per partition. +/// Inferring that from the root would let a merge that needs every piece run where it cannot see +/// them. +fn execution_locality(root: &NativeNode, canonical_producer: bool) -> InputLocality { + if canonical_producer { + InputLocality::PartitionLocal + } else { + input_locality(root) + } +} + +/// Derives the partition contract from the bound root, not from a physical property registry. pub fn input_locality(root: &NativeNode) -> InputLocality { // A `Partial` aggregate folds only the rows its own partition reads and exports the state it // folded; the `Final` half above the exchange is what needs every contribution in one place. @@ -1704,6 +1632,26 @@ fn state_routing(root: &NativeNode) -> Option<(StateGroup, SeriesRouting)> { } } +/// Whether `input` is a router with `outputs` partitions routing by `policy`. +fn routes_as(input: &dyn ExecutionPlan, outputs: usize, policy: &SeriesRouting) -> bool { + input + .downcast_ref::() + .is_some_and(|router| router.outputs() == outputs && router.routing_policy() == policy) +} + +/// A router with `outputs` partitions over `input`, as the explicit-label frames it publishes. +fn routed_frames( + input: Arc, + outputs: usize, + policy: SeriesRouting, +) -> DataFusionResult<(Arc, RawLabelSource, SeriesOrdering)> { + let routed: Arc = Arc::new(SeriesRepartitionExec::try_new_with_routing( + input, outputs, policy, + )?); + let ordering = series_frame_ordering(routed.schema().as_ref())?; + Ok((routed, RawLabelSource::Explicit, ordering)) +} + /// How many owners the groups of a state input have to be split across. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum StateGroup { @@ -1801,41 +1749,24 @@ pub fn tree_source_fields(tree: &NativeTree) -> DataFusionResult .collect()) } -/// Validates a decoded plain-row node's schema against the tree that produces it. -/// -/// A deserialized node carries its own output schema, so this is where a payload that names -/// columns the tree cannot produce is refused, before the node runs. -fn validate_plain_output_schema( +/// Classifies the row table `tree` answers under `schema`, refusing columns its root cannot fill. +fn classify_plain_output( schema: &SchemaRef, tree: &NativeTree, tags: &[String], time: &str, promql: &str, -) -> DataFusionResult<()> { - let fields = match &tree.root().output { - NativeType::Samples(s) => s.fields.to_vec(), +) -> DataFusionResult> { + match &tree.root().output { + NativeType::Samples(series) => classify_output(schema, &series.fields, tags, time, promql), NativeType::Scalar(_) => { - let non_time_columns = schema - .fields() - .iter() - .filter(|field| field.name().as_str() != time) - .count(); - if non_time_columns != 1 { - return Err(DataFusionError::Plan(format!( - "FusedSeriesExec scalar root cannot produce {} tag columns", - non_time_columns.saturating_sub(1) - ))); - } - scalar_root_fields(schema, &[], time)? + let fields = scalar_root_fields(schema, tags, time)?; + classify_output(schema, &fields, tags, time, promql) } - NativeType::AggregateState(_) => { - return Err(DataFusionError::Plan( - "PlainRows does not support aggregate-state roots".into(), - )); - } - }; - classify_output(schema, &fields, tags, time, promql)?; - Ok(()) + NativeType::AggregateState(_) => Err(DataFusionError::Plan( + "PlainRows does not support aggregate-state roots".into(), + )), + } } /// Validates the tree's bound inputs and carries the root kind with their schemas. @@ -1913,10 +1844,11 @@ fn scalar_root_fields( "missing value column in scalar root output schema".to_string(), )); }; - if values.next().is_some() { - return Err(DataFusionError::Plan( - "scalar root output schema must contain exactly one value column".into(), - )); + let extra = values.count(); + if extra > 0 { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec scalar root cannot produce {extra} tag columns" + ))); } Ok(vec![FieldSpec { name: Arc::from(value.name().as_str()), @@ -1990,17 +1922,6 @@ pub(crate) fn classify_output( promql: &str, ) -> DataFusionResult> { let field_names = output_field_names(output_schema, series_fields, promql); - if output_schema - .fields() - .iter() - .filter(|field| field.name().as_str() == time_column) - .count() - > 1 - { - return Err(DataFusionError::Plan(format!( - "duplicate time column {time_column:?} in FusedSeriesExec output schema" - ))); - } for (index, tag) in tags.iter().enumerate() { if tags[..index].contains(tag) { return Err(DataFusionError::Plan(format!( @@ -2120,11 +2041,6 @@ pub(crate) fn classify_output( ))); } } - if output_schema.fields().len() != 1 + series_fields.len() + tags.len() { - return Err(DataFusionError::Plan( - "FusedSeriesExec output schema has an unexpected number of columns".into(), - )); - } Ok(classification) } @@ -2206,7 +2122,6 @@ pub struct FusedSeriesExec { /// or this cache must gain invalidation; otherwise the membership regression test will fail. own_metrics: MetricsSet, format: FusedOutputFormat, - matching_parallelism: Option, /// Whether this node is a partition-local canonical producer. canonical_producer: bool, /// This node's partitioning, emission and boundedness. @@ -2251,26 +2166,16 @@ struct StoredSeriesLabels { /// kernel has normalized their labels. /// /// `logical_tags` are the tag names every stored series of the scan reports, and `key_columns` are -/// the columns the scan keys one series by. Two facts make the drop injective, and both are read -/// from the scan's own binding rather than from a tree above it: +/// the columns the scan keys one series by. The drop is injective when: /// -/// - Neither the tags nor the key columns may be a metadata label. `__type__` and `__unit__` go with -/// the metric name when a kernel drops it, so a scan that keys a series by either of them stops -/// telling two series apart once the name is gone. -/// - Every key column must always decode a value, which is what a non-nullable column states. A -/// kernel that drops the name drops every label whose value is empty with it, and a nullable -/// column lets one series hold `NULL` while another holds `''`: two different storage keys, which -/// decode to an absent label and to an empty one, so both are handed over as no label at all once -/// the empty one is dropped. Two such series that agree on every other tag then leave as one -/// identity, whether they arrive in one partition or in two. +/// - no tag or key column is a metadata label, since `__type__` and `__unit__` go with the name; +/// - every key column is non-nullable. A kernel that drops the name also drops empty label values, +/// so a series holding `NULL` and one holding `''` in a nullable key column would leave as one +/// identity. /// -/// The physical per-series scan asks this of its own binding to decide whether a node may stream, so -/// that its partitions hand over whole series. The plan-time canonical proof does not read it: the -/// labels alone decide whether a metadata drop is collected, and the planner reads this rule only to -/// count the statements that proof leaves unproved -/// ([`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys)). -/// Keeping the rule here is what stops the scan's own answer - read from the bound scan at execution - -/// from drifting away from the one the plan-time count is stated with. +/// The physical scan and the planner's count of unproved drops +/// ([`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys)) +/// share this rule so they cannot drift apart. pub fn keys_survive_metadata_drop<'a, 'b>( logical_tags: impl IntoIterator, key_columns: impl IntoIterator, @@ -2326,17 +2231,11 @@ impl StoredSeriesLabels { /// selection of an info sample and a filtering comparison hand that series over under the labels it /// read. /// -/// `labels` states what the scan below the tree proves about those labels: the tags each stored -/// series reports, and whether they tell two of them apart once the metadata labels and the empty -/// values are gone. A node that drops the metric name - a range function such as `rate`, -/// `timestamp`, a math or histogram map, a parameterized map, and an arithmetic or `bool` scalar -/// broadcast - drops `__type__` and `__unit__` with it, and normalizes away every empty label value. -/// The name such a node drops is the one a single-metric scan binds for every series it reads, so -/// dropping it merges nothing; such a node therefore keeps two series apart exactly when the scan -/// keys its series by labels that survive the drop, which is what `labels` states. Without that -/// proof the name is part of what tells two series apart, and the node can file two of them under -/// one output label set - as it can when the key it drops the empty value of is one column of the -/// two series that holds `NULL` in one of them and `''` in the other. +/// `labels` states what the scan below the tree proves about those labels. A node that drops the +/// metric name - a range function such as `rate`, `timestamp`, a math or histogram map, a +/// parameterized map, and an arithmetic or `bool` scalar broadcast - drops the name a single-metric +/// scan binds for every series, so it keeps two series apart exactly when +/// [`keys_survive_metadata_drop`] holds for the scan. /// /// Everything else answers one series per group or set it names, or pairs several inputs, so an /// identity above it is not an identity of what it read. @@ -2522,18 +2421,10 @@ impl FusedSeriesExec { /// metric name over a scan that reads one metric and keys its series by labels that survive the /// drop. /// - /// A node that drops the metric name is proved rather than refused outright: a `PrimaryKey` - /// binding reads one metric, so the name those nodes drop is the one every stored series - /// carries, and what tells two of them apart are the tags the binding names. Requiring the rows - /// to carry those tags, refusing a binding that keys a series by `__type__` or `__unit__` - - /// which a name-dropping kernel removes with the name - and refusing a binding whose key columns - /// are not every one of them non-nullable, because only a nullable column lets one series hold - /// `NULL` where another holds `''`, which such a kernel normalizes into one absent label, is - /// what keeps this an identity of what the tree read. A scan that states none of those facts - /// proves nothing, and a row table that would not carry the tags below it proves nothing either, - /// so both are refused here rather than refined later: the router above a producer that claims - /// [`CompleteDisjoint`] stops checking for duplicates, and a refusal only keeps the merging path - /// it would otherwise have taken. + /// A name-dropping chain also needs the rows to carry every tag the scan binds and + /// [`keys_survive_metadata_drop`] to hold. Anything unproved answers `false`: the router above a + /// producer that claims [`CompleteDisjoint`] stops checking for duplicates, while a refusal only + /// keeps the merging path. /// /// [`CompleteDisjoint`]: crate::extension_plan::IdentityCompletion::CompleteDisjoint pub fn has_partition_disjoint_identities(&self) -> bool { @@ -2558,39 +2449,8 @@ impl FusedSeriesExec { preserves_partition_identity(self.tree.root(), labels.as_ref()) } - /// Creates the node, rejecting whatever this node cannot execute or convert. - /// - /// `input` produces native raw series frames: the series' encoded key, its finality, its - /// timestamps and its fields, plus the complete labels when `label_source` is - /// [`RawLabelSource::Explicit`]. `time_column` and `tags` name the columns of the output, which - /// is a row table rather than a frame. - /// - /// The parameters stay separate because each is a fact its own caller has: the query, the plan - /// below, the frame's label binding and ordering, the tree, and the three things the output - /// schema is classified by. A struct over them would be the same list under another name. - #[allow(clippy::too_many_arguments)] - pub fn try_new( - promql: Arc, - inputs: Vec<(Arc, RawLabelSource, SeriesOrdering)>, - tree: Arc, - output_schema: SchemaRef, - time_column: String, - tags: Vec, - ) -> DataFusionResult { - Self::build( - promql, - inputs, - tree, - output_schema, - time_column, - tags, - None, - FusedOutputFormat::PlainRows, - None, - false, - ) - } - + /// Builds the node from what its logical [`FusedSeries`] proved, rejecting inputs this node + /// cannot execute or convert. #[allow(clippy::too_many_arguments)] fn build( promql: Arc, @@ -2601,35 +2461,9 @@ impl FusedSeriesExec { tags: Vec, metric_name: Option>, format: FusedOutputFormat, - matching_parallelism: Option, canonical_producer: bool, ) -> DataFusionResult { - // A partition-local canonical merge is an explicit contract about this node's inputs, so it - // replaces the tree's own classification rather than being folded into it: the tree's root - // merge reads across series in general, and only the caller knows that these partitions each - // hold whole series. - let locality = if canonical_producer { - InputLocality::PartitionLocal - } else { - input_locality(tree.root()) - }; - if canonical_producer { - if !matches!(tree.root().expr, NativeExpr::Merge { .. }) { - return Err(DataFusionError::Plan( - "a canonical boundary requires a merge at the tree's root".into(), - )); - } - if matches!(&tree.root().output, NativeType::AggregateState(_)) { - return Err(DataFusionError::Plan( - "a canonical boundary exports series frames, not aggregate state".into(), - )); - } - if format != FusedOutputFormat::SeriesFrame { - return Err(DataFusionError::Plan( - "a canonical merge producer exports a series frame".into(), - )); - } - } + let locality = execution_locality(tree.root(), canonical_producer); let (raw_schemas, source_kinds, root_kind) = validate_physical_tree(&tree)?; if inputs.len() != raw_schemas.len() { return Err(DataFusionError::Plan(format!( @@ -2641,15 +2475,8 @@ impl FusedSeriesExec { // Building a state proves the runtime executes this tree; drop the validation state now. let _ = NativeExecutionState::try_new(&tree, Arc::new(UnboundedMemoryPool::default()), None)?; - let output_series = tree.root().output.samples(); - let scalar_root = matches!(tree.root().output, NativeType::Scalar(_)); - let partial_root = matches!(&tree.root().expr, NativeExpr::Aggregate { op, .. } if op.stage == AggregateStage::Partial); - if partial_root && format != FusedOutputFormat::SeriesFrame { - return Err(DataFusionError::Plan( - "FusedSeries Partial stage requires SeriesFrame output".into(), - )); - } - let frame_schema = if format == FusedOutputFormat::SeriesFrame { + let frame_output = format == FusedOutputFormat::SeriesFrame; + let classification = if frame_output { if inputs.iter().any(|(input, _, _)| { matches!( input.properties().boundedness, @@ -2667,27 +2494,9 @@ impl FusedSeriesExec { "FusedSeriesExec schema does not match: declared {output_schema:?}, expected {declared:?}" ))); } - true - } else { - false - }; - let classification = if partial_root || frame_schema { Vec::new() - } else if scalar_root { - let scalar_fields = scalar_root_fields(&output_schema, &tags, &time_column)?; - classify_output(&output_schema, &scalar_fields, &tags, &time_column, &promql)? } else { - classify_output( - &output_schema, - &output_series - .ok_or_else(|| { - DataFusionError::Plan("FusedSeries output is not samples".into()) - })? - .fields, - &tags, - &time_column, - &promql, - )? + classify_plain_output(&output_schema, &tree, &tags, &time_column, &promql)? }; let partition_count = inputs.first().map_or(1, |(input, _, _)| { input.properties().partitioning.partition_count() @@ -2727,13 +2536,7 @@ impl FusedSeriesExec { "FusedSeries reads aggregate state but holds no Final aggregate".into(), ) })?; - if owners == StateGroup::Single - || input - .downcast_ref::() - .is_none_or(|router| { - router.outputs() != count || router.routing_policy() != &policy - }) - { + if owners == StateGroup::Single || !routes_as(input.as_ref(), count, &policy) { return Err(DataFusionError::Plan(format!( "FusedSeries state input {index} requires a direct owner router with the Final routing policy" ))); @@ -2746,12 +2549,11 @@ impl FusedSeriesExec { } if let InputLocality::MatchingLocal(policy) = &locality && count > 1 - && input - .downcast_ref::() - .is_none_or(|router| { - router.outputs() != count - || router.routing_policy() != &SeriesRouting::Matching(policy.clone()) - }) + && !routes_as( + input.as_ref(), + count, + &SeriesRouting::Matching(policy.clone()), + ) { return Err(DataFusionError::Plan(format!( "FusedSeries matching-local input {index} requires a direct matching-key SeriesRepartitionExec with {count} outputs" @@ -2824,30 +2626,10 @@ impl FusedSeriesExec { unpack_raw_series(empty(), Some(raw_schemas[index].clone()))?; } FusedInputKind::AggregateState => { - let bound = tree - .root() - .inputs() - .into_iter() - .find(|bound| bound.source_index == index) - .ok_or_else(|| { - DataFusionError::Plan(format!( - "FusedSeries state source {index} has no bound input" - )) - })?; - let NativeType::AggregateState(state) = &bound.output else { - return Err(DataFusionError::Plan(format!( - "FusedSeries source {index} is declared aggregate state but its binding is not" - ))); - }; + let state = state_binding_of(&tree.root().inputs(), index)?; let _ = unpack_aggregate_state( empty(), - Some(Arc::new( - datatypes::series::aggregate_state::AggregateStateSchema::try_new( - state.kind, - state.components.to_vec(), - ) - .map_err(|error| DataFusionError::Plan(error.to_string()))?, - )), + Some(frame_state_schema(&state)?), Some(raw_schemas[index].clone()), )?; } @@ -2856,12 +2638,12 @@ impl FusedSeriesExec { let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(output_schema.clone()), Partitioning::UnknownPartitioning(partition_count), - if partial_root || frame_schema { + if frame_output { // Partial aggregate state and canonical frame series are emitted only after EOF. EmissionType::Final } else { - // A frame's identities, and every other output, are emitted while the input is - // still arriving, so the node's emission type is the input's. + // Rows leave while the input is still arriving, so the node's emission type is the + // input's. inputs.first().map_or(EmissionType::Final, |(input, _, _)| { input.properties().emission_type }) @@ -2894,7 +2676,6 @@ impl FusedSeriesExec { own_metrics, properties, format, - matching_parallelism, canonical_producer, }) } @@ -3030,7 +2811,6 @@ impl ExecutionPlan for FusedSeriesExec { self.tags.to_vec(), self.metric_name.clone(), self.format, - self.matching_parallelism, self.canonical_producer, )?)) } @@ -3040,24 +2820,30 @@ impl ExecutionPlan for FusedSeriesExec { partition: usize, context: Arc, ) -> DataFusionResult { - let FusedExecution { stream, state } = self.output_stream(partition, context)?; - match (self.format, state) { - (FusedOutputFormat::SeriesFrame, Some(state)) => { + match self.output_kind()? { + // A row table is the query's answer, not a publication another native operator reads. + FusedOutputKind::Rows => Ok(Box::pin(FusedSeriesStream { + execution: self.output_stream(partition, context)?, + classification: Arc::clone(&self.classification), + tags: Arc::clone(&self.tags), + output_schema: self.output_schema.clone(), + })), + FusedOutputKind::Evaluated(schema) => { + let source: SendableEvaluatedSeriesStream = Box::pin( + self.output_stream(partition, context)? + .evaluated() + .map_ok(|chunk| (chunk.series, chunk.is_last)), + ); + Ok(pack_evaluated_series(source, schema)?) + } + FusedOutputKind::State(state) => { let source: SendableStateSeriesStream = Box::pin(FusedStateStream { - source: stream, + execution: self.output_stream(partition, context)?, pending: Vec::new().into_iter(), reservation: None, }); Ok(pack_aggregate_state(source, state.declared, state.series)?) } - (FusedOutputFormat::SeriesFrame, None) => { - let schema = evaluated_output(&self.tree)?; - let source: SendableEvaluatedSeriesStream = - Box::pin(FusedEvaluatedStream { source: stream }); - Ok(pack_evaluated_series(source, schema)?) - } - // A row table is the query's answer, not a publication another native operator reads. - (FusedOutputFormat::PlainRows, _) => Ok(Box::pin(stream)), } } } @@ -3077,23 +2863,20 @@ impl SeriesExecutionPlan for FusedSeriesExec { partition: usize, context: Arc, ) -> DataFusionResult { - if self.format != FusedOutputFormat::SeriesFrame { - return Err(DataFusionError::Execution(format!( + match self.output_kind()? { + FusedOutputKind::Rows => Err(DataFusionError::Execution(format!( "FusedSeries partition {partition} answers a row table, which is read as rows" - ))); - } - let FusedExecution { stream, state } = self.output_stream(partition, context)?; - match state { - Some(state) => Ok(Box::pin(FusedStateChunks { - source: stream, + ))), + FusedOutputKind::Evaluated(_) => Ok(Box::pin( + self.output_stream(partition, context)? + .evaluated() + .map_ok(|chunk| HandedSeriesChunk::uncharged(SeriesChunk::Evaluated(chunk))), + )), + FusedOutputKind::State(state) => Ok(Box::pin(FusedStateChunks { + execution: self.output_stream(partition, context)?, declared: state.binding, pending: Vec::new().into_iter(), })), - None => { - let source: SendableEvaluatedSeriesStream = - Box::pin(FusedEvaluatedStream { source: stream }); - Ok(Box::pin(FusedEvaluatedChunks { source })) - } } } } @@ -3107,6 +2890,22 @@ impl FusedSeriesExec { self.format == FusedOutputFormat::SeriesFrame } + /// What one execution answers. A `SeriesFrame` root that exports state is a `Partial` + /// aggregate; `build` refused every other combination. + fn output_kind(&self) -> DataFusionResult { + if self.format == FusedOutputFormat::PlainRows { + return Ok(FusedOutputKind::Rows); + } + match &self.tree.root().output { + NativeType::AggregateState(binding) => Ok(FusedOutputKind::State(FusedStateOutput { + declared: frame_state_schema(binding)?, + binding: Arc::clone(binding), + series: Arc::new(state_series_schema(binding)), + })), + _ => Ok(FusedOutputKind::Evaluated(evaluated_output(&self.tree)?)), + } + } + /// One partition's execution, before it is put in the form a consumer asked for. /// /// Both entry points start here, so the tree, its input and the evidence one execution claims are @@ -3133,7 +2932,7 @@ impl FusedSeriesExec { } else { None }; - let mut claim = evidence.as_ref().map(|evidence| EvidenceClaim { + let evidence_claim = evidence.as_ref().map(|evidence| EvidenceClaim { evidence: Arc::clone(evidence), active: true, }); @@ -3145,20 +2944,12 @@ impl FusedSeriesExec { self.metric_name.clone(), self.series_schemas.len(), ); - let mut state = match NativeExecutionState::try_new_with_sources( + let mut state = NativeExecutionState::try_new_with_sources( &self.tree, Arc::clone(&context.runtime_env().memory_pool), - evidence.clone(), + evidence, &sources, - ) { - Ok(state) => state, - Err(error) => { - if let Some(claim) = &mut claim { - claim.abort(); - } - return Err(error); - } - }; + )?; // The planner registers the query's collector in the session's `ConfigOptions.extensions` // rather than the separate `SessionConfig` container, so it is read from where it was // written. The HTTP entry point holds a strong reference to that same collector for the life @@ -3231,16 +3022,9 @@ impl FusedSeriesExec { } FusedInputKind::AggregateState => { let binding = state_binding_of(&bound_inputs, source)?; - let declared = Arc::new( - datatypes::series::aggregate_state::AggregateStateSchema::try_new( - binding.kind, - binding.components.to_vec(), - ) - .map_err(|error| DataFusionError::Plan(error.to_string()))?, - ); let decoded = unpack_aggregate_state( frames, - Some(declared.clone()), + Some(frame_state_schema(&binding)?), Some(Arc::clone(&self.series_schemas[source])), )?; streams.push( @@ -3281,33 +3065,6 @@ impl FusedSeriesExec { let input_ids = (0..self.series_schemas.len()) .map(|source| state.input_ids(source).collect()) .collect(); - // One reading of the root decides both the mode and its binding, so the mode cannot - // disagree with its binding: a Partial root without state output is a plan error. - let state_binding = match (&self.tree.root().expr, &self.tree.root().output) { - (NativeExpr::Aggregate { op, .. }, NativeType::AggregateState(binding)) - if op.stage == AggregateStage::Partial => - { - Some(Arc::clone(binding)) - } - (NativeExpr::Aggregate { op, .. }, _) if op.stage == AggregateStage::Partial => { - return Err(DataFusionError::Plan( - "FusedSeries Partial root must produce aggregate state".into(), - )); - } - _ => None, - }; - let state_mode = state_binding.is_some(); - let state_schema = state_binding - .as_ref() - .map(|binding| { - datatypes::series::aggregate_state::AggregateStateSchema::try_new( - binding.kind, - binding.components.to_vec(), - ) - .map(Arc::new) - .map_err(|error| DataFusionError::Plan(error.to_string())) - }) - .transpose()?; let mut executor = NativeExecutor::new(state); let inputs = if streams.is_empty() { executor.end_of_input()?; @@ -3315,50 +3072,16 @@ impl FusedSeriesExec { } else { Some(futures::stream::select_all(streams)) }; - // A frame is encoded from the tree's own evaluated output, and only when the node answers - // values rather than state: partial state is a third output the format does not reach. - let frame_mode = self.format == FusedOutputFormat::SeriesFrame && !state_mode; - let stream = FusedSeriesStream { + Ok(FusedExecution { + evidence_claim, inputs, executor: Some(executor), input_ids, - classification: Arc::clone(&self.classification), - tags: Arc::clone(&self.tags), - output_schema: self.output_schema.clone(), - state_mode, - frame_mode, - ready: VecDeque::new(), done: false, - duplicate_evidence: evidence, - evidence_completed: false, - evidence_claim: claim, - }; - Ok(FusedExecution { - state: state_binding.as_ref().map(|binding| FusedStateOutput { - declared: state_schema - .clone() - .expect("a binding declares a frame state layout"), - binding: Arc::clone(binding), - series: Arc::new(SeriesSchema { - fields: binding.accumulators.clone(), - eval_grid: Some(Arc::clone(&binding.grid)), - }), - }), - stream, }) } } -impl Drop for FusedSeriesStream { - fn drop(&mut self) { - if !self.evidence_completed - && let Some(claim) = &mut self.evidence_claim - { - claim.abort(); - } - } -} - /// Converts one evaluated chunk into one output batch. /// /// The time column is the absolute grid positions the chunk carries, missing samples are nulls and @@ -3468,18 +3191,18 @@ enum FusedChunk { State(StateChunk), } -/// One partition's execution: the tree's own output, and its state layout when it exports state. -struct FusedExecution { - /// The tree's output, which a consumer reads as values, as state, or as rows. - stream: FusedSeriesStream, - /// What a `Partial` root exports. - state: Option, +/// What one execution of [`FusedSeriesExec`] answers. +enum FusedOutputKind { + Rows, + /// Evaluated series of this layout. + Evaluated(Arc), + State(FusedStateOutput), } /// The aggregate state a `Partial` root exports. struct FusedStateOutput { /// The layout as the frame path declares it, which is what the packer takes. - declared: Arc, + declared: Arc, /// The same layout as the tree's binding, which is what a handed-over chunk names. binding: Arc, /// The series schema the export is of. @@ -3547,11 +3270,7 @@ fn in_process_feed( state_schema.kind, binding.kind ))); } - let declared = SeriesSchema { - fields: state_schema.accumulators.clone(), - eval_grid: Some(Arc::clone(&state_schema.grid)), - }; - ensure_declared_series(&declared, series, source)?; + ensure_declared_series(&state_series_schema(state_schema), series, source)?; } } FusedChunk::State(chunk) @@ -3622,9 +3341,7 @@ fn ensure_declared_series( /// A failure in the handover's own error type. fn failed(reason: String) -> BoxedError { - BoxedError::new(common_query::error::Error::from( - DataFusionError::Execution(reason), - )) + boxed(DataFusionError::Execution(reason)) } /// The native histogram column of one evaluated field. @@ -3677,8 +3394,13 @@ fn canonical_histogram(view: &HistogramView<'_>) -> NativeHistogram { } } -/// The batches one execution of [`FusedSeriesExec`] yields. -pub struct FusedSeriesStream { +/// One partition's execution of the tree: the inputs it reads and the executor they feed. +/// +/// The stream wrapping it decides what it pulls from the executor: rows, evaluated chunks or +/// exported state. +struct FusedExecution { + /// Aborts on drop unless the execution completed. + evidence_claim: Option, /// Every input partition, read concurrently, or `None` once they all ended. /// /// Each decoder holds its current batch, decoded chunks and upstream source. Dropping this on @@ -3689,23 +3411,8 @@ pub struct FusedSeriesStream { executor: Option, /// Runtime input IDs for each source index. input_ids: Vec>, - /// Where each output column comes from. - classification: Arc<[OutputColumn]>, - /// The tag column names, indexed by `OutputColumn::Tag`. - tags: Arc<[String]>, - /// The schema of every batch this stream yields. - output_schema: SchemaRef, - /// Whether the root exports aggregate-state chunks. - state_mode: bool, - /// Whether output is a declared SeriesFrame rather than rows. - frame_mode: bool, - /// The batches the executor settled since the last poll of the input. - ready: VecDeque, - /// Whether the input ended and everything it settled has been handed out. + /// Whether the input ended and everything the tree settled has been handed out. done: bool, - duplicate_evidence: Option>, - evidence_completed: bool, - evidence_claim: Option, } struct EvidenceClaim { @@ -3720,13 +3427,13 @@ impl EvidenceClaim { self.active = false; } } - fn complete(&mut self) -> bool { - if self.active { - self.active = false; - self.evidence.complete() - } else { - false + + /// Completes this partition's claim, answering the duplicate verdict once every partition has. + fn complete(&mut self) -> Option { + if !std::mem::replace(&mut self.active, false) || !self.evidence.complete() { + return None; } + self.evidence.take_verdict() } } @@ -3736,8 +3443,74 @@ impl Drop for EvidenceClaim { } } -impl FusedSeriesStream { - /// Hands one raw chunk over and queues what it settled. +impl FusedExecution { + /// Runs the tree until `settled` takes an output from it, or until the input and everything + /// the tree settled from it are both exhausted. + fn poll_settled( + &mut self, + cx: &mut Context<'_>, + mut settled: impl FnMut(&mut NativeExecutor) -> DataFusionResult>, + ) -> Poll>> { + for _ in 0..POLL_BUDGET { + if self.done { + return Poll::Ready(None); + } + match self.executor.as_mut().map_or(Ok(None), &mut settled) { + Ok(Some(output)) => return Poll::Ready(Some(Ok(output))), + Ok(None) => {} + Err(error) => return Poll::Ready(Some(Err(self.fail(error)))), + } + let Some(inputs) = self.inputs.as_mut() else { + // The input ended and the tree has nothing more: closing the execution returns its + // reservations now rather than when the stream is dropped. + self.done = true; + self.executor = None; + if let Some(candidate) = self + .evidence_claim + .as_mut() + .and_then(EvidenceClaim::complete) + { + let error = DataFusionError::Execution(candidate.message()); + return Poll::Ready(Some(Err(self.fail(error)))); + } + return Poll::Ready(None); + }; + match Pin::new(inputs).poll_next(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + self.inputs = None; + // Only the input is ended here; the answers are pulled one per poll above, so + // each leaves as the tree settles it rather than all at once. + if let Some(executor) = self.executor.as_mut() + && let Err(error) = executor.end_of_input() + { + return Poll::Ready(Some(Err(self.fail(error)))); + } + } + Poll::Ready(Some(Err(error))) => { + let error = DataFusionError::External(Box::new(error)); + return Poll::Ready(Some(Err(self.fail(error)))); + } + Poll::Ready(Some(Ok(feed))) => { + if let Err(error) = self.push(feed) { + return Poll::Ready(Some(Err(self.fail(error)))); + } + } + } + } + cx.waker().wake_by_ref(); + Poll::Pending + } + + /// The evaluated chunks the tree settles. + fn evaluated(mut self) -> impl Stream> + Send { + futures::stream::poll_fn(move |cx| { + self.poll_settled(cx, NativeExecutor::next_chunk) + .map_err(boxed) + }) + } + + /// Hands one input chunk to the tree. fn push(&mut self, feed: FusedFeed) -> DataFusionResult<()> { let FusedFeed { source, @@ -3765,14 +3538,13 @@ impl FusedSeriesStream { // payload, so it is never bound to several inputs -- and it stays refused either way. if let [input_id] = input_ids.as_slice() { match chunk { - FusedChunk::Raw(value) => executor.push_raw(*input_id, value)?, - FusedChunk::Evaluated(value) => executor.push_evaluated(*input_id, value)?, - FusedChunk::State(chunk) => executor.push_state(*input_id, chunk)?, + FusedChunk::Raw(value) => executor.push_raw(*input_id, value), + FusedChunk::Evaluated(value) => executor.push_evaluated(*input_id, value), + FusedChunk::State(chunk) => executor.push_state(*input_id, chunk), } } else { - let chunk = Some(chunk); for input_id in input_ids { - match chunk.as_ref().expect("the feed is read at most twice") { + match &chunk { FusedChunk::Raw(value) => executor.push_raw(*input_id, value.clone())?, FusedChunk::Evaluated(value) => { executor.push_evaluated(*input_id, value.clone())? @@ -3788,200 +3560,35 @@ impl FusedSeriesStream { } } } - } - if self.frame_mode || self.state_mode { - Ok(()) - } else { - let mut settled = Vec::new(); - while let Some(chunk) = executor.next_chunk()? { - settled.push(chunk); - } - for chunk in settled { - self.convert_rows(chunk)?; - } Ok(()) } } - /// Ends the input, so the tree settles what it was holding. + /// Ends the execution in `error`, releasing the executor and the inputs. /// - /// `finish()` would be the same thing plus a drain, but the drain collects: it holds the whole - /// answer in a `Vec` before anything is handed out, so a tree that answers many chunks after its - /// input ends would sit on all of them while the consumer waits for the first. Only the input is - /// ended here, and the answers are pulled one per call below, so each chunk leaves as the tree - /// settles it and what has not been pulled yet stays charged to the node holding it. - fn close_input(&mut self) -> DataFusionResult<()> { - match self.executor.as_mut() { - Some(executor) => executor.end_of_input(), - // Every answer was pulled and the execution closed itself. - None => Ok(()), - } - } - - /// Pulls the next answer the tree settles after its input ended, or `None` when it has none. - /// - /// One chunk per call is what keeps this a stream: collecting them first would hold the whole - /// answer while the consumer waits for the first, and would charge the pool for all of it at - /// once. `None` is also when the execution closes and returns its reservations, so it is - /// dropped here rather than staying alive until the stream is. - fn pull_one(&mut self) -> DataFusionResult> { - if self.state_mode { - return Ok(None); - } - let Some(executor) = self.executor.as_mut() else { - return Ok(None); - }; - match executor.next_chunk() { - Ok(Some(chunk)) => Ok(Some(chunk)), - Ok(None) => { - self.executor = None; - Ok(None) - } - Err(error) => Err(error), - } - } - - /// Ends the stream in an error, releasing the execution and the inputs. - /// - /// An ordinary drop of the stream releases all of this as well, so this is not about the last - /// release: it is about a consumer that keeps the terminated stream, which would otherwise - /// hold the evaluator, the decoder's held batch and chunks, and the plan upstream of it. - fn fail(&mut self) { + /// An ordinary drop releases all of this as well; this is for a consumer that keeps the + /// terminated stream, which would otherwise hold the evaluator, the decoders' held batches and + /// the plan upstream of them. + fn fail(&mut self, error: DataFusionError) -> DataFusionError { self.done = true; - if !self.evidence_completed { - if let Some(claim) = &mut self.evidence_claim { - claim.abort(); - } - self.evidence_completed = true; + if let Some(claim) = &mut self.evidence_claim { + claim.abort(); } self.executor = None; self.inputs = None; - // This reservation belongs only to this execution. Release it even if the consumer keeps - // the failed stream and the plan alive. - // A batch queued before the error was settled by a run that has now stopped. - self.ready.clear(); - } - - /// Converts one settled chunk into a row batch. Evaluated frames leave this driver as chunks. - fn convert_rows(&mut self, chunk: EvaluatedChunk) -> DataFusionResult<()> { - let batch = series_to_record_batch( - &self.classification, - &self.tags, - &self.output_schema, - &chunk, - )?; - self.ready.push_back(batch); - Ok(()) + error } } -enum FusedOutput { - Rows(RecordBatch), - Evaluated(EvaluatedChunk), - /// Aggregate state decoded from a declared state frame. - State(StateChunk), -} - -impl FusedSeriesStream { - fn poll_output(&mut self, cx: &mut Context<'_>) -> Poll>> { - for _ in 0..POLL_BUDGET { - if let Some(batch) = self.ready.pop_front() { - return Poll::Ready(Some(Ok(FusedOutput::Rows(batch)))); - } - if self.state_mode && !self.done { - match self - .executor - .as_mut() - .map_or(Ok(None), NativeExecutor::next_state) - { - Ok(Some(chunk)) => return Poll::Ready(Some(Ok(FusedOutput::State(chunk)))), - Ok(None) if self.inputs.is_none() => self.executor = None, - Ok(None) => {} - Err(error) => { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - } - if self.frame_mode && !self.done { - match self - .executor - .as_mut() - .map_or(Ok(None), NativeExecutor::next_chunk) - { - Ok(Some(chunk)) => return Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk)))), - Ok(None) if self.inputs.is_none() => self.executor = None, - Ok(None) => {} - Err(error) => { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - } - if self.done { - return Poll::Ready(None); - } - let Some(inputs) = self.inputs.as_mut() else { - match self.pull_one() { - Ok(Some(chunk)) if self.frame_mode => { - return Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk)))); - } - Ok(Some(chunk)) => { - if let Err(error) = self.convert_rows(chunk) { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - Ok(None) => { - self.done = true; - if self - .evidence_claim - .as_mut() - .is_some_and(EvidenceClaim::complete) - && let Some(candidate) = self - .duplicate_evidence - .as_ref() - .and_then(|evidence| evidence.take_verdict()) - { - self.fail(); - return Poll::Ready(Some(Err(DataFusionError::Execution( - candidate.message(), - )))); - } - self.evidence_completed = true; - continue; - } - Err(error) => { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - continue; - }; - match Pin::new(inputs).poll_next(cx) { - Poll::Pending => return Poll::Pending, - Poll::Ready(None) => { - self.inputs = None; - if let Err(error) = self.close_input() { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - Poll::Ready(Some(Err(error))) => { - self.fail(); - return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); - } - Poll::Ready(Some(Ok(feed))) => { - if let Err(error) = self.push(feed) { - self.fail(); - return Poll::Ready(Some(Err(error))); - } - } - } - } - cx.waker().wake_by_ref(); - Poll::Pending - } +/// The row batches one execution of [`FusedSeriesExec`] yields. +pub struct FusedSeriesStream { + execution: FusedExecution, + /// Where each output column comes from. + classification: Arc<[OutputColumn]>, + /// The tag column names, indexed by `OutputColumn::Tag`. + tags: Arc<[String]>, + /// The schema of every batch this stream yields. + output_schema: SchemaRef, } impl RecordBatchStream for FusedSeriesStream { @@ -3994,40 +3601,39 @@ impl Stream for FusedSeriesStream { type Item = DataFusionResult; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - match self.poll_output(cx) { - Poll::Ready(Some(Ok(FusedOutput::Rows(batch)))) => Poll::Ready(Some(Ok(batch))), - Poll::Ready(Some(Ok(FusedOutput::Evaluated(_) | FusedOutput::State(_)))) => { - self.fail(); - Poll::Ready(Some(Err(DataFusionError::Internal( - "evaluated chunk reached the row stream adapter".into(), - )))) - } - Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), - Poll::Ready(None) => Poll::Ready(None), - Poll::Pending => Poll::Pending, - } + let Self { + execution, + classification, + tags, + output_schema, + } = &mut *self; + execution.poll_settled(cx, |executor| { + executor + .next_chunk()? + .map(|chunk| series_to_record_batch(classification, tags, output_schema, &chunk)) + .transpose() + }) } } -/// The tree's evaluated output, handed over as the chunks a native consumer reads. -struct FusedEvaluatedChunks { - source: SendableEvaluatedSeriesStream, +fn boxed(error: DataFusionError) -> BoxedError { + BoxedError::new(common_query::error::Error::from(error)) } -impl Stream for FusedEvaluatedChunks { - type Item = Result; - - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - match Pin::new(&mut self.source).poll_next(cx) { - Poll::Ready(Some(Ok((series, is_last)))) => { - Poll::Ready(Some(Ok(HandedSeriesChunk::uncharged( - SeriesChunk::Evaluated(EvaluatedChunk { series, is_last }), - )))) - } - Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), - Poll::Ready(None) => Poll::Ready(None), - Poll::Pending => Poll::Pending, - } +/// The groups of the next state chunk a `Partial` root exports, with the charge they carry. +fn next_state_series( + executor: &mut NativeExecutor, +) -> DataFusionResult, Option)>> { + match executor.next_state()? { + Some(StateChunk::Series { + series, + reservation, + .. + }) => Ok(Some((series, reservation))), + Some(StateChunk::Row(_)) => Err(DataFusionError::Internal( + "row state reached the state export".into(), + )), + None => Ok(None), } } @@ -4037,7 +3643,7 @@ impl Stream for FusedEvaluatedChunks { /// one group and holds it is holding the bytes of the batch that group was folded in, so the /// reservation is shared by every group of that batch and released with the last of them. struct FusedStateChunks { - source: FusedSeriesStream, + execution: FusedExecution, /// The layout every group of this export was folded on. declared: Arc, /// The groups of the batch last taken off the tree, in the order it folded them, each with a @@ -4046,10 +3652,7 @@ struct FusedStateChunks { /// The reference is taken once per group rather than held by this stream, so the batch's charge /// is released when the last group a consumer holds is dropped - not when this stream is polled /// again, and not when it goes away either. - pending: std::vec::IntoIter<( - datatypes::series::aggregate_state::StateSeries, - Option>, - )>, + pending: std::vec::IntoIter<(StateSeries, Option>)>, } impl Stream for FusedStateChunks { @@ -4074,106 +3677,38 @@ impl Stream for FusedStateChunks { None => HandedSeriesChunk::uncharged(chunk), }))); } - match Pin::new(&mut this.source).poll_output(cx) { - Poll::Ready(Some(Ok(FusedOutput::State(chunk)))) => { - let StateChunk::Series { - series, - reservation, - .. - } = chunk - else { - Pin::new(&mut this.source).fail(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(DataFusionError::Internal( - "row state reached the state chunk stream".into(), - )), - )))); - }; - this.pending = { - // One reference per group, so none of them is this stream's to hold. - let held = reservation.map(Arc::new); - series - .into_iter() - .map(|group| (group, held.clone())) - .collect::>() - .into_iter() - }; + match std::task::ready!(this.execution.poll_settled(cx, next_state_series)) { + Some(Ok((series, reservation))) => { + let held = reservation.map(Arc::new); + this.pending = series + .into_iter() + .map(|group| (group, held.clone())) + .collect::>() + .into_iter(); } - Poll::Ready(Some(Ok(_))) => { - Pin::new(&mut this.source).fail(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(DataFusionError::Internal( - "non-state output reached the state chunk stream".into(), - )), - )))); - } - Poll::Ready(Some(Err(error))) => { - Pin::new(&mut this.source).fail(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(error), - )))); - } - Poll::Ready(None) => return Poll::Ready(None), - Poll::Pending => return Poll::Pending, + Some(Err(error)) => return Poll::Ready(Some(Err(boxed(error)))), + None => return Poll::Ready(None), } } } } -struct FusedEvaluatedStream { - source: FusedSeriesStream, -} - -impl Stream for FusedEvaluatedStream { - type Item = Result<(datatypes::series::samples::Series, bool), common_error::ext::BoxedError>; - - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - match Pin::new(&mut self.source).poll_output(cx) { - Poll::Ready(Some(Ok(FusedOutput::Evaluated(chunk)))) => { - Poll::Ready(Some(Ok((chunk.series, chunk.is_last)))) - } - Poll::Ready(Some(Ok(FusedOutput::Rows(_) | FusedOutput::State(_)))) => { - Pin::new(&mut self.source).fail(); - Poll::Ready(Some(Err(common_error::ext::BoxedError::new( - common_query::error::Error::from(DataFusionError::Internal( - "row batch reached the evaluated stream adapter".into(), - )), - )))) - } - Poll::Ready(Some(Err(error))) => { - Pin::new(&mut self.source).fail(); - Poll::Ready(Some(Err(common_error::ext::BoxedError::new( - common_query::error::Error::from(error), - )))) - } - Poll::Ready(None) => Poll::Ready(None), - Poll::Pending => Poll::Pending, - } - } -} - +/// Exported state, handed to the frame packer one group at a time. struct FusedStateStream { - source: FusedSeriesStream, + execution: FusedExecution, /// The series of the one producer chunk being handed out. - pending: std::vec::IntoIter, + pending: std::vec::IntoIter, /// What that chunk still holds, released once its last series has been handed out. reservation: Option, } -impl FusedStateStream { - /// Drops what this stream still held and ends it: the packer above reads nothing more. - fn finish(&mut self) { - self.pending = Vec::new().into_iter(); - self.reservation = None; - } -} - impl Stream for FusedStateStream { - type Item = Result<(datatypes::series::aggregate_state::StateSeries, bool), BoxedError>; + type Item = Result<(StateSeries, bool), BoxedError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; loop { - if let Some(series) = self.pending.next() { + if let Some(series) = this.pending.next() { // is_last closes this producer's partial chunk chain; Final still merges every // producer's contribution before completing a group. return Poll::Ready(Some(Ok((series, true)))); @@ -4183,47 +3718,15 @@ impl Stream for FusedStateStream { // this point is what keeps the last series' payload accounted for while the packer // still reads it; dropping the exhausted iterator here keeps its spare capacity from // outliving the charge that covered it. - self.reservation = None; - self.pending = Vec::new().into_iter(); - match Pin::new(&mut self.source).poll_output(cx) { - Poll::Ready(Some(Ok(FusedOutput::State(chunk)))) => { - let StateChunk::Series { - series, - reservation, - .. - } = chunk - else { - Pin::new(&mut self.source).fail(); - self.finish(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(DataFusionError::Internal( - "row state reached state export stream".into(), - )), - )))); - }; - self.pending = series.into_iter(); - self.reservation = reservation; + this.reservation = None; + this.pending = Vec::new().into_iter(); + match std::task::ready!(this.execution.poll_settled(cx, next_state_series)) { + Some(Ok((series, reservation))) => { + this.pending = series.into_iter(); + this.reservation = reservation; } - Poll::Ready(Some(Ok(_))) => { - Pin::new(&mut self.source).fail(); - self.finish(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(DataFusionError::Internal( - "non-state output reached state stream".into(), - )), - )))); - } - Poll::Ready(Some(Err(error))) => { - self.finish(); - return Poll::Ready(Some(Err(BoxedError::new( - common_query::error::Error::from(error), - )))); - } - Poll::Ready(None) => { - self.finish(); - return Poll::Ready(None); - } - Poll::Pending => return Poll::Pending, + Some(Err(error)) => return Poll::Ready(Some(Err(boxed(error)))), + None => return Poll::Ready(None), } } } diff --git a/src/promql/src/native/split.rs b/src/promql/src/native/split.rs index 142eca59d1a..d04a9e45396 100644 --- a/src/promql/src/native/split.rs +++ b/src/promql/src/native/split.rs @@ -26,12 +26,13 @@ use std::sync::Arc; use datafusion::error::{DataFusionError, Result as DfResult}; use datatypes::series::SeriesOrdering; +use datatypes::series::aggregate_state::{AggregateStateKind, StateComponent}; use datatypes::series::samples::{FieldSpec, SeriesSchema}; use crate::map::MathOp; use crate::native::plan::{ - AggregateKind, AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundVectorOp, - Grouping, MapOp, NativeExpr, NativeNode, NativeTree, NativeType, aggregate_state_binding, + AggregateStage, AggregateStateSchema, BoundAggregate, BoundInput, BoundVectorOp, Grouping, + MapOp, NativeExpr, NativeNode, NativeTree, NativeType, aggregate_state_binding, }; pub(crate) struct Split { @@ -42,6 +43,8 @@ pub(crate) struct Split { op: BoundAggregate, /// The cut aggregate's output, which the exported state is indexed by. schema: Arc, + /// The state the cut aggregate exports. + state: Arc, /// The suffix reads whole histograms rather than individual groups. histogram: bool, /// The suffix rewrites at least one label of the histogram routing key. @@ -102,7 +105,7 @@ pub(crate) fn split( Ok(Some(inner)) } NativeExpr::Aggregate { input, op } => { - check_cut(op, fields, time_index)?; + let (kind, components) = check_cut(op, fields, time_index)?; match split(input, fields, time_index)? { Some(_) => Err(declined("an aggregate above a split aggregate")), None => { @@ -110,9 +113,16 @@ pub(crate) fn split( let NativeType::Samples(schema) = &node.output else { return Err(declined("an aggregate that produces no values")); }; - if schema.eval_grid.is_none() { + let Some(grid) = &schema.eval_grid else { return Err(declined("an aggregate that produces no values")); - } + }; + let state = Arc::new(AggregateStateSchema { + group: op.group.clone(), + kind, + components: components.into(), + accumulators: schema.fields.clone(), + grid: Arc::clone(grid), + }); Ok(Some(Split { prefix: (**input).clone(), // Source indices are local to one execution; the suffix has one input. @@ -127,6 +137,7 @@ pub(crate) fn split( }, op: op.clone(), schema: Arc::clone(schema), + state, histogram: false, label_rewrite: false, })) @@ -351,19 +362,19 @@ pub(crate) fn prefix_fields(tree: &NativeTree) -> DfResult> { .ok_or_else(|| declined("a tree that reads no raw series")) } -/// Refuses a non-`Complete` aggregate, a `quantile` (no fixed-width state), and a `by(...)` naming -/// a value field or the time index. +/// The state `op` exports when it is cut. Refuses a non-`Complete` aggregate, a `quantile` (no +/// fixed-width state), and a `by(...)` naming a value field or the time index. pub(crate) fn check_cut( op: &BoundAggregate, fields: &[FieldSpec], time_index: &str, -) -> DfResult<()> { +) -> DfResult<(AggregateStateKind, Vec)> { if op.stage != AggregateStage::Complete { return Err(declined("an aggregate that is not `Complete`")); } - if matches!(op.kind, AggregateKind::Quantile { .. }) { + let Some(state) = aggregate_state_binding(op.kind, op.field_kind) else { return Err(declined("a `quantile` aggregate")); - } + }; if let Grouping::By(labels) = &op.group && labels.iter().any(|label| { label.as_ref() == time_index @@ -374,7 +385,7 @@ pub(crate) fn check_cut( { return Err(declined("an aggregate grouped by a value field")); } - Ok(()) + Ok(state) } /// Checks that the prefix answers one series from one series' samples: maps and constant-sided @@ -447,31 +458,16 @@ pub struct SplitTrees { } impl Split { - /// `Ok(None)` when the aggregate has no mergeable state. - pub fn into_trees(self) -> DfResult> { + pub fn into_trees(self) -> DfResult { let Self { prefix, suffix, op, schema, + state, histogram: _, label_rewrite: _, } = self; - let Some((kind, components)) = aggregate_state_binding(op.kind, op.field_kind) else { - return Ok(None); - }; - let Some(grid) = schema.eval_grid.clone() else { - return Err(DataFusionError::Internal( - "a split aggregate has no evaluation grid".into(), - )); - }; - let state = Arc::new(AggregateStateSchema { - group: op.group.clone(), - kind, - components: components.into(), - accumulators: schema.fields.clone(), - grid, - }); let partial = NativeTree::try_new(NativeNode { expr: NativeExpr::Aggregate { input: Box::new(prefix), @@ -501,10 +497,10 @@ impl Split { output: NativeType::Samples(Arc::clone(&schema)), }; let root = enter_suffix(suffix, &merged)?; - Ok(Some(SplitTrees { + Ok(SplitTrees { partial, final_tree: NativeTree::try_new(root)?, - })) + }) } }