Skip to main content

promql/extension_plan/
fused_series.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! One node that runs a compiled native tree over raw series.
16//!
17//! [`FusedSeries`] is the logical half: it holds the PromQL text the tree was compiled from, the
18//! tree itself and the binding its input was compiled against. [`FusedSeriesExec`] is the physical
19//! half: it owns one execution of that tree per partition, decodes its input frames into raw
20//! series chunks, and converts evaluated chunks back into batches. An input that is one of our own
21//! in-process operators hands its chunks over instead of frames
22//! ([`crate::extension_plan::SeriesExecutionPlan`]), which is the same chunks with no round trip
23//! through a batch. The decision is per input and taken by asking the input
24//! ([`crate::extension_plan::series_execution_plan`]): one source can be read in process while
25//! another is decoded from its frames, because each input is either one of ours or it is not. Every
26//! content a native input publishes goes the same way, aggregate state included: a state row is
27//! handed over as the row it is, not left on a frame path of its own.
28//!
29//! Both halves show their own compiled tree in `EXPLAIN`, rendered by [`NativeTree`]'s display.
30//! The logical node shows its tree without metrics; the physical node includes each tree node's
31//! recorded metrics when available. The text is what names the value columns, not a plan line:
32//! neither half echoes the query.
33//!
34//! Scope of this layer: the input is a stream of native raw series frames
35//! ([`raw_series_frame_schema`](datatypes::series::frame::raw_series_frame_schema)) — one row per
36//! chunk, carrying the series' encoded key, its finality, its timestamps and its fields, plus the
37//! complete labels when the frame is explicit — with each series' rows contiguous and its
38//! timestamps ascending, which is what the caller's [`SeriesOrdering`] names. The output is one
39//! batch per evaluated chunk, with the statement's grid timestamps in the declared time column.
40//! Each source contributes exactly one partition per output partition; this node has no internal
41//! gather. Physical planning must normalize global consumers to one partition, and matching locality
42//! requires a verified matching-key router on both operands. Everything the tree cannot do is
43//! rejected when the execution plan is built, not when the first
44//! batch arrives: a tree the native runtime does not execute, a frame whose schema the tree's input
45//! was not compiled against, or an output schema the conversion cannot classify.
46
47use 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
125/// The label a metric name is stored under, which is not a tag column of the input.
126const METRIC_NAME: &str = "__name__";
127
128/// How many input steps one poll of [`FusedSeriesStream`] runs before it wakes itself.
129///
130/// A step polls the input once and hands what it settled to the executor. Settling is not
131/// guaranteed: raw samples before the first evaluation point settle nothing, so an input of many
132/// such chunks would otherwise be read to its end inside one poll, holding the task's thread for
133/// an unbounded time and delaying both other tasks on it and the cancellation the consumer asked
134/// for. The budget makes that a poll that yields instead, and the waker makes sure it is polled
135/// again, so nothing is lost by stopping early.
136const POLL_BUDGET: usize = 64;
137
138/// The statement grid and output naming that travel with a compiled tree.
139///
140/// Source schemas belong to the tree's input nodes. This binding supplies the grid that addresses
141/// evaluated chunks, the time column and the metric and full raw tag names a region scan child is
142/// bound with. A child that already produces raw frames, a [`RawSeriesSource`] per table of a
143/// cross-table tree, carries its own binding instead. The output tags are the output schema's. The
144/// logical node checks that the root produces values on that grid; frames carry each series'
145/// actual labels and timestamps.
146///
147/// [`RawSeriesSource`]: super::RawSeriesSource
148#[derive(Clone, Debug)]
149pub struct FusedSeriesBinding {
150    /// The statement's grid, which is the grid every evaluated chunk is addressed on.
151    pub grid: Arc<EvalGrid>,
152    /// The metric name every input series is bound to, when the input reads one named metric.
153    ///
154    /// The requirement that a binding naming [`METRIC_NAME`] among [`tags`](Self::tags) also declares
155    /// this name belongs to the bare-scan arm of `plan_fused_series`, not to this node: a child that
156    /// is a region scan is asked for the series of this one metric, while a child that already
157    /// produces raw frames - a discovered selector's `RawSeriesSource`, or the union of them - names
158    /// each series in its own labels and is accepted with `None` here. A reader of the output still
159    /// sees which range functions dropped the name, which needs no binding.
160    pub metric_name: Option<Arc<str>>,
161    /// The output column holding the grid timestamps.
162    pub time_index: String,
163    /// The full logical tag names used to bind region scan children, before output-label projection.
164    ///
165    /// [`METRIC_NAME`] is special: it is resolved to the series' metric name instead of a column,
166    /// which is how a reader sees that a range function dropped it.
167    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/// What one bound child of this node produces.
215///
216/// Aggregate state is not a sample input: it carries mergeable accumulators rather than query
217/// values, even though both state and evaluated samples are addressed on a grid.
218#[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/// The output representation fixed when a fused plan is built.
239#[derive(
240    Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
241)]
242pub enum FusedOutputFormat {
243    /// The existing tabular query result.
244    PlainRows,
245    /// A self-describing evaluated SeriesFrame.
246    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
264/// The declaration is the shared schema; group, fields and grid live in the native binding and
265/// are checked when a frame is decoded against an expected binding.
266fn 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/// The logical plan of one node that runs a compiled native tree.
326///
327/// The node records the query the tree was compiled from, because that text names the value
328/// columns it publishes, and it carries the binding the tree's input was compiled against so the
329/// execution plan can be built from it. `EXPLAIN` shows the compiled tree.
330#[derive(Debug)]
331pub struct FusedSeries {
332    /// The PromQL text this tree was compiled from, which names the value columns it publishes.
333    promql: Arc<str>,
334    /// The compiled tree to run.
335    tree: NativeTree,
336    /// What the tree's input was compiled against.
337    binding: FusedSeriesBinding,
338    /// Plans producing the inputs, in source-index order.
339    children: Vec<LogicalPlan>,
340    /// The columns this node produces.
341    output_schema: DFSchemaRef,
342    /// Fixed output representation, chosen when the node is built.
343    format: FusedOutputFormat,
344    /// The half of a canonical boundary this node is, if any.
345    ///
346    /// A [`NativeExpr::Merge`] collects every fragment of one canonical label set, which a node that
347    /// runs per scan partition cannot promise in general - and it is why a tree holding one is
348    /// normally gathered into a single execution. A canonical boundary keeps the query's width by
349    /// letting a producer merge what each partition holds and routing the pieces of one label set
350    /// across partitions; a consumer above it therefore reads whole label sets as ordinary frames.
351    /// That a node is the producer cannot be read off its tree - the merge is at its root - so it is
352    /// stated here by the caller that built the boundary.
353    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
376/// Experimental FusedSeries envelope version. The format is not persisted; any incompatible
377/// layout change may reset this rather than reserving numbers for unreleased revisions.
378const 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    /// Whether this node is the partition-local producer of a canonical merge; part of the node's
391    /// identity, not of where it may be placed.
392    #[serde(default)]
393    canonical_producer: bool,
394}
395
396impl FusedSeries {
397    /// Serializes the native tree and the binding required to reconstruct this plan node.
398    /// The PromQL text identifies expression-named output fields; children remain ordinary
399    /// Substrait inputs.
400    ///
401    /// This is only the node's own encoding. Whether a planner is allowed to place this node on
402    /// another machine is a separate decision, made by the planner and the transport, not here.
403    ///
404    /// The envelope is [`FUSED_SERIES_ENVELOPE_VERSION`], the payload's length in bytes, then the
405    /// postcard payload itself.
406    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    /// Rebuilds a serialized FusedSeries node, validating its carried output schema against the
431    /// execution contract. Substrait attaches children separately.
432    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        // Placement is not part of the encoding: the envelope keeps the bytes it has always had, and
510        // a node read back from one is placed by its shape, which keeps a producer above the regions.
511        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    /// The name this node is shown under.
525    pub const fn name() -> &'static str {
526        "FusedSeries"
527    }
528
529    /// Creates the node, checking that `tree` is legal against `binding`.
530    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    /// Creates the state-exporting half of a split aggregate.
548    ///
549    /// The node runs a `Partial` tree and answers aggregate-state frames, so its output layout is
550    /// the one `tree` declares rather than a caller's: the alternative is a caller free to declare a
551    /// state frame the tree does not produce, which `try_new_with_format` would then only catch for
552    /// some of its columns.
553    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    /// The two trees a native aggregate over `tree` is split into, if it can be split at all.
576    ///
577    /// The first runs where the series are read and answers the state each partition folded; the
578    /// second runs where every partition's state has arrived and answers the statement's series.
579    /// `time_index` is the column the tree's grid points are reported under.
580    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            // A shape the split cannot carry is not a failure: the caller keeps the plan it would
589            // have built without this route.
590            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    /// The evaluated series-frame schema declared by a native tree's root.
599    pub fn series_frame_schema(tree: &NativeTree) -> DataFusionResult<SchemaRef> {
600        series_frame_output_schema(evaluated_output(tree)?.as_ref())
601    }
602
603    /// Creates a node with an explicitly selected output format.
604    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        // The binding is checked against each child, since a discovered selector binds one
613        // source per metric. A `SeriesFrame` node over several evaluated inputs stays legal
614        // here.
615        validate_binding(&tree, &binding, &children)?;
616        // State is a frame, not a row table: a `Partial` root has no row layout to publish, so
617        // the mismatch is refused where the format is chosen rather than where the exec is
618        // built.
619        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    /// Creates a producer whose terminal canonical merge is answered per input partition.
651    ///
652    /// The tree's root has to be a [`NativeExpr::Merge`], because that is the node this flag changes
653    /// the meaning of: instead of collecting every piece of a label set in one execution, the node
654    /// collects the pieces its own partition holds and exports one series per label set as a series
655    /// frame. What that leaves undone - the pieces of one label set that landed in other partitions -
656    /// is the canonical router's work above this node, and the caller that builds it is the one that
657    /// knows the pieces are split that way.
658    ///
659    /// `output_schema` is the frame the evaluated root declares; it is derived here rather than
660    /// taken from the caller so the two cannot disagree.
661    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    /// Whether a canonical producer's input prefix is safe to run at its local execution width.
689    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    /// Whether this node is the partition-local producer of a canonical boundary.
696    pub fn is_canonical_producer(&self) -> bool {
697        self.canonical_producer
698    }
699
700    /// The PromQL text this node was compiled from, which names the value columns it publishes.
701    pub fn promql(&self) -> &str {
702        &self.promql
703    }
704
705    /// The selected output representation.
706    pub fn format(&self) -> FusedOutputFormat {
707        self.format
708    }
709
710    /// Whether this node's tree reads its input as aggregate state rather than as series.
711    ///
712    /// A state root is the `Final` half of a split aggregate, which reads what the `Partial` half
713    /// exported. The kind is the tree's own: its inputs' bindings decide what each child must
714    /// produce, so a caller that needs to recognize the second half of a split does not have to
715    /// read the first one's labels.
716    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    /// The compiled tree this node runs.
725    pub fn tree(&self) -> &NativeTree {
726        &self.tree
727    }
728
729    /// Child plans in source-index order.
730    pub fn children(&self) -> &[LogicalPlan] {
731        &self.children
732    }
733
734    /// What the tree's input was compiled against.
735    pub fn binding(&self) -> &FusedSeriesBinding {
736        &self.binding
737    }
738
739    /// The physical node that runs raw frame sources as this node's inputs.
740    ///
741    /// Each tuple binds a frame producer to its label source and ordering. Building the node
742    /// rejects incompatible frames or an output
743    /// schema the conversion cannot classify.
744    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    /// Builds the physical plan using an explicit target width for matching-local work.
752    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        // Validate every declared frame and ordering before inserting any exchanges.
820        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                    // Final folds every row of each original group on one owner. A histogram suffix
835                    // additionally requires related groups on that same owner; the policy is
836                    // derived from the Final grouping and the suffix, not matching-key classes.
837                    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                    // One routing key needs only one owner. Multiple keys split work the way the
844                    // session asks; an unspecified width preserves the producers' width.
845                    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                        // Rebuild over the producer, not the old router's row slices, which retain
857                        // their parent payload and would otherwise be charged once per row again.
858                        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                    // Region streams may each close the same storage key. Reconcile those
880                    // fragments even when the merged stream has only one output partition.
881                    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                    // A per-series tree reads each raw series on its own, so its width is a choice:
895                    // route the raw frames by their stored key up to the width this execution was
896                    // asked for, and each series still lands on exactly one owner.
897                    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                    // Already the one partition a global tree needs; wrapping it would add a node
974                    // that changes nothing.
975                    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                    // Either there is no router yet or the one there routes by another key. The
981                    // second case re-routes what the first produced: a router's output is plain
982                    // partitions, so another one above it is a legitimate shuffle rather than a
983                    // no-op, and refusing the query would be worse than paying for the move.
984                    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    /// Routes a canonical producer's frames by label set: the canonical collection step above it.
1018    ///
1019    /// The producer cannot do this itself.
1020    ///
1021    /// The producer answers one series per label set *per partition*: it merged what it found there.
1022    /// The pieces of one set that landed in other partitions are still apart, and every consumer
1023    /// above this boundary reads whole label sets, so they are collected here - by canonical label
1024    /// set, not by matching key, and by the conservative completion contract, because a producer can
1025    /// only promise one series per set per partition and not that each set lives in one partition.
1026    ///
1027    /// This router is the boundary's middle stage and nothing else: a query whose tree holds no
1028    /// canonical merge never reaches this code, and a merge that is not a boundary stays where it is.
1029    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        // The producer's own partitions are where the pieces are, so the router runs at exactly that
1037        // width: it neither invents more owners than there is work for nor collects every piece into
1038        // one. The session's `target_partitions` is not consulted, because it describes the session
1039        // that plans this node and not the work below it: this boundary is planned where its producer
1040        // runs - in the region for a regional producer - and the producer's width is already the
1041        // scan's, which the frontend assigned. Asking the region's own default instead would gather
1042        // every piece into a single owner, which is the shape this boundary exists to avoid.
1043        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    /// The locality this node's physical execution runs at.
1052    ///
1053    /// Normally that is the tree's own classification: a tree that reads across series answers one
1054    /// partition and gathers what it reads. A partition-local canonical merge is the one deliberate
1055    /// exception, and it is a fact about *this* node's contract rather than about the tree, so it is
1056    /// read here and not inferred from the root: the caller that built the node knows its inputs are
1057    /// whole per partition, and the merge it ends with collects only that partition's fragments.
1058    /// Treating every merge as partition-local would instead let a merge that needs every piece run
1059    /// where it cannot see them.
1060    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    /// The label columns of the output, independent of the raw-input binding.
1069    ///
1070    /// A scalar root has no labels; its one other column is the value. The planner decides them
1071    /// from the whole tree - a match narrows them, `or` joins both sides' and a wrapper around
1072    /// either keeps them - and the output schema is where it records that.
1073    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            // Roles are types here too: a value is a float or a native histogram, so every other
1079            // non-time column of a row table is one of this output's labels, whatever its name.
1080            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        // The tree's operands are bound inside it; there is no expression for an optimizer to
1132        // rewrite separately from the tree that owns it.
1133        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
1233/// The schemas read by distinct raw sources, in dense source-index order.
1234fn 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    /// Each series is answered on its own, so the tree runs on whatever partitions its input has.
1295    PartitionLocal,
1296    /// The tree pairs series of whole vectors by one match key, so those classes must meet.
1297    MatchingLocal(MatchingLabels),
1298    /// The tree reads across series, so it needs every input on one partition.
1299    SinglePartition,
1300}
1301
1302/// The one source every leaf of `node` reads, when the tree keeps the matching key of that source.
1303fn 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        // `scalar()`, `topk`, a histogram function and a fold with a per-point argument read the
1375        // whole vector at a point, so they answer one value (or a whole ranking, or one series per
1376        // group) rather than one output series per input series.
1377        | NativeExpr::ScalarOf { .. }
1378        | NativeExpr::ParameterizedTopK { .. }
1379        | NativeExpr::ParameterizedHistogram { .. }
1380        | NativeExpr::ParameterizedAggregate { .. } => None,
1381    }
1382}
1383
1384/// Whether every operation in `node` preserves the labels used by `matching`.
1385///
1386/// This is deliberately separate from `same_source`: a subtree can read one source while
1387/// changing the labels used to route its eventual vector match.
1388fn 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                // Label rewrites and histogram maps are not proven to retain the requested key.
1408                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        // These operations can change labels or select/merge series; absent a node-specific
1451        // proof, do not claim that the routed key survives.
1452        _ => false,
1453    }
1454}
1455
1456/// Whether matching operands can be segmented as independent single-source computations and
1457/// at least one fails to preserve the requested key.
1458///
1459/// This is the key-change case the planner can handle by cutting the operands before matching.
1460/// A failed preservation proof alone does not establish that a key was changed. The planner and
1461/// [`input_locality`] share this predicate so that this admission rule cannot drift from locality.
1462pub 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
1470/// Derives the partition contract from the bound root, not from a physical property registry.
1471/// Whether `node` contains a vector-vector binary, which matches series of the whole vector.
1472///
1473/// A tree of unary nodes evaluates each series on its own, so its partitions need nothing from
1474/// each other. A binary with two vector sides pairs by match key instead, and every series of one
1475/// key class has to reach the same partition.
1476fn 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        // The fold reads its group, and its argument may be a scalar expression with a match of its
1505        // own inside it: `quantile(scalar(a * on(k) b), c)`. A vector match anywhere in the tree
1506        // needs its match keys co-located, wherever it sits.
1507        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
1518/// The vector/vector match this tree performs, looking through the pointwise nodes wrapped on top.
1519///
1520/// A match pairs series of two whole vectors, so where it sits — including under a scalar
1521/// broadcast or a pointwise wrapper — is the place that needs matching-key co-location. The scalar
1522/// side has to be a value that reads no source for that to hold: a scalar-output side that read a
1523/// whole vector (`scalar(c)`) only exists once every series of it is gathered, so a match under it is
1524/// not the unit of locality and the tree needs one partition instead. Answering `None` here leaves
1525/// that decision to [`reads_across_series`].
1526fn 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    // A `Partial` aggregate folds only the rows its own partition reads and exports the state it
1554    // folded; the `Final` half above the exchange is what needs every contribution in one place.
1555    // Reading it as a global fold instead would gather the scan into one partition and throw away
1556    // the parallelism the split exists to keep.
1557    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            // The root's grid does not reliably indicate source content after windowing; inspect its bound inputs.
1566            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        // Only a tree that matches two vectors needs its matching-key classes to meet in one
1577        // partition. A tree of unary nodes answers each series on its own, and asking for the
1578        // router there would both cost a shuffle and hide the ownership a Window needs.
1579        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    // A match between two different sources needs its match keys co-located, wherever the match
1591    // sits under the pointwise nodes above it.
1592    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
1606/// The owner count and routing policy required by a Final aggregate and its suffix.
1607///
1608/// State rows already carry the cut's full group labels. Histogram suffixes need a coarser key:
1609/// every bound of one histogram and every histogram whose metadata-free outputs collide must
1610/// meet, while the Final kernel still folds separately by the original group labels.
1611///
1612/// A suffix that folds across groups needs every group's rows in one place, whatever the Final's
1613/// grouping is: splitting the rows of one vector by group would answer one fold per owner rather
1614/// than the fold of the whole vector. Such a consumer is a whole-vector operation -- the ranking
1615/// operations, `scalar()`, and the fold whose argument is read per point -- and the walk below
1616/// records it as it descends, so a `quantile(time(), v)` above a grouped `Final` reads every owner
1617/// instead of one, and one whose parameter is the state itself reads it at all.
1618fn state_routing(root: &NativeNode) -> Option<(StateGroup, SeriesRouting)> {
1619    /// `gathered` says whether a node passed on the way down reads more than one group at a time.
1620    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            // A fold that is not this one reads the values of the rows below it and folds whole
1626            // groups together, so what it reads has to be in one place.
1627            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            // A parameterized histogram is a histogram suffix too: its function folds the bounds of
1634            // one histogram, so every bound has to meet where it runs.
1635            NativeExpr::ParameterizedHistogram { input, op, .. } => find(
1636                input,
1637                histogram || matches!(op, crate::native::plan::BoundVectorOp::Histogram(_)),
1638                gathered,
1639            ),
1640            // These answer from the whole vector rather than from one series at a time: `scalar()`
1641            // and the per-point `k` of a ranking operation read every series.
1642            NativeExpr::ScalarOf { input } | NativeExpr::ParameterizedTopK { input, .. } => {
1643                find(input, histogram, true)
1644            }
1645            // A fold whose argument is read per point folds its group's whole sample set, and the
1646            // state it reads may sit under either child: as the vector it folds, or as the series
1647            // its `scalar()` argument is answered from. Either way this node reads across groups,
1648            // so neither half may be left to another owner.
1649            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/// How many owners the groups of a state input have to be split across.
1697#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1698enum StateGroup {
1699    /// One group: every row belongs to it, so one owner folds the answer.
1700    Single,
1701    /// More than one group: the rows can be split by their group's labels.
1702    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    // A tree built without its constructor carries no proof of its contracts, and one without an
1712    // input has no scan to refuse it later.
1713    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
1734/// Sources whose evaluated series must be kept together for partitioned windows.
1735fn partitioned_window_sources(node: &NativeNode) -> DataFusionResult<Vec<usize>> {
1736    fn visit(node: &NativeNode, sources: &mut Vec<usize>) -> DataFusionResult<()> {
1737        // A subquery window reads an evaluated input, whose fragments belong to one series
1738        // wherever they were produced, so it needs no owner of its own. A raw window anywhere
1739        // below it still does, so the walk continues into the input either way.
1740        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
1779/// Fields read by each distinct raw source in source-index order.
1780pub 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
1793/// Validates a decoded plain-row node's schema against the tree that produces it.
1794///
1795/// A deserialized node carries its own output schema, so this is where a payload that names
1796/// columns the tree cannot produce is refused, before the node runs.
1797fn 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
1830/// Validates the tree's bound inputs and carries the root kind with their schemas.
1831///
1832/// The root kind must travel with the schemas because an evaluated sample schema and an
1833/// aggregate-state schema both have a grid, but require different physical frame decoders.
1834fn 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/// The sample kind an output field column carries.
1862///
1863/// A field's samples are floats or native histograms: the raw frame keeps those two payloads apart,
1864/// and a field never mixes them. The kind decides the Arrow column the conversion writes.
1865#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
1866pub enum FieldKind {
1867    /// One `Float64` cell per row.
1868    Float,
1869    /// One canonical native histogram `Struct` per row.
1870    Histogram,
1871}
1872
1873/// Where one output column of [`FusedSeriesExec`] comes from.
1874#[derive(Clone, Copy, Debug)]
1875pub(crate) enum OutputColumn {
1876    /// The evaluation grid timestamps of the current chunk.
1877    Time,
1878    /// Series field by index in the bound series schema.
1879    Field { index: usize, kind: FieldKind },
1880    /// Declared logical tag by index in the caller-supplied tag list.
1881    Tag(usize),
1882}
1883
1884/// The caller-named value field used by the ordinary row conversion for a label-free scalar.
1885fn 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
1915/// Whether a column of this type carries a field's samples.
1916///
1917/// A role is a type: a field holds floats or the canonical native histogram struct, a tag is
1918/// `Utf8` and time is a timestamp. A name says nothing about which of those a column is.
1919fn is_value_column(data_type: &DataType) -> bool {
1920    data_type == &DataType::Float64 || data_type == &native_histogram_value_type().as_arrow_type()
1921}
1922
1923/// Whether `names` name exactly the columns in `value_names`, one name per column.
1924fn 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
1935/// Names the fields in a row schema, in `series_fields` order.
1936///
1937/// A caller names a value column either after the expression that produced it or after the tree's
1938/// field, so the typed value columns are what decide which: the expression names are used only
1939/// when they name exactly those columns, and the field names when those do. Deciding by type keeps
1940/// a tag that shares a field's name from being read as that field. The result stays in
1941/// `series_fields` order because a name is bound back to its field by that index, so a reordered
1942/// output still reads every column from its own field.
1943fn 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
1973/// Classifies every output column, rejecting anything the conversion cannot produce.
1974pub(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            // A field holds floats or the canonical native histogram struct; anything else has no
2042            // conversion, and the plan that names it is refused here rather than at the first row.
2043            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            // A grid point inside the statement's interval can have no value in this field.
2055            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            // `rate` and the map kernels drop `__name__`, so a tag can be absent from a row.
2077            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
2120/// Whether the tree has a binary with two vector operands that can produce a duplicate verdict.
2121fn 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
2132/// Evidence shared by the output partitions of this plan's single execution.
2133struct 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
2158/// The physical node that runs a compiled native tree over its input's raw series.
2159pub struct FusedSeriesExec {
2160    /// The PromQL text the tree was compiled from, which names the value columns it publishes.
2161    promql: Arc<str>,
2162    /// The tree this node runs, shared by every partition's execution.
2163    tree: Arc<NativeTree>,
2164    /// Each source's compiled raw schema, used to decode only that source's frames.
2165    series_schemas: Vec<Arc<SeriesSchema>>,
2166    source_kinds: Vec<FusedInputKind>,
2167    /// Physical input plans, preserving each source's frame binding and ordering.
2168    inputs: Vec<(Arc<dyn ExecutionPlan>, RawLabelSource, SeriesOrdering)>,
2169    /// Where each output column comes from.
2170    classification: Arc<[OutputColumn]>,
2171    /// The output column holding the grid timestamps, kept so this node can be rebuilt over a new
2172    /// child without losing which column its time came from.
2173    time_column: String,
2174    /// The tag column names, indexed by [`OutputColumn::Tag`].
2175    tags: Arc<[String]>,
2176    /// The one metric every input series is named, taken from the binding.
2177    ///
2178    /// The canonical pass judged a dropped label set by this: a node that drops the metric name is
2179    /// only told to stream when everything below it is named the same one. The execution reads it
2180    /// so the collection it performs at run time is decided by that same proof; `None` is a binding
2181    /// that names no metric - one raw source per input - and every consumer then collects.
2182    metric_name: Option<Arc<str>>,
2183    /// The columns this node produces.
2184    output_schema: SchemaRef,
2185    /// The evidence claimed by this plan's output partitions.
2186    duplicate_evidence: Mutex<EvidenceClaims>,
2187    /// Per-node metrics, registered by each execution of the tree, and the tree itself.
2188    ///
2189    /// Shared with the tree's own registration, which reads these figures when a reader asks for
2190    /// the tree: that reader outlives this borrow, and must never keep the set alive.
2191    metric: Arc<ExecutionPlanMetricsSet>,
2192    /// The fixed membership returned by `metrics()`: at construction only the `native.tree` Custom
2193    /// is registered; later per-partition `native.<path>.*` figures were always filtered out.
2194    /// If a physical operator metric is registered during execution, it must also be included here
2195    /// or this cache must gain invalidation; otherwise the membership regression test will fail.
2196    own_metrics: MetricsSet,
2197    format: FusedOutputFormat,
2198    matching_parallelism: Option<usize>,
2199    /// Whether this node is a partition-local canonical producer.
2200    canonical_producer: bool,
2201    /// This node's partitioning, emission and boundedness.
2202    properties: Arc<PlanProperties>,
2203}
2204
2205/// Registers the tree `tree` runs as one of the metrics `metric` holds.
2206///
2207/// What is registered reads the tree when it is asked for, because a node's figures are only final
2208/// once the tree ran, and `ANALYZE` reads them after it did. The reader holds `metric` weakly: the
2209/// set holds the reader, so a strong handle would keep the set alive for as long as the reader.
2210fn 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/// The label facts a per-series scan states about the series below a tree.
2225///
2226/// A `PrimaryKey` binding names one metric and lists the tags it binds, so every stored series under
2227/// it reports that name and exactly those tags. A walk that has to decide whether a node that drops
2228/// the metric name still tells two stored series apart needs both: the name such a node drops is the
2229/// one every series of the scan shares, and what is left to tell them apart are the tags.
2230#[derive(Clone, Debug)]
2231struct StoredSeriesLabels {
2232    /// Every tag name a stored series reports besides its metric name.
2233    tags: Arc<[Arc<str>]>,
2234    /// Whether the primary key keeps telling two stored series apart once a name-dropping kernel
2235    /// has normalized their labels; see [`keys_survive_metadata_drop`] for the rule itself.
2236    keys_survive_metadata_drop: bool,
2237}
2238
2239/// Whether the storage key of a scan keeps telling its stored series apart once a name-dropping
2240/// kernel has normalized their labels.
2241///
2242/// `logical_tags` are the tag names every stored series of the scan reports, and `key_columns` are
2243/// the columns the scan keys one series by. Two facts make the drop injective, and both are read
2244/// from the scan's own binding rather than from a tree above it:
2245///
2246/// - Neither the tags nor the key columns may be a metadata label. `__type__` and `__unit__` go with
2247///   the metric name when a kernel drops it, so a scan that keys a series by either of them stops
2248///   telling two series apart once the name is gone.
2249/// - Every key column must always decode a value, which is what a non-nullable column states. A
2250///   kernel that drops the name drops every label whose value is empty with it, and a nullable
2251///   column lets one series hold `NULL` while another holds `''`: two different storage keys, which
2252///   decode to an absent label and to an empty one, so both are handed over as no label at all once
2253///   the empty one is dropped. Two such series that agree on every other tag then leave as one
2254///   identity, whether they arrive in one partition or in two.
2255///
2256/// The physical per-series scan asks this of its own binding to decide whether a node may stream, so
2257/// that its partitions hand over whole series. The plan-time canonical proof does not read it: the
2258/// labels alone decide whether a metadata drop is collected, and the planner reads this rule only to
2259/// count the statements that proof leaves unproved
2260/// ([`leaves_a_drop_to_the_storage_keys`](crate::native::plan::leaves_a_drop_to_the_storage_keys)).
2261/// Keeping the rule here is what stops the scan's own answer - read from the bound scan at execution -
2262/// from drifting away from the one the plan-time count is stated with.
2263pub 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    /// The labels `label_source` proves about every stored series it reads.
2276    fn of(label_source: &RawLabelSource) -> Option<Self> {
2277        // A `PrimaryKey` binding names one metric, which is what makes the name a name-dropping node
2278        // removes constant over the series below it.
2279        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    /// Whether the tags that tell stored series apart are all among the tags the rows carry.
2302    ///
2303    /// The rows this node emits carry `output` and no other label, so a tag the output does not name
2304    /// is one the rows drop: two stored series that differ only there would leave as one identity.
2305    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
2312/// Whether every series `node` emits is one series it read, under labels that still tell it apart.
2313///
2314/// A leaf reads one stored series at a time, and an instant selection of the sample, an instant
2315/// selection of an info sample and a filtering comparison hand that series over under the labels it
2316/// read.
2317///
2318/// `labels` states what the scan below the tree proves about those labels: the tags each stored
2319/// series reports, and whether they tell two of them apart once the metadata labels and the empty
2320/// values are gone. A node that drops the metric name - a range function such as `rate`,
2321/// `timestamp`, a math or histogram map, a parameterized map, and an arithmetic or `bool` scalar
2322/// broadcast - drops `__type__` and `__unit__` with it, and normalizes away every empty label value.
2323/// The name such a node drops is the one a single-metric scan binds for every series it reads, so
2324/// dropping it merges nothing; such a node therefore keeps two series apart exactly when the scan
2325/// keys its series by labels that survive the drop, which is what `labels` states. Without that
2326/// proof the name is part of what tells two series apart, and the node can file two of them under
2327/// one output label set - as it can when the key it drops the empty value of is one column of the
2328/// two series that holds `NULL` in one of them and `''` in the other.
2329///
2330/// Everything else answers one series per group or set it names, or pairs several inputs, so an
2331/// identity above it is not an identity of what it read.
2332fn 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            // Only `timestamp(x)` drops the name; a selection of the sample or of an info sample
2339            // keeps the labels it read.
2340            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            // The parameters are scalars that read no source, so they carry no labels of the series
2356            // this node reaches; the kernel drops the name as a math map does.
2357            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
2370/// Whether a point-wise map keeps every series it reads apart, given what the scan states.
2371///
2372/// A math kernel drops the metric name and a histogram kernel drops the name alone, so both need the
2373/// proof a name-dropping window needs. A label rewrite writes a destination of its own: a label no
2374/// series carries cannot make two of them equal, so writing one keeps them apart, while writing a
2375/// label some series carries - or a metadata label, `__name__` among them - can fold two series into
2376/// one label set. `None` when the input's labels are not derivable, because a destination that may
2377/// already be carried proves nothing.
2378fn 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                // A rewrite that can only write an empty value deletes its destination, which
2398                // publishes no label a later operation could carry.
2399                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
2410/// Whether a binary node with a source-free scalar on one side keeps every series of its vector side
2411/// apart.
2412///
2413/// A scalar carries no labels, so the operation reaches each series of the vector side as it is. An
2414/// arithmetic operation and a `bool` comparison drop the metric name and the metadata labels with
2415/// it, so each needs the proof a name-dropping map needs; a filtering comparison keeps the label set
2416/// it read, which is exactly the identity its input had.
2417fn 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    // `scalar(a)` is a scalar that read a whole vector, so only a value that reads no source is one
2429    // this node can pair with each series on its own.
2430    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
2442/// Returns whether the scan's bound logical tags cover every user-visible primary-key column.
2443///
2444/// Internal metric-engine keys are not output labels. The per-series scan guarantees `__tsid` is
2445/// derived from user tags; within one logical table, distinct series are distinguished by their
2446/// user-visible primary-key columns. Requiring all of those columns prevents distinct stored series
2447/// from collapsing onto one output identity.
2448fn 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
2470/// What the plan below a fused node proves about the series it hands over.
2471enum InputProof {
2472    /// A per-series scan whose bound tags cover its primary key: every stored series is one series
2473    /// here, and the labels its binding states tell the walk what a stored series carries.
2474    Scan(Option<StoredSeriesLabels>),
2475    /// A producer that already confines each identity to one partition, whose labels this node has
2476    /// no binding to enumerate.
2477    Confined,
2478}
2479
2480/// The proof `plan` states about the series below it, through the wrappers that pass rows on.
2481fn 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        // The provenance flag only says the child is a SeriesScanExec; it does not say the bound
2489        // tags cover the primary key. Check the child the same way the direct SeriesScanExec branch
2490        // does, so a raw source cannot claim disjointness a bare scan would refuse.
2491        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    /// Returns whether each output series identity is confined to one input partition.
2506    ///
2507    /// This is true only for a single per-series scan whose bound tags cover its primary key, a raw
2508    /// source that kept that provenance, or another proven fused chain, whose native tree answers
2509    /// every series it reads as that series: an instant selection of the sample or of an info sample,
2510    /// a filtering comparison, a window that keeps the metric name, or a chain of nodes that drop the
2511    /// metric name over a scan that reads one metric and keys its series by labels that survive the
2512    /// drop.
2513    ///
2514    /// A node that drops the metric name is proved rather than refused outright: a `PrimaryKey`
2515    /// binding reads one metric, so the name those nodes drop is the one every stored series
2516    /// carries, and what tells two of them apart are the tags the binding names. Requiring the rows
2517    /// to carry those tags, refusing a binding that keys a series by `__type__` or `__unit__` -
2518    /// which a name-dropping kernel removes with the name - and refusing a binding whose key columns
2519    /// are not every one of them non-nullable, because only a nullable column lets one series hold
2520    /// `NULL` where another holds `''`, which such a kernel normalizes into one absent label, is
2521    /// what keeps this an identity of what the tree read. A scan that states none of those facts
2522    /// proves nothing, and a row table that would not carry the tags below it proves nothing either,
2523    /// so both are refused here rather than refined later: the router above a producer that claims
2524    /// [`CompleteDisjoint`] stops checking for duplicates, and a refusal only keeps the merging path
2525    /// it would otherwise have taken.
2526    ///
2527    /// [`CompleteDisjoint`]: crate::extension_plan::IdentityCompletion::CompleteDisjoint
2528    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        // A row table carries the node's tag columns and nothing else, so the tags have to say which
2540        // labels the rows hold; a frame carries each series' whole label set instead.
2541        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    /// Creates the node, rejecting whatever this node cannot execute or convert.
2551    ///
2552    /// `input` produces native raw series frames: the series' encoded key, its finality, its
2553    /// timestamps and its fields, plus the complete labels when `label_source` is
2554    /// [`RawLabelSource::Explicit`]. `time_column` and `tags` name the columns of the output, which
2555    /// is a row table rather than a frame.
2556    ///
2557    /// The parameters stay separate because each is a fact its own caller has: the query, the plan
2558    /// below, the frame's label binding and ordering, the tree, and the three things the output
2559    /// schema is classified by. A struct over them would be the same list under another name.
2560    #[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        // A partition-local canonical merge is an explicit contract about this node's inputs, so it
2597        // replaces the tree's own classification rather than being folded into it: the tree's root
2598        // merge reads across series in general, and only the caller knows that these partitions each
2599        // hold whole series.
2600        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        // Building a state proves the runtime executes this tree; drop the validation state now.
2631        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            // State is the one input a cross-series tree may read from more than one partition:
2709            // the router above the producers put every row of a group in exactly one of them, so
2710            // the `Final` aggregate folds that group's whole contribution where it arrives. Any
2711            // other global input has no such owner and has to be gathered.
2712            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                // Partial aggregate state and canonical frame series are emitted only after EOF.
2850                EmissionType::Final
2851            } else {
2852                // A frame's identities, and every other output, are emitted while the input is
2853                // still arriving, so the node's emission type is the input's.
2854                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    /// The name this node is shown under.
2892    pub const fn name() -> &'static str {
2893        "FusedSeriesExec"
2894    }
2895
2896    /// The figures the tree this node runs recorded, keyed by the path each node registered under.
2897    fn node_metrics(&self) -> NodeMetricsSnapshot {
2898        NodeMetricsSnapshot::read(&self.metric)
2899    }
2900
2901    /// Every registration this node's tree made, exactly as it was registered.
2902    ///
2903    /// [`Self::metrics`] leaves these out because a flat set cannot say which node recorded what;
2904    /// this is the same set unfiltered, for a reader that keys by name - the names are
2905    /// `native.<path>.<metric>` (see [`crate::native::metrics`]).
2906    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    /// The compiled tree, one line per node.
2925    ///
2926    /// Each node's own figures are read from the metrics this node registered, so a statement that
2927    /// never ran - every plain `EXPLAIN`, verbose included - draws the tree without them. That is
2928    /// the whole difference between `EXPLAIN` and `ANALYZE` here: nothing switches it on.
2929    fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> fmt::Result {
2930        write!(f, "FusedSeriesExec")?;
2931        // On the operator's own line, where the logical node also puts it: a second line would read
2932        // as another node beside the tree this one draws.
2933        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    /// The metrics this node records itself, which is none of its tree's.
2950    ///
2951    /// A [`MetricsSet`] is a flat, name-keyed bag: reporting the tree's figures through it would
2952    /// attribute every node's figures to this node, because the reader cannot tell them apart. Each
2953    /// node reports its own on its own line instead - and, as data, through the tree this node
2954    /// registers as [`NativeTreeMetric`] - so they are left out here and this node reports only what
2955    /// an operator of its own would add.
2956    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    /// No optimizer exchange is requested here: evaluated-input partition counts and window owner
2965    /// routing are normalized explicitly while constructing the physical plan. Raw-input layout is
2966    /// left to its existing execution path.
2967    fn input_distribution_requirements(&self) -> InputDistributionRequirements {
2968        InputDistributionRequirements::new(
2969            self.inputs
2970                .iter()
2971                .map(|(_, _, _)| Distribution::UnspecifiedDistribution)
2972                .collect(),
2973        )
2974    }
2975
2976    /// Splitting the input further would not help: a second partition is a second set of series
2977    /// answered by a second tree, which this node already runs, and raising the count is what an
2978    /// optimizer does by adding a round-robin exchange that reorders nothing it can rely on.
2979    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        // The tree's operands are bound inside it; this node owns no expression of its own.
2992        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        // Rebuilt rather than patched: the new child's schema is what the frame is validated
3012        // against, so a child that changed shape is refused instead of decoded with a stale layout.
3013        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            // A row table is the query's answer, not a publication another native operator reads.
3049            (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    /// One partition's tree, handed over as the chunks a native consumer reads.
3060    ///
3061    /// The same execution the frame entry point runs, without the encode: the evaluated values the
3062    /// tree settled, each with the finality the packer would have given it, or - for a `Partial`
3063    /// root - the groups it folded, handed over exactly as its own aggregate produced them.
3064    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    /// Whether this node's output is a publication another native operator can read in process.
3092    ///
3093    /// A `SeriesFrame` - of values or of exported state - is one. The plain row table this node
3094    /// answers a statement with is not: rows are the query's answer, and `execute` hands them out.
3095    pub fn hands_over_series(&self) -> bool {
3096        self.format == FusedOutputFormat::SeriesFrame
3097    }
3098
3099    /// One partition's execution, before it is put in the form a consumer asked for.
3100    ///
3101    /// Both entry points start here, so the tree, its input and the evidence one execution claims are
3102    /// built once and the same way; they differ only in what they do with what the tree produced.
3103    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        // The canonical pass decided where a merge belongs from the labels the binding names; the
3130        // execution judges the collection it performs by the same fact, so an already-streaming
3131        // window is not turned into a collecting one here.
3132        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        // The planner registers the query's collector in the session's `ConfigOptions.extensions`
3152        // rather than the separate `SessionConfig` container, so it is read from where it was
3153        // written. The HTTP entry point holds a strong reference to that same collector for the life
3154        // of the response; a query without one - an internal execution, or a caller that never
3155        // asked for annotations - simply records nothing.
3156        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            // One input, one answer, asked of the input itself: an operator that can hand its
3171            // chunks over is asked for them, and everything else is asked for its frames. Asking
3172            // the input is what makes the two paths one decision - calling `execute_series` *is*
3173            // the statement that this input is read in process - and it is asked of every content
3174            // alike, aggregate state included.
3175            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                // What the frame path would compare a state publication against before it folds a
3179                // row of it: the series layout this node binds, and - per row, inside
3180                // `in_process_feed` - the state layout this node's aggregate declared.
3181                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        // One reading of the root decides both the mode and its binding, so the mode cannot
3274        // disagree with its binding: a Partial root without state output is a plan error.
3275        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        // A frame is encoded from the tree's own evaluated output, and only when the node answers
3308        // values rather than state: partial state is a third output the format does not reach.
3309        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
3351/// Converts one evaluated chunk into one output batch.
3352///
3353/// The time column is the absolute grid positions the chunk carries, missing samples are nulls and
3354/// ordinary NaN stays a value.
3355pub(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    // A chunk that forms one run is read from its range, which lends the grid's buffers and so
3363    // allocates nothing. A chunk whose rows form several runs has no single range to read
3364    // ([`EvaluatedChunk::range`] answers `None` for it), and the positions between its runs are
3365    // holes rather than rows: the axis is walked for its carried rows instead, which is the one
3366    // traversal that visits exactly those.
3367    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                // `__name__` resolves to the metric name, every other tag through the label set.
3399                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
3412/// Converts one evaluated series field into the column `kind` names.
3413///
3414/// Dense float samples are reused as they are: the array already carries exactly the right nulls
3415/// and keeps NaN a value, so copying it through `Samples::iter()` would only cost an allocation
3416/// and a re-encode. Histograms are gathered into the canonical struct column, one payload per row
3417/// and null where the grid point has no sample.
3418fn 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/// One chunk a child handed over, in the form the child's frame declared it in.
3450#[derive(Debug)]
3451enum FusedChunk {
3452    /// Raw samples: one scan series, with its own timestamps.
3453    Raw(RawSeriesChunk),
3454    /// Values a producer already evaluated on the grid the frame declares.
3455    Evaluated(EvaluatedChunk),
3456    /// Aggregate state decoded from a declared state frame.
3457    State(StateChunk),
3458}
3459
3460/// One partition's execution: the tree's own output, and its state layout when it exports state.
3461struct FusedExecution {
3462    /// The tree's output, which a consumer reads as values, as state, or as rows.
3463    stream: FusedSeriesStream,
3464    /// What a `Partial` root exports.
3465    state: Option<FusedStateOutput>,
3466}
3467
3468/// The aggregate state a `Partial` root exports.
3469struct FusedStateOutput {
3470    /// The layout as the frame path declares it, which is what the packer takes.
3471    declared: Arc<datatypes::series::aggregate_state::AggregateStateSchema>,
3472    /// The same layout as the tree's binding, which is what a handed-over chunk names.
3473    binding: Arc<AggregateStateSchema>,
3474    /// The series schema the export is of.
3475    series: Arc<SeriesSchema>,
3476}
3477
3478/// One chunk and the source index it belongs to, and what the producer charged it to.
3479///
3480/// The charge is held for as long as this value is: it is dropped once the chunk has been pushed
3481/// into the tree, which is the point where the executor's copy of the values is its own and the
3482/// producer's accounting of them is over. A framed input has no charge here - its charge lives in
3483/// the packer's handoff - so the field is empty on that path and nothing changes for it.
3484struct FusedFeed {
3485    source: usize,
3486    chunk: FusedChunk,
3487    charge: Option<SeriesCharge>,
3488}
3489
3490/// One chunk a native input handed over, as the form this node's runtime reads that source in.
3491///
3492/// The variant has to be the one the tree bound the source to: a source compiled as raw samples
3493/// cannot be read as evaluated values, and treating one as the other would misread the plan rather
3494/// than merely slow it down, so a mismatch is reported.
3495fn 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            // The two checks the frame path makes before it folds state, on the same two properties:
3513            // the state layout the export was declared on is the kind and component layout this
3514            // node's aggregate declared, and the series it was exported on is the series this node
3515            // binds. After them the chunk travels as it is - a `Final` merges the groups a producer
3516            // folded exactly as it merges the row a frame decodes to.
3517            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
3562/// The aggregate-state binding `source` was compiled with.
3563///
3564/// Both entry points read it from the same place, so a source declared aggregate state is folded
3565/// against the layout its tree declared whether its operator published frames or rows.
3566fn 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
3586/// `declared` is the series layout `expected` binds, as `unpack_aggregate_state` checks it.
3587///
3588/// A frame says which series its state is of in its declaration; a chunk carries that declaration's
3589/// series schema instead, so the check the decoder makes on the frame is made here on the same two
3590/// properties: the field names in order, and the evaluation grid.
3591fn 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
3612/// A failure in the handover's own error type.
3613fn failed(reason: String) -> BoxedError {
3614    BoxedError::new(common_query::error::Error::from(
3615        DataFusionError::Execution(reason),
3616    ))
3617}
3618
3619/// The native histogram column of one evaluated field.
3620///
3621/// The column is the canonical native-histogram struct - the layout the Prometheus response reads
3622/// and the one every classic histogram kernel already emits - built by the same encoder those
3623/// kernels use. A row whose grid point has no sample is null.
3624fn 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
3640/// One evaluated histogram in the canonical query-time form.
3641///
3642/// A [`HistogramView`] borrows spans and buckets out of a shared table; the canonical form owns
3643/// them, which is what the output column holds.
3644fn 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
3669/// The batches one execution of [`FusedSeriesExec`] yields.
3670pub struct FusedSeriesStream {
3671    /// Every input partition, read concurrently, or `None` once they all ended.
3672    ///
3673    /// Each decoder holds its current batch, decoded chunks and upstream source. Dropping this on
3674    /// error releases them even if the consumer keeps the terminated stream; a partition read on a
3675    /// spawned task is released once its runtime cancels the task, not by the time this returns.
3676    inputs: Option<SelectAll<futures::stream::BoxStream<'static, Result<FusedFeed, BoxedError>>>>,
3677    /// The execution of this node's tree, or `None` once it has been closed.
3678    executor: Option<NativeExecutor>,
3679    /// Runtime input IDs for each source index.
3680    input_ids: Vec<Vec<InputId>>,
3681    /// Where each output column comes from.
3682    classification: Arc<[OutputColumn]>,
3683    /// The tag column names, indexed by `OutputColumn::Tag`.
3684    tags: Arc<[String]>,
3685    /// The schema of every batch this stream yields.
3686    output_schema: SchemaRef,
3687    /// Whether the root exports aggregate-state chunks.
3688    state_mode: bool,
3689    /// Whether output is a declared SeriesFrame rather than rows.
3690    frame_mode: bool,
3691    /// The batches the executor settled since the last poll of the input.
3692    ready: VecDeque<RecordBatch>,
3693    /// Whether the input ended and everything it settled has been handed out.
3694    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    /// Hands one raw chunk over and queues what it settled.
3730    fn push(&mut self, feed: FusedFeed) -> DataFusionResult<()> {
3731        let FusedFeed {
3732            source,
3733            chunk,
3734            charge,
3735        } = feed;
3736        // What the producer charged this chunk is released when this call returns. That is the
3737        // whole point of holding it here rather than in the handover stream: the tree reads the
3738        // chunk below, so the reservation covers the bytes for as long as they are read and not one
3739        // poll less - and the copy the executor keeps, when it keeps one, is accounted by the tree.
3740        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        // One source feeding several runtime inputs hands each the same value, cloned per input,
3752        // which is what the base route does. One runtime input is the common shape and needs no
3753        // copy: the chunk moves into it. A producer's state batch carries the charge for its whole
3754        // payload, so it is never bound to several inputs -- and it stays refused either way.
3755        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    /// Ends the input, so the tree settles what it was holding.
3796    ///
3797    /// `finish()` would be the same thing plus a drain, but the drain collects: it holds the whole
3798    /// answer in a `Vec` before anything is handed out, so a tree that answers many chunks after its
3799    /// input ends would sit on all of them while the consumer waits for the first. Only the input is
3800    /// ended here, and the answers are pulled one per call below, so each chunk leaves as the tree
3801    /// settles it and what has not been pulled yet stays charged to the node holding it.
3802    fn close_input(&mut self) -> DataFusionResult<()> {
3803        match self.executor.as_mut() {
3804            Some(executor) => executor.end_of_input(),
3805            // Every answer was pulled and the execution closed itself.
3806            None => Ok(()),
3807        }
3808    }
3809
3810    /// Pulls the next answer the tree settles after its input ended, or `None` when it has none.
3811    ///
3812    /// One chunk per call is what keeps this a stream: collecting them first would hold the whole
3813    /// answer while the consumer waits for the first, and would charge the pool for all of it at
3814    /// once. `None` is also when the execution closes and returns its reservations, so it is
3815    /// dropped here rather than staying alive until the stream is.
3816    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    /// Ends the stream in an error, releasing the execution and the inputs.
3834    ///
3835    /// An ordinary drop of the stream releases all of this as well, so this is not about the last
3836    /// release: it is about a consumer that keeps the terminated stream, which would otherwise
3837    /// hold the evaluator, the decoder's held batch and chunks, and the plan upstream of it.
3838    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        // This reservation belongs only to this execution. Release it even if the consumer keeps
3849        // the failed stream and the plan alive.
3850        // A batch queued before the error was settled by a run that has now stopped.
3851        self.ready.clear();
3852    }
3853
3854    /// Converts one settled chunk into a row batch. Evaluated frames leave this driver as chunks.
3855    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    /// Aggregate state decoded from a declared state frame.
3871    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
4001/// The tree's evaluated output, handed over as the chunks a native consumer reads.
4002struct 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
4023/// Exported state, handed over one group at a time as the chunks a `Final` merges.
4024///
4025/// The charge the tree's own export carried rides on the groups it is cut into: a reader that takes
4026/// one group and holds it is holding the bytes of the batch that group was folded in, so the
4027/// reservation is shared by every group of that batch and released with the last of them.
4028struct FusedStateChunks {
4029    source: FusedSeriesStream,
4030    /// The layout every group of this export was folded on.
4031    declared: Arc<AggregateStateSchema>,
4032    /// The groups of the batch last taken off the tree, in the order it folded them, each with a
4033    /// reference to the charge that batch carried.
4034    ///
4035    /// The reference is taken once per group rather than held by this stream, so the batch's charge
4036    /// is released when the last group a consumer holds is dropped - not when this stream is polled
4037    /// again, and not when it goes away either.
4038    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                // A `Partial` closes every group it exports: the fold of one partition is whole, and
4052                // the `Final` above merges the partitions' publications rather than continuing one
4053                // chain.
4054                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                        // One reference per group, so none of them is this stream's to hold.
4083                        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    /// The series of the one producer chunk being handed out.
4147    pending: std::vec::IntoIter<datatypes::series::aggregate_state::StateSeries>,
4148    /// What that chunk still holds, released once its last series has been handed out.
4149    reservation: Option<MemoryReservation>,
4150}
4151
4152impl FusedStateStream {
4153    /// Drops what this stream still held and ends it: the packer above reads nothing more.
4154    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                // is_last closes this producer's partial chunk chain; Final still merges every
4167                // producer's contribution before completing a group.
4168                return Poll::Ready(Some(Ok((series, true))));
4169            }
4170            // Every series of that chunk has been handed out, so its charge and the buffer those
4171            // series came from both go back before the next chunk is read. Holding the charge until
4172            // this point is what keeps the last series' payload accounted for while the packer
4173            // still reads it; dropping the exhausted iterator here keeps its spare capacity from
4174            // outliving the charge that covered it.
4175            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}