From 5185b0c30deedaa6cf0fd486840f5f7d2212ca35 Mon Sep 17 00:00:00 2001 From: discord9 <55937128+discord9@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:08:49 +0800 Subject: [PATCH] perf(promql): emit one batch per evaluated chunk instead of one per series `FusedSeriesStream` asked the evaluator for a series and got one only when the input series ended, so a long series held every row until its last raw chunk and then arrived as a single batch. The evaluator now hands out each part of a series as soon as it decides it, so the stream can forward it. The consequence is that trimming moves here. A chunk's span now reports the positions the evaluator decided rather than the positions holding a value, so trailing and leading positions decided to be missing are inside it: `trim_to_values` cuts a chunk back to its first and last row holding a value before the batch is built, and a chunk that decided nothing but missing positions produces no batch. That is the same trim the evaluator's builder used to do while it was also the one deciding what a series reported. `map_math` now returns `Option`, because it drops the metadata labels and skips histogram points, so a chain can end with no value at all; `apply_maps` stops at that point instead of failing. This is not only a convenience: a series whose evaluated points are all historic histograms would otherwise reach the output conversion, which rejects histograms outright, and fail the query. Dropping it in the map chain is what lets `sum_over_time` of such a series return nothing rather than an error, matching Prometheus. A trimmed chunk is rebuilt against the evaluated schema (`evaluator.output_schema()`), not the raw input schema, which has no grid and is rejected by `Series::try_new`. Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> (cherry picked from commit f787b055f12fbd44bbeb8c4638d7ad10b99a7bb0) (cherry picked from commit ce0cfecb5fecd53d848cbb9ec54e5e1cf7b688e1) --- Cargo.lock | 1 + src/promql/src/extension_plan.rs | 1 + src/promql/src/extension_plan/fused_series.rs | 981 ++++++++++ .../src/extension_plan/fused_series/tests.rs | 1628 +++++++++++++++++ tests-integration/Cargo.toml | 1 + .../nested_merge_scan_capability_test.rs | 194 ++ 6 files changed, 2806 insertions(+) create mode 100644 src/promql/src/extension_plan/fused_series.rs create mode 100644 src/promql/src/extension_plan/fused_series/tests.rs diff --git a/Cargo.lock b/Cargo.lock index ea2a530d6b5..9597ed92347 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15115,6 +15115,7 @@ dependencies = [ "paste", "pipeline", "plugins", + "promql", "prost 0.14.1", "query", "rand 0.9.4", diff --git a/src/promql/src/extension_plan.rs b/src/promql/src/extension_plan.rs index 750ee41b5e8..2be41e175b5 100644 --- a/src/promql/src/extension_plan.rs +++ b/src/promql/src/extension_plan.rs @@ -14,6 +14,7 @@ mod absent; mod empty_metric; +pub mod fused_series; mod histogram_fold; mod instant_manipulate; mod normalize; diff --git a/src/promql/src/extension_plan/fused_series.rs b/src/promql/src/extension_plan/fused_series.rs new file mode 100644 index 00000000000..3eb5b6b7c67 --- /dev/null +++ b/src/promql/src/extension_plan/fused_series.rs @@ -0,0 +1,981 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! One physical node that evaluates one range function and then 0..N float map kernels over raw +//! series, converting every completed evaluated series directly into one output batch. +//! +//! There is no `SeriesFrame` pack/unpack and no intermediate `RecordBatch` between the evaluation +//! and the map kernels: both stages run over typed [`Series`] values inside this node. +//! +//! Phase 1 scope: the child produces raw frames of one partition with explicit labels and is not +//! interleaved, and the output schema must classify into exactly one timestamp column, one +//! `Float64` column per series field, and one `Utf8` column per declared tag. Anything outside +//! this scope is rejected at construction instead of silently falling back. The field and tag +//! columns must be declared nullable: a grid point inside the trimmed interval can be missing, and +//! the range functions and the map kernels drop `__name__`. +//! +//! This node computes floats only, and admitting raw samples is the caller's responsibility: +//! validating the declared frame schema cannot prove that the samples are float, so a histogram +//! or mixed sample passes construction and surfaces at run time as [`RangeEvaluator`]'s (or a map +//! kernel's) `NotImplemented`. That runtime type check is kept rather than replaced by a schema +//! check that could not prove the same thing. +//! +//! Duplicate label sets follow Prometheus' range-query rule. `rate` and the map kernels drop +//! `__name__`, so two distinct raw series can reach the same final label set; if both have a +//! sample at the same evaluation timestamp that is an error (`vector cannot contain metrics with +//! the same labelset`), while series whose occupied grid points are disjoint are legal and +//! Prometheus merges them into one output series. This node emits such series as separate batches +//! and defers that merge to matrix assembly, so no sample is dropped. +//! +//! Memory: the only state retained across polls that grows with the output is the per-stream +//! label-set occupancy map, and its bytes are reserved on the task's memory pool. The range-window +//! samples [`RangeEvaluator`] retains across chunks and the batches already handed downstream are +//! deliberately not reserved here. +//! +//! The child's `is_last` is the only completion signal. This node neither recomputes finality +//! across inputs nor emits a series it has not seen finalized, so a child that merges regions must +//! recompute `is_last` globally before handing its frames over; a region-local flag would finalize +//! a series early. + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::fmt::{self, Formatter}; +use std::mem::size_of; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use common_query::series_frame::unpack_raw_series; +use datafusion::arrow::array::{ + Array, ArrayRef, Float64Array, StringArray, TimestampMillisecondArray, +}; +use datafusion::arrow::datatypes::{DataType, SchemaRef, TimeUnit}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::error::{DataFusionError, Result}; +use datafusion::execution::context::TaskContext; +use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation}; +use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr}; +use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType}; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties, RecordBatchStream, + SendableRecordBatchStream, +}; +use datatypes::series::samples::{ + DenseSamplesRef, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridRange, TimeAxis}; +use datatypes::series::{MetricName, SeriesOrdering}; +use futures::Stream; +use store_api::region_engine::{RawLabelSource, SendableRawSeriesStream}; + +use crate::map::{MathOp, map_math}; +use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; +use crate::source::materialize_raw_labels; + +#[cfg(test)] +mod tests; + +/// Where one output column of this node comes from. +#[derive(Clone, Copy, Debug)] +enum OutputColumn { + /// The evaluation grid timestamps of the current interval. + Time, + /// Series field by index in the input series schema. + Field(usize), + /// Declared logical tag by index in the caller-supplied tag list. + Tag(usize), +} + +/// Evaluates one range function followed by 0..N float map kernels per raw series. +pub struct FusedSeriesExec { + input: Arc, + /// Raw (no evaluation grid) schema of the input and of the evaluated series. + series_schema: Arc, + label_source: RawLabelSource, + ordering: SeriesOrdering, + grid: Arc, + window: RangeWindow, + function: RangeFunction, + maps: Vec, + output_schema: SchemaRef, + tags: Vec, + time_column: String, + /// One entry per output column, in output column order. + classification: Arc<[OutputColumn]>, + properties: Arc, +} + +impl FusedSeriesExec { + /// Creates the node, rejecting everything the phase 1 contract cannot execute. + #[allow(clippy::too_many_arguments)] + pub fn try_new( + input: Arc, + series_schema: Arc, + label_source: RawLabelSource, + ordering: SeriesOrdering, + grid: Arc, + window: RangeWindow, + function: RangeFunction, + maps: Vec, + output_schema: SchemaRef, + tags: Vec, + time_column: String, + ) -> Result { + let partition_count = input.properties().partitioning.partition_count(); + if partition_count != 1 { + return Err(DataFusionError::Plan(format!( + "FusedSeriesExec requires a single-partition input, got {partition_count} partitions" + ))); + } + if series_schema.eval_grid.is_some() { + return Err(DataFusionError::Plan( + "FusedSeriesExec input must be a raw series schema without an evaluation grid" + .into(), + )); + } + // Both bindings are accepted: explicit chunks already carry complete labels, and + // primary-key chunks are decoded through `materialize_raw_labels` in `execute`. + if ordering == SeriesOrdering::Interleaved { + return Err(DataFusionError::Plan( + "FusedSeriesExec does not support interleaved raw series ordering".into(), + )); + } + // Surfaces invalid windows, smoothing/trend factors and predict_linear overflow here + // rather than on the first chunk. + drop(RangeEvaluator::try_new( + &series_schema, + grid.clone(), + window, + function, + )?); + validate_raw_frame_schema(&input, &series_schema, &label_source, ordering)?; + let classification = classify_output(&output_schema, &series_schema, &tags, &time_column)?; + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(output_schema.clone()), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Ok(Self { + input, + series_schema, + label_source, + ordering, + grid, + window, + function, + maps, + output_schema, + tags, + time_column, + classification: classification.into(), + properties, + }) + } + + fn name() -> &'static str { + "FusedSeriesExec" + } +} + +impl std::fmt::Debug for FusedSeriesExec { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("FusedSeriesExec").finish() + } +} + +impl DisplayAs for FusedSeriesExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter<'_>) -> fmt::Result { + let maps: Vec<_> = self.maps.iter().map(|op| describe_map(*op)).collect(); + write!( + f, + "FusedSeriesExec: eval={}, range={}ms, offset={}ms, maps=[{}]", + describe_function(self.function), + self.window.range_ms, + self.window.offset_ms, + maps.join(", ") + ) + } +} + +impl ExecutionPlan for FusedSeriesExec { + fn name(&self) -> &str { + Self::name() + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [child] = <[Arc; 1]>::try_from(children).map_err(|children| { + DataFusionError::Plan(format!( + "FusedSeriesExec requires exactly one child, got {}", + children.len() + )) + })?; + if child.schema() != self.input.schema() { + return Err(DataFusionError::Plan( + "FusedSeriesExec child must keep its declared raw series frame schema".into(), + )); + } + let exec = Self::try_new( + child, + self.series_schema.clone(), + self.label_source.clone(), + self.ordering, + self.grid.clone(), + self.window, + self.function, + self.maps.clone(), + self.output_schema.clone(), + self.tags.clone(), + self.time_column.clone(), + )?; + Ok(Arc::new(exec)) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + if partition != 0 { + return Err(DataFusionError::Execution(format!( + "FusedSeriesExec has a single partition, got partition {partition}" + ))); + } + let memory_pool = Arc::clone(&context.runtime_env().memory_pool); + let frame = self.input.execute(0, context)?; + let input = unpack_raw_series( + frame, + self.series_schema.clone(), + self.label_source.clone(), + self.ordering, + )?; + // `RangeEvaluator` needs complete labels. Explicit sources already supply them; a + // scan-bound primary-key source is decoded here instead of in every consumer. + let input = materialize_raw_labels(input).map_err(|error| { + DataFusionError::Execution(format!("cannot materialize raw series labels: {error}")) + })?; + // The kernels are `FnMut` and not cloneable, so every stream needs its own evaluator. + let evaluator = RangeEvaluator::try_new( + &self.series_schema, + self.grid.clone(), + self.window, + self.function, + )?; + // Taken before the evaluator moves into the stream; the stream needs it to rebuild a + // trimmed chunk. + let output_series_schema = evaluator.output_schema().clone(); + Ok(Box::pin(FusedSeriesStream { + input, + evaluator: Some(evaluator), + maps: self.maps.clone(), + tags: self.tags.clone().into(), + output_series_schema, + output_schema: self.output_schema.clone(), + classification: self.classification.clone(), + // Fresh per stream: two streams must never share duplicate-label-set state. + seen: HashMap::new(), + reservation: MemoryConsumer::new("FusedSeriesStream").register(&memory_pool), + finished: false, + })) + } +} + +/// Checks that the child's declared schema is a legal raw frame for this binding. +/// +/// The check runs at construction time by feeding an empty stream with the declared schema +/// through the same decoder execution uses, and discarding the resulting stream. +fn validate_raw_frame_schema( + input: &Arc, + series_schema: &Arc, + label_source: &RawLabelSource, + ordering: SeriesOrdering, +) -> Result<()> { + let empty = futures::stream::empty::>(); + let frame = Box::pin(RecordBatchStreamAdapter::new(input.schema(), empty)); + drop(unpack_raw_series( + frame, + series_schema.clone(), + label_source.clone(), + ordering, + )?); + Ok(()) +} + +/// Classifies every output column, rejecting anything outside the phase 1 output contract. +fn classify_output( + output_schema: &SchemaRef, + series_schema: &SeriesSchema, + tags: &[String], + time_column: &str, +) -> Result> { + for (index, tag) in tags.iter().enumerate() { + if tags[..index].contains(tag) { + return Err(DataFusionError::Plan(format!( + "duplicate tag column {tag:?} in FusedSeriesExec output schema" + ))); + } + if tag == time_column { + return Err(DataFusionError::Plan(format!( + "tag column {tag:?} of FusedSeriesExec cannot be the time column" + ))); + } + if series_schema + .fields + .iter() + .any(|field| field.name.as_ref() == tag) + { + return Err(DataFusionError::Plan(format!( + "tag column {tag:?} of FusedSeriesExec clashes with a series field" + ))); + } + } + + let mut time_seen = false; + let mut field_seen = vec![false; series_schema.fields.len()]; + let mut tag_seen = vec![false; tags.len()]; + let mut classification = Vec::with_capacity(output_schema.fields().len()); + for field in output_schema.fields() { + let name = field.name(); + if name == time_column { + if std::mem::replace(&mut time_seen, true) { + return Err(DataFusionError::Plan(format!( + "duplicate time column {name:?} in FusedSeriesExec output schema" + ))); + } + match field.data_type() { + DataType::Timestamp(TimeUnit::Millisecond, None) => {} + other => { + return Err(DataFusionError::Plan(format!( + "time column {name:?} of FusedSeriesExec must be Timestamp(Millisecond, \ + None), got {other:?}" + ))); + } + } + if field.is_nullable() { + return Err(DataFusionError::Plan(format!( + "time column {name:?} of FusedSeriesExec must not be nullable" + ))); + } + classification.push(OutputColumn::Time); + continue; + } + if let Some(index) = series_schema + .fields + .iter() + .position(|field| field.name.as_ref() == name) + { + if std::mem::replace(&mut field_seen[index], true) { + return Err(DataFusionError::Plan(format!( + "duplicate field column {name:?} in FusedSeriesExec output schema" + ))); + } + if field.data_type() != &DataType::Float64 { + return Err(DataFusionError::Plan(format!( + "field column {name:?} of FusedSeriesExec must be Float64, got {:?}", + field.data_type() + ))); + } + // A grid point inside the trimmed interval can have no value in this field. + if !field.is_nullable() { + return Err(DataFusionError::Plan(format!( + "field column {name:?} of FusedSeriesExec must be nullable, because a grid \ + point can be missing" + ))); + } + classification.push(OutputColumn::Field(index)); + continue; + } + if let Some(index) = tags.iter().position(|tag| tag == name) { + if std::mem::replace(&mut tag_seen[index], true) { + return Err(DataFusionError::Plan(format!( + "duplicate tag column {name:?} in FusedSeriesExec output schema" + ))); + } + if field.data_type() != &DataType::Utf8 { + return Err(DataFusionError::Plan(format!( + "tag column {name:?} of FusedSeriesExec must be Utf8, got {:?}", + field.data_type() + ))); + } + // `rate` and the map kernels drop `__name__`, so any tag can be absent. + if !field.is_nullable() { + return Err(DataFusionError::Plan(format!( + "tag column {name:?} of FusedSeriesExec must be nullable, because range \ + functions and map kernels drop the metric name" + ))); + } + classification.push(OutputColumn::Tag(index)); + continue; + } + return Err(DataFusionError::Plan(format!( + "unknown column {name:?} in FusedSeriesExec output schema" + ))); + } + + if !time_seen { + return Err(DataFusionError::Plan(format!( + "missing time column {time_column:?} in FusedSeriesExec output schema" + ))); + } + for (index, seen) in field_seen.iter().enumerate() { + if !seen { + return Err(DataFusionError::Plan(format!( + "missing field column {:?} in FusedSeriesExec output schema", + series_schema.fields[index].name + ))); + } + } + for (index, seen) in tag_seen.iter().enumerate() { + if !seen { + return Err(DataFusionError::Plan(format!( + "missing tag column {:?} in FusedSeriesExec output schema", + tags[index] + ))); + } + } + Ok(classification) +} + +/// Converts one evaluated series into exactly one output batch. +/// +/// The time column is the trimmed absolute interval of the series, missing samples are nulls and +/// ordinary NaN stays a value. +fn series_to_record_batch( + classification: &[OutputColumn], + tags: &[String], + output_schema: &SchemaRef, + series: &Series, +) -> Result { + let TimeAxis::Grid(range) = &series.time else { + return Err(DataFusionError::Execution( + "FusedSeriesExec requires evaluated series on a time grid".into(), + )); + }; + let rows = range.len(); + let mut columns: Vec = Vec::with_capacity(classification.len()); + for (position, column) in classification.iter().enumerate() { + match column { + OutputColumn::Time => columns.push(Arc::new(TimestampMillisecondArray::new( + range.timestamps(), + None, + ))), + OutputColumn::Field(index) => { + let samples = series.fields.get(*index).ok_or_else(|| { + DataFusionError::Execution(format!( + "evaluated series has no field at index {index}" + )) + })?; + if samples.len() != rows { + return Err(DataFusionError::Execution(format!( + "evaluated series field {index} has {} rows, time axis has {rows}", + samples.len() + ))); + } + columns.push(field_column(samples)?); + } + OutputColumn::Tag(index) => { + // `__name__` resolves to the metric name, every other tag through the label set. + let name = tags.get(*index).ok_or_else(|| { + DataFusionError::Execution(format!( + "output column {position} declares unavailable tag {index}" + )) + })?; + let value = series.metric.get(name); + columns.push(Arc::new(StringArray::from(vec![value; rows]))); + } + } + } + Ok(RecordBatch::try_new(output_schema.clone(), columns)?) +} + +/// Converts one evaluated series field into one `Float64` column. +/// +/// Dense float samples are reused as they are: the array already carries exactly the right nulls +/// and keeps NaN a value, so copying it through `Samples::iter()` would only cost an allocation +/// and a re-encode. Chunked samples go through the iterator, and histograms have no float column. +fn field_column(samples: &Samples) -> Result { + match samples.dense() { + Some(DenseSamplesRef::Float(values)) => Ok(Arc::new(values.clone())), + Some(DenseSamplesRef::Histogram(_)) | Some(DenseSamplesRef::Mixed(_)) => { + Err(DataFusionError::NotImplemented( + "FusedSeriesExec cannot output histogram samples".into(), + )) + } + None => { + let values = samples + .iter() + .map(|sample| match sample { + SampleRef::Float(value) => Ok(Some(value)), + SampleRef::Missing => Ok(None), + SampleRef::Histogram(_) => Err(DataFusionError::NotImplemented( + "FusedSeriesExec cannot output histogram samples".into(), + )), + }) + .collect::>>()?; + Ok(Arc::new(Float64Array::from(values))) + } + } +} + +/// The PromQL name of a range function, for `EXPLAIN`. +fn describe_function(function: RangeFunction) -> String { + match function { + RangeFunction::Rate => "rate".to_string(), + RangeFunction::Increase => "increase".to_string(), + RangeFunction::Delta => "delta".to_string(), + RangeFunction::Irate => "irate".to_string(), + RangeFunction::Idelta => "idelta".to_string(), + RangeFunction::AvgOverTime => "avg_over_time".to_string(), + RangeFunction::MinOverTime => "min_over_time".to_string(), + RangeFunction::MaxOverTime => "max_over_time".to_string(), + RangeFunction::SumOverTime => "sum_over_time".to_string(), + RangeFunction::CountOverTime => "count_over_time".to_string(), + RangeFunction::LastOverTime => "last_over_time".to_string(), + RangeFunction::PresentOverTime => "present_over_time".to_string(), + RangeFunction::StddevOverTime => "stddev_over_time".to_string(), + RangeFunction::StdvarOverTime => "stdvar_over_time".to_string(), + RangeFunction::QuantileOverTime(quantile) => { + format!("quantile_over_time({quantile})") + } + RangeFunction::Resets => "resets".to_string(), + RangeFunction::Changes => "changes".to_string(), + RangeFunction::Deriv => "deriv".to_string(), + RangeFunction::PredictLinear(duration) => format!("predict_linear({duration})"), + RangeFunction::DoubleExponentialSmoothing { smoothing, trend } => { + format!("double_exponential_smoothing({smoothing}, {trend})") + } + RangeFunction::FirstOverTime => "first_over_time".to_string(), + RangeFunction::MadOverTime => "mad_over_time".to_string(), + RangeFunction::TsOfFirstOverTime => "ts_of_first_over_time".to_string(), + RangeFunction::TsOfLastOverTime => "ts_of_last_over_time".to_string(), + RangeFunction::TsOfMinOverTime => "ts_of_min_over_time".to_string(), + RangeFunction::TsOfMaxOverTime => "ts_of_max_over_time".to_string(), + } +} + +/// The PromQL name of a float map kernel, for `EXPLAIN`. +fn describe_map(op: MathOp) -> String { + match op { + MathOp::Abs => "abs".to_string(), + MathOp::Ceil => "ceil".to_string(), + MathOp::Floor => "floor".to_string(), + MathOp::Sqrt => "sqrt".to_string(), + MathOp::Round { nearest } => format!("round({nearest})"), + } +} + +/// Applies every map kernel in order and returns the final series. +/// +/// The kernels work on typed [`Series`]; the duplicate-label-set check and the conversion into a +/// record batch both need the result of this stage, so no batch is built in between. +fn apply_maps( + evaluator: &RangeEvaluator, + maps: &[MathOp], + series: Series, +) -> Result> { + let mut series = series; + for op in maps { + let Some(mapped) = map_math(evaluator.output_schema(), &series, *op)? else { + return Ok(None); + }; + series = mapped; + } + Ok(Some(series)) +} + +/// Maximum number of raw chunks one `poll_next` call consumes before yielding. +/// +/// A child that is always ready can deliver many short-lived series whose evaluation yields no +/// output at all, which would let a single poll monopolize the executor thread; +/// `unpack_raw_series`'s yield only covers consecutive empty record batches, not this case. The +/// budget is per poll, so a poll that returns a batch starts the next one fresh. +const MAX_CHUNKS_PER_POLL: usize = 64; + +/// A canonical, collision-free encoding of a final label set. +/// +/// [`MetricName`] implements `PartialEq + Eq` but not `Hash`, and it is a dependency-owned type, +/// so the duplicate-label-set state keys on these bytes instead of on the label set itself. Every +/// component carries a length prefix: label names and values are arbitrary UTF-8, so a separator +/// byte could occur inside a component and let two different label sets encode to the same bytes. +/// [`MetricName`] keeps its tags sorted by name, so one label set has exactly one encoding. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct LabelsKey(Vec); + +impl LabelsKey { + /// Encodes the metric name, marked for presence, and then every label, name before value. + fn new(metric: &MetricName) -> Self { + let mut bytes = Vec::new(); + match metric.name() { + // The marker keeps an absent metric name distinct from an empty one. + Some(name) => { + bytes.push(1); + push_component(&mut bytes, name); + } + None => bytes.push(0), + } + for tag in metric.tags() { + push_component(&mut bytes, &tag.name); + push_component(&mut bytes, &tag.value); + } + Self(bytes) + } + + /// Number of bytes this key occupies, for the memory reservation. + fn len(&self) -> usize { + self.0.len() + } +} + +/// Appends one length-prefixed UTF-8 component. +fn push_component(bytes: &mut Vec, component: &str) { + bytes.extend_from_slice(&component.len().to_le_bytes()); + bytes.extend_from_slice(component.as_bytes()); +} + +/// Renders a label set the way Prometheus prints one, for the duplicate-label-set error. +fn render_labels(metric: &MetricName) -> String { + let mut parts = Vec::new(); + if let Some(name) = metric.name() { + parts.push(format!("__name__={name:?}")); + } + parts.extend( + metric + .tags() + .iter() + .map(|tag| format!("{}={:?}", tag.name, tag.value)), + ); + format!("{{{}}}", parts.join(", ")) +} + +/// The grid indices of the trimmed interval that hold a value, as merged runs. +/// +/// Each run is `(start, end_exclusive)` over absolute grid indices. A row whose every field is +/// missing is not occupied: Prometheus has no point there, so it cannot collide with another +/// series. +fn occupied_runs(series: &Series) -> Result> { + let TimeAxis::Grid(range) = &series.time else { + return Err(DataFusionError::Execution( + "FusedSeriesExec requires evaluated series on a time grid".into(), + )); + }; + let mut runs: Vec<(usize, usize)> = Vec::new(); + for offset in 0..range.len() { + if !series + .fields + .iter() + .any(|samples| has_value(samples, offset)) + { + continue; + } + let index = range.start() + offset; + match runs.last_mut() { + Some((_, end)) if *end == index => *end += 1, + _ => runs.push((index, index + 1)), + } + } + Ok(runs) +} + +/// Whether one field holds a value, rather than a missing position, at `index`. +fn has_value(samples: &Samples, index: usize) -> bool { + match samples.dense() { + Some(DenseSamplesRef::Float(values)) => values.is_valid(index), + Some(DenseSamplesRef::Histogram(values)) => values.indices().is_valid(index), + Some(DenseSamplesRef::Mixed(values)) => { + values.floats().is_valid(index) || values.histograms().indices().is_valid(index) + } + None => !matches!(samples.sample(index), SampleRef::Missing), + } +} + +/// Whether two sorted, disjoint run lists share at least one grid index. +fn runs_overlap(stored: &[(usize, usize)], new: &[(usize, usize)]) -> bool { + let (mut left, mut right) = (0, 0); + while left < stored.len() && right < new.len() { + let (stored_start, stored_end) = stored[left]; + let (new_start, new_end) = new[right]; + if new_start < stored_end && stored_start < new_end { + return true; + } + if stored_end <= new_start { + left += 1; + } else { + right += 1; + } + } + false +} + +/// Adds sorted, disjoint `new` runs to the sorted, disjoint `stored` runs, coalescing neighbours. +fn merge_runs(stored: &mut Vec<(usize, usize)>, new: &[(usize, usize)]) { + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(stored.len() + new.len()); + let (mut left, mut right) = (0, 0); + while left < stored.len() || right < new.len() { + let run = match (stored.get(left), new.get(right)) { + (Some(stored), Some(new)) if stored.0 <= new.0 => { + left += 1; + *stored + } + (Some(_), Some(new)) => { + right += 1; + *new + } + (Some(stored), None) => { + left += 1; + *stored + } + (None, Some(new)) => { + right += 1; + *new + } + (None, None) => break, + }; + match merged.last_mut() { + Some(last) if run.0 <= last.1 => last.1 = last.1.max(run.1), + _ => merged.push(run), + } + } + *stored = merged; +} + +/// Trims a chunk to the rows that hold a value in some field. +/// +/// A chunk's range covers every grid position the evaluator decided, including positions it +/// decided to hold no value: that progress is what lets a window above it advance. The output does +/// not report those, because a range query returns a row only where the expression has a value. So +/// a chunk that decided nothing but missing positions produces no batch at all, and one whose +/// values sit inside a wider decided span is trimmed to them -- the same trim the evaluator's +/// builder used to do before its span started reporting progress. +fn trim_to_values(schema: &Arc, series: &Series) -> Result> { + let TimeAxis::Grid(range) = &series.time else { + return Err(DataFusionError::Execution( + "FusedSeriesExec requires evaluated series on a time grid".into(), + )); + }; + let fields = series.fields.as_slice(); + let holds_value = |row: usize| { + fields + .iter() + .any(|field| !matches!(field.sample(row), SampleRef::Missing)) + }; + let Some(first) = (0..range.len()).find(|&row| holds_value(row)) else { + return Ok(None); + }; + let last = (0..range.len()) + .rfind(|&row| holds_value(row)) + .expect("the first value was found above"); + if first == 0 && last + 1 == range.len() { + return Ok(Some(series.clone())); + } + + let len = last + 1 - first; + let trimmed = || -> std::result::Result { + let samples = fields + .iter() + .map(|field| field.slice(first, len)) + .collect::, _>>()?; + let time = GridRange::try_new(range.grid().clone(), range.start() + first, len)?; + let fields = SeriesFields::try_from_vec(samples)?; + Series::try_new(schema, series.metric.clone(), TimeAxis::Grid(time), fields) + }; + trimmed() + .map(Some) + .map_err(|error| DataFusionError::Execution(format!("cannot trim a chunk: {error}"))) +} + +/// Turns raw series chunks into one output batch per completed series. +struct FusedSeriesStream { + input: SendableRawSeriesStream, + /// `None` once the stream is finished; `finish(self)` consumes the evaluator. + evaluator: Option, + maps: Vec, + tags: Arc<[String]>, + /// The typed schema the evaluated chunks carry, which trimming rebuilds them against. + output_series_schema: Arc, + output_schema: SchemaRef, + classification: Arc<[OutputColumn]>, + /// The grid positions each final label set already occupies, as merged, sorted runs. + seen: HashMap>, + /// Accounts for `seen`; batches already handed downstream are not reserved. Released at + /// [`Self::abort`] on every error path, and by [`MemoryReservation`]'s own `Drop` otherwise. + reservation: MemoryReservation, + finished: bool, +} + +impl FusedSeriesStream { + /// Marks the stream terminal and gives everything it still retained back to the pool. + fn abort(&mut self) { + self.finished = true; + self.evaluator = None; + self.seen = HashMap::new(); + self.reservation.free(); + } + + /// Claims the occupied grid positions of one finished series for its final label set. + /// + /// A collision is an error only when both series hold a sample at the same evaluation + /// timestamp, which is Prometheus' range-query rule. Series with disjoint points are legal: + /// Prometheus merges them into one output series, while this node emits them as separate + /// batches and defers that merge to matrix assembly, so every sample survives. + fn claim_label_set(&mut self, series: &Series) -> Result<()> { + let runs = occupied_runs(series)?; + let key = LabelsKey::new(&series.metric); + match self.seen.entry(key) { + Entry::Occupied(mut entry) => { + let stored = entry.get_mut(); + if runs_overlap(stored, &runs) { + return Err(DataFusionError::Execution(format!( + "vector cannot contain metrics with the same labelset: {}", + render_labels(&series.metric) + ))); + } + merge_runs(stored, &runs); + } + Entry::Vacant(entry) => { + // Only the label-set state is this node's own cross-poll state that grows with + // the output, so it is the only thing reserved here. + let bytes = entry.key().len() + runs.len() * 2 * size_of::(); + self.reservation.try_grow(bytes)?; + entry.insert(runs); + } + } + Ok(()) + } + + /// Registers the label set of one finished series and converts it into one output batch. + fn emit(&mut self, series: &Series) -> Result> { + let schema = self.output_series_schema.clone(); + let Some(series) = trim_to_values(&schema, series)? else { + return Ok(None); + }; + self.claim_label_set(&series)?; + series_to_record_batch( + &self.classification, + &self.tags, + &self.output_schema, + &series, + ) + .map(Some) + } +} + +impl RecordBatchStream for FusedSeriesStream { + fn schema(&self) -> SchemaRef { + self.output_schema.clone() + } +} + +impl Stream for FusedSeriesStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.as_mut().get_mut(); + if this.finished { + return Poll::Ready(None); + } + // Every call starts a fresh budget, so returning a batch below resets it. + let mut consumed = 0usize; + loop { + if consumed == MAX_CHUNKS_PER_POLL { + // The whole budget went into chunks that produced no batch; hand the executor + // thread back instead of draining an always-ready child here. + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let polled = this.input.as_mut().poll_next(cx); + let chunk = match polled { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + let Some(evaluator) = this.evaluator.take() else { + this.finished = true; + return Poll::Ready(None); + }; + return match evaluator.finish() { + Ok(()) => { + this.finished = true; + Poll::Ready(None) + } + Err(error) => { + this.abort(); + Poll::Ready(Some(Err(error))) + } + }; + } + Poll::Ready(Some(Err(error))) => { + this.abort(); + return Poll::Ready(Some(Err(DataFusionError::External(Box::new(error))))); + } + Poll::Ready(Some(Ok(chunk))) => chunk, + }; + consumed += 1; + let evaluated = { + let maps = &this.maps; + let Some(evaluator) = this.evaluator.as_mut() else { + this.finished = true; + return Poll::Ready(None); + }; + // A push hands out the grid positions it finished, not only the last one of a + // series, so one series can produce several batches as its input arrives. The + // label-set bookkeeping already merges the disjoint runs of one series, and a + // later chunk of it cannot overlap an earlier one. + evaluator + .push(&chunk) + .and_then(|evaluated| match evaluated { + Some(evaluated) => apply_maps(evaluator, maps, evaluated.series), + None => Ok(None), + }) + }; + let series = match evaluated { + Ok(series) => series, + Err(error) => { + this.abort(); + return Poll::Ready(Some(Err(error))); + } + }; + let Some(series) = series else { + continue; + }; + return match this.emit(&series) { + Ok(Some(batch)) => Poll::Ready(Some(Ok(batch))), + // The chunk settled only positions without a value, so it produces no row and + // the loop keeps consuming input. + Ok(None) => continue, + Err(error) => { + this.abort(); + Poll::Ready(Some(Err(error))) + } + }; + } + } +} diff --git a/src/promql/src/extension_plan/fused_series/tests.rs b/src/promql/src/extension_plan/fused_series/tests.rs new file mode 100644 index 00000000000..394bf6e7c92 --- /dev/null +++ b/src/promql/src/extension_plan/fused_series/tests.rs @@ -0,0 +1,1628 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! End-to-end checks of [`FusedSeriesExec`] against the same kernels driven directly. +//! +//! The reference path pushes the same chunks through a fresh [`RangeEvaluator`], applies the same +//! `map_math` chain and converts with the same private conversion, so a test fails when the +//! node's plumbing (finalization, ordering, labels, trimming) diverges, not when a kernel's +//! numerics change. Kernel numerics have their own tests. + +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::task::{Context, Poll}; + +use common_query::prometheus::PROMETHEUS_STALE_NAN_BITS; +use datafusion::arrow::array::{ + Array, Float64Array, StringArray, TimestampMillisecondArray, UInt32Array, +}; +use datafusion::arrow::buffer::{Buffer, ScalarBuffer}; +use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::common::tree_node::TreeNodeRecursion; +use datafusion::error::{DataFusionError, Result}; +use datafusion::execution::context::TaskContext; +use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr}; +use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType}; +use datafusion::physical_plan::test::TestMemoryExec; +use datafusion::physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties, RecordBatchStream, + SendableRecordBatchStream, displayable, +}; +use datatypes::series::frame::{ + RawLabelMode, RawSeriesChunkCursor, RawSeriesFrameBuilder, raw_series_frame_schema, +}; +use datatypes::series::histogram::HistogramBatchBuilder; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; +use datatypes::series::samples::{ + FieldSpec, HistogramSamples, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{EvalGrid, GridSpec, TimeAxis}; +use datatypes::series::{Label, MetricName, SeriesOrdering}; +use futures::{Stream, StreamExt}; +use store_api::region_engine::RawLabelSource; + +use crate::grid_series::reference::OwnedHistogram; + +use super::{ + FusedSeriesExec, MAX_CHUNKS_PER_POLL, apply_maps, classify_output, series_to_record_batch, + trim_to_values, +}; +use crate::map::MathOp; +use crate::range_eval::{RangeEvaluator, RangeFunction, RangeWindow}; + +const TIME: &str = "time"; +const VALUE: &str = "value"; +const VALUE2: &str = "value2"; +const GRID_START: i64 = 300_000; +const GRID_STEP: i64 = 60_000; +const GRID_LEN: u64 = 5; + +/// Source timestamp and `value` of one raw row; `None` is a missing value. +type Row = (i64, Option); + +fn series_schema() -> Arc { + fields_schema(&[VALUE]) +} + +/// A raw series schema with one `Float64` field per name. +fn fields_schema(names: &[&str]) -> Arc { + Arc::new(SeriesSchema { + fields: names + .iter() + .map(|name| FieldSpec { + name: Arc::from(*name), + }) + .collect(), + eval_grid: None, + }) +} + +/// The two-field schema of the multi-field case. +fn two_field_schema() -> Arc { + fields_schema(&[VALUE, VALUE2]) +} + +/// One `Float64` value column plus one nullable `Utf8` column per tag and a non-null timestamp. +fn output_schema(tags: &[&str]) -> SchemaRef { + output_schema_of(&[VALUE], tags) +} + +/// One `Float64` column per field name, one nullable `Utf8` column per tag, then the timestamp. +fn output_schema_of(fields: &[&str], tags: &[&str]) -> SchemaRef { + let mut columns = fields + .iter() + .map(|name| Field::new(*name, DataType::Float64, true)) + .collect::>(); + columns.extend( + tags.iter() + .map(|tag| Field::new(*tag, DataType::Utf8, true)), + ); + columns.push(Field::new( + TIME, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + )); + Arc::new(Schema::new(columns)) +} + +fn metric(host: &str) -> MetricName { + named_metric(host, "http_requests_total") +} + +fn named_metric(host: &str, name: &str) -> MetricName { + MetricName::try_new( + Some(Arc::from(name)), + vec![Label { + name: Arc::from("host"), + value: Arc::from(host), + }], + ) + .unwrap() +} + +fn chunk(key: u8, host: &str, rows: &[Row], is_last: bool) -> RawSeriesChunk { + chunk_with(key, metric(host), rows, is_last) +} + +/// [`chunk`] with an explicit metric name: `rate` drops `__name__`, so two differently named raw +/// series can still reach the same final label set. +fn named_chunk(name: &str, key: u8, host: &str, rows: &[Row], is_last: bool) -> RawSeriesChunk { + chunk_with(key, named_metric(host, name), rows, is_last) +} + +fn chunk_with(key: u8, metric: MetricName, rows: &[Row], is_last: bool) -> RawSeriesChunk { + let timestamps = rows + .iter() + .map(|(timestamp, _)| *timestamp) + .collect::>(); + let values = rows.iter().map(|(_, value)| *value).collect::>(); + raw_chunk( + &series_schema(), + key, + metric, + ×tamps, + vec![Samples::from_float(Float64Array::from(values))], + is_last, + ) +} + +/// One two-field raw chunk, from `(timestamp, value, value2)` rows. +fn two_field_chunk( + key: u8, + rows: &[(i64, Option, Option)], + is_last: bool, +) -> RawSeriesChunk { + let timestamps = rows + .iter() + .map(|(timestamp, _, _)| *timestamp) + .collect::>(); + let values = rows.iter().map(|(_, value, _)| *value).collect::>(); + let others = rows.iter().map(|(_, _, value)| *value).collect::>(); + raw_chunk( + &two_field_schema(), + key, + metric("a"), + ×tamps, + vec![ + Samples::from_float(Float64Array::from(values)), + Samples::from_float(Float64Array::from(others)), + ], + is_last, + ) +} + +/// Builds one raw chunk from explicit per-field samples. +fn raw_chunk( + schema: &SeriesSchema, + key: u8, + metric: MetricName, + timestamps: &[i64], + fields: Vec, + is_last: bool, +) -> RawSeriesChunk { + RawSeriesChunk::try_new( + schema, + Buffer::from(vec![key]), + Some(metric), + RawTimestamps::try_new(ScalarBuffer::from(timestamps.to_vec())).unwrap(), + SeriesFields::try_from_vec(fields).unwrap(), + is_last, + ) + .unwrap() +} + +fn frame_schema() -> SchemaRef { + frame_schema_of(&series_schema()) +} + +fn frame_schema_of(schema: &SeriesSchema) -> SchemaRef { + raw_series_frame_schema(schema, RawLabelMode::Explicit).unwrap() +} + +/// Packs `chunks` into raw frame batches, buffering rows across chunks like a real producer. +fn frame_batches(chunks: &[RawSeriesChunk]) -> Vec { + frame_batches_of(&series_schema(), chunks) +} + +fn frame_batches_of(schema: &SeriesSchema, chunks: &[RawSeriesChunk]) -> Vec { + let mut builder = RawSeriesFrameBuilder::try_new( + schema, + RawLabelMode::Explicit, + RawSeriesFrameBuilder::DEFAULT_MAX_ROWS, + RawSeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .unwrap(); + let mut batches = Vec::new(); + for chunk in chunks { + let mut cursor = + RawSeriesChunkCursor::try_new(schema, RawLabelMode::Explicit, chunk.clone()).unwrap(); + while let Some(batch) = cursor.append_to(&mut builder).unwrap() { + batches.push(batch); + } + } + if let Some(batch) = builder.flush().unwrap() { + batches.push(batch); + } + batches +} + +fn memory_child(chunks: &[RawSeriesChunk]) -> Arc { + memory_child_of(&series_schema(), chunks) +} + +fn memory_child_of(schema: &SeriesSchema, chunks: &[RawSeriesChunk]) -> Arc { + Arc::new( + TestMemoryExec::try_new( + &[frame_batches_of(schema, chunks)], + frame_schema_of(schema), + None, + ) + .unwrap(), + ) +} + +fn grid() -> Arc { + Arc::new( + EvalGrid::try_new(GridSpec::try_new(GRID_START, GRID_STEP, GRID_LEN).unwrap()).unwrap(), + ) +} + +fn stale() -> f64 { + f64::from_bits(PROMETHEUS_STALE_NAN_BITS) +} + +/// Nine once-per-minute counter samples from 60s to 540s, rising `step` per sample, so that every +/// grid point from 300s on has a full five-sample window. +fn counter_rows(step: f64) -> Vec { + (1..=9) + .map(|minute| (minute * 60_000, Some(minute as f64 * step))) + .collect() +} + +/// Splits `rows` into chunks at the given row boundaries; the last chunk is the final one. +fn counter_chunks(key: u8, host: &str, rows: &[Row], bounds: &[usize]) -> Vec { + let mut chunks = Vec::new(); + let mut start = 0; + for &end in bounds { + chunks.push(chunk(key, host, &rows[start..end], end == rows.len())); + start = end; + } + if start < rows.len() { + chunks.push(chunk(key, host, &rows[start..], true)); + } + chunks +} + +/// One fused node configuration plus the reference path over the same configuration. +#[derive(Clone)] +struct Case { + schema: Arc, + grid: Arc, + window: RangeWindow, + function: RangeFunction, + maps: Vec, + output_schema: SchemaRef, + tags: Vec, +} + +impl Case { + fn new(tags: &[&str], window: RangeWindow, function: RangeFunction, maps: Vec) -> Self { + Self { + schema: series_schema(), + grid: grid(), + window, + function, + maps, + output_schema: output_schema(tags), + tags: tags.iter().map(|tag| tag.to_string()).collect(), + } + } + + fn with_series_schema(&self, schema: Arc) -> Self { + Self { + schema, + ..self.clone() + } + } + + fn with_output_schema(&self, output_schema: SchemaRef) -> Self { + Self { + output_schema, + ..self.clone() + } + } + + fn fused(&self, child: Arc) -> Result { + FusedSeriesExec::try_new( + child, + self.schema.clone(), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + self.grid.clone(), + self.window, + self.function, + self.maps.clone(), + self.output_schema.clone(), + self.tags.clone(), + TIME.to_string(), + ) + } + + /// Evaluation, then the same map chain, then the same conversion, without the node. + fn reference(&self, chunks: &[RawSeriesChunk]) -> Vec<(Series, RecordBatch)> { + let schema = self.schema.clone(); + let mut evaluator = + RangeEvaluator::try_new(&schema, self.grid.clone(), self.window, self.function) + .unwrap(); + let classification = + classify_output(&self.output_schema, &schema, &self.tags, TIME).unwrap(); + let mut out = Vec::new(); + for chunk in chunks { + let Some(evaluated) = evaluator.push(chunk).unwrap() else { + continue; + }; + let Some(series) = apply_maps(&evaluator, &self.maps, evaluated.series).unwrap() else { + continue; + }; + // The node trims a chunk to the rows holding a value before emitting it, because the + // chunk's span reports decided positions rather than valued ones. + let Some(series) = trim_to_values(evaluator.output_schema(), &series).unwrap() else { + continue; + }; + let batch = + series_to_record_batch(&classification, &self.tags, &self.output_schema, &series) + .unwrap(); + out.push((series, batch)); + } + out + } +} + +async fn run(exec: FusedSeriesExec) -> Vec> { + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + let mut items = Vec::new(); + while let Some(item) = stream.next().await { + items.push(item); + } + items +} + +fn collect(items: Vec>) -> Vec { + items + .into_iter() + .map(|item| item.expect("the fused stream must not fail")) + .collect() +} + +fn float_column(batch: &RecordBatch, name: &str) -> Vec> { + let array = batch + .column_by_name(name) + .unwrap_or_else(|| panic!("missing column {name}")) + .as_any() + .downcast_ref::() + .unwrap(); + (0..array.len()) + .map(|row| array.is_valid(row).then(|| array.value(row))) + .collect() +} + +fn timestamp_column(batch: &RecordBatch, name: &str) -> Vec { + let array = batch + .column_by_name(name) + .unwrap_or_else(|| panic!("missing column {name}")) + .as_any() + .downcast_ref::() + .unwrap(); + assert!(array.null_count() == 0, "timestamp column has nulls"); + array.values().to_vec() +} + +fn string_column(batch: &RecordBatch, name: &str) -> Vec> { + let array = batch + .column_by_name(name) + .unwrap_or_else(|| panic!("missing column {name}")) + .as_any() + .downcast_ref::() + .unwrap(); + (0..array.len()) + .map(|row| array.is_valid(row).then(|| array.value(row).to_string())) + .collect() +} + +/// The batches holding `label`. The node emits one series per batch, so a batch's first `host` +/// identifies the whole batch; the assertion guards that premise against a future change that +/// packs several series into one batch, which would make the helpers below silently misattribute +/// rows. +fn batches_of<'a>(batches: &'a [RecordBatch], label: &str) -> Vec<&'a RecordBatch> { + batches + .iter() + .filter(|batch| { + let hosts = string_column(batch, "host"); + let matches = hosts.first().and_then(|host| host.as_deref()) == Some(label); + if matches { + assert!( + hosts.iter().all(|host| host.as_deref() == Some(label)), + "a batch mixing several series breaks the row helpers" + ); + } + matches + }) + .collect() +} + +/// Concatenates one column across every batch carrying `label`, so a series split over several +/// batches reads as the single row sequence a reader would see. +fn rows_of(batches: &[RecordBatch], label: &str, column: &str) -> Vec> { + batches_of(batches, label) + .into_iter() + .flat_map(|batch| string_column(batch, column)) + .collect() +} + +fn values_of(batches: &[RecordBatch], label: &str) -> Vec> { + batches_of(batches, label) + .into_iter() + .flat_map(|batch| float_column(batch, VALUE)) + .collect() +} + +fn timestamps_of(batches: &[RecordBatch], label: &str) -> Vec { + batches_of(batches, label) + .into_iter() + .flat_map(|batch| timestamp_column(batch, TIME)) + .collect() +} + +fn series_batch_count(batches: &[RecordBatch], label: &str) -> usize { + batches_of(batches, label).len() +} + +fn grid_range(series: &Series) -> (usize, usize) { + let TimeAxis::Grid(range) = &series.time else { + panic!("expected a grid series, got {:?}", series.time); + }; + (range.start(), range.len()) +} + +/// Asserts the node emitted exactly the reference batches, comparing values bit for bit. +fn assert_matches_reference( + actual: &[RecordBatch], + reference: &[(Series, RecordBatch)], + context: &str, +) { + assert_eq!( + actual.len(), + reference.len(), + "{context}: batch count, actual {actual:?}" + ); + for (index, (actual, (_, expected))) in actual.iter().zip(reference).enumerate() { + let context = format!("{context} batch {index}"); + assert_eq!(actual.schema(), expected.schema(), "{context}: schema"); + assert_eq!( + actual.num_rows(), + expected.num_rows(), + "{context}: row count" + ); + for (actual, expected) in actual.columns().iter().zip(expected.columns()) { + match expected.data_type() { + DataType::Float64 => { + let actual = actual.as_any().downcast_ref::().unwrap(); + let expected = expected.as_any().downcast_ref::().unwrap(); + let bits = |array: &Float64Array| { + (0..array.len()) + .map(|row| array.is_valid(row).then(|| array.value(row).to_bits())) + .collect::>() + }; + assert_eq!(bits(actual), bits(expected), "{context}: value column"); + } + DataType::Utf8 => { + let actual = actual.as_any().downcast_ref::().unwrap(); + let expected = expected.as_any().downcast_ref::().unwrap(); + let values = |array: &StringArray| { + (0..array.len()) + .map(|row| array.is_valid(row).then(|| array.value(row).to_string())) + .collect::>() + }; + assert_eq!(values(actual), values(expected), "{context}: string column"); + } + DataType::Timestamp(TimeUnit::Millisecond, None) => { + let actual = actual + .as_any() + .downcast_ref::() + .unwrap(); + let expected = expected + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + actual.values().to_vec(), + expected.values().to_vec(), + "{context}: timestamp column" + ); + } + other => panic!("{context}: unexpected column type {other:?}"), + } + } + } +} + +/// Concatenates every message in an error's source chain. +fn error_chain(error: &DataFusionError) -> String { + let mut message = error.to_string(); + let mut source = std::error::Error::source(error); + while let Some(error) = source { + message.push_str(": "); + message.push_str(&error.to_string()); + source = error.source(); + } + message +} + +#[tokio::test] +async fn rate_over_three_chunks_matches_reference_and_prometheus() { + let chunks = vec![ + chunk( + 1, + "a", + &[ + (60_000, Some(60.0)), + (120_000, Some(120.0)), + (180_000, Some(180.0)), + ], + false, + ), + chunk( + 1, + "a", + &[ + (240_000, Some(240.0)), + (300_000, Some(300.0)), + (360_000, Some(360.0)), + ], + false, + ), + chunk( + 1, + "a", + &[ + (420_000, Some(420.0)), + (480_000, Some(480.0)), + (540_000, Some(540.0)), + ], + true, + ), + ]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "rate"); + + // A counter rising 60 per minute sampled once a minute extrapolates over a 5m window to + // exactly one increment per second at every point. + assert_eq!(values_of(&batches, "a"), vec![Some(1.0); GRID_LEN as usize]); + assert_eq!( + timestamps_of(&batches, "a"), + vec![300_000, 360_000, 420_000, 480_000, 540_000] + ); + // The counter arrives in three chunks, so the node must hand the series out as it goes + // instead of holding it until the last chunk closes it. + assert!( + series_batch_count(&batches, "a") > 1, + "a series spanning several input chunks must stream in several batches, got {}", + series_batch_count(&batches, "a") + ); + // The reference hands the series out in chunks too, so the first chunk starts the grid and + // the last one runs it to the end; together they cover the whole span. + let (first, _) = &reference[0]; + let (last, _) = reference.last().unwrap(); + assert_eq!(grid_range(first).0, 0); + let (start, len) = grid_range(last); + assert_eq!(start + len, GRID_LEN as usize); + assert_eq!(last.metric.get("host"), Some("a")); + // `rate` drops the metric name on its own, so the reference keeps only the ordinary label. + assert_eq!(last.metric.get("__name__"), None); +} + +#[tokio::test] +async fn abs_of_rate_drops_the_metric_name_column() { + let chunks = counter_chunks(1, "a", &counter_rows(60.0), &[5]); + let case = Case::new( + &["__name__", "host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![MathOp::Abs], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "abs(rate)"); + + let batch = &batches[0]; + assert_eq!( + string_column(batch, "__name__"), + vec![None; batch.num_rows()], + "the metric name is dropped, so a `__name__` column is null" + ); + assert_eq!( + string_column(batch, "host"), + vec![Some("a".to_string()); batch.num_rows()] + ); + assert_eq!( + float_column(batch, VALUE), + vec![Some(1.0); batch.num_rows()], + "every five-minute window holds a full five-sample rate of one per second" + ); + + let mut expected = metric("a"); + expected.remove("__name__"); + let (series, _) = &reference[0]; + assert_eq!(series.metric, expected); + assert!( + series + .metric + .tags() + .iter() + .all(|tag| tag.name.as_ref() != "__name__") + ); +} + +#[tokio::test] +async fn sqrt_of_abs_of_rate_matches_reference() { + let chunks = counter_chunks(1, "a", &counter_rows(60.0), &[5]); + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![MathOp::Abs, MathOp::Sqrt], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "sqrt(abs(rate))"); + assert_eq!( + float_column(&batches[0], VALUE), + vec![Some(1.0); batches[0].num_rows()] + ); +} + +#[tokio::test] +async fn two_series_in_one_frame_stay_separate() { + let mut chunks = counter_chunks(1, "a", &counter_rows(60.0), &[5]); + chunks.extend(counter_chunks(2, "b", &counter_rows(120.0), &[5])); + // Both series fit in one frame batch, so the node splits them only by `is_last`. + assert_eq!(frame_batches(&chunks).len(), 1); + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "two series"); + + assert_eq!( + rows_of(&batches, "a", "host"), + vec![Some("a".to_string()); 5] + ); + assert_eq!( + values_of(&batches, "a"), + vec![Some(1.0); 5], + "series a must not see series b's counter" + ); + assert_eq!( + rows_of(&batches, "b", "host"), + vec![Some("b".to_string()); 5] + ); + assert_eq!( + values_of(&batches, "b"), + vec![Some(2.0); 5], + "series b must not see series a's counter" + ); +} + +#[tokio::test] +async fn duplicate_final_label_set_at_one_grid_point_is_an_error() { + // `rate` drops `__name__`, so both raw series reach `{host="x"}` and both cover every grid + // point: Prometheus rejects that at a shared evaluation timestamp. + let rows = counter_rows(60.0); + let chunks = vec![ + named_chunk("a_total", 1, "x", &rows, true), + named_chunk("b_total", 2, "x", &rows, true), + ]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let items = run(case.fused(memory_child(&chunks)).unwrap()).await; + assert_eq!( + items.len(), + 2, + "the first series is emitted, then the collision surfaces" + ); + assert!(items[0].is_ok(), "{:?}", items[0]); + let error = items.into_iter().nth(1).unwrap().err().unwrap(); + let message = error_chain(&error); + assert!( + message.contains("vector cannot contain metrics with the same labelset"), + "{message}" + ); + assert!( + message.contains("host=\"x\""), + "the label set must be readable: {message}" + ); +} + +#[tokio::test] +async fn duplicate_final_label_set_with_disjoint_grid_points_is_emitted() { + // `a_total` only has a window result at 300s while `b_total` only has them at 480s and 540s, + // so the two series share a final label set but no evaluation timestamp: Prometheus merges + // them into one output series, this node emits both batches instead. + let chunks = vec![ + named_chunk( + "a_total", + 1, + "x", + &[(60_000, Some(60.0)), (120_000, Some(120.0))], + true, + ), + named_chunk( + "b_total", + 2, + "x", + &[(420_000, Some(420.0)), (480_000, Some(480.0))], + true, + ), + ]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "disjoint label sets"); + + assert_eq!(batches.len(), 2, "{batches:?}"); + assert_eq!( + batches + .iter() + .map(RecordBatch::num_rows) + .collect::>(), + vec![1, 2], + "each series keeps the points its own windows produced" + ); + let timestamps = batches + .iter() + .flat_map(|batch| timestamp_column(batch, TIME)) + .collect::>(); + let mut distinct = timestamps.clone(); + distinct.sort_unstable(); + distinct.dedup(); + assert_eq!( + distinct.len(), + timestamps.len(), + "no grid point may repeat: {timestamps:?}" + ); + assert_eq!( + distinct, + vec![300_000, 480_000, 540_000], + "both series must survive with every point" + ); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 3, + "no point may be lost" + ); +} + +#[tokio::test] +async fn empty_frame_emits_no_batch() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let items = run(case.fused(memory_child(&[])).unwrap()).await; + assert!(items.is_empty(), "unexpected items: {items:?}"); +} + +/// One raw chunk whose single field holds native histograms, one per listed timestamp. +fn histogram_chunk(timestamps: &[i64], is_last: bool) -> RawSeriesChunk { + let text = "0/0/0/4014000000000000/4014000000000000/1/0_1/4014000000000000///"; + let mut builder = HistogramBatchBuilder::new(); + let mut indices = Vec::new(); + for _ in timestamps { + indices.push(Some( + builder.push(OwnedHistogram::parse(text).view()).unwrap(), + )); + } + let histograms = + HistogramSamples::try_new(UInt32Array::from(indices), builder.finish().unwrap()).unwrap(); + let floats = Float64Array::from(vec![None; timestamps.len()]); + raw_chunk( + &series_schema(), + 1, + metric("a"), + timestamps, + vec![Samples::try_from_mixed(floats, histograms).unwrap()], + is_last, + ) +} + +#[tokio::test] +async fn a_histogram_series_is_dropped_by_a_float_map_chain() { + // `sum_over_time` keeps histograms, so every grid point of this series holds one. A float map + // kernel cannot represent them and reports no series; the node must drop the series there. + // Trimming cannot stand in for that: a histogram sample is not missing, so the untrimmed + // series would still count as holding a value. + let chunks = vec![histogram_chunk( + &[300_000, 360_000, 420_000, 480_000, 540_000], + true, + )]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![MathOp::Abs], + ); + // The evaluation itself does produce histograms here, so the map chain is what removes them. + let reference = case.reference(&chunks); + assert!( + reference.is_empty(), + "the map chain must drop the histogram series, got {} chunks", + reference.len() + ); + + let items = run(case.fused(memory_child(&chunks)).unwrap()).await; + assert!(items.is_empty(), "unexpected items: {items:?}"); +} + +#[tokio::test] +async fn a_decided_span_holding_no_value_is_dropped_by_the_map_chain() { + // One sample cannot produce a rate, so every position this series decides is empty. A map + // kernel reports such a series as no series at all, and the node must drop it there instead + // of emitting an empty batch or failing. + let chunks = vec![chunk(1, "a", &[(300_000, Some(1.0))], true)]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![MathOp::Abs], + ); + let items = run(case.fused(memory_child(&chunks)).unwrap()).await; + assert!(items.is_empty(), "unexpected items: {items:?}"); +} + +#[tokio::test] +async fn short_lived_series_is_trimmed_to_its_absolute_interval() { + let chunks = vec![chunk( + 1, + "a", + &[(420_000, Some(1.0)), (480_000, Some(2.0))], + true, + )]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "trimmed"); + + let batch = &batches[0]; + // Only grid points 2 and 3 have a sample in their window. + assert_eq!(timestamp_column(batch, TIME), vec![420_000, 480_000]); + assert_eq!( + float_column(batch, VALUE), + vec![Some(1.0), Some(2.0)], + "the trimmed interval keeps its absolute grid timestamps" + ); + assert_eq!(grid_range(&reference[0].0), (2, 2)); +} + +#[tokio::test] +async fn nonzero_offset_is_passed_through_without_moving_the_grid() { + let chunks = vec![chunk( + 1, + "a", + &[ + (420_000, Some(1.0)), + (480_000, Some(2.0)), + (540_000, Some(3.0)), + ], + true, + )]; + let offset = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 60_000, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![], + ); + let plain = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![], + ); + let reference = offset.reference(&chunks); + let batches = collect(run(offset.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "offset"); + + let timestamps = timestamp_column(&batches[0], TIME); + assert!( + timestamps + .iter() + .all(|timestamp| (timestamp - GRID_START) % GRID_STEP == 0), + "the node must not shift the grid timestamps: {timestamps:?}" + ); + let plain_batches = collect(run(plain.fused(memory_child(&chunks)).unwrap()).await); + assert_ne!( + float_column(&plain_batches[0], VALUE), + float_column(&batches[0], VALUE), + "the offset must reach the evaluator instead of being ignored" + ); +} + +#[tokio::test] +async fn two_fields_convert_both_columns_and_keep_a_half_missing_row() { + let schema = two_field_schema(); + let chunks = vec![two_field_chunk( + 1, + &[ + (420_000, Some(1.0), Some(10.0)), + (480_000, None, Some(20.0)), + (540_000, Some(3.0), Some(30.0)), + ], + true, + )]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![], + ) + .with_series_schema(schema.clone()) + .with_output_schema(output_schema_of(&[VALUE, VALUE2], &["host"])); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child_of(&schema, &chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "two fields"); + + let batch = &batches[0]; + assert_eq!( + timestamp_column(batch, TIME), + vec![420_000, 480_000, 540_000] + ); + assert_eq!( + float_column(batch, VALUE), + vec![Some(1.0), None, Some(3.0)], + "only the missing field is null" + ); + assert_eq!( + float_column(batch, VALUE2), + vec![Some(10.0), Some(20.0), Some(30.0)], + "the row stays because this field has a value" + ); +} + +#[tokio::test] +async fn missing_point_inside_the_trimmed_range_becomes_a_null_row() { + let chunks = vec![chunk( + 1, + "a", + &[(420_000, Some(1.0)), (540_000, Some(3.0))], + true, + )]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::SumOverTime, + vec![], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, "missing point"); + + let batch = &batches[0]; + assert_eq!( + timestamp_column(batch, TIME), + vec![420_000, 480_000, 540_000] + ); + assert_eq!( + float_column(batch, VALUE), + vec![Some(1.0), None, Some(3.0)], + "the empty middle window is a null row, not a dropped or shifted one" + ); + assert_eq!(grid_range(&reference[0].0), (2, 3)); +} + +#[tokio::test] +async fn nan_stays_a_value_and_a_stale_marker_only_clears_its_window() { + // (context, function, rows, expected timestamps, expected values) + let cases = [ + ( + "ordinary NaN", + RangeFunction::AvgOverTime, + vec![(420_000, Some(f64::NAN)), (540_000, Some(f64::NAN))], + vec![420_000, 480_000, 540_000], + vec![Some(f64::NAN), None, Some(f64::NAN)], + ), + ( + "stale marker", + RangeFunction::SumOverTime, + vec![ + (420_000, Some(stale())), + (480_000, Some(1.0)), + (540_000, Some(3.0)), + ], + vec![480_000, 540_000], + vec![Some(1.0), Some(3.0)], + ), + ]; + let describe = |values: &[Option]| -> Vec> { + values.iter().map(|value| value.map(f64::to_bits)).collect() + }; + for (context, function, rows, expected_timestamps, expected_values) in cases { + let chunks = vec![chunk(1, "a", &rows, true)]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + function, + vec![MathOp::Abs], + ); + let reference = case.reference(&chunks); + let batches = collect(run(case.fused(memory_child(&chunks)).unwrap()).await); + assert_matches_reference(&batches, &reference, context); + + let batch = &batches[0]; + assert_eq!( + timestamp_column(batch, TIME), + expected_timestamps, + "{context}: absolute grid timestamps" + ); + let actual = float_column(batch, VALUE); + assert_eq!( + describe(&actual), + describe(&expected_values), + "{context}: expected {expected_values:?}, got {actual:?}" + ); + } + + // An ordinary NaN is a value, never a null, and the missing middle window is a row, so the + // row count stays that of the trimmed interval. + let nan_chunks = vec![chunk( + 1, + "a", + &[(420_000, Some(f64::NAN)), (540_000, Some(f64::NAN))], + true, + )]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 60_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::AvgOverTime, + vec![MathOp::Abs], + ); + let batch = &collect(run(case.fused(memory_child(&nan_chunks)).unwrap()).await)[0]; + let values = float_column(batch, VALUE); + assert_eq!(batch.num_rows(), 3, "the null row is kept, not dropped"); + assert!(values[0].is_some_and(f64::is_nan), "{values:?}"); + assert_eq!(values[1], None); + assert!(values[2].is_some_and(f64::is_nan), "{values:?}"); +} + +#[tokio::test] +async fn truncated_input_fails_at_eof_without_reexecuting_the_child() { + let chunks = vec![chunk( + 1, + "a", + &[(60_000, Some(60.0)), (120_000, Some(120.0))], + false, + )]; + let executes = Arc::new(AtomicUsize::new(0)); + let plan = ProbeExec::new( + frame_batches(&chunks), + Arc::clone(&executes), + Arc::new(AtomicBool::new(false)), + ); + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let items = run(case.fused(Arc::new(plan)).unwrap()).await; + assert_eq!(items.len(), 1, "expected exactly one error item"); + let error = items.into_iter().next().unwrap().err().unwrap(); + assert!( + error_chain(&error).contains("final"), + "unexpected error: {error}" + ); + assert_eq!( + executes.load(Ordering::SeqCst), + 1, + "the child must not be re-executed after an error" + ); +} + +#[tokio::test] +async fn out_of_order_chunks_are_rejected_by_raw_frame_validation() { + let chunks = vec![ + chunk(1, "a", &[(420_000, Some(1.0)), (540_000, Some(2.0))], false), + chunk(1, "a", &[(300_000, Some(3.0))], true), + ]; + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let items = run(case.fused(memory_child(&chunks)).unwrap()).await; + assert_eq!(items.len(), 1, "expected exactly one error item"); + let error = items.into_iter().next().unwrap().err().unwrap(); + assert!( + error_chain(&error).contains("not increasing"), + "unexpected error: {error}" + ); +} + +#[tokio::test] +async fn construction_rejects_unsupported_inputs() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + + let two_partitions: Arc = + Arc::new(TestMemoryExec::try_new(&[vec![], vec![]], frame_schema(), None).unwrap()); + let error = case.fused(two_partitions).err().unwrap(); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + assert!(error.to_string().contains("single-partition"), "{error}"); + + let mut fields = output_schema(&["host"]) + .fields() + .iter() + .map(|field| field.as_ref().clone()) + .collect::>(); + fields.push(Field::new("bogus", DataType::Utf8, true)); + let unknown = Arc::new(Schema::new(fields)); + let error = case + .with_output_schema(unknown) + .fused(memory_child(&[])) + .err() + .unwrap(); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + assert!(error.to_string().contains("unknown column"), "{error}"); + + let wrong_type = Arc::new(Schema::new(vec![ + Field::new(VALUE, DataType::Int64, true), + Field::new("host", DataType::Utf8, true), + Field::new( + TIME, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + ])); + let error = case + .with_output_schema(wrong_type) + .fused(memory_child(&[])) + .err() + .unwrap(); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + assert!(error.to_string().contains("must be Float64"), "{error}"); +} + +#[tokio::test] +async fn construction_rejects_a_non_nullable_field_column() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let not_nullable = Arc::new(Schema::new(vec![ + Field::new(VALUE, DataType::Float64, false), + Field::new("host", DataType::Utf8, true), + Field::new( + TIME, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + ])); + let error = case + .with_output_schema(not_nullable) + .fused(memory_child(&[])) + .err() + .unwrap(); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + let message = error.to_string(); + assert!(message.contains(VALUE), "{message}"); + assert!(message.contains("must be nullable"), "{message}"); +} + +#[tokio::test] +async fn construction_rejects_a_non_nullable_tag_column() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let not_nullable = Arc::new(Schema::new(vec![ + Field::new(VALUE, DataType::Float64, true), + Field::new("host", DataType::Utf8, false), + Field::new( + TIME, + DataType::Timestamp(TimeUnit::Millisecond, None), + false, + ), + ])); + let error = case + .with_output_schema(not_nullable) + .fused(memory_child(&[])) + .err() + .unwrap(); + assert!(matches!(error, DataFusionError::Plan(_)), "{error}"); + let message = error.to_string(); + assert!(message.contains("host"), "{message}"); + assert!(message.contains("must be nullable"), "{message}"); +} + +#[tokio::test] +async fn execute_rejects_a_nonzero_partition() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let exec = case.fused(memory_child(&[])).unwrap(); + let error = exec + .execute(1, Arc::new(TaskContext::default())) + .err() + .unwrap(); + assert!(matches!(error, DataFusionError::Execution(_)), "{error}"); +} + +#[tokio::test] +async fn explain_shows_the_function_and_the_map_chain() { + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![MathOp::Abs, MathOp::Sqrt], + ); + let exec = case.fused(memory_child(&[])).unwrap(); + // `DisplayableExecutionPlan` has no `Display` impl in this fork; `indent` covers both + // display formats. + for text in [ + displayable(&exec).indent(false).to_string(), + displayable(&exec).indent(true).to_string(), + ] { + assert!(text.starts_with("FusedSeriesExec:"), "{text}"); + assert!(text.contains("eval=rate"), "{text}"); + assert!(text.contains("range=300000ms"), "{text}"); + assert!(text.contains("offset=0ms"), "{text}"); + assert!(text.contains("maps=[abs, sqrt]"), "{text}"); + assert_eq!(text.matches("sqrt").count(), 1, "{text}"); + } +} + +#[tokio::test] +async fn dropping_the_stream_releases_the_child() { + let chunks = vec![ + chunk( + 1, + "a", + &[(60_000, Some(60.0)), (120_000, Some(120.0))], + true, + ), + chunk( + 2, + "b", + &[(60_000, Some(120.0)), (120_000, Some(240.0))], + true, + ), + ]; + let dropped = Arc::new(AtomicBool::new(false)); + let plan = ProbeExec::new( + frame_batches(&chunks), + Arc::new(AtomicUsize::new(0)), + Arc::clone(&dropped), + ); + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let exec = case.fused(Arc::new(plan)).unwrap(); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + assert!(stream.next().await.unwrap().is_ok()); + assert!( + !dropped.load(Ordering::SeqCst), + "the child stream is still owned" + ); + drop(stream); + assert!( + dropped.load(Ordering::SeqCst), + "dropping the fused stream must drop the child stream" + ); +} + +#[tokio::test] +async fn a_poll_consumes_at_most_the_chunk_budget() { + // Every series has a single sample, so `rate` has no window result and no batch comes out of + // any of these chunks: without a budget one poll would drain the whole always-ready child. + // The input size is fixed rather than derived from the constant, so changing the budget + // changes one side of the comparison instead of rescaling both. + const SERIES: u32 = 200; + let chunks = (0..SERIES) + .map(|index| { + let key = u8::try_from(index).unwrap(); + let host = format!("h{index}"); + chunk(key, &host, &[(60_000, Some(1.0))], true) + }) + .collect::>(); + // One frame batch per chunk, so the child hands out exactly one chunk per poll. + let batches = chunks + .iter() + .flat_map(|chunk| frame_batches(std::slice::from_ref(chunk))) + .collect::>(); + assert_eq!(batches.len(), chunks.len()); + let plan = ProbeExec::new( + batches, + Arc::new(AtomicUsize::new(0)), + Arc::new(AtomicBool::new(false)), + ); + let yields = Arc::clone(&plan.yields); + let case = Case::new( + &["host"], + RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }, + RangeFunction::Rate, + vec![], + ); + let exec = case.fused(Arc::new(plan)).unwrap(); + let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap(); + + let waker = futures::task::noop_waker(); + let mut context = Context::from_waker(&waker); + let polled = stream.as_mut().poll_next(&mut context); + assert!( + polled.is_pending(), + "one poll must not drain the input: {polled:?}" + ); + let consumed = yields.load(Ordering::SeqCst); + assert!(consumed > 0, "the poll must make progress"); + assert!( + consumed <= MAX_CHUNKS_PER_POLL, + "consumed {consumed} chunks in one poll, budget is {MAX_CHUNKS_PER_POLL}" + ); + assert!( + (consumed as u32) < SERIES, + "consumed {consumed} of {SERIES} chunks, the whole input was drained" + ); +} + +/// Emits prepared raw frame batches and reports how often it ran and when its stream was dropped. +struct ProbeExec { + batches: Vec, + schema: SchemaRef, + properties: Arc, + executes: Arc, + dropped: Arc, + /// Number of batches the child stream handed out, i.e. the fused node's chunk inputs. + yields: Arc, +} + +impl ProbeExec { + fn new( + batches: Vec, + executes: Arc, + dropped: Arc, + ) -> Self { + let schema = frame_schema(); + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(schema.clone()), + Partitioning::UnknownPartitioning(1), + EmissionType::Incremental, + Boundedness::Bounded, + )); + Self { + batches, + schema, + properties, + executes, + dropped, + yields: Arc::new(AtomicUsize::new(0)), + } + } +} + +impl std::fmt::Debug for ProbeExec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ProbeExec").finish() + } +} + +impl DisplayAs for ProbeExec { + fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ProbeExec") + } +} + +impl ExecutionPlan for ProbeExec { + fn name(&self) -> &str { + "ProbeExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![] + } + + fn apply_expressions( + &self, + _f: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + + fn with_new_children( + self: Arc, + _children: Vec>, + ) -> Result> { + Ok(self) + } + + fn execute( + &self, + _partition: usize, + _context: Arc, + ) -> Result { + self.executes.fetch_add(1, Ordering::SeqCst); + Ok(Box::pin(ProbeStream { + batches: self.batches.clone().into_iter(), + schema: self.schema.clone(), + dropped: Arc::clone(&self.dropped), + yields: Arc::clone(&self.yields), + })) + } +} + +struct ProbeStream { + batches: std::vec::IntoIter, + schema: SchemaRef, + dropped: Arc, + yields: Arc, +} + +impl RecordBatchStream for ProbeStream { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } +} + +impl Stream for ProbeStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let batch = self.batches.next(); + if batch.is_some() { + self.yields.fetch_add(1, Ordering::SeqCst); + } + Poll::Ready(batch.map(Ok)) + } +} + +impl Drop for ProbeStream { + fn drop(&mut self) { + self.dropped.store(true, Ordering::SeqCst); + } +} diff --git a/tests-integration/Cargo.toml b/tests-integration/Cargo.toml index 79df85475d9..b5d9bc36141 100644 --- a/tests-integration/Cargo.toml +++ b/tests-integration/Cargo.toml @@ -56,6 +56,7 @@ meta-srv = { workspace = true, features = ["mock"] } mito2.workspace = true object-store.workspace = true operator.workspace = true +promql.workspace = true prost.workspace = true query.workspace = true rand.workspace = true diff --git a/tests-integration/src/tests/nested_merge_scan_capability_test.rs b/tests-integration/src/tests/nested_merge_scan_capability_test.rs index 7c696e7373e..80d1ccdf7c8 100644 --- a/tests-integration/src/tests/nested_merge_scan_capability_test.rs +++ b/tests-integration/src/tests/nested_merge_scan_capability_test.rs @@ -747,3 +747,197 @@ fn multiset(mut rows: Vec>) -> Vec> { rows.sort(); rows } + +/// End-to-end check that a fused evaluation node consumes a real storage raw-series scan. +/// +/// The child is the production `SeriesScanExec` over a real mito region whose labels are bound +/// to the primary key, so this exercises the label decoding that storage actually requires. The +/// expected values are derived from the inserted fixture, so the assertion does not repeat the +/// implementation under test. +#[tokio::test] +async fn test_fused_series_exec_over_real_storage_scan() { + use std::sync::Arc; + + use api::v1::SemanticType; + use datafusion::arrow::array::Array; + use datafusion::physical_plan::ExecutionPlan; + use datatypes::series::samples::SeriesSchema; + use datatypes::series::time::{EvalGrid, GridSpec}; + use futures_util::TryStreamExt; + use promql::extension_plan::fused_series::FusedSeriesExec; + use promql::range_eval::{RangeFunction, RangeWindow}; + use store_api::region_engine::{BoundTag, PrepareRequest, RawLabelSource, RegionEngine}; + use store_api::storage::{RegionId, ScanRequest, TimeSeriesDistribution}; + use table::table::scan::RegionScanExec; + + const TABLE: &str = "fused_series_real_scan"; + common_telemetry::init_default_ut_logging(); + let cluster = build_cluster("test_fused_series_exec_over_real_storage_scan").await; + let frontend = cluster.fe_instance().clone(); + execute_sql(&frontend, &format!( + "CREATE TABLE {TABLE} (host STRING, metric_value DOUBLE, ts TIMESTAMP, TIME INDEX (ts), PRIMARY KEY(host)) ENGINE=mito" + )).await; + // One series, one sample per 60s, rising 60 per sample, so `rate` over 5m is exactly 1/s. + let rows = (1..=9) + .map(|i| format!("('alpha', {}, {})", 60 * i, i * 60_000)) + .collect::>() + .join(", "); + execute_sql(&frontend, &format!("INSERT INTO {TABLE} VALUES {rows}")).await; + + let leaders = region_leaders(&frontend, TABLE).await; + assert_eq!(1, leaders.len(), "fixture is required to have one region"); + let (®ion_id, &(node_id, _)) = leaders.iter().next().unwrap(); + let region_id = RegionId::from_u64(region_id); + let engine = region_server(&cluster, node_id).mito_engine().unwrap(); + let metadata = engine.find_region(region_id).unwrap().metadata(); + + // Build the production raw-series leaf straight from the real region engine. The engine's + // own `execute_raw_series` entry point also starts the scan stream, and a scanner serves a + // partition once, so the leaf has to be obtained before anything is polled. + let request = ScanRequest { + projection: Some(vec![ + metadata + .column_metadatas + .iter() + .position(|c| c.column_schema.name == "host") + .unwrap(), + metadata + .column_metadatas + .iter() + .position(|c| c.column_schema.name == "metric_value") + .unwrap(), + metadata + .column_metadatas + .iter() + .position(|c| c.column_schema.name == "ts") + .unwrap(), + ]), + distribution: Some(TimeSeriesDistribution::PerSeries), + preserve_pk_dictionary_encoding: true, + ..Default::default() + }; + let mut scanner = engine + .handle_query(region_id, request.clone()) + .await + .unwrap(); + let mut labels = Vec::new(); + for column in metadata.column_metadatas.iter() { + if column.semantic_type == SemanticType::Tag { + labels.push(BoundTag { + column_id: column.column_id, + name: Arc::from(column.column_schema.name.as_str()), + }); + } + } + let label_source = RawLabelSource::PrimaryKey { + metric_name: Arc::from(TABLE), + physical_metadata: metadata.clone(), + logical_tags: labels.into(), + }; + let ranges = scanner.properties().partitions.clone(); + scanner + .prepare(PrepareRequest { + ranges: Some(ranges.clone()), + target_partitions: Some(ranges.len()), + ..Default::default() + }) + .unwrap(); + let child = Arc::new(RegionScanExec::new(scanner, request, None).unwrap()) + .try_to_series_scan(label_source.clone()) + .unwrap() + .expect("mito region must support a native raw-series scan"); + let series_schema: Arc = Arc::clone(child.series_schema()); + let ordering = child.raw_series_ordering(); + assert!(matches!(label_source, RawLabelSource::PrimaryKey { .. })); + + let grid = Arc::new(EvalGrid::try_new(GridSpec::try_new(300_000, 60_000, 5).unwrap()).unwrap()); + let output_schema = Arc::new(datafusion::arrow::datatypes::Schema::new(vec![ + datafusion::arrow::datatypes::Field::new( + "metric_value", + datafusion::arrow::datatypes::DataType::Float64, + true, + ), + datafusion::arrow::datatypes::Field::new( + "host", + datafusion::arrow::datatypes::DataType::Utf8, + true, + ), + datafusion::arrow::datatypes::Field::new( + "ts", + datafusion::arrow::datatypes::DataType::Timestamp( + datafusion::arrow::datatypes::TimeUnit::Millisecond, + None, + ), + false, + ), + ])); + let window = RangeWindow { + range_ms: 300_000, + offset_ms: 0, + anchor_ms: None, + }; + + // A scanner serves partition 0 exactly once, so the fused node consumes the real storage + // stream directly and the expected values below come from the fixture, not from a second run + // of the same kernels. + let fused = FusedSeriesExec::try_new( + child, + series_schema, + label_source, + ordering, + grid, + window, + RangeFunction::Rate, + vec![], + output_schema, + vec!["host".to_string()], + "ts".to_string(), + ) + .unwrap(); + let mut stream = fused + .execute( + 0, + Arc::new(datafusion::execution::context::TaskContext::default()), + ) + .unwrap(); + let mut batches = Vec::new(); + while let Some(batch) = stream.try_next().await.unwrap() { + batches.push(batch); + } + assert_eq!(1, batches.len(), "one series expected from the fused node"); + + // The counter rises 60 per minute, so every five-minute window is exactly one per second. + let values = batches[0] + .column_by_name("metric_value") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(5, values.len(), "five grid points at 300s..540s"); + for row in 0..values.len() { + assert_eq!(1.0, values.value(row), "rate row {row}"); + } + let hosts = batches[0] + .column_by_name("host") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..hosts.len() { + assert_eq!( + "alpha", + hosts.value(row), + "primary-key label must decode to the real label value" + ); + } + let timestamps = batches[0] + .column_by_name("ts") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let ts = (0..timestamps.len()) + .map(|row| timestamps.value(row)) + .collect::>(); + assert_eq!(vec![300_000, 360_000, 420_000, 480_000, 540_000], ts); +}